bpf: reject non-exact register type matches in regsafe()
[platform/kernel/linux-starfive.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
28 #include "disasm.h"
29
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32         [_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168         /* verifer state is 'st'
169          * before processing instruction 'insn_idx'
170          * and after processing instruction 'prev_insn_idx'
171          */
172         struct bpf_verifier_state st;
173         int insn_idx;
174         int prev_insn_idx;
175         struct bpf_verifier_stack_elem *next;
176         /* length of verifier log at the time this state was pushed on stack */
177         u32 log_pos;
178 };
179
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
181 #define BPF_COMPLEXITY_LIMIT_STATES     64
182
183 #define BPF_MAP_KEY_POISON      (1ULL << 63)
184 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
185
186 #define BPF_MAP_PTR_UNPRIV      1UL
187 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
188                                           POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193
194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 {
196         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
197 }
198
199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 {
201         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
202 }
203
204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205                               const struct bpf_map *map, bool unpriv)
206 {
207         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208         unpriv |= bpf_map_ptr_unpriv(aux);
209         aux->map_ptr_state = (unsigned long)map |
210                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211 }
212
213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 {
215         return aux->map_key_state & BPF_MAP_KEY_POISON;
216 }
217
218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 {
220         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221 }
222
223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 {
225         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226 }
227
228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 {
230         bool poisoned = bpf_map_key_poisoned(aux);
231
232         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
234 }
235
236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 {
238         return insn->code == (BPF_JMP | BPF_CALL) &&
239                insn->src_reg == BPF_PSEUDO_CALL;
240 }
241
242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 {
244         return insn->code == (BPF_JMP | BPF_CALL) &&
245                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246 }
247
248 struct bpf_call_arg_meta {
249         struct bpf_map *map_ptr;
250         bool raw_mode;
251         bool pkt_access;
252         u8 release_regno;
253         int regno;
254         int access_size;
255         int mem_size;
256         u64 msize_max_value;
257         int ref_obj_id;
258         int map_uid;
259         int func_id;
260         struct btf *btf;
261         u32 btf_id;
262         struct btf *ret_btf;
263         u32 ret_btf_id;
264         u32 subprogno;
265         struct btf_field *kptr_field;
266         u8 uninit_dynptr_regno;
267 };
268
269 struct btf *btf_vmlinux;
270
271 static DEFINE_MUTEX(bpf_verifier_lock);
272
273 static const struct bpf_line_info *
274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 {
276         const struct bpf_line_info *linfo;
277         const struct bpf_prog *prog;
278         u32 i, nr_linfo;
279
280         prog = env->prog;
281         nr_linfo = prog->aux->nr_linfo;
282
283         if (!nr_linfo || insn_off >= prog->len)
284                 return NULL;
285
286         linfo = prog->aux->linfo;
287         for (i = 1; i < nr_linfo; i++)
288                 if (insn_off < linfo[i].insn_off)
289                         break;
290
291         return &linfo[i - 1];
292 }
293
294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295                        va_list args)
296 {
297         unsigned int n;
298
299         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300
301         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302                   "verifier log line truncated - local buffer too short\n");
303
304         if (log->level == BPF_LOG_KERNEL) {
305                 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306
307                 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
308                 return;
309         }
310
311         n = min(log->len_total - log->len_used - 1, n);
312         log->kbuf[n] = '\0';
313         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314                 log->len_used += n;
315         else
316                 log->ubuf = NULL;
317 }
318
319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320 {
321         char zero = 0;
322
323         if (!bpf_verifier_log_needed(log))
324                 return;
325
326         log->len_used = new_pos;
327         if (put_user(zero, log->ubuf + new_pos))
328                 log->ubuf = NULL;
329 }
330
331 /* log_level controls verbosity level of eBPF verifier.
332  * bpf_verifier_log_write() is used to dump the verification trace to the log,
333  * so the user can figure out what's wrong with the program
334  */
335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336                                            const char *fmt, ...)
337 {
338         va_list args;
339
340         if (!bpf_verifier_log_needed(&env->log))
341                 return;
342
343         va_start(args, fmt);
344         bpf_verifier_vlog(&env->log, fmt, args);
345         va_end(args);
346 }
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348
349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 {
351         struct bpf_verifier_env *env = private_data;
352         va_list args;
353
354         if (!bpf_verifier_log_needed(&env->log))
355                 return;
356
357         va_start(args, fmt);
358         bpf_verifier_vlog(&env->log, fmt, args);
359         va_end(args);
360 }
361
362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363                             const char *fmt, ...)
364 {
365         va_list args;
366
367         if (!bpf_verifier_log_needed(log))
368                 return;
369
370         va_start(args, fmt);
371         bpf_verifier_vlog(log, fmt, args);
372         va_end(args);
373 }
374 EXPORT_SYMBOL_GPL(bpf_log);
375
376 static const char *ltrim(const char *s)
377 {
378         while (isspace(*s))
379                 s++;
380
381         return s;
382 }
383
384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385                                          u32 insn_off,
386                                          const char *prefix_fmt, ...)
387 {
388         const struct bpf_line_info *linfo;
389
390         if (!bpf_verifier_log_needed(&env->log))
391                 return;
392
393         linfo = find_linfo(env, insn_off);
394         if (!linfo || linfo == env->prev_linfo)
395                 return;
396
397         if (prefix_fmt) {
398                 va_list args;
399
400                 va_start(args, prefix_fmt);
401                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
402                 va_end(args);
403         }
404
405         verbose(env, "%s\n",
406                 ltrim(btf_name_by_offset(env->prog->aux->btf,
407                                          linfo->line_off)));
408
409         env->prev_linfo = linfo;
410 }
411
412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413                                    struct bpf_reg_state *reg,
414                                    struct tnum *range, const char *ctx,
415                                    const char *reg_name)
416 {
417         char tn_buf[48];
418
419         verbose(env, "At %s the register %s ", ctx, reg_name);
420         if (!tnum_is_unknown(reg->var_off)) {
421                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422                 verbose(env, "has value %s", tn_buf);
423         } else {
424                 verbose(env, "has unknown scalar value");
425         }
426         tnum_strn(tn_buf, sizeof(tn_buf), *range);
427         verbose(env, " should have been in %s\n", tn_buf);
428 }
429
430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
431 {
432         type = base_type(type);
433         return type == PTR_TO_PACKET ||
434                type == PTR_TO_PACKET_META;
435 }
436
437 static bool type_is_sk_pointer(enum bpf_reg_type type)
438 {
439         return type == PTR_TO_SOCKET ||
440                 type == PTR_TO_SOCK_COMMON ||
441                 type == PTR_TO_TCP_SOCK ||
442                 type == PTR_TO_XDP_SOCK;
443 }
444
445 static bool reg_type_not_null(enum bpf_reg_type type)
446 {
447         return type == PTR_TO_SOCKET ||
448                 type == PTR_TO_TCP_SOCK ||
449                 type == PTR_TO_MAP_VALUE ||
450                 type == PTR_TO_MAP_KEY ||
451                 type == PTR_TO_SOCK_COMMON;
452 }
453
454 static bool type_is_ptr_alloc_obj(u32 type)
455 {
456         return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
457 }
458
459 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
460 {
461         struct btf_record *rec = NULL;
462         struct btf_struct_meta *meta;
463
464         if (reg->type == PTR_TO_MAP_VALUE) {
465                 rec = reg->map_ptr->record;
466         } else if (type_is_ptr_alloc_obj(reg->type)) {
467                 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
468                 if (meta)
469                         rec = meta->record;
470         }
471         return rec;
472 }
473
474 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
475 {
476         return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
477 }
478
479 static bool type_is_rdonly_mem(u32 type)
480 {
481         return type & MEM_RDONLY;
482 }
483
484 static bool type_may_be_null(u32 type)
485 {
486         return type & PTR_MAYBE_NULL;
487 }
488
489 static bool is_acquire_function(enum bpf_func_id func_id,
490                                 const struct bpf_map *map)
491 {
492         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
493
494         if (func_id == BPF_FUNC_sk_lookup_tcp ||
495             func_id == BPF_FUNC_sk_lookup_udp ||
496             func_id == BPF_FUNC_skc_lookup_tcp ||
497             func_id == BPF_FUNC_ringbuf_reserve ||
498             func_id == BPF_FUNC_kptr_xchg)
499                 return true;
500
501         if (func_id == BPF_FUNC_map_lookup_elem &&
502             (map_type == BPF_MAP_TYPE_SOCKMAP ||
503              map_type == BPF_MAP_TYPE_SOCKHASH))
504                 return true;
505
506         return false;
507 }
508
509 static bool is_ptr_cast_function(enum bpf_func_id func_id)
510 {
511         return func_id == BPF_FUNC_tcp_sock ||
512                 func_id == BPF_FUNC_sk_fullsock ||
513                 func_id == BPF_FUNC_skc_to_tcp_sock ||
514                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
515                 func_id == BPF_FUNC_skc_to_udp6_sock ||
516                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
517                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
518                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
519 }
520
521 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
522 {
523         return func_id == BPF_FUNC_dynptr_data;
524 }
525
526 static bool is_callback_calling_function(enum bpf_func_id func_id)
527 {
528         return func_id == BPF_FUNC_for_each_map_elem ||
529                func_id == BPF_FUNC_timer_set_callback ||
530                func_id == BPF_FUNC_find_vma ||
531                func_id == BPF_FUNC_loop ||
532                func_id == BPF_FUNC_user_ringbuf_drain;
533 }
534
535 static bool is_storage_get_function(enum bpf_func_id func_id)
536 {
537         return func_id == BPF_FUNC_sk_storage_get ||
538                func_id == BPF_FUNC_inode_storage_get ||
539                func_id == BPF_FUNC_task_storage_get ||
540                func_id == BPF_FUNC_cgrp_storage_get;
541 }
542
543 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
544                                         const struct bpf_map *map)
545 {
546         int ref_obj_uses = 0;
547
548         if (is_ptr_cast_function(func_id))
549                 ref_obj_uses++;
550         if (is_acquire_function(func_id, map))
551                 ref_obj_uses++;
552         if (is_dynptr_ref_function(func_id))
553                 ref_obj_uses++;
554
555         return ref_obj_uses > 1;
556 }
557
558 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
559 {
560         return BPF_CLASS(insn->code) == BPF_STX &&
561                BPF_MODE(insn->code) == BPF_ATOMIC &&
562                insn->imm == BPF_CMPXCHG;
563 }
564
565 /* string representation of 'enum bpf_reg_type'
566  *
567  * Note that reg_type_str() can not appear more than once in a single verbose()
568  * statement.
569  */
570 static const char *reg_type_str(struct bpf_verifier_env *env,
571                                 enum bpf_reg_type type)
572 {
573         char postfix[16] = {0}, prefix[64] = {0};
574         static const char * const str[] = {
575                 [NOT_INIT]              = "?",
576                 [SCALAR_VALUE]          = "scalar",
577                 [PTR_TO_CTX]            = "ctx",
578                 [CONST_PTR_TO_MAP]      = "map_ptr",
579                 [PTR_TO_MAP_VALUE]      = "map_value",
580                 [PTR_TO_STACK]          = "fp",
581                 [PTR_TO_PACKET]         = "pkt",
582                 [PTR_TO_PACKET_META]    = "pkt_meta",
583                 [PTR_TO_PACKET_END]     = "pkt_end",
584                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
585                 [PTR_TO_SOCKET]         = "sock",
586                 [PTR_TO_SOCK_COMMON]    = "sock_common",
587                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
588                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
589                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
590                 [PTR_TO_BTF_ID]         = "ptr_",
591                 [PTR_TO_MEM]            = "mem",
592                 [PTR_TO_BUF]            = "buf",
593                 [PTR_TO_FUNC]           = "func",
594                 [PTR_TO_MAP_KEY]        = "map_key",
595                 [CONST_PTR_TO_DYNPTR]   = "dynptr_ptr",
596         };
597
598         if (type & PTR_MAYBE_NULL) {
599                 if (base_type(type) == PTR_TO_BTF_ID)
600                         strncpy(postfix, "or_null_", 16);
601                 else
602                         strncpy(postfix, "_or_null", 16);
603         }
604
605         snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
606                  type & MEM_RDONLY ? "rdonly_" : "",
607                  type & MEM_RINGBUF ? "ringbuf_" : "",
608                  type & MEM_USER ? "user_" : "",
609                  type & MEM_PERCPU ? "percpu_" : "",
610                  type & MEM_RCU ? "rcu_" : "",
611                  type & PTR_UNTRUSTED ? "untrusted_" : "",
612                  type & PTR_TRUSTED ? "trusted_" : ""
613         );
614
615         snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
616                  prefix, str[base_type(type)], postfix);
617         return env->type_str_buf;
618 }
619
620 static char slot_type_char[] = {
621         [STACK_INVALID] = '?',
622         [STACK_SPILL]   = 'r',
623         [STACK_MISC]    = 'm',
624         [STACK_ZERO]    = '0',
625         [STACK_DYNPTR]  = 'd',
626 };
627
628 static void print_liveness(struct bpf_verifier_env *env,
629                            enum bpf_reg_liveness live)
630 {
631         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
632             verbose(env, "_");
633         if (live & REG_LIVE_READ)
634                 verbose(env, "r");
635         if (live & REG_LIVE_WRITTEN)
636                 verbose(env, "w");
637         if (live & REG_LIVE_DONE)
638                 verbose(env, "D");
639 }
640
641 static int get_spi(s32 off)
642 {
643         return (-off - 1) / BPF_REG_SIZE;
644 }
645
646 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
647 {
648         int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
649
650         /* We need to check that slots between [spi - nr_slots + 1, spi] are
651          * within [0, allocated_stack).
652          *
653          * Please note that the spi grows downwards. For example, a dynptr
654          * takes the size of two stack slots; the first slot will be at
655          * spi and the second slot will be at spi - 1.
656          */
657         return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
658 }
659
660 static struct bpf_func_state *func(struct bpf_verifier_env *env,
661                                    const struct bpf_reg_state *reg)
662 {
663         struct bpf_verifier_state *cur = env->cur_state;
664
665         return cur->frame[reg->frameno];
666 }
667
668 static const char *kernel_type_name(const struct btf* btf, u32 id)
669 {
670         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
671 }
672
673 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
674 {
675         env->scratched_regs |= 1U << regno;
676 }
677
678 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
679 {
680         env->scratched_stack_slots |= 1ULL << spi;
681 }
682
683 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
684 {
685         return (env->scratched_regs >> regno) & 1;
686 }
687
688 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
689 {
690         return (env->scratched_stack_slots >> regno) & 1;
691 }
692
693 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
694 {
695         return env->scratched_regs || env->scratched_stack_slots;
696 }
697
698 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
699 {
700         env->scratched_regs = 0U;
701         env->scratched_stack_slots = 0ULL;
702 }
703
704 /* Used for printing the entire verifier state. */
705 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
706 {
707         env->scratched_regs = ~0U;
708         env->scratched_stack_slots = ~0ULL;
709 }
710
711 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
712 {
713         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
714         case DYNPTR_TYPE_LOCAL:
715                 return BPF_DYNPTR_TYPE_LOCAL;
716         case DYNPTR_TYPE_RINGBUF:
717                 return BPF_DYNPTR_TYPE_RINGBUF;
718         default:
719                 return BPF_DYNPTR_TYPE_INVALID;
720         }
721 }
722
723 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
724 {
725         return type == BPF_DYNPTR_TYPE_RINGBUF;
726 }
727
728 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
729                               enum bpf_dynptr_type type,
730                               bool first_slot);
731
732 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
733                                 struct bpf_reg_state *reg);
734
735 static void mark_dynptr_stack_regs(struct bpf_reg_state *sreg1,
736                                    struct bpf_reg_state *sreg2,
737                                    enum bpf_dynptr_type type)
738 {
739         __mark_dynptr_reg(sreg1, type, true);
740         __mark_dynptr_reg(sreg2, type, false);
741 }
742
743 static void mark_dynptr_cb_reg(struct bpf_reg_state *reg,
744                                enum bpf_dynptr_type type)
745 {
746         __mark_dynptr_reg(reg, type, true);
747 }
748
749
750 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
751                                    enum bpf_arg_type arg_type, int insn_idx)
752 {
753         struct bpf_func_state *state = func(env, reg);
754         enum bpf_dynptr_type type;
755         int spi, i, id;
756
757         spi = get_spi(reg->off);
758
759         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
760                 return -EINVAL;
761
762         for (i = 0; i < BPF_REG_SIZE; i++) {
763                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
764                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
765         }
766
767         type = arg_to_dynptr_type(arg_type);
768         if (type == BPF_DYNPTR_TYPE_INVALID)
769                 return -EINVAL;
770
771         mark_dynptr_stack_regs(&state->stack[spi].spilled_ptr,
772                                &state->stack[spi - 1].spilled_ptr, type);
773
774         if (dynptr_type_refcounted(type)) {
775                 /* The id is used to track proper releasing */
776                 id = acquire_reference_state(env, insn_idx);
777                 if (id < 0)
778                         return id;
779
780                 state->stack[spi].spilled_ptr.ref_obj_id = id;
781                 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
782         }
783
784         return 0;
785 }
786
787 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
788 {
789         struct bpf_func_state *state = func(env, reg);
790         int spi, i;
791
792         spi = get_spi(reg->off);
793
794         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
795                 return -EINVAL;
796
797         for (i = 0; i < BPF_REG_SIZE; i++) {
798                 state->stack[spi].slot_type[i] = STACK_INVALID;
799                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
800         }
801
802         /* Invalidate any slices associated with this dynptr */
803         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
804                 WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
805
806         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
807         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
808         return 0;
809 }
810
811 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
812 {
813         struct bpf_func_state *state = func(env, reg);
814         int spi, i;
815
816         if (reg->type == CONST_PTR_TO_DYNPTR)
817                 return false;
818
819         spi = get_spi(reg->off);
820         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
821                 return true;
822
823         for (i = 0; i < BPF_REG_SIZE; i++) {
824                 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
825                     state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
826                         return false;
827         }
828
829         return true;
830 }
831
832 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
833 {
834         struct bpf_func_state *state = func(env, reg);
835         int spi;
836         int i;
837
838         /* This already represents first slot of initialized bpf_dynptr */
839         if (reg->type == CONST_PTR_TO_DYNPTR)
840                 return true;
841
842         spi = get_spi(reg->off);
843         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
844             !state->stack[spi].spilled_ptr.dynptr.first_slot)
845                 return false;
846
847         for (i = 0; i < BPF_REG_SIZE; i++) {
848                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
849                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
850                         return false;
851         }
852
853         return true;
854 }
855
856 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
857                                     enum bpf_arg_type arg_type)
858 {
859         struct bpf_func_state *state = func(env, reg);
860         enum bpf_dynptr_type dynptr_type;
861         int spi;
862
863         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
864         if (arg_type == ARG_PTR_TO_DYNPTR)
865                 return true;
866
867         dynptr_type = arg_to_dynptr_type(arg_type);
868         if (reg->type == CONST_PTR_TO_DYNPTR) {
869                 return reg->dynptr.type == dynptr_type;
870         } else {
871                 spi = get_spi(reg->off);
872                 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
873         }
874 }
875
876 /* The reg state of a pointer or a bounded scalar was saved when
877  * it was spilled to the stack.
878  */
879 static bool is_spilled_reg(const struct bpf_stack_state *stack)
880 {
881         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
882 }
883
884 static void scrub_spilled_slot(u8 *stype)
885 {
886         if (*stype != STACK_INVALID)
887                 *stype = STACK_MISC;
888 }
889
890 static void print_verifier_state(struct bpf_verifier_env *env,
891                                  const struct bpf_func_state *state,
892                                  bool print_all)
893 {
894         const struct bpf_reg_state *reg;
895         enum bpf_reg_type t;
896         int i;
897
898         if (state->frameno)
899                 verbose(env, " frame%d:", state->frameno);
900         for (i = 0; i < MAX_BPF_REG; i++) {
901                 reg = &state->regs[i];
902                 t = reg->type;
903                 if (t == NOT_INIT)
904                         continue;
905                 if (!print_all && !reg_scratched(env, i))
906                         continue;
907                 verbose(env, " R%d", i);
908                 print_liveness(env, reg->live);
909                 verbose(env, "=");
910                 if (t == SCALAR_VALUE && reg->precise)
911                         verbose(env, "P");
912                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
913                     tnum_is_const(reg->var_off)) {
914                         /* reg->off should be 0 for SCALAR_VALUE */
915                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
916                         verbose(env, "%lld", reg->var_off.value + reg->off);
917                 } else {
918                         const char *sep = "";
919
920                         verbose(env, "%s", reg_type_str(env, t));
921                         if (base_type(t) == PTR_TO_BTF_ID)
922                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
923                         verbose(env, "(");
924 /*
925  * _a stands for append, was shortened to avoid multiline statements below.
926  * This macro is used to output a comma separated list of attributes.
927  */
928 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
929
930                         if (reg->id)
931                                 verbose_a("id=%d", reg->id);
932                         if (reg->ref_obj_id)
933                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
934                         if (t != SCALAR_VALUE)
935                                 verbose_a("off=%d", reg->off);
936                         if (type_is_pkt_pointer(t))
937                                 verbose_a("r=%d", reg->range);
938                         else if (base_type(t) == CONST_PTR_TO_MAP ||
939                                  base_type(t) == PTR_TO_MAP_KEY ||
940                                  base_type(t) == PTR_TO_MAP_VALUE)
941                                 verbose_a("ks=%d,vs=%d",
942                                           reg->map_ptr->key_size,
943                                           reg->map_ptr->value_size);
944                         if (tnum_is_const(reg->var_off)) {
945                                 /* Typically an immediate SCALAR_VALUE, but
946                                  * could be a pointer whose offset is too big
947                                  * for reg->off
948                                  */
949                                 verbose_a("imm=%llx", reg->var_off.value);
950                         } else {
951                                 if (reg->smin_value != reg->umin_value &&
952                                     reg->smin_value != S64_MIN)
953                                         verbose_a("smin=%lld", (long long)reg->smin_value);
954                                 if (reg->smax_value != reg->umax_value &&
955                                     reg->smax_value != S64_MAX)
956                                         verbose_a("smax=%lld", (long long)reg->smax_value);
957                                 if (reg->umin_value != 0)
958                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
959                                 if (reg->umax_value != U64_MAX)
960                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
961                                 if (!tnum_is_unknown(reg->var_off)) {
962                                         char tn_buf[48];
963
964                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
965                                         verbose_a("var_off=%s", tn_buf);
966                                 }
967                                 if (reg->s32_min_value != reg->smin_value &&
968                                     reg->s32_min_value != S32_MIN)
969                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
970                                 if (reg->s32_max_value != reg->smax_value &&
971                                     reg->s32_max_value != S32_MAX)
972                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
973                                 if (reg->u32_min_value != reg->umin_value &&
974                                     reg->u32_min_value != U32_MIN)
975                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
976                                 if (reg->u32_max_value != reg->umax_value &&
977                                     reg->u32_max_value != U32_MAX)
978                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
979                         }
980 #undef verbose_a
981
982                         verbose(env, ")");
983                 }
984         }
985         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
986                 char types_buf[BPF_REG_SIZE + 1];
987                 bool valid = false;
988                 int j;
989
990                 for (j = 0; j < BPF_REG_SIZE; j++) {
991                         if (state->stack[i].slot_type[j] != STACK_INVALID)
992                                 valid = true;
993                         types_buf[j] = slot_type_char[
994                                         state->stack[i].slot_type[j]];
995                 }
996                 types_buf[BPF_REG_SIZE] = 0;
997                 if (!valid)
998                         continue;
999                 if (!print_all && !stack_slot_scratched(env, i))
1000                         continue;
1001                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1002                 print_liveness(env, state->stack[i].spilled_ptr.live);
1003                 if (is_spilled_reg(&state->stack[i])) {
1004                         reg = &state->stack[i].spilled_ptr;
1005                         t = reg->type;
1006                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1007                         if (t == SCALAR_VALUE && reg->precise)
1008                                 verbose(env, "P");
1009                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1010                                 verbose(env, "%lld", reg->var_off.value + reg->off);
1011                 } else {
1012                         verbose(env, "=%s", types_buf);
1013                 }
1014         }
1015         if (state->acquired_refs && state->refs[0].id) {
1016                 verbose(env, " refs=%d", state->refs[0].id);
1017                 for (i = 1; i < state->acquired_refs; i++)
1018                         if (state->refs[i].id)
1019                                 verbose(env, ",%d", state->refs[i].id);
1020         }
1021         if (state->in_callback_fn)
1022                 verbose(env, " cb");
1023         if (state->in_async_callback_fn)
1024                 verbose(env, " async_cb");
1025         verbose(env, "\n");
1026         mark_verifier_state_clean(env);
1027 }
1028
1029 static inline u32 vlog_alignment(u32 pos)
1030 {
1031         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1032                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1033 }
1034
1035 static void print_insn_state(struct bpf_verifier_env *env,
1036                              const struct bpf_func_state *state)
1037 {
1038         if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1039                 /* remove new line character */
1040                 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1041                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1042         } else {
1043                 verbose(env, "%d:", env->insn_idx);
1044         }
1045         print_verifier_state(env, state, false);
1046 }
1047
1048 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1049  * small to hold src. This is different from krealloc since we don't want to preserve
1050  * the contents of dst.
1051  *
1052  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1053  * not be allocated.
1054  */
1055 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1056 {
1057         size_t bytes;
1058
1059         if (ZERO_OR_NULL_PTR(src))
1060                 goto out;
1061
1062         if (unlikely(check_mul_overflow(n, size, &bytes)))
1063                 return NULL;
1064
1065         if (ksize(dst) < ksize(src)) {
1066                 kfree(dst);
1067                 dst = kmalloc_track_caller(kmalloc_size_roundup(bytes), flags);
1068                 if (!dst)
1069                         return NULL;
1070         }
1071
1072         memcpy(dst, src, bytes);
1073 out:
1074         return dst ? dst : ZERO_SIZE_PTR;
1075 }
1076
1077 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1078  * small to hold new_n items. new items are zeroed out if the array grows.
1079  *
1080  * Contrary to krealloc_array, does not free arr if new_n is zero.
1081  */
1082 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1083 {
1084         size_t alloc_size;
1085         void *new_arr;
1086
1087         if (!new_n || old_n == new_n)
1088                 goto out;
1089
1090         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1091         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1092         if (!new_arr) {
1093                 kfree(arr);
1094                 return NULL;
1095         }
1096         arr = new_arr;
1097
1098         if (new_n > old_n)
1099                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1100
1101 out:
1102         return arr ? arr : ZERO_SIZE_PTR;
1103 }
1104
1105 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1106 {
1107         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1108                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1109         if (!dst->refs)
1110                 return -ENOMEM;
1111
1112         dst->acquired_refs = src->acquired_refs;
1113         return 0;
1114 }
1115
1116 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1117 {
1118         size_t n = src->allocated_stack / BPF_REG_SIZE;
1119
1120         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1121                                 GFP_KERNEL);
1122         if (!dst->stack)
1123                 return -ENOMEM;
1124
1125         dst->allocated_stack = src->allocated_stack;
1126         return 0;
1127 }
1128
1129 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1130 {
1131         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1132                                     sizeof(struct bpf_reference_state));
1133         if (!state->refs)
1134                 return -ENOMEM;
1135
1136         state->acquired_refs = n;
1137         return 0;
1138 }
1139
1140 static int grow_stack_state(struct bpf_func_state *state, int size)
1141 {
1142         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1143
1144         if (old_n >= n)
1145                 return 0;
1146
1147         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1148         if (!state->stack)
1149                 return -ENOMEM;
1150
1151         state->allocated_stack = size;
1152         return 0;
1153 }
1154
1155 /* Acquire a pointer id from the env and update the state->refs to include
1156  * this new pointer reference.
1157  * On success, returns a valid pointer id to associate with the register
1158  * On failure, returns a negative errno.
1159  */
1160 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1161 {
1162         struct bpf_func_state *state = cur_func(env);
1163         int new_ofs = state->acquired_refs;
1164         int id, err;
1165
1166         err = resize_reference_state(state, state->acquired_refs + 1);
1167         if (err)
1168                 return err;
1169         id = ++env->id_gen;
1170         state->refs[new_ofs].id = id;
1171         state->refs[new_ofs].insn_idx = insn_idx;
1172         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1173
1174         return id;
1175 }
1176
1177 /* release function corresponding to acquire_reference_state(). Idempotent. */
1178 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1179 {
1180         int i, last_idx;
1181
1182         last_idx = state->acquired_refs - 1;
1183         for (i = 0; i < state->acquired_refs; i++) {
1184                 if (state->refs[i].id == ptr_id) {
1185                         /* Cannot release caller references in callbacks */
1186                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1187                                 return -EINVAL;
1188                         if (last_idx && i != last_idx)
1189                                 memcpy(&state->refs[i], &state->refs[last_idx],
1190                                        sizeof(*state->refs));
1191                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1192                         state->acquired_refs--;
1193                         return 0;
1194                 }
1195         }
1196         return -EINVAL;
1197 }
1198
1199 static void free_func_state(struct bpf_func_state *state)
1200 {
1201         if (!state)
1202                 return;
1203         kfree(state->refs);
1204         kfree(state->stack);
1205         kfree(state);
1206 }
1207
1208 static void clear_jmp_history(struct bpf_verifier_state *state)
1209 {
1210         kfree(state->jmp_history);
1211         state->jmp_history = NULL;
1212         state->jmp_history_cnt = 0;
1213 }
1214
1215 static void free_verifier_state(struct bpf_verifier_state *state,
1216                                 bool free_self)
1217 {
1218         int i;
1219
1220         for (i = 0; i <= state->curframe; i++) {
1221                 free_func_state(state->frame[i]);
1222                 state->frame[i] = NULL;
1223         }
1224         clear_jmp_history(state);
1225         if (free_self)
1226                 kfree(state);
1227 }
1228
1229 /* copy verifier state from src to dst growing dst stack space
1230  * when necessary to accommodate larger src stack
1231  */
1232 static int copy_func_state(struct bpf_func_state *dst,
1233                            const struct bpf_func_state *src)
1234 {
1235         int err;
1236
1237         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1238         err = copy_reference_state(dst, src);
1239         if (err)
1240                 return err;
1241         return copy_stack_state(dst, src);
1242 }
1243
1244 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1245                                const struct bpf_verifier_state *src)
1246 {
1247         struct bpf_func_state *dst;
1248         int i, err;
1249
1250         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1251                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1252                                             GFP_USER);
1253         if (!dst_state->jmp_history)
1254                 return -ENOMEM;
1255         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1256
1257         /* if dst has more stack frames then src frame, free them */
1258         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1259                 free_func_state(dst_state->frame[i]);
1260                 dst_state->frame[i] = NULL;
1261         }
1262         dst_state->speculative = src->speculative;
1263         dst_state->active_rcu_lock = src->active_rcu_lock;
1264         dst_state->curframe = src->curframe;
1265         dst_state->active_lock.ptr = src->active_lock.ptr;
1266         dst_state->active_lock.id = src->active_lock.id;
1267         dst_state->branches = src->branches;
1268         dst_state->parent = src->parent;
1269         dst_state->first_insn_idx = src->first_insn_idx;
1270         dst_state->last_insn_idx = src->last_insn_idx;
1271         for (i = 0; i <= src->curframe; i++) {
1272                 dst = dst_state->frame[i];
1273                 if (!dst) {
1274                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1275                         if (!dst)
1276                                 return -ENOMEM;
1277                         dst_state->frame[i] = dst;
1278                 }
1279                 err = copy_func_state(dst, src->frame[i]);
1280                 if (err)
1281                         return err;
1282         }
1283         return 0;
1284 }
1285
1286 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1287 {
1288         while (st) {
1289                 u32 br = --st->branches;
1290
1291                 /* WARN_ON(br > 1) technically makes sense here,
1292                  * but see comment in push_stack(), hence:
1293                  */
1294                 WARN_ONCE((int)br < 0,
1295                           "BUG update_branch_counts:branches_to_explore=%d\n",
1296                           br);
1297                 if (br)
1298                         break;
1299                 st = st->parent;
1300         }
1301 }
1302
1303 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1304                      int *insn_idx, bool pop_log)
1305 {
1306         struct bpf_verifier_state *cur = env->cur_state;
1307         struct bpf_verifier_stack_elem *elem, *head = env->head;
1308         int err;
1309
1310         if (env->head == NULL)
1311                 return -ENOENT;
1312
1313         if (cur) {
1314                 err = copy_verifier_state(cur, &head->st);
1315                 if (err)
1316                         return err;
1317         }
1318         if (pop_log)
1319                 bpf_vlog_reset(&env->log, head->log_pos);
1320         if (insn_idx)
1321                 *insn_idx = head->insn_idx;
1322         if (prev_insn_idx)
1323                 *prev_insn_idx = head->prev_insn_idx;
1324         elem = head->next;
1325         free_verifier_state(&head->st, false);
1326         kfree(head);
1327         env->head = elem;
1328         env->stack_size--;
1329         return 0;
1330 }
1331
1332 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1333                                              int insn_idx, int prev_insn_idx,
1334                                              bool speculative)
1335 {
1336         struct bpf_verifier_state *cur = env->cur_state;
1337         struct bpf_verifier_stack_elem *elem;
1338         int err;
1339
1340         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1341         if (!elem)
1342                 goto err;
1343
1344         elem->insn_idx = insn_idx;
1345         elem->prev_insn_idx = prev_insn_idx;
1346         elem->next = env->head;
1347         elem->log_pos = env->log.len_used;
1348         env->head = elem;
1349         env->stack_size++;
1350         err = copy_verifier_state(&elem->st, cur);
1351         if (err)
1352                 goto err;
1353         elem->st.speculative |= speculative;
1354         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1355                 verbose(env, "The sequence of %d jumps is too complex.\n",
1356                         env->stack_size);
1357                 goto err;
1358         }
1359         if (elem->st.parent) {
1360                 ++elem->st.parent->branches;
1361                 /* WARN_ON(branches > 2) technically makes sense here,
1362                  * but
1363                  * 1. speculative states will bump 'branches' for non-branch
1364                  * instructions
1365                  * 2. is_state_visited() heuristics may decide not to create
1366                  * a new state for a sequence of branches and all such current
1367                  * and cloned states will be pointing to a single parent state
1368                  * which might have large 'branches' count.
1369                  */
1370         }
1371         return &elem->st;
1372 err:
1373         free_verifier_state(env->cur_state, true);
1374         env->cur_state = NULL;
1375         /* pop all elements and return */
1376         while (!pop_stack(env, NULL, NULL, false));
1377         return NULL;
1378 }
1379
1380 #define CALLER_SAVED_REGS 6
1381 static const int caller_saved[CALLER_SAVED_REGS] = {
1382         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1383 };
1384
1385 /* This helper doesn't clear reg->id */
1386 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1387 {
1388         reg->var_off = tnum_const(imm);
1389         reg->smin_value = (s64)imm;
1390         reg->smax_value = (s64)imm;
1391         reg->umin_value = imm;
1392         reg->umax_value = imm;
1393
1394         reg->s32_min_value = (s32)imm;
1395         reg->s32_max_value = (s32)imm;
1396         reg->u32_min_value = (u32)imm;
1397         reg->u32_max_value = (u32)imm;
1398 }
1399
1400 /* Mark the unknown part of a register (variable offset or scalar value) as
1401  * known to have the value @imm.
1402  */
1403 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1404 {
1405         /* Clear off and union(map_ptr, range) */
1406         memset(((u8 *)reg) + sizeof(reg->type), 0,
1407                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1408         reg->id = 0;
1409         reg->ref_obj_id = 0;
1410         ___mark_reg_known(reg, imm);
1411 }
1412
1413 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1414 {
1415         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1416         reg->s32_min_value = (s32)imm;
1417         reg->s32_max_value = (s32)imm;
1418         reg->u32_min_value = (u32)imm;
1419         reg->u32_max_value = (u32)imm;
1420 }
1421
1422 /* Mark the 'variable offset' part of a register as zero.  This should be
1423  * used only on registers holding a pointer type.
1424  */
1425 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1426 {
1427         __mark_reg_known(reg, 0);
1428 }
1429
1430 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1431 {
1432         __mark_reg_known(reg, 0);
1433         reg->type = SCALAR_VALUE;
1434 }
1435
1436 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1437                                 struct bpf_reg_state *regs, u32 regno)
1438 {
1439         if (WARN_ON(regno >= MAX_BPF_REG)) {
1440                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1441                 /* Something bad happened, let's kill all regs */
1442                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1443                         __mark_reg_not_init(env, regs + regno);
1444                 return;
1445         }
1446         __mark_reg_known_zero(regs + regno);
1447 }
1448
1449 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1450                               bool first_slot)
1451 {
1452         /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1453          * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1454          * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1455          */
1456         __mark_reg_known_zero(reg);
1457         reg->type = CONST_PTR_TO_DYNPTR;
1458         reg->dynptr.type = type;
1459         reg->dynptr.first_slot = first_slot;
1460 }
1461
1462 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1463 {
1464         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1465                 const struct bpf_map *map = reg->map_ptr;
1466
1467                 if (map->inner_map_meta) {
1468                         reg->type = CONST_PTR_TO_MAP;
1469                         reg->map_ptr = map->inner_map_meta;
1470                         /* transfer reg's id which is unique for every map_lookup_elem
1471                          * as UID of the inner map.
1472                          */
1473                         if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1474                                 reg->map_uid = reg->id;
1475                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1476                         reg->type = PTR_TO_XDP_SOCK;
1477                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1478                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1479                         reg->type = PTR_TO_SOCKET;
1480                 } else {
1481                         reg->type = PTR_TO_MAP_VALUE;
1482                 }
1483                 return;
1484         }
1485
1486         reg->type &= ~PTR_MAYBE_NULL;
1487 }
1488
1489 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1490 {
1491         return type_is_pkt_pointer(reg->type);
1492 }
1493
1494 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1495 {
1496         return reg_is_pkt_pointer(reg) ||
1497                reg->type == PTR_TO_PACKET_END;
1498 }
1499
1500 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1501 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1502                                     enum bpf_reg_type which)
1503 {
1504         /* The register can already have a range from prior markings.
1505          * This is fine as long as it hasn't been advanced from its
1506          * origin.
1507          */
1508         return reg->type == which &&
1509                reg->id == 0 &&
1510                reg->off == 0 &&
1511                tnum_equals_const(reg->var_off, 0);
1512 }
1513
1514 /* Reset the min/max bounds of a register */
1515 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1516 {
1517         reg->smin_value = S64_MIN;
1518         reg->smax_value = S64_MAX;
1519         reg->umin_value = 0;
1520         reg->umax_value = U64_MAX;
1521
1522         reg->s32_min_value = S32_MIN;
1523         reg->s32_max_value = S32_MAX;
1524         reg->u32_min_value = 0;
1525         reg->u32_max_value = U32_MAX;
1526 }
1527
1528 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1529 {
1530         reg->smin_value = S64_MIN;
1531         reg->smax_value = S64_MAX;
1532         reg->umin_value = 0;
1533         reg->umax_value = U64_MAX;
1534 }
1535
1536 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1537 {
1538         reg->s32_min_value = S32_MIN;
1539         reg->s32_max_value = S32_MAX;
1540         reg->u32_min_value = 0;
1541         reg->u32_max_value = U32_MAX;
1542 }
1543
1544 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1545 {
1546         struct tnum var32_off = tnum_subreg(reg->var_off);
1547
1548         /* min signed is max(sign bit) | min(other bits) */
1549         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1550                         var32_off.value | (var32_off.mask & S32_MIN));
1551         /* max signed is min(sign bit) | max(other bits) */
1552         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1553                         var32_off.value | (var32_off.mask & S32_MAX));
1554         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1555         reg->u32_max_value = min(reg->u32_max_value,
1556                                  (u32)(var32_off.value | var32_off.mask));
1557 }
1558
1559 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1560 {
1561         /* min signed is max(sign bit) | min(other bits) */
1562         reg->smin_value = max_t(s64, reg->smin_value,
1563                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1564         /* max signed is min(sign bit) | max(other bits) */
1565         reg->smax_value = min_t(s64, reg->smax_value,
1566                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1567         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1568         reg->umax_value = min(reg->umax_value,
1569                               reg->var_off.value | reg->var_off.mask);
1570 }
1571
1572 static void __update_reg_bounds(struct bpf_reg_state *reg)
1573 {
1574         __update_reg32_bounds(reg);
1575         __update_reg64_bounds(reg);
1576 }
1577
1578 /* Uses signed min/max values to inform unsigned, and vice-versa */
1579 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1580 {
1581         /* Learn sign from signed bounds.
1582          * If we cannot cross the sign boundary, then signed and unsigned bounds
1583          * are the same, so combine.  This works even in the negative case, e.g.
1584          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1585          */
1586         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1587                 reg->s32_min_value = reg->u32_min_value =
1588                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1589                 reg->s32_max_value = reg->u32_max_value =
1590                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1591                 return;
1592         }
1593         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1594          * boundary, so we must be careful.
1595          */
1596         if ((s32)reg->u32_max_value >= 0) {
1597                 /* Positive.  We can't learn anything from the smin, but smax
1598                  * is positive, hence safe.
1599                  */
1600                 reg->s32_min_value = reg->u32_min_value;
1601                 reg->s32_max_value = reg->u32_max_value =
1602                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1603         } else if ((s32)reg->u32_min_value < 0) {
1604                 /* Negative.  We can't learn anything from the smax, but smin
1605                  * is negative, hence safe.
1606                  */
1607                 reg->s32_min_value = reg->u32_min_value =
1608                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1609                 reg->s32_max_value = reg->u32_max_value;
1610         }
1611 }
1612
1613 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1614 {
1615         /* Learn sign from signed bounds.
1616          * If we cannot cross the sign boundary, then signed and unsigned bounds
1617          * are the same, so combine.  This works even in the negative case, e.g.
1618          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1619          */
1620         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1621                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1622                                                           reg->umin_value);
1623                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1624                                                           reg->umax_value);
1625                 return;
1626         }
1627         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1628          * boundary, so we must be careful.
1629          */
1630         if ((s64)reg->umax_value >= 0) {
1631                 /* Positive.  We can't learn anything from the smin, but smax
1632                  * is positive, hence safe.
1633                  */
1634                 reg->smin_value = reg->umin_value;
1635                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1636                                                           reg->umax_value);
1637         } else if ((s64)reg->umin_value < 0) {
1638                 /* Negative.  We can't learn anything from the smax, but smin
1639                  * is negative, hence safe.
1640                  */
1641                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1642                                                           reg->umin_value);
1643                 reg->smax_value = reg->umax_value;
1644         }
1645 }
1646
1647 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1648 {
1649         __reg32_deduce_bounds(reg);
1650         __reg64_deduce_bounds(reg);
1651 }
1652
1653 /* Attempts to improve var_off based on unsigned min/max information */
1654 static void __reg_bound_offset(struct bpf_reg_state *reg)
1655 {
1656         struct tnum var64_off = tnum_intersect(reg->var_off,
1657                                                tnum_range(reg->umin_value,
1658                                                           reg->umax_value));
1659         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1660                                                 tnum_range(reg->u32_min_value,
1661                                                            reg->u32_max_value));
1662
1663         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1664 }
1665
1666 static void reg_bounds_sync(struct bpf_reg_state *reg)
1667 {
1668         /* We might have learned new bounds from the var_off. */
1669         __update_reg_bounds(reg);
1670         /* We might have learned something about the sign bit. */
1671         __reg_deduce_bounds(reg);
1672         /* We might have learned some bits from the bounds. */
1673         __reg_bound_offset(reg);
1674         /* Intersecting with the old var_off might have improved our bounds
1675          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1676          * then new var_off is (0; 0x7f...fc) which improves our umax.
1677          */
1678         __update_reg_bounds(reg);
1679 }
1680
1681 static bool __reg32_bound_s64(s32 a)
1682 {
1683         return a >= 0 && a <= S32_MAX;
1684 }
1685
1686 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1687 {
1688         reg->umin_value = reg->u32_min_value;
1689         reg->umax_value = reg->u32_max_value;
1690
1691         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1692          * be positive otherwise set to worse case bounds and refine later
1693          * from tnum.
1694          */
1695         if (__reg32_bound_s64(reg->s32_min_value) &&
1696             __reg32_bound_s64(reg->s32_max_value)) {
1697                 reg->smin_value = reg->s32_min_value;
1698                 reg->smax_value = reg->s32_max_value;
1699         } else {
1700                 reg->smin_value = 0;
1701                 reg->smax_value = U32_MAX;
1702         }
1703 }
1704
1705 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1706 {
1707         /* special case when 64-bit register has upper 32-bit register
1708          * zeroed. Typically happens after zext or <<32, >>32 sequence
1709          * allowing us to use 32-bit bounds directly,
1710          */
1711         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1712                 __reg_assign_32_into_64(reg);
1713         } else {
1714                 /* Otherwise the best we can do is push lower 32bit known and
1715                  * unknown bits into register (var_off set from jmp logic)
1716                  * then learn as much as possible from the 64-bit tnum
1717                  * known and unknown bits. The previous smin/smax bounds are
1718                  * invalid here because of jmp32 compare so mark them unknown
1719                  * so they do not impact tnum bounds calculation.
1720                  */
1721                 __mark_reg64_unbounded(reg);
1722         }
1723         reg_bounds_sync(reg);
1724 }
1725
1726 static bool __reg64_bound_s32(s64 a)
1727 {
1728         return a >= S32_MIN && a <= S32_MAX;
1729 }
1730
1731 static bool __reg64_bound_u32(u64 a)
1732 {
1733         return a >= U32_MIN && a <= U32_MAX;
1734 }
1735
1736 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1737 {
1738         __mark_reg32_unbounded(reg);
1739         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1740                 reg->s32_min_value = (s32)reg->smin_value;
1741                 reg->s32_max_value = (s32)reg->smax_value;
1742         }
1743         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1744                 reg->u32_min_value = (u32)reg->umin_value;
1745                 reg->u32_max_value = (u32)reg->umax_value;
1746         }
1747         reg_bounds_sync(reg);
1748 }
1749
1750 /* Mark a register as having a completely unknown (scalar) value. */
1751 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1752                                struct bpf_reg_state *reg)
1753 {
1754         /*
1755          * Clear type, off, and union(map_ptr, range) and
1756          * padding between 'type' and union
1757          */
1758         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1759         reg->type = SCALAR_VALUE;
1760         reg->id = 0;
1761         reg->ref_obj_id = 0;
1762         reg->var_off = tnum_unknown;
1763         reg->frameno = 0;
1764         reg->precise = !env->bpf_capable;
1765         __mark_reg_unbounded(reg);
1766 }
1767
1768 static void mark_reg_unknown(struct bpf_verifier_env *env,
1769                              struct bpf_reg_state *regs, u32 regno)
1770 {
1771         if (WARN_ON(regno >= MAX_BPF_REG)) {
1772                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1773                 /* Something bad happened, let's kill all regs except FP */
1774                 for (regno = 0; regno < BPF_REG_FP; regno++)
1775                         __mark_reg_not_init(env, regs + regno);
1776                 return;
1777         }
1778         __mark_reg_unknown(env, regs + regno);
1779 }
1780
1781 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1782                                 struct bpf_reg_state *reg)
1783 {
1784         __mark_reg_unknown(env, reg);
1785         reg->type = NOT_INIT;
1786 }
1787
1788 static void mark_reg_not_init(struct bpf_verifier_env *env,
1789                               struct bpf_reg_state *regs, u32 regno)
1790 {
1791         if (WARN_ON(regno >= MAX_BPF_REG)) {
1792                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1793                 /* Something bad happened, let's kill all regs except FP */
1794                 for (regno = 0; regno < BPF_REG_FP; regno++)
1795                         __mark_reg_not_init(env, regs + regno);
1796                 return;
1797         }
1798         __mark_reg_not_init(env, regs + regno);
1799 }
1800
1801 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1802                             struct bpf_reg_state *regs, u32 regno,
1803                             enum bpf_reg_type reg_type,
1804                             struct btf *btf, u32 btf_id,
1805                             enum bpf_type_flag flag)
1806 {
1807         if (reg_type == SCALAR_VALUE) {
1808                 mark_reg_unknown(env, regs, regno);
1809                 return;
1810         }
1811         mark_reg_known_zero(env, regs, regno);
1812         regs[regno].type = PTR_TO_BTF_ID | flag;
1813         regs[regno].btf = btf;
1814         regs[regno].btf_id = btf_id;
1815 }
1816
1817 #define DEF_NOT_SUBREG  (0)
1818 static void init_reg_state(struct bpf_verifier_env *env,
1819                            struct bpf_func_state *state)
1820 {
1821         struct bpf_reg_state *regs = state->regs;
1822         int i;
1823
1824         for (i = 0; i < MAX_BPF_REG; i++) {
1825                 mark_reg_not_init(env, regs, i);
1826                 regs[i].live = REG_LIVE_NONE;
1827                 regs[i].parent = NULL;
1828                 regs[i].subreg_def = DEF_NOT_SUBREG;
1829         }
1830
1831         /* frame pointer */
1832         regs[BPF_REG_FP].type = PTR_TO_STACK;
1833         mark_reg_known_zero(env, regs, BPF_REG_FP);
1834         regs[BPF_REG_FP].frameno = state->frameno;
1835 }
1836
1837 #define BPF_MAIN_FUNC (-1)
1838 static void init_func_state(struct bpf_verifier_env *env,
1839                             struct bpf_func_state *state,
1840                             int callsite, int frameno, int subprogno)
1841 {
1842         state->callsite = callsite;
1843         state->frameno = frameno;
1844         state->subprogno = subprogno;
1845         state->callback_ret_range = tnum_range(0, 0);
1846         init_reg_state(env, state);
1847         mark_verifier_state_scratched(env);
1848 }
1849
1850 /* Similar to push_stack(), but for async callbacks */
1851 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1852                                                 int insn_idx, int prev_insn_idx,
1853                                                 int subprog)
1854 {
1855         struct bpf_verifier_stack_elem *elem;
1856         struct bpf_func_state *frame;
1857
1858         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1859         if (!elem)
1860                 goto err;
1861
1862         elem->insn_idx = insn_idx;
1863         elem->prev_insn_idx = prev_insn_idx;
1864         elem->next = env->head;
1865         elem->log_pos = env->log.len_used;
1866         env->head = elem;
1867         env->stack_size++;
1868         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1869                 verbose(env,
1870                         "The sequence of %d jumps is too complex for async cb.\n",
1871                         env->stack_size);
1872                 goto err;
1873         }
1874         /* Unlike push_stack() do not copy_verifier_state().
1875          * The caller state doesn't matter.
1876          * This is async callback. It starts in a fresh stack.
1877          * Initialize it similar to do_check_common().
1878          */
1879         elem->st.branches = 1;
1880         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1881         if (!frame)
1882                 goto err;
1883         init_func_state(env, frame,
1884                         BPF_MAIN_FUNC /* callsite */,
1885                         0 /* frameno within this callchain */,
1886                         subprog /* subprog number within this prog */);
1887         elem->st.frame[0] = frame;
1888         return &elem->st;
1889 err:
1890         free_verifier_state(env->cur_state, true);
1891         env->cur_state = NULL;
1892         /* pop all elements and return */
1893         while (!pop_stack(env, NULL, NULL, false));
1894         return NULL;
1895 }
1896
1897
1898 enum reg_arg_type {
1899         SRC_OP,         /* register is used as source operand */
1900         DST_OP,         /* register is used as destination operand */
1901         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1902 };
1903
1904 static int cmp_subprogs(const void *a, const void *b)
1905 {
1906         return ((struct bpf_subprog_info *)a)->start -
1907                ((struct bpf_subprog_info *)b)->start;
1908 }
1909
1910 static int find_subprog(struct bpf_verifier_env *env, int off)
1911 {
1912         struct bpf_subprog_info *p;
1913
1914         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1915                     sizeof(env->subprog_info[0]), cmp_subprogs);
1916         if (!p)
1917                 return -ENOENT;
1918         return p - env->subprog_info;
1919
1920 }
1921
1922 static int add_subprog(struct bpf_verifier_env *env, int off)
1923 {
1924         int insn_cnt = env->prog->len;
1925         int ret;
1926
1927         if (off >= insn_cnt || off < 0) {
1928                 verbose(env, "call to invalid destination\n");
1929                 return -EINVAL;
1930         }
1931         ret = find_subprog(env, off);
1932         if (ret >= 0)
1933                 return ret;
1934         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1935                 verbose(env, "too many subprograms\n");
1936                 return -E2BIG;
1937         }
1938         /* determine subprog starts. The end is one before the next starts */
1939         env->subprog_info[env->subprog_cnt++].start = off;
1940         sort(env->subprog_info, env->subprog_cnt,
1941              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1942         return env->subprog_cnt - 1;
1943 }
1944
1945 #define MAX_KFUNC_DESCS 256
1946 #define MAX_KFUNC_BTFS  256
1947
1948 struct bpf_kfunc_desc {
1949         struct btf_func_model func_model;
1950         u32 func_id;
1951         s32 imm;
1952         u16 offset;
1953 };
1954
1955 struct bpf_kfunc_btf {
1956         struct btf *btf;
1957         struct module *module;
1958         u16 offset;
1959 };
1960
1961 struct bpf_kfunc_desc_tab {
1962         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1963         u32 nr_descs;
1964 };
1965
1966 struct bpf_kfunc_btf_tab {
1967         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1968         u32 nr_descs;
1969 };
1970
1971 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1972 {
1973         const struct bpf_kfunc_desc *d0 = a;
1974         const struct bpf_kfunc_desc *d1 = b;
1975
1976         /* func_id is not greater than BTF_MAX_TYPE */
1977         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1978 }
1979
1980 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1981 {
1982         const struct bpf_kfunc_btf *d0 = a;
1983         const struct bpf_kfunc_btf *d1 = b;
1984
1985         return d0->offset - d1->offset;
1986 }
1987
1988 static const struct bpf_kfunc_desc *
1989 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1990 {
1991         struct bpf_kfunc_desc desc = {
1992                 .func_id = func_id,
1993                 .offset = offset,
1994         };
1995         struct bpf_kfunc_desc_tab *tab;
1996
1997         tab = prog->aux->kfunc_tab;
1998         return bsearch(&desc, tab->descs, tab->nr_descs,
1999                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2000 }
2001
2002 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2003                                          s16 offset)
2004 {
2005         struct bpf_kfunc_btf kf_btf = { .offset = offset };
2006         struct bpf_kfunc_btf_tab *tab;
2007         struct bpf_kfunc_btf *b;
2008         struct module *mod;
2009         struct btf *btf;
2010         int btf_fd;
2011
2012         tab = env->prog->aux->kfunc_btf_tab;
2013         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2014                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2015         if (!b) {
2016                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2017                         verbose(env, "too many different module BTFs\n");
2018                         return ERR_PTR(-E2BIG);
2019                 }
2020
2021                 if (bpfptr_is_null(env->fd_array)) {
2022                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2023                         return ERR_PTR(-EPROTO);
2024                 }
2025
2026                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2027                                             offset * sizeof(btf_fd),
2028                                             sizeof(btf_fd)))
2029                         return ERR_PTR(-EFAULT);
2030
2031                 btf = btf_get_by_fd(btf_fd);
2032                 if (IS_ERR(btf)) {
2033                         verbose(env, "invalid module BTF fd specified\n");
2034                         return btf;
2035                 }
2036
2037                 if (!btf_is_module(btf)) {
2038                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
2039                         btf_put(btf);
2040                         return ERR_PTR(-EINVAL);
2041                 }
2042
2043                 mod = btf_try_get_module(btf);
2044                 if (!mod) {
2045                         btf_put(btf);
2046                         return ERR_PTR(-ENXIO);
2047                 }
2048
2049                 b = &tab->descs[tab->nr_descs++];
2050                 b->btf = btf;
2051                 b->module = mod;
2052                 b->offset = offset;
2053
2054                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2055                      kfunc_btf_cmp_by_off, NULL);
2056         }
2057         return b->btf;
2058 }
2059
2060 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2061 {
2062         if (!tab)
2063                 return;
2064
2065         while (tab->nr_descs--) {
2066                 module_put(tab->descs[tab->nr_descs].module);
2067                 btf_put(tab->descs[tab->nr_descs].btf);
2068         }
2069         kfree(tab);
2070 }
2071
2072 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2073 {
2074         if (offset) {
2075                 if (offset < 0) {
2076                         /* In the future, this can be allowed to increase limit
2077                          * of fd index into fd_array, interpreted as u16.
2078                          */
2079                         verbose(env, "negative offset disallowed for kernel module function call\n");
2080                         return ERR_PTR(-EINVAL);
2081                 }
2082
2083                 return __find_kfunc_desc_btf(env, offset);
2084         }
2085         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2086 }
2087
2088 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2089 {
2090         const struct btf_type *func, *func_proto;
2091         struct bpf_kfunc_btf_tab *btf_tab;
2092         struct bpf_kfunc_desc_tab *tab;
2093         struct bpf_prog_aux *prog_aux;
2094         struct bpf_kfunc_desc *desc;
2095         const char *func_name;
2096         struct btf *desc_btf;
2097         unsigned long call_imm;
2098         unsigned long addr;
2099         int err;
2100
2101         prog_aux = env->prog->aux;
2102         tab = prog_aux->kfunc_tab;
2103         btf_tab = prog_aux->kfunc_btf_tab;
2104         if (!tab) {
2105                 if (!btf_vmlinux) {
2106                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2107                         return -ENOTSUPP;
2108                 }
2109
2110                 if (!env->prog->jit_requested) {
2111                         verbose(env, "JIT is required for calling kernel function\n");
2112                         return -ENOTSUPP;
2113                 }
2114
2115                 if (!bpf_jit_supports_kfunc_call()) {
2116                         verbose(env, "JIT does not support calling kernel function\n");
2117                         return -ENOTSUPP;
2118                 }
2119
2120                 if (!env->prog->gpl_compatible) {
2121                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2122                         return -EINVAL;
2123                 }
2124
2125                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2126                 if (!tab)
2127                         return -ENOMEM;
2128                 prog_aux->kfunc_tab = tab;
2129         }
2130
2131         /* func_id == 0 is always invalid, but instead of returning an error, be
2132          * conservative and wait until the code elimination pass before returning
2133          * error, so that invalid calls that get pruned out can be in BPF programs
2134          * loaded from userspace.  It is also required that offset be untouched
2135          * for such calls.
2136          */
2137         if (!func_id && !offset)
2138                 return 0;
2139
2140         if (!btf_tab && offset) {
2141                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2142                 if (!btf_tab)
2143                         return -ENOMEM;
2144                 prog_aux->kfunc_btf_tab = btf_tab;
2145         }
2146
2147         desc_btf = find_kfunc_desc_btf(env, offset);
2148         if (IS_ERR(desc_btf)) {
2149                 verbose(env, "failed to find BTF for kernel function\n");
2150                 return PTR_ERR(desc_btf);
2151         }
2152
2153         if (find_kfunc_desc(env->prog, func_id, offset))
2154                 return 0;
2155
2156         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2157                 verbose(env, "too many different kernel function calls\n");
2158                 return -E2BIG;
2159         }
2160
2161         func = btf_type_by_id(desc_btf, func_id);
2162         if (!func || !btf_type_is_func(func)) {
2163                 verbose(env, "kernel btf_id %u is not a function\n",
2164                         func_id);
2165                 return -EINVAL;
2166         }
2167         func_proto = btf_type_by_id(desc_btf, func->type);
2168         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2169                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2170                         func_id);
2171                 return -EINVAL;
2172         }
2173
2174         func_name = btf_name_by_offset(desc_btf, func->name_off);
2175         addr = kallsyms_lookup_name(func_name);
2176         if (!addr) {
2177                 verbose(env, "cannot find address for kernel function %s\n",
2178                         func_name);
2179                 return -EINVAL;
2180         }
2181
2182         call_imm = BPF_CALL_IMM(addr);
2183         /* Check whether or not the relative offset overflows desc->imm */
2184         if ((unsigned long)(s32)call_imm != call_imm) {
2185                 verbose(env, "address of kernel function %s is out of range\n",
2186                         func_name);
2187                 return -EINVAL;
2188         }
2189
2190         desc = &tab->descs[tab->nr_descs++];
2191         desc->func_id = func_id;
2192         desc->imm = call_imm;
2193         desc->offset = offset;
2194         err = btf_distill_func_proto(&env->log, desc_btf,
2195                                      func_proto, func_name,
2196                                      &desc->func_model);
2197         if (!err)
2198                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2199                      kfunc_desc_cmp_by_id_off, NULL);
2200         return err;
2201 }
2202
2203 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2204 {
2205         const struct bpf_kfunc_desc *d0 = a;
2206         const struct bpf_kfunc_desc *d1 = b;
2207
2208         if (d0->imm > d1->imm)
2209                 return 1;
2210         else if (d0->imm < d1->imm)
2211                 return -1;
2212         return 0;
2213 }
2214
2215 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2216 {
2217         struct bpf_kfunc_desc_tab *tab;
2218
2219         tab = prog->aux->kfunc_tab;
2220         if (!tab)
2221                 return;
2222
2223         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2224              kfunc_desc_cmp_by_imm, NULL);
2225 }
2226
2227 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2228 {
2229         return !!prog->aux->kfunc_tab;
2230 }
2231
2232 const struct btf_func_model *
2233 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2234                          const struct bpf_insn *insn)
2235 {
2236         const struct bpf_kfunc_desc desc = {
2237                 .imm = insn->imm,
2238         };
2239         const struct bpf_kfunc_desc *res;
2240         struct bpf_kfunc_desc_tab *tab;
2241
2242         tab = prog->aux->kfunc_tab;
2243         res = bsearch(&desc, tab->descs, tab->nr_descs,
2244                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2245
2246         return res ? &res->func_model : NULL;
2247 }
2248
2249 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2250 {
2251         struct bpf_subprog_info *subprog = env->subprog_info;
2252         struct bpf_insn *insn = env->prog->insnsi;
2253         int i, ret, insn_cnt = env->prog->len;
2254
2255         /* Add entry function. */
2256         ret = add_subprog(env, 0);
2257         if (ret)
2258                 return ret;
2259
2260         for (i = 0; i < insn_cnt; i++, insn++) {
2261                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2262                     !bpf_pseudo_kfunc_call(insn))
2263                         continue;
2264
2265                 if (!env->bpf_capable) {
2266                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2267                         return -EPERM;
2268                 }
2269
2270                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2271                         ret = add_subprog(env, i + insn->imm + 1);
2272                 else
2273                         ret = add_kfunc_call(env, insn->imm, insn->off);
2274
2275                 if (ret < 0)
2276                         return ret;
2277         }
2278
2279         /* Add a fake 'exit' subprog which could simplify subprog iteration
2280          * logic. 'subprog_cnt' should not be increased.
2281          */
2282         subprog[env->subprog_cnt].start = insn_cnt;
2283
2284         if (env->log.level & BPF_LOG_LEVEL2)
2285                 for (i = 0; i < env->subprog_cnt; i++)
2286                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2287
2288         return 0;
2289 }
2290
2291 static int check_subprogs(struct bpf_verifier_env *env)
2292 {
2293         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2294         struct bpf_subprog_info *subprog = env->subprog_info;
2295         struct bpf_insn *insn = env->prog->insnsi;
2296         int insn_cnt = env->prog->len;
2297
2298         /* now check that all jumps are within the same subprog */
2299         subprog_start = subprog[cur_subprog].start;
2300         subprog_end = subprog[cur_subprog + 1].start;
2301         for (i = 0; i < insn_cnt; i++) {
2302                 u8 code = insn[i].code;
2303
2304                 if (code == (BPF_JMP | BPF_CALL) &&
2305                     insn[i].imm == BPF_FUNC_tail_call &&
2306                     insn[i].src_reg != BPF_PSEUDO_CALL)
2307                         subprog[cur_subprog].has_tail_call = true;
2308                 if (BPF_CLASS(code) == BPF_LD &&
2309                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2310                         subprog[cur_subprog].has_ld_abs = true;
2311                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2312                         goto next;
2313                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2314                         goto next;
2315                 off = i + insn[i].off + 1;
2316                 if (off < subprog_start || off >= subprog_end) {
2317                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2318                         return -EINVAL;
2319                 }
2320 next:
2321                 if (i == subprog_end - 1) {
2322                         /* to avoid fall-through from one subprog into another
2323                          * the last insn of the subprog should be either exit
2324                          * or unconditional jump back
2325                          */
2326                         if (code != (BPF_JMP | BPF_EXIT) &&
2327                             code != (BPF_JMP | BPF_JA)) {
2328                                 verbose(env, "last insn is not an exit or jmp\n");
2329                                 return -EINVAL;
2330                         }
2331                         subprog_start = subprog_end;
2332                         cur_subprog++;
2333                         if (cur_subprog < env->subprog_cnt)
2334                                 subprog_end = subprog[cur_subprog + 1].start;
2335                 }
2336         }
2337         return 0;
2338 }
2339
2340 /* Parentage chain of this register (or stack slot) should take care of all
2341  * issues like callee-saved registers, stack slot allocation time, etc.
2342  */
2343 static int mark_reg_read(struct bpf_verifier_env *env,
2344                          const struct bpf_reg_state *state,
2345                          struct bpf_reg_state *parent, u8 flag)
2346 {
2347         bool writes = parent == state->parent; /* Observe write marks */
2348         int cnt = 0;
2349
2350         while (parent) {
2351                 /* if read wasn't screened by an earlier write ... */
2352                 if (writes && state->live & REG_LIVE_WRITTEN)
2353                         break;
2354                 if (parent->live & REG_LIVE_DONE) {
2355                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2356                                 reg_type_str(env, parent->type),
2357                                 parent->var_off.value, parent->off);
2358                         return -EFAULT;
2359                 }
2360                 /* The first condition is more likely to be true than the
2361                  * second, checked it first.
2362                  */
2363                 if ((parent->live & REG_LIVE_READ) == flag ||
2364                     parent->live & REG_LIVE_READ64)
2365                         /* The parentage chain never changes and
2366                          * this parent was already marked as LIVE_READ.
2367                          * There is no need to keep walking the chain again and
2368                          * keep re-marking all parents as LIVE_READ.
2369                          * This case happens when the same register is read
2370                          * multiple times without writes into it in-between.
2371                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2372                          * then no need to set the weak REG_LIVE_READ32.
2373                          */
2374                         break;
2375                 /* ... then we depend on parent's value */
2376                 parent->live |= flag;
2377                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2378                 if (flag == REG_LIVE_READ64)
2379                         parent->live &= ~REG_LIVE_READ32;
2380                 state = parent;
2381                 parent = state->parent;
2382                 writes = true;
2383                 cnt++;
2384         }
2385
2386         if (env->longest_mark_read_walk < cnt)
2387                 env->longest_mark_read_walk = cnt;
2388         return 0;
2389 }
2390
2391 /* This function is supposed to be used by the following 32-bit optimization
2392  * code only. It returns TRUE if the source or destination register operates
2393  * on 64-bit, otherwise return FALSE.
2394  */
2395 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2396                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2397 {
2398         u8 code, class, op;
2399
2400         code = insn->code;
2401         class = BPF_CLASS(code);
2402         op = BPF_OP(code);
2403         if (class == BPF_JMP) {
2404                 /* BPF_EXIT for "main" will reach here. Return TRUE
2405                  * conservatively.
2406                  */
2407                 if (op == BPF_EXIT)
2408                         return true;
2409                 if (op == BPF_CALL) {
2410                         /* BPF to BPF call will reach here because of marking
2411                          * caller saved clobber with DST_OP_NO_MARK for which we
2412                          * don't care the register def because they are anyway
2413                          * marked as NOT_INIT already.
2414                          */
2415                         if (insn->src_reg == BPF_PSEUDO_CALL)
2416                                 return false;
2417                         /* Helper call will reach here because of arg type
2418                          * check, conservatively return TRUE.
2419                          */
2420                         if (t == SRC_OP)
2421                                 return true;
2422
2423                         return false;
2424                 }
2425         }
2426
2427         if (class == BPF_ALU64 || class == BPF_JMP ||
2428             /* BPF_END always use BPF_ALU class. */
2429             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2430                 return true;
2431
2432         if (class == BPF_ALU || class == BPF_JMP32)
2433                 return false;
2434
2435         if (class == BPF_LDX) {
2436                 if (t != SRC_OP)
2437                         return BPF_SIZE(code) == BPF_DW;
2438                 /* LDX source must be ptr. */
2439                 return true;
2440         }
2441
2442         if (class == BPF_STX) {
2443                 /* BPF_STX (including atomic variants) has multiple source
2444                  * operands, one of which is a ptr. Check whether the caller is
2445                  * asking about it.
2446                  */
2447                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2448                         return true;
2449                 return BPF_SIZE(code) == BPF_DW;
2450         }
2451
2452         if (class == BPF_LD) {
2453                 u8 mode = BPF_MODE(code);
2454
2455                 /* LD_IMM64 */
2456                 if (mode == BPF_IMM)
2457                         return true;
2458
2459                 /* Both LD_IND and LD_ABS return 32-bit data. */
2460                 if (t != SRC_OP)
2461                         return  false;
2462
2463                 /* Implicit ctx ptr. */
2464                 if (regno == BPF_REG_6)
2465                         return true;
2466
2467                 /* Explicit source could be any width. */
2468                 return true;
2469         }
2470
2471         if (class == BPF_ST)
2472                 /* The only source register for BPF_ST is a ptr. */
2473                 return true;
2474
2475         /* Conservatively return true at default. */
2476         return true;
2477 }
2478
2479 /* Return the regno defined by the insn, or -1. */
2480 static int insn_def_regno(const struct bpf_insn *insn)
2481 {
2482         switch (BPF_CLASS(insn->code)) {
2483         case BPF_JMP:
2484         case BPF_JMP32:
2485         case BPF_ST:
2486                 return -1;
2487         case BPF_STX:
2488                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2489                     (insn->imm & BPF_FETCH)) {
2490                         if (insn->imm == BPF_CMPXCHG)
2491                                 return BPF_REG_0;
2492                         else
2493                                 return insn->src_reg;
2494                 } else {
2495                         return -1;
2496                 }
2497         default:
2498                 return insn->dst_reg;
2499         }
2500 }
2501
2502 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2503 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2504 {
2505         int dst_reg = insn_def_regno(insn);
2506
2507         if (dst_reg == -1)
2508                 return false;
2509
2510         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2511 }
2512
2513 static void mark_insn_zext(struct bpf_verifier_env *env,
2514                            struct bpf_reg_state *reg)
2515 {
2516         s32 def_idx = reg->subreg_def;
2517
2518         if (def_idx == DEF_NOT_SUBREG)
2519                 return;
2520
2521         env->insn_aux_data[def_idx - 1].zext_dst = true;
2522         /* The dst will be zero extended, so won't be sub-register anymore. */
2523         reg->subreg_def = DEF_NOT_SUBREG;
2524 }
2525
2526 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2527                          enum reg_arg_type t)
2528 {
2529         struct bpf_verifier_state *vstate = env->cur_state;
2530         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2531         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2532         struct bpf_reg_state *reg, *regs = state->regs;
2533         bool rw64;
2534
2535         if (regno >= MAX_BPF_REG) {
2536                 verbose(env, "R%d is invalid\n", regno);
2537                 return -EINVAL;
2538         }
2539
2540         mark_reg_scratched(env, regno);
2541
2542         reg = &regs[regno];
2543         rw64 = is_reg64(env, insn, regno, reg, t);
2544         if (t == SRC_OP) {
2545                 /* check whether register used as source operand can be read */
2546                 if (reg->type == NOT_INIT) {
2547                         verbose(env, "R%d !read_ok\n", regno);
2548                         return -EACCES;
2549                 }
2550                 /* We don't need to worry about FP liveness because it's read-only */
2551                 if (regno == BPF_REG_FP)
2552                         return 0;
2553
2554                 if (rw64)
2555                         mark_insn_zext(env, reg);
2556
2557                 return mark_reg_read(env, reg, reg->parent,
2558                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2559         } else {
2560                 /* check whether register used as dest operand can be written to */
2561                 if (regno == BPF_REG_FP) {
2562                         verbose(env, "frame pointer is read only\n");
2563                         return -EACCES;
2564                 }
2565                 reg->live |= REG_LIVE_WRITTEN;
2566                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2567                 if (t == DST_OP)
2568                         mark_reg_unknown(env, regs, regno);
2569         }
2570         return 0;
2571 }
2572
2573 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
2574 {
2575         env->insn_aux_data[idx].jmp_point = true;
2576 }
2577
2578 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
2579 {
2580         return env->insn_aux_data[insn_idx].jmp_point;
2581 }
2582
2583 /* for any branch, call, exit record the history of jmps in the given state */
2584 static int push_jmp_history(struct bpf_verifier_env *env,
2585                             struct bpf_verifier_state *cur)
2586 {
2587         u32 cnt = cur->jmp_history_cnt;
2588         struct bpf_idx_pair *p;
2589         size_t alloc_size;
2590
2591         if (!is_jmp_point(env, env->insn_idx))
2592                 return 0;
2593
2594         cnt++;
2595         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2596         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2597         if (!p)
2598                 return -ENOMEM;
2599         p[cnt - 1].idx = env->insn_idx;
2600         p[cnt - 1].prev_idx = env->prev_insn_idx;
2601         cur->jmp_history = p;
2602         cur->jmp_history_cnt = cnt;
2603         return 0;
2604 }
2605
2606 /* Backtrack one insn at a time. If idx is not at the top of recorded
2607  * history then previous instruction came from straight line execution.
2608  */
2609 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2610                              u32 *history)
2611 {
2612         u32 cnt = *history;
2613
2614         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2615                 i = st->jmp_history[cnt - 1].prev_idx;
2616                 (*history)--;
2617         } else {
2618                 i--;
2619         }
2620         return i;
2621 }
2622
2623 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2624 {
2625         const struct btf_type *func;
2626         struct btf *desc_btf;
2627
2628         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2629                 return NULL;
2630
2631         desc_btf = find_kfunc_desc_btf(data, insn->off);
2632         if (IS_ERR(desc_btf))
2633                 return "<error>";
2634
2635         func = btf_type_by_id(desc_btf, insn->imm);
2636         return btf_name_by_offset(desc_btf, func->name_off);
2637 }
2638
2639 /* For given verifier state backtrack_insn() is called from the last insn to
2640  * the first insn. Its purpose is to compute a bitmask of registers and
2641  * stack slots that needs precision in the parent verifier state.
2642  */
2643 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2644                           u32 *reg_mask, u64 *stack_mask)
2645 {
2646         const struct bpf_insn_cbs cbs = {
2647                 .cb_call        = disasm_kfunc_name,
2648                 .cb_print       = verbose,
2649                 .private_data   = env,
2650         };
2651         struct bpf_insn *insn = env->prog->insnsi + idx;
2652         u8 class = BPF_CLASS(insn->code);
2653         u8 opcode = BPF_OP(insn->code);
2654         u8 mode = BPF_MODE(insn->code);
2655         u32 dreg = 1u << insn->dst_reg;
2656         u32 sreg = 1u << insn->src_reg;
2657         u32 spi;
2658
2659         if (insn->code == 0)
2660                 return 0;
2661         if (env->log.level & BPF_LOG_LEVEL2) {
2662                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2663                 verbose(env, "%d: ", idx);
2664                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2665         }
2666
2667         if (class == BPF_ALU || class == BPF_ALU64) {
2668                 if (!(*reg_mask & dreg))
2669                         return 0;
2670                 if (opcode == BPF_MOV) {
2671                         if (BPF_SRC(insn->code) == BPF_X) {
2672                                 /* dreg = sreg
2673                                  * dreg needs precision after this insn
2674                                  * sreg needs precision before this insn
2675                                  */
2676                                 *reg_mask &= ~dreg;
2677                                 *reg_mask |= sreg;
2678                         } else {
2679                                 /* dreg = K
2680                                  * dreg needs precision after this insn.
2681                                  * Corresponding register is already marked
2682                                  * as precise=true in this verifier state.
2683                                  * No further markings in parent are necessary
2684                                  */
2685                                 *reg_mask &= ~dreg;
2686                         }
2687                 } else {
2688                         if (BPF_SRC(insn->code) == BPF_X) {
2689                                 /* dreg += sreg
2690                                  * both dreg and sreg need precision
2691                                  * before this insn
2692                                  */
2693                                 *reg_mask |= sreg;
2694                         } /* else dreg += K
2695                            * dreg still needs precision before this insn
2696                            */
2697                 }
2698         } else if (class == BPF_LDX) {
2699                 if (!(*reg_mask & dreg))
2700                         return 0;
2701                 *reg_mask &= ~dreg;
2702
2703                 /* scalars can only be spilled into stack w/o losing precision.
2704                  * Load from any other memory can be zero extended.
2705                  * The desire to keep that precision is already indicated
2706                  * by 'precise' mark in corresponding register of this state.
2707                  * No further tracking necessary.
2708                  */
2709                 if (insn->src_reg != BPF_REG_FP)
2710                         return 0;
2711
2712                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2713                  * that [fp - off] slot contains scalar that needs to be
2714                  * tracked with precision
2715                  */
2716                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2717                 if (spi >= 64) {
2718                         verbose(env, "BUG spi %d\n", spi);
2719                         WARN_ONCE(1, "verifier backtracking bug");
2720                         return -EFAULT;
2721                 }
2722                 *stack_mask |= 1ull << spi;
2723         } else if (class == BPF_STX || class == BPF_ST) {
2724                 if (*reg_mask & dreg)
2725                         /* stx & st shouldn't be using _scalar_ dst_reg
2726                          * to access memory. It means backtracking
2727                          * encountered a case of pointer subtraction.
2728                          */
2729                         return -ENOTSUPP;
2730                 /* scalars can only be spilled into stack */
2731                 if (insn->dst_reg != BPF_REG_FP)
2732                         return 0;
2733                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2734                 if (spi >= 64) {
2735                         verbose(env, "BUG spi %d\n", spi);
2736                         WARN_ONCE(1, "verifier backtracking bug");
2737                         return -EFAULT;
2738                 }
2739                 if (!(*stack_mask & (1ull << spi)))
2740                         return 0;
2741                 *stack_mask &= ~(1ull << spi);
2742                 if (class == BPF_STX)
2743                         *reg_mask |= sreg;
2744         } else if (class == BPF_JMP || class == BPF_JMP32) {
2745                 if (opcode == BPF_CALL) {
2746                         if (insn->src_reg == BPF_PSEUDO_CALL)
2747                                 return -ENOTSUPP;
2748                         /* BPF helpers that invoke callback subprogs are
2749                          * equivalent to BPF_PSEUDO_CALL above
2750                          */
2751                         if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2752                                 return -ENOTSUPP;
2753                         /* regular helper call sets R0 */
2754                         *reg_mask &= ~1;
2755                         if (*reg_mask & 0x3f) {
2756                                 /* if backtracing was looking for registers R1-R5
2757                                  * they should have been found already.
2758                                  */
2759                                 verbose(env, "BUG regs %x\n", *reg_mask);
2760                                 WARN_ONCE(1, "verifier backtracking bug");
2761                                 return -EFAULT;
2762                         }
2763                 } else if (opcode == BPF_EXIT) {
2764                         return -ENOTSUPP;
2765                 }
2766         } else if (class == BPF_LD) {
2767                 if (!(*reg_mask & dreg))
2768                         return 0;
2769                 *reg_mask &= ~dreg;
2770                 /* It's ld_imm64 or ld_abs or ld_ind.
2771                  * For ld_imm64 no further tracking of precision
2772                  * into parent is necessary
2773                  */
2774                 if (mode == BPF_IND || mode == BPF_ABS)
2775                         /* to be analyzed */
2776                         return -ENOTSUPP;
2777         }
2778         return 0;
2779 }
2780
2781 /* the scalar precision tracking algorithm:
2782  * . at the start all registers have precise=false.
2783  * . scalar ranges are tracked as normal through alu and jmp insns.
2784  * . once precise value of the scalar register is used in:
2785  *   .  ptr + scalar alu
2786  *   . if (scalar cond K|scalar)
2787  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2788  *   backtrack through the verifier states and mark all registers and
2789  *   stack slots with spilled constants that these scalar regisers
2790  *   should be precise.
2791  * . during state pruning two registers (or spilled stack slots)
2792  *   are equivalent if both are not precise.
2793  *
2794  * Note the verifier cannot simply walk register parentage chain,
2795  * since many different registers and stack slots could have been
2796  * used to compute single precise scalar.
2797  *
2798  * The approach of starting with precise=true for all registers and then
2799  * backtrack to mark a register as not precise when the verifier detects
2800  * that program doesn't care about specific value (e.g., when helper
2801  * takes register as ARG_ANYTHING parameter) is not safe.
2802  *
2803  * It's ok to walk single parentage chain of the verifier states.
2804  * It's possible that this backtracking will go all the way till 1st insn.
2805  * All other branches will be explored for needing precision later.
2806  *
2807  * The backtracking needs to deal with cases like:
2808  *   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)
2809  * r9 -= r8
2810  * r5 = r9
2811  * if r5 > 0x79f goto pc+7
2812  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2813  * r5 += 1
2814  * ...
2815  * call bpf_perf_event_output#25
2816  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2817  *
2818  * and this case:
2819  * r6 = 1
2820  * call foo // uses callee's r6 inside to compute r0
2821  * r0 += r6
2822  * if r0 == 0 goto
2823  *
2824  * to track above reg_mask/stack_mask needs to be independent for each frame.
2825  *
2826  * Also if parent's curframe > frame where backtracking started,
2827  * the verifier need to mark registers in both frames, otherwise callees
2828  * may incorrectly prune callers. This is similar to
2829  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2830  *
2831  * For now backtracking falls back into conservative marking.
2832  */
2833 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2834                                      struct bpf_verifier_state *st)
2835 {
2836         struct bpf_func_state *func;
2837         struct bpf_reg_state *reg;
2838         int i, j;
2839
2840         /* big hammer: mark all scalars precise in this path.
2841          * pop_stack may still get !precise scalars.
2842          * We also skip current state and go straight to first parent state,
2843          * because precision markings in current non-checkpointed state are
2844          * not needed. See why in the comment in __mark_chain_precision below.
2845          */
2846         for (st = st->parent; st; st = st->parent) {
2847                 for (i = 0; i <= st->curframe; i++) {
2848                         func = st->frame[i];
2849                         for (j = 0; j < BPF_REG_FP; j++) {
2850                                 reg = &func->regs[j];
2851                                 if (reg->type != SCALAR_VALUE)
2852                                         continue;
2853                                 reg->precise = true;
2854                         }
2855                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2856                                 if (!is_spilled_reg(&func->stack[j]))
2857                                         continue;
2858                                 reg = &func->stack[j].spilled_ptr;
2859                                 if (reg->type != SCALAR_VALUE)
2860                                         continue;
2861                                 reg->precise = true;
2862                         }
2863                 }
2864         }
2865 }
2866
2867 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2868 {
2869         struct bpf_func_state *func;
2870         struct bpf_reg_state *reg;
2871         int i, j;
2872
2873         for (i = 0; i <= st->curframe; i++) {
2874                 func = st->frame[i];
2875                 for (j = 0; j < BPF_REG_FP; j++) {
2876                         reg = &func->regs[j];
2877                         if (reg->type != SCALAR_VALUE)
2878                                 continue;
2879                         reg->precise = false;
2880                 }
2881                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2882                         if (!is_spilled_reg(&func->stack[j]))
2883                                 continue;
2884                         reg = &func->stack[j].spilled_ptr;
2885                         if (reg->type != SCALAR_VALUE)
2886                                 continue;
2887                         reg->precise = false;
2888                 }
2889         }
2890 }
2891
2892 /*
2893  * __mark_chain_precision() backtracks BPF program instruction sequence and
2894  * chain of verifier states making sure that register *regno* (if regno >= 0)
2895  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2896  * SCALARS, as well as any other registers and slots that contribute to
2897  * a tracked state of given registers/stack slots, depending on specific BPF
2898  * assembly instructions (see backtrack_insns() for exact instruction handling
2899  * logic). This backtracking relies on recorded jmp_history and is able to
2900  * traverse entire chain of parent states. This process ends only when all the
2901  * necessary registers/slots and their transitive dependencies are marked as
2902  * precise.
2903  *
2904  * One important and subtle aspect is that precise marks *do not matter* in
2905  * the currently verified state (current state). It is important to understand
2906  * why this is the case.
2907  *
2908  * First, note that current state is the state that is not yet "checkpointed",
2909  * i.e., it is not yet put into env->explored_states, and it has no children
2910  * states as well. It's ephemeral, and can end up either a) being discarded if
2911  * compatible explored state is found at some point or BPF_EXIT instruction is
2912  * reached or b) checkpointed and put into env->explored_states, branching out
2913  * into one or more children states.
2914  *
2915  * In the former case, precise markings in current state are completely
2916  * ignored by state comparison code (see regsafe() for details). Only
2917  * checkpointed ("old") state precise markings are important, and if old
2918  * state's register/slot is precise, regsafe() assumes current state's
2919  * register/slot as precise and checks value ranges exactly and precisely. If
2920  * states turn out to be compatible, current state's necessary precise
2921  * markings and any required parent states' precise markings are enforced
2922  * after the fact with propagate_precision() logic, after the fact. But it's
2923  * important to realize that in this case, even after marking current state
2924  * registers/slots as precise, we immediately discard current state. So what
2925  * actually matters is any of the precise markings propagated into current
2926  * state's parent states, which are always checkpointed (due to b) case above).
2927  * As such, for scenario a) it doesn't matter if current state has precise
2928  * markings set or not.
2929  *
2930  * Now, for the scenario b), checkpointing and forking into child(ren)
2931  * state(s). Note that before current state gets to checkpointing step, any
2932  * processed instruction always assumes precise SCALAR register/slot
2933  * knowledge: if precise value or range is useful to prune jump branch, BPF
2934  * verifier takes this opportunity enthusiastically. Similarly, when
2935  * register's value is used to calculate offset or memory address, exact
2936  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2937  * what we mentioned above about state comparison ignoring precise markings
2938  * during state comparison, BPF verifier ignores and also assumes precise
2939  * markings *at will* during instruction verification process. But as verifier
2940  * assumes precision, it also propagates any precision dependencies across
2941  * parent states, which are not yet finalized, so can be further restricted
2942  * based on new knowledge gained from restrictions enforced by their children
2943  * states. This is so that once those parent states are finalized, i.e., when
2944  * they have no more active children state, state comparison logic in
2945  * is_state_visited() would enforce strict and precise SCALAR ranges, if
2946  * required for correctness.
2947  *
2948  * To build a bit more intuition, note also that once a state is checkpointed,
2949  * the path we took to get to that state is not important. This is crucial
2950  * property for state pruning. When state is checkpointed and finalized at
2951  * some instruction index, it can be correctly and safely used to "short
2952  * circuit" any *compatible* state that reaches exactly the same instruction
2953  * index. I.e., if we jumped to that instruction from a completely different
2954  * code path than original finalized state was derived from, it doesn't
2955  * matter, current state can be discarded because from that instruction
2956  * forward having a compatible state will ensure we will safely reach the
2957  * exit. States describe preconditions for further exploration, but completely
2958  * forget the history of how we got here.
2959  *
2960  * This also means that even if we needed precise SCALAR range to get to
2961  * finalized state, but from that point forward *that same* SCALAR register is
2962  * never used in a precise context (i.e., it's precise value is not needed for
2963  * correctness), it's correct and safe to mark such register as "imprecise"
2964  * (i.e., precise marking set to false). This is what we rely on when we do
2965  * not set precise marking in current state. If no child state requires
2966  * precision for any given SCALAR register, it's safe to dictate that it can
2967  * be imprecise. If any child state does require this register to be precise,
2968  * we'll mark it precise later retroactively during precise markings
2969  * propagation from child state to parent states.
2970  *
2971  * Skipping precise marking setting in current state is a mild version of
2972  * relying on the above observation. But we can utilize this property even
2973  * more aggressively by proactively forgetting any precise marking in the
2974  * current state (which we inherited from the parent state), right before we
2975  * checkpoint it and branch off into new child state. This is done by
2976  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2977  * finalized states which help in short circuiting more future states.
2978  */
2979 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2980                                   int spi)
2981 {
2982         struct bpf_verifier_state *st = env->cur_state;
2983         int first_idx = st->first_insn_idx;
2984         int last_idx = env->insn_idx;
2985         struct bpf_func_state *func;
2986         struct bpf_reg_state *reg;
2987         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2988         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2989         bool skip_first = true;
2990         bool new_marks = false;
2991         int i, err;
2992
2993         if (!env->bpf_capable)
2994                 return 0;
2995
2996         /* Do sanity checks against current state of register and/or stack
2997          * slot, but don't set precise flag in current state, as precision
2998          * tracking in the current state is unnecessary.
2999          */
3000         func = st->frame[frame];
3001         if (regno >= 0) {
3002                 reg = &func->regs[regno];
3003                 if (reg->type != SCALAR_VALUE) {
3004                         WARN_ONCE(1, "backtracing misuse");
3005                         return -EFAULT;
3006                 }
3007                 new_marks = true;
3008         }
3009
3010         while (spi >= 0) {
3011                 if (!is_spilled_reg(&func->stack[spi])) {
3012                         stack_mask = 0;
3013                         break;
3014                 }
3015                 reg = &func->stack[spi].spilled_ptr;
3016                 if (reg->type != SCALAR_VALUE) {
3017                         stack_mask = 0;
3018                         break;
3019                 }
3020                 new_marks = true;
3021                 break;
3022         }
3023
3024         if (!new_marks)
3025                 return 0;
3026         if (!reg_mask && !stack_mask)
3027                 return 0;
3028
3029         for (;;) {
3030                 DECLARE_BITMAP(mask, 64);
3031                 u32 history = st->jmp_history_cnt;
3032
3033                 if (env->log.level & BPF_LOG_LEVEL2)
3034                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3035
3036                 if (last_idx < 0) {
3037                         /* we are at the entry into subprog, which
3038                          * is expected for global funcs, but only if
3039                          * requested precise registers are R1-R5
3040                          * (which are global func's input arguments)
3041                          */
3042                         if (st->curframe == 0 &&
3043                             st->frame[0]->subprogno > 0 &&
3044                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
3045                             stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3046                                 bitmap_from_u64(mask, reg_mask);
3047                                 for_each_set_bit(i, mask, 32) {
3048                                         reg = &st->frame[0]->regs[i];
3049                                         if (reg->type != SCALAR_VALUE) {
3050                                                 reg_mask &= ~(1u << i);
3051                                                 continue;
3052                                         }
3053                                         reg->precise = true;
3054                                 }
3055                                 return 0;
3056                         }
3057
3058                         verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3059                                 st->frame[0]->subprogno, reg_mask, stack_mask);
3060                         WARN_ONCE(1, "verifier backtracking bug");
3061                         return -EFAULT;
3062                 }
3063
3064                 for (i = last_idx;;) {
3065                         if (skip_first) {
3066                                 err = 0;
3067                                 skip_first = false;
3068                         } else {
3069                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3070                         }
3071                         if (err == -ENOTSUPP) {
3072                                 mark_all_scalars_precise(env, st);
3073                                 return 0;
3074                         } else if (err) {
3075                                 return err;
3076                         }
3077                         if (!reg_mask && !stack_mask)
3078                                 /* Found assignment(s) into tracked register in this state.
3079                                  * Since this state is already marked, just return.
3080                                  * Nothing to be tracked further in the parent state.
3081                                  */
3082                                 return 0;
3083                         if (i == first_idx)
3084                                 break;
3085                         i = get_prev_insn_idx(st, i, &history);
3086                         if (i >= env->prog->len) {
3087                                 /* This can happen if backtracking reached insn 0
3088                                  * and there are still reg_mask or stack_mask
3089                                  * to backtrack.
3090                                  * It means the backtracking missed the spot where
3091                                  * particular register was initialized with a constant.
3092                                  */
3093                                 verbose(env, "BUG backtracking idx %d\n", i);
3094                                 WARN_ONCE(1, "verifier backtracking bug");
3095                                 return -EFAULT;
3096                         }
3097                 }
3098                 st = st->parent;
3099                 if (!st)
3100                         break;
3101
3102                 new_marks = false;
3103                 func = st->frame[frame];
3104                 bitmap_from_u64(mask, reg_mask);
3105                 for_each_set_bit(i, mask, 32) {
3106                         reg = &func->regs[i];
3107                         if (reg->type != SCALAR_VALUE) {
3108                                 reg_mask &= ~(1u << i);
3109                                 continue;
3110                         }
3111                         if (!reg->precise)
3112                                 new_marks = true;
3113                         reg->precise = true;
3114                 }
3115
3116                 bitmap_from_u64(mask, stack_mask);
3117                 for_each_set_bit(i, mask, 64) {
3118                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
3119                                 /* the sequence of instructions:
3120                                  * 2: (bf) r3 = r10
3121                                  * 3: (7b) *(u64 *)(r3 -8) = r0
3122                                  * 4: (79) r4 = *(u64 *)(r10 -8)
3123                                  * doesn't contain jmps. It's backtracked
3124                                  * as a single block.
3125                                  * During backtracking insn 3 is not recognized as
3126                                  * stack access, so at the end of backtracking
3127                                  * stack slot fp-8 is still marked in stack_mask.
3128                                  * However the parent state may not have accessed
3129                                  * fp-8 and it's "unallocated" stack space.
3130                                  * In such case fallback to conservative.
3131                                  */
3132                                 mark_all_scalars_precise(env, st);
3133                                 return 0;
3134                         }
3135
3136                         if (!is_spilled_reg(&func->stack[i])) {
3137                                 stack_mask &= ~(1ull << i);
3138                                 continue;
3139                         }
3140                         reg = &func->stack[i].spilled_ptr;
3141                         if (reg->type != SCALAR_VALUE) {
3142                                 stack_mask &= ~(1ull << i);
3143                                 continue;
3144                         }
3145                         if (!reg->precise)
3146                                 new_marks = true;
3147                         reg->precise = true;
3148                 }
3149                 if (env->log.level & BPF_LOG_LEVEL2) {
3150                         verbose(env, "parent %s regs=%x stack=%llx marks:",
3151                                 new_marks ? "didn't have" : "already had",
3152                                 reg_mask, stack_mask);
3153                         print_verifier_state(env, func, true);
3154                 }
3155
3156                 if (!reg_mask && !stack_mask)
3157                         break;
3158                 if (!new_marks)
3159                         break;
3160
3161                 last_idx = st->last_insn_idx;
3162                 first_idx = st->first_insn_idx;
3163         }
3164         return 0;
3165 }
3166
3167 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3168 {
3169         return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3170 }
3171
3172 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3173 {
3174         return __mark_chain_precision(env, frame, regno, -1);
3175 }
3176
3177 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3178 {
3179         return __mark_chain_precision(env, frame, -1, spi);
3180 }
3181
3182 static bool is_spillable_regtype(enum bpf_reg_type type)
3183 {
3184         switch (base_type(type)) {
3185         case PTR_TO_MAP_VALUE:
3186         case PTR_TO_STACK:
3187         case PTR_TO_CTX:
3188         case PTR_TO_PACKET:
3189         case PTR_TO_PACKET_META:
3190         case PTR_TO_PACKET_END:
3191         case PTR_TO_FLOW_KEYS:
3192         case CONST_PTR_TO_MAP:
3193         case PTR_TO_SOCKET:
3194         case PTR_TO_SOCK_COMMON:
3195         case PTR_TO_TCP_SOCK:
3196         case PTR_TO_XDP_SOCK:
3197         case PTR_TO_BTF_ID:
3198         case PTR_TO_BUF:
3199         case PTR_TO_MEM:
3200         case PTR_TO_FUNC:
3201         case PTR_TO_MAP_KEY:
3202                 return true;
3203         default:
3204                 return false;
3205         }
3206 }
3207
3208 /* Does this register contain a constant zero? */
3209 static bool register_is_null(struct bpf_reg_state *reg)
3210 {
3211         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3212 }
3213
3214 static bool register_is_const(struct bpf_reg_state *reg)
3215 {
3216         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3217 }
3218
3219 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3220 {
3221         return tnum_is_unknown(reg->var_off) &&
3222                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3223                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3224                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3225                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3226 }
3227
3228 static bool register_is_bounded(struct bpf_reg_state *reg)
3229 {
3230         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3231 }
3232
3233 static bool __is_pointer_value(bool allow_ptr_leaks,
3234                                const struct bpf_reg_state *reg)
3235 {
3236         if (allow_ptr_leaks)
3237                 return false;
3238
3239         return reg->type != SCALAR_VALUE;
3240 }
3241
3242 static void save_register_state(struct bpf_func_state *state,
3243                                 int spi, struct bpf_reg_state *reg,
3244                                 int size)
3245 {
3246         int i;
3247
3248         state->stack[spi].spilled_ptr = *reg;
3249         if (size == BPF_REG_SIZE)
3250                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3251
3252         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3253                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3254
3255         /* size < 8 bytes spill */
3256         for (; i; i--)
3257                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3258 }
3259
3260 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3261  * stack boundary and alignment are checked in check_mem_access()
3262  */
3263 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3264                                        /* stack frame we're writing to */
3265                                        struct bpf_func_state *state,
3266                                        int off, int size, int value_regno,
3267                                        int insn_idx)
3268 {
3269         struct bpf_func_state *cur; /* state of the current function */
3270         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3271         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3272         struct bpf_reg_state *reg = NULL;
3273
3274         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3275         if (err)
3276                 return err;
3277         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3278          * so it's aligned access and [off, off + size) are within stack limits
3279          */
3280         if (!env->allow_ptr_leaks &&
3281             state->stack[spi].slot_type[0] == STACK_SPILL &&
3282             size != BPF_REG_SIZE) {
3283                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3284                 return -EACCES;
3285         }
3286
3287         cur = env->cur_state->frame[env->cur_state->curframe];
3288         if (value_regno >= 0)
3289                 reg = &cur->regs[value_regno];
3290         if (!env->bypass_spec_v4) {
3291                 bool sanitize = reg && is_spillable_regtype(reg->type);
3292
3293                 for (i = 0; i < size; i++) {
3294                         if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3295                                 sanitize = true;
3296                                 break;
3297                         }
3298                 }
3299
3300                 if (sanitize)
3301                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3302         }
3303
3304         mark_stack_slot_scratched(env, spi);
3305         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3306             !register_is_null(reg) && env->bpf_capable) {
3307                 if (dst_reg != BPF_REG_FP) {
3308                         /* The backtracking logic can only recognize explicit
3309                          * stack slot address like [fp - 8]. Other spill of
3310                          * scalar via different register has to be conservative.
3311                          * Backtrack from here and mark all registers as precise
3312                          * that contributed into 'reg' being a constant.
3313                          */
3314                         err = mark_chain_precision(env, value_regno);
3315                         if (err)
3316                                 return err;
3317                 }
3318                 save_register_state(state, spi, reg, size);
3319         } else if (reg && is_spillable_regtype(reg->type)) {
3320                 /* register containing pointer is being spilled into stack */
3321                 if (size != BPF_REG_SIZE) {
3322                         verbose_linfo(env, insn_idx, "; ");
3323                         verbose(env, "invalid size of register spill\n");
3324                         return -EACCES;
3325                 }
3326                 if (state != cur && reg->type == PTR_TO_STACK) {
3327                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3328                         return -EINVAL;
3329                 }
3330                 save_register_state(state, spi, reg, size);
3331         } else {
3332                 u8 type = STACK_MISC;
3333
3334                 /* regular write of data into stack destroys any spilled ptr */
3335                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3336                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3337                 if (is_spilled_reg(&state->stack[spi]))
3338                         for (i = 0; i < BPF_REG_SIZE; i++)
3339                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3340
3341                 /* only mark the slot as written if all 8 bytes were written
3342                  * otherwise read propagation may incorrectly stop too soon
3343                  * when stack slots are partially written.
3344                  * This heuristic means that read propagation will be
3345                  * conservative, since it will add reg_live_read marks
3346                  * to stack slots all the way to first state when programs
3347                  * writes+reads less than 8 bytes
3348                  */
3349                 if (size == BPF_REG_SIZE)
3350                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3351
3352                 /* when we zero initialize stack slots mark them as such */
3353                 if (reg && register_is_null(reg)) {
3354                         /* backtracking doesn't work for STACK_ZERO yet. */
3355                         err = mark_chain_precision(env, value_regno);
3356                         if (err)
3357                                 return err;
3358                         type = STACK_ZERO;
3359                 }
3360
3361                 /* Mark slots affected by this stack write. */
3362                 for (i = 0; i < size; i++)
3363                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3364                                 type;
3365         }
3366         return 0;
3367 }
3368
3369 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3370  * known to contain a variable offset.
3371  * This function checks whether the write is permitted and conservatively
3372  * tracks the effects of the write, considering that each stack slot in the
3373  * dynamic range is potentially written to.
3374  *
3375  * 'off' includes 'regno->off'.
3376  * 'value_regno' can be -1, meaning that an unknown value is being written to
3377  * the stack.
3378  *
3379  * Spilled pointers in range are not marked as written because we don't know
3380  * what's going to be actually written. This means that read propagation for
3381  * future reads cannot be terminated by this write.
3382  *
3383  * For privileged programs, uninitialized stack slots are considered
3384  * initialized by this write (even though we don't know exactly what offsets
3385  * are going to be written to). The idea is that we don't want the verifier to
3386  * reject future reads that access slots written to through variable offsets.
3387  */
3388 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3389                                      /* func where register points to */
3390                                      struct bpf_func_state *state,
3391                                      int ptr_regno, int off, int size,
3392                                      int value_regno, int insn_idx)
3393 {
3394         struct bpf_func_state *cur; /* state of the current function */
3395         int min_off, max_off;
3396         int i, err;
3397         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3398         bool writing_zero = false;
3399         /* set if the fact that we're writing a zero is used to let any
3400          * stack slots remain STACK_ZERO
3401          */
3402         bool zero_used = false;
3403
3404         cur = env->cur_state->frame[env->cur_state->curframe];
3405         ptr_reg = &cur->regs[ptr_regno];
3406         min_off = ptr_reg->smin_value + off;
3407         max_off = ptr_reg->smax_value + off + size;
3408         if (value_regno >= 0)
3409                 value_reg = &cur->regs[value_regno];
3410         if (value_reg && register_is_null(value_reg))
3411                 writing_zero = true;
3412
3413         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3414         if (err)
3415                 return err;
3416
3417
3418         /* Variable offset writes destroy any spilled pointers in range. */
3419         for (i = min_off; i < max_off; i++) {
3420                 u8 new_type, *stype;
3421                 int slot, spi;
3422
3423                 slot = -i - 1;
3424                 spi = slot / BPF_REG_SIZE;
3425                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3426                 mark_stack_slot_scratched(env, spi);
3427
3428                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3429                         /* Reject the write if range we may write to has not
3430                          * been initialized beforehand. If we didn't reject
3431                          * here, the ptr status would be erased below (even
3432                          * though not all slots are actually overwritten),
3433                          * possibly opening the door to leaks.
3434                          *
3435                          * We do however catch STACK_INVALID case below, and
3436                          * only allow reading possibly uninitialized memory
3437                          * later for CAP_PERFMON, as the write may not happen to
3438                          * that slot.
3439                          */
3440                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3441                                 insn_idx, i);
3442                         return -EINVAL;
3443                 }
3444
3445                 /* Erase all spilled pointers. */
3446                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3447
3448                 /* Update the slot type. */
3449                 new_type = STACK_MISC;
3450                 if (writing_zero && *stype == STACK_ZERO) {
3451                         new_type = STACK_ZERO;
3452                         zero_used = true;
3453                 }
3454                 /* If the slot is STACK_INVALID, we check whether it's OK to
3455                  * pretend that it will be initialized by this write. The slot
3456                  * might not actually be written to, and so if we mark it as
3457                  * initialized future reads might leak uninitialized memory.
3458                  * For privileged programs, we will accept such reads to slots
3459                  * that may or may not be written because, if we're reject
3460                  * them, the error would be too confusing.
3461                  */
3462                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3463                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3464                                         insn_idx, i);
3465                         return -EINVAL;
3466                 }
3467                 *stype = new_type;
3468         }
3469         if (zero_used) {
3470                 /* backtracking doesn't work for STACK_ZERO yet. */
3471                 err = mark_chain_precision(env, value_regno);
3472                 if (err)
3473                         return err;
3474         }
3475         return 0;
3476 }
3477
3478 /* When register 'dst_regno' is assigned some values from stack[min_off,
3479  * max_off), we set the register's type according to the types of the
3480  * respective stack slots. If all the stack values are known to be zeros, then
3481  * so is the destination reg. Otherwise, the register is considered to be
3482  * SCALAR. This function does not deal with register filling; the caller must
3483  * ensure that all spilled registers in the stack range have been marked as
3484  * read.
3485  */
3486 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3487                                 /* func where src register points to */
3488                                 struct bpf_func_state *ptr_state,
3489                                 int min_off, int max_off, int dst_regno)
3490 {
3491         struct bpf_verifier_state *vstate = env->cur_state;
3492         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3493         int i, slot, spi;
3494         u8 *stype;
3495         int zeros = 0;
3496
3497         for (i = min_off; i < max_off; i++) {
3498                 slot = -i - 1;
3499                 spi = slot / BPF_REG_SIZE;
3500                 stype = ptr_state->stack[spi].slot_type;
3501                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3502                         break;
3503                 zeros++;
3504         }
3505         if (zeros == max_off - min_off) {
3506                 /* any access_size read into register is zero extended,
3507                  * so the whole register == const_zero
3508                  */
3509                 __mark_reg_const_zero(&state->regs[dst_regno]);
3510                 /* backtracking doesn't support STACK_ZERO yet,
3511                  * so mark it precise here, so that later
3512                  * backtracking can stop here.
3513                  * Backtracking may not need this if this register
3514                  * doesn't participate in pointer adjustment.
3515                  * Forward propagation of precise flag is not
3516                  * necessary either. This mark is only to stop
3517                  * backtracking. Any register that contributed
3518                  * to const 0 was marked precise before spill.
3519                  */
3520                 state->regs[dst_regno].precise = true;
3521         } else {
3522                 /* have read misc data from the stack */
3523                 mark_reg_unknown(env, state->regs, dst_regno);
3524         }
3525         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3526 }
3527
3528 /* Read the stack at 'off' and put the results into the register indicated by
3529  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3530  * spilled reg.
3531  *
3532  * 'dst_regno' can be -1, meaning that the read value is not going to a
3533  * register.
3534  *
3535  * The access is assumed to be within the current stack bounds.
3536  */
3537 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3538                                       /* func where src register points to */
3539                                       struct bpf_func_state *reg_state,
3540                                       int off, int size, int dst_regno)
3541 {
3542         struct bpf_verifier_state *vstate = env->cur_state;
3543         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3544         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3545         struct bpf_reg_state *reg;
3546         u8 *stype, type;
3547
3548         stype = reg_state->stack[spi].slot_type;
3549         reg = &reg_state->stack[spi].spilled_ptr;
3550
3551         if (is_spilled_reg(&reg_state->stack[spi])) {
3552                 u8 spill_size = 1;
3553
3554                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3555                         spill_size++;
3556
3557                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3558                         if (reg->type != SCALAR_VALUE) {
3559                                 verbose_linfo(env, env->insn_idx, "; ");
3560                                 verbose(env, "invalid size of register fill\n");
3561                                 return -EACCES;
3562                         }
3563
3564                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3565                         if (dst_regno < 0)
3566                                 return 0;
3567
3568                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
3569                                 /* The earlier check_reg_arg() has decided the
3570                                  * subreg_def for this insn.  Save it first.
3571                                  */
3572                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
3573
3574                                 state->regs[dst_regno] = *reg;
3575                                 state->regs[dst_regno].subreg_def = subreg_def;
3576                         } else {
3577                                 for (i = 0; i < size; i++) {
3578                                         type = stype[(slot - i) % BPF_REG_SIZE];
3579                                         if (type == STACK_SPILL)
3580                                                 continue;
3581                                         if (type == STACK_MISC)
3582                                                 continue;
3583                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3584                                                 off, i, size);
3585                                         return -EACCES;
3586                                 }
3587                                 mark_reg_unknown(env, state->regs, dst_regno);
3588                         }
3589                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3590                         return 0;
3591                 }
3592
3593                 if (dst_regno >= 0) {
3594                         /* restore register state from stack */
3595                         state->regs[dst_regno] = *reg;
3596                         /* mark reg as written since spilled pointer state likely
3597                          * has its liveness marks cleared by is_state_visited()
3598                          * which resets stack/reg liveness for state transitions
3599                          */
3600                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3601                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3602                         /* If dst_regno==-1, the caller is asking us whether
3603                          * it is acceptable to use this value as a SCALAR_VALUE
3604                          * (e.g. for XADD).
3605                          * We must not allow unprivileged callers to do that
3606                          * with spilled pointers.
3607                          */
3608                         verbose(env, "leaking pointer from stack off %d\n",
3609                                 off);
3610                         return -EACCES;
3611                 }
3612                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3613         } else {
3614                 for (i = 0; i < size; i++) {
3615                         type = stype[(slot - i) % BPF_REG_SIZE];
3616                         if (type == STACK_MISC)
3617                                 continue;
3618                         if (type == STACK_ZERO)
3619                                 continue;
3620                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3621                                 off, i, size);
3622                         return -EACCES;
3623                 }
3624                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3625                 if (dst_regno >= 0)
3626                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3627         }
3628         return 0;
3629 }
3630
3631 enum bpf_access_src {
3632         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3633         ACCESS_HELPER = 2,  /* the access is performed by a helper */
3634 };
3635
3636 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3637                                          int regno, int off, int access_size,
3638                                          bool zero_size_allowed,
3639                                          enum bpf_access_src type,
3640                                          struct bpf_call_arg_meta *meta);
3641
3642 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3643 {
3644         return cur_regs(env) + regno;
3645 }
3646
3647 /* Read the stack at 'ptr_regno + off' and put the result into the register
3648  * 'dst_regno'.
3649  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3650  * but not its variable offset.
3651  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3652  *
3653  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3654  * filling registers (i.e. reads of spilled register cannot be detected when
3655  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3656  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3657  * offset; for a fixed offset check_stack_read_fixed_off should be used
3658  * instead.
3659  */
3660 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3661                                     int ptr_regno, int off, int size, int dst_regno)
3662 {
3663         /* The state of the source register. */
3664         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3665         struct bpf_func_state *ptr_state = func(env, reg);
3666         int err;
3667         int min_off, max_off;
3668
3669         /* Note that we pass a NULL meta, so raw access will not be permitted.
3670          */
3671         err = check_stack_range_initialized(env, ptr_regno, off, size,
3672                                             false, ACCESS_DIRECT, NULL);
3673         if (err)
3674                 return err;
3675
3676         min_off = reg->smin_value + off;
3677         max_off = reg->smax_value + off;
3678         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3679         return 0;
3680 }
3681
3682 /* check_stack_read dispatches to check_stack_read_fixed_off or
3683  * check_stack_read_var_off.
3684  *
3685  * The caller must ensure that the offset falls within the allocated stack
3686  * bounds.
3687  *
3688  * 'dst_regno' is a register which will receive the value from the stack. It
3689  * can be -1, meaning that the read value is not going to a register.
3690  */
3691 static int check_stack_read(struct bpf_verifier_env *env,
3692                             int ptr_regno, int off, int size,
3693                             int dst_regno)
3694 {
3695         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3696         struct bpf_func_state *state = func(env, reg);
3697         int err;
3698         /* Some accesses are only permitted with a static offset. */
3699         bool var_off = !tnum_is_const(reg->var_off);
3700
3701         /* The offset is required to be static when reads don't go to a
3702          * register, in order to not leak pointers (see
3703          * check_stack_read_fixed_off).
3704          */
3705         if (dst_regno < 0 && var_off) {
3706                 char tn_buf[48];
3707
3708                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3709                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3710                         tn_buf, off, size);
3711                 return -EACCES;
3712         }
3713         /* Variable offset is prohibited for unprivileged mode for simplicity
3714          * since it requires corresponding support in Spectre masking for stack
3715          * ALU. See also retrieve_ptr_limit().
3716          */
3717         if (!env->bypass_spec_v1 && var_off) {
3718                 char tn_buf[48];
3719
3720                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3721                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3722                                 ptr_regno, tn_buf);
3723                 return -EACCES;
3724         }
3725
3726         if (!var_off) {
3727                 off += reg->var_off.value;
3728                 err = check_stack_read_fixed_off(env, state, off, size,
3729                                                  dst_regno);
3730         } else {
3731                 /* Variable offset stack reads need more conservative handling
3732                  * than fixed offset ones. Note that dst_regno >= 0 on this
3733                  * branch.
3734                  */
3735                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3736                                                dst_regno);
3737         }
3738         return err;
3739 }
3740
3741
3742 /* check_stack_write dispatches to check_stack_write_fixed_off or
3743  * check_stack_write_var_off.
3744  *
3745  * 'ptr_regno' is the register used as a pointer into the stack.
3746  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3747  * 'value_regno' is the register whose value we're writing to the stack. It can
3748  * be -1, meaning that we're not writing from a register.
3749  *
3750  * The caller must ensure that the offset falls within the maximum stack size.
3751  */
3752 static int check_stack_write(struct bpf_verifier_env *env,
3753                              int ptr_regno, int off, int size,
3754                              int value_regno, int insn_idx)
3755 {
3756         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3757         struct bpf_func_state *state = func(env, reg);
3758         int err;
3759
3760         if (tnum_is_const(reg->var_off)) {
3761                 off += reg->var_off.value;
3762                 err = check_stack_write_fixed_off(env, state, off, size,
3763                                                   value_regno, insn_idx);
3764         } else {
3765                 /* Variable offset stack reads need more conservative handling
3766                  * than fixed offset ones.
3767                  */
3768                 err = check_stack_write_var_off(env, state,
3769                                                 ptr_regno, off, size,
3770                                                 value_regno, insn_idx);
3771         }
3772         return err;
3773 }
3774
3775 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3776                                  int off, int size, enum bpf_access_type type)
3777 {
3778         struct bpf_reg_state *regs = cur_regs(env);
3779         struct bpf_map *map = regs[regno].map_ptr;
3780         u32 cap = bpf_map_flags_to_cap(map);
3781
3782         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3783                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3784                         map->value_size, off, size);
3785                 return -EACCES;
3786         }
3787
3788         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3789                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3790                         map->value_size, off, size);
3791                 return -EACCES;
3792         }
3793
3794         return 0;
3795 }
3796
3797 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3798 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3799                               int off, int size, u32 mem_size,
3800                               bool zero_size_allowed)
3801 {
3802         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3803         struct bpf_reg_state *reg;
3804
3805         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3806                 return 0;
3807
3808         reg = &cur_regs(env)[regno];
3809         switch (reg->type) {
3810         case PTR_TO_MAP_KEY:
3811                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3812                         mem_size, off, size);
3813                 break;
3814         case PTR_TO_MAP_VALUE:
3815                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3816                         mem_size, off, size);
3817                 break;
3818         case PTR_TO_PACKET:
3819         case PTR_TO_PACKET_META:
3820         case PTR_TO_PACKET_END:
3821                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3822                         off, size, regno, reg->id, off, mem_size);
3823                 break;
3824         case PTR_TO_MEM:
3825         default:
3826                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3827                         mem_size, off, size);
3828         }
3829
3830         return -EACCES;
3831 }
3832
3833 /* check read/write into a memory region with possible variable offset */
3834 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3835                                    int off, int size, u32 mem_size,
3836                                    bool zero_size_allowed)
3837 {
3838         struct bpf_verifier_state *vstate = env->cur_state;
3839         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3840         struct bpf_reg_state *reg = &state->regs[regno];
3841         int err;
3842
3843         /* We may have adjusted the register pointing to memory region, so we
3844          * need to try adding each of min_value and max_value to off
3845          * to make sure our theoretical access will be safe.
3846          *
3847          * The minimum value is only important with signed
3848          * comparisons where we can't assume the floor of a
3849          * value is 0.  If we are using signed variables for our
3850          * index'es we need to make sure that whatever we use
3851          * will have a set floor within our range.
3852          */
3853         if (reg->smin_value < 0 &&
3854             (reg->smin_value == S64_MIN ||
3855              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3856               reg->smin_value + off < 0)) {
3857                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3858                         regno);
3859                 return -EACCES;
3860         }
3861         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3862                                  mem_size, zero_size_allowed);
3863         if (err) {
3864                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3865                         regno);
3866                 return err;
3867         }
3868
3869         /* If we haven't set a max value then we need to bail since we can't be
3870          * sure we won't do bad things.
3871          * If reg->umax_value + off could overflow, treat that as unbounded too.
3872          */
3873         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3874                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3875                         regno);
3876                 return -EACCES;
3877         }
3878         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3879                                  mem_size, zero_size_allowed);
3880         if (err) {
3881                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3882                         regno);
3883                 return err;
3884         }
3885
3886         return 0;
3887 }
3888
3889 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3890                                const struct bpf_reg_state *reg, int regno,
3891                                bool fixed_off_ok)
3892 {
3893         /* Access to this pointer-typed register or passing it to a helper
3894          * is only allowed in its original, unmodified form.
3895          */
3896
3897         if (reg->off < 0) {
3898                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3899                         reg_type_str(env, reg->type), regno, reg->off);
3900                 return -EACCES;
3901         }
3902
3903         if (!fixed_off_ok && reg->off) {
3904                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3905                         reg_type_str(env, reg->type), regno, reg->off);
3906                 return -EACCES;
3907         }
3908
3909         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3910                 char tn_buf[48];
3911
3912                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3913                 verbose(env, "variable %s access var_off=%s disallowed\n",
3914                         reg_type_str(env, reg->type), tn_buf);
3915                 return -EACCES;
3916         }
3917
3918         return 0;
3919 }
3920
3921 int check_ptr_off_reg(struct bpf_verifier_env *env,
3922                       const struct bpf_reg_state *reg, int regno)
3923 {
3924         return __check_ptr_off_reg(env, reg, regno, false);
3925 }
3926
3927 static int map_kptr_match_type(struct bpf_verifier_env *env,
3928                                struct btf_field *kptr_field,
3929                                struct bpf_reg_state *reg, u32 regno)
3930 {
3931         const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
3932         int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
3933         const char *reg_name = "";
3934
3935         /* Only unreferenced case accepts untrusted pointers */
3936         if (kptr_field->type == BPF_KPTR_UNREF)
3937                 perm_flags |= PTR_UNTRUSTED;
3938
3939         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3940                 goto bad_type;
3941
3942         if (!btf_is_kernel(reg->btf)) {
3943                 verbose(env, "R%d must point to kernel BTF\n", regno);
3944                 return -EINVAL;
3945         }
3946         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3947         reg_name = kernel_type_name(reg->btf, reg->btf_id);
3948
3949         /* For ref_ptr case, release function check should ensure we get one
3950          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3951          * normal store of unreferenced kptr, we must ensure var_off is zero.
3952          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3953          * reg->off and reg->ref_obj_id are not needed here.
3954          */
3955         if (__check_ptr_off_reg(env, reg, regno, true))
3956                 return -EACCES;
3957
3958         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3959          * we also need to take into account the reg->off.
3960          *
3961          * We want to support cases like:
3962          *
3963          * struct foo {
3964          *         struct bar br;
3965          *         struct baz bz;
3966          * };
3967          *
3968          * struct foo *v;
3969          * v = func();        // PTR_TO_BTF_ID
3970          * val->foo = v;      // reg->off is zero, btf and btf_id match type
3971          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3972          *                    // first member type of struct after comparison fails
3973          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3974          *                    // to match type
3975          *
3976          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3977          * is zero. We must also ensure that btf_struct_ids_match does not walk
3978          * the struct to match type against first member of struct, i.e. reject
3979          * second case from above. Hence, when type is BPF_KPTR_REF, we set
3980          * strict mode to true for type match.
3981          */
3982         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3983                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
3984                                   kptr_field->type == BPF_KPTR_REF))
3985                 goto bad_type;
3986         return 0;
3987 bad_type:
3988         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3989                 reg_type_str(env, reg->type), reg_name);
3990         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3991         if (kptr_field->type == BPF_KPTR_UNREF)
3992                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3993                         targ_name);
3994         else
3995                 verbose(env, "\n");
3996         return -EINVAL;
3997 }
3998
3999 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4000                                  int value_regno, int insn_idx,
4001                                  struct btf_field *kptr_field)
4002 {
4003         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4004         int class = BPF_CLASS(insn->code);
4005         struct bpf_reg_state *val_reg;
4006
4007         /* Things we already checked for in check_map_access and caller:
4008          *  - Reject cases where variable offset may touch kptr
4009          *  - size of access (must be BPF_DW)
4010          *  - tnum_is_const(reg->var_off)
4011          *  - kptr_field->offset == off + reg->var_off.value
4012          */
4013         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4014         if (BPF_MODE(insn->code) != BPF_MEM) {
4015                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4016                 return -EACCES;
4017         }
4018
4019         /* We only allow loading referenced kptr, since it will be marked as
4020          * untrusted, similar to unreferenced kptr.
4021          */
4022         if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4023                 verbose(env, "store to referenced kptr disallowed\n");
4024                 return -EACCES;
4025         }
4026
4027         if (class == BPF_LDX) {
4028                 val_reg = reg_state(env, value_regno);
4029                 /* We can simply mark the value_regno receiving the pointer
4030                  * value from map as PTR_TO_BTF_ID, with the correct type.
4031                  */
4032                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4033                                 kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
4034                 /* For mark_ptr_or_null_reg */
4035                 val_reg->id = ++env->id_gen;
4036         } else if (class == BPF_STX) {
4037                 val_reg = reg_state(env, value_regno);
4038                 if (!register_is_null(val_reg) &&
4039                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4040                         return -EACCES;
4041         } else if (class == BPF_ST) {
4042                 if (insn->imm) {
4043                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4044                                 kptr_field->offset);
4045                         return -EACCES;
4046                 }
4047         } else {
4048                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4049                 return -EACCES;
4050         }
4051         return 0;
4052 }
4053
4054 /* check read/write into a map element with possible variable offset */
4055 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4056                             int off, int size, bool zero_size_allowed,
4057                             enum bpf_access_src src)
4058 {
4059         struct bpf_verifier_state *vstate = env->cur_state;
4060         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4061         struct bpf_reg_state *reg = &state->regs[regno];
4062         struct bpf_map *map = reg->map_ptr;
4063         struct btf_record *rec;
4064         int err, i;
4065
4066         err = check_mem_region_access(env, regno, off, size, map->value_size,
4067                                       zero_size_allowed);
4068         if (err)
4069                 return err;
4070
4071         if (IS_ERR_OR_NULL(map->record))
4072                 return 0;
4073         rec = map->record;
4074         for (i = 0; i < rec->cnt; i++) {
4075                 struct btf_field *field = &rec->fields[i];
4076                 u32 p = field->offset;
4077
4078                 /* If any part of a field  can be touched by load/store, reject
4079                  * this program. To check that [x1, x2) overlaps with [y1, y2),
4080                  * it is sufficient to check x1 < y2 && y1 < x2.
4081                  */
4082                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4083                     p < reg->umax_value + off + size) {
4084                         switch (field->type) {
4085                         case BPF_KPTR_UNREF:
4086                         case BPF_KPTR_REF:
4087                                 if (src != ACCESS_DIRECT) {
4088                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
4089                                         return -EACCES;
4090                                 }
4091                                 if (!tnum_is_const(reg->var_off)) {
4092                                         verbose(env, "kptr access cannot have variable offset\n");
4093                                         return -EACCES;
4094                                 }
4095                                 if (p != off + reg->var_off.value) {
4096                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4097                                                 p, off + reg->var_off.value);
4098                                         return -EACCES;
4099                                 }
4100                                 if (size != bpf_size_to_bytes(BPF_DW)) {
4101                                         verbose(env, "kptr access size must be BPF_DW\n");
4102                                         return -EACCES;
4103                                 }
4104                                 break;
4105                         default:
4106                                 verbose(env, "%s cannot be accessed directly by load/store\n",
4107                                         btf_field_type_name(field->type));
4108                                 return -EACCES;
4109                         }
4110                 }
4111         }
4112         return 0;
4113 }
4114
4115 #define MAX_PACKET_OFF 0xffff
4116
4117 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4118                                        const struct bpf_call_arg_meta *meta,
4119                                        enum bpf_access_type t)
4120 {
4121         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4122
4123         switch (prog_type) {
4124         /* Program types only with direct read access go here! */
4125         case BPF_PROG_TYPE_LWT_IN:
4126         case BPF_PROG_TYPE_LWT_OUT:
4127         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4128         case BPF_PROG_TYPE_SK_REUSEPORT:
4129         case BPF_PROG_TYPE_FLOW_DISSECTOR:
4130         case BPF_PROG_TYPE_CGROUP_SKB:
4131                 if (t == BPF_WRITE)
4132                         return false;
4133                 fallthrough;
4134
4135         /* Program types with direct read + write access go here! */
4136         case BPF_PROG_TYPE_SCHED_CLS:
4137         case BPF_PROG_TYPE_SCHED_ACT:
4138         case BPF_PROG_TYPE_XDP:
4139         case BPF_PROG_TYPE_LWT_XMIT:
4140         case BPF_PROG_TYPE_SK_SKB:
4141         case BPF_PROG_TYPE_SK_MSG:
4142                 if (meta)
4143                         return meta->pkt_access;
4144
4145                 env->seen_direct_write = true;
4146                 return true;
4147
4148         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4149                 if (t == BPF_WRITE)
4150                         env->seen_direct_write = true;
4151
4152                 return true;
4153
4154         default:
4155                 return false;
4156         }
4157 }
4158
4159 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4160                                int size, bool zero_size_allowed)
4161 {
4162         struct bpf_reg_state *regs = cur_regs(env);
4163         struct bpf_reg_state *reg = &regs[regno];
4164         int err;
4165
4166         /* We may have added a variable offset to the packet pointer; but any
4167          * reg->range we have comes after that.  We are only checking the fixed
4168          * offset.
4169          */
4170
4171         /* We don't allow negative numbers, because we aren't tracking enough
4172          * detail to prove they're safe.
4173          */
4174         if (reg->smin_value < 0) {
4175                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4176                         regno);
4177                 return -EACCES;
4178         }
4179
4180         err = reg->range < 0 ? -EINVAL :
4181               __check_mem_access(env, regno, off, size, reg->range,
4182                                  zero_size_allowed);
4183         if (err) {
4184                 verbose(env, "R%d offset is outside of the packet\n", regno);
4185                 return err;
4186         }
4187
4188         /* __check_mem_access has made sure "off + size - 1" is within u16.
4189          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4190          * otherwise find_good_pkt_pointers would have refused to set range info
4191          * that __check_mem_access would have rejected this pkt access.
4192          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4193          */
4194         env->prog->aux->max_pkt_offset =
4195                 max_t(u32, env->prog->aux->max_pkt_offset,
4196                       off + reg->umax_value + size - 1);
4197
4198         return err;
4199 }
4200
4201 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4202 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4203                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
4204                             struct btf **btf, u32 *btf_id)
4205 {
4206         struct bpf_insn_access_aux info = {
4207                 .reg_type = *reg_type,
4208                 .log = &env->log,
4209         };
4210
4211         if (env->ops->is_valid_access &&
4212             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4213                 /* A non zero info.ctx_field_size indicates that this field is a
4214                  * candidate for later verifier transformation to load the whole
4215                  * field and then apply a mask when accessed with a narrower
4216                  * access than actual ctx access size. A zero info.ctx_field_size
4217                  * will only allow for whole field access and rejects any other
4218                  * type of narrower access.
4219                  */
4220                 *reg_type = info.reg_type;
4221
4222                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4223                         *btf = info.btf;
4224                         *btf_id = info.btf_id;
4225                 } else {
4226                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4227                 }
4228                 /* remember the offset of last byte accessed in ctx */
4229                 if (env->prog->aux->max_ctx_offset < off + size)
4230                         env->prog->aux->max_ctx_offset = off + size;
4231                 return 0;
4232         }
4233
4234         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4235         return -EACCES;
4236 }
4237
4238 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4239                                   int size)
4240 {
4241         if (size < 0 || off < 0 ||
4242             (u64)off + size > sizeof(struct bpf_flow_keys)) {
4243                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4244                         off, size);
4245                 return -EACCES;
4246         }
4247         return 0;
4248 }
4249
4250 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4251                              u32 regno, int off, int size,
4252                              enum bpf_access_type t)
4253 {
4254         struct bpf_reg_state *regs = cur_regs(env);
4255         struct bpf_reg_state *reg = &regs[regno];
4256         struct bpf_insn_access_aux info = {};
4257         bool valid;
4258
4259         if (reg->smin_value < 0) {
4260                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4261                         regno);
4262                 return -EACCES;
4263         }
4264
4265         switch (reg->type) {
4266         case PTR_TO_SOCK_COMMON:
4267                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4268                 break;
4269         case PTR_TO_SOCKET:
4270                 valid = bpf_sock_is_valid_access(off, size, t, &info);
4271                 break;
4272         case PTR_TO_TCP_SOCK:
4273                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4274                 break;
4275         case PTR_TO_XDP_SOCK:
4276                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4277                 break;
4278         default:
4279                 valid = false;
4280         }
4281
4282
4283         if (valid) {
4284                 env->insn_aux_data[insn_idx].ctx_field_size =
4285                         info.ctx_field_size;
4286                 return 0;
4287         }
4288
4289         verbose(env, "R%d invalid %s access off=%d size=%d\n",
4290                 regno, reg_type_str(env, reg->type), off, size);
4291
4292         return -EACCES;
4293 }
4294
4295 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4296 {
4297         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4298 }
4299
4300 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4301 {
4302         const struct bpf_reg_state *reg = reg_state(env, regno);
4303
4304         return reg->type == PTR_TO_CTX;
4305 }
4306
4307 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4308 {
4309         const struct bpf_reg_state *reg = reg_state(env, regno);
4310
4311         return type_is_sk_pointer(reg->type);
4312 }
4313
4314 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4315 {
4316         const struct bpf_reg_state *reg = reg_state(env, regno);
4317
4318         return type_is_pkt_pointer(reg->type);
4319 }
4320
4321 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4322 {
4323         const struct bpf_reg_state *reg = reg_state(env, regno);
4324
4325         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4326         return reg->type == PTR_TO_FLOW_KEYS;
4327 }
4328
4329 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4330 {
4331         /* A referenced register is always trusted. */
4332         if (reg->ref_obj_id)
4333                 return true;
4334
4335         /* If a register is not referenced, it is trusted if it has the
4336          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4337          * other type modifiers may be safe, but we elect to take an opt-in
4338          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4339          * not.
4340          *
4341          * Eventually, we should make PTR_TRUSTED the single source of truth
4342          * for whether a register is trusted.
4343          */
4344         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4345                !bpf_type_has_unsafe_modifiers(reg->type);
4346 }
4347
4348 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4349 {
4350         return reg->type & MEM_RCU;
4351 }
4352
4353 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4354                                    const struct bpf_reg_state *reg,
4355                                    int off, int size, bool strict)
4356 {
4357         struct tnum reg_off;
4358         int ip_align;
4359
4360         /* Byte size accesses are always allowed. */
4361         if (!strict || size == 1)
4362                 return 0;
4363
4364         /* For platforms that do not have a Kconfig enabling
4365          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4366          * NET_IP_ALIGN is universally set to '2'.  And on platforms
4367          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4368          * to this code only in strict mode where we want to emulate
4369          * the NET_IP_ALIGN==2 checking.  Therefore use an
4370          * unconditional IP align value of '2'.
4371          */
4372         ip_align = 2;
4373
4374         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4375         if (!tnum_is_aligned(reg_off, size)) {
4376                 char tn_buf[48];
4377
4378                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4379                 verbose(env,
4380                         "misaligned packet access off %d+%s+%d+%d size %d\n",
4381                         ip_align, tn_buf, reg->off, off, size);
4382                 return -EACCES;
4383         }
4384
4385         return 0;
4386 }
4387
4388 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4389                                        const struct bpf_reg_state *reg,
4390                                        const char *pointer_desc,
4391                                        int off, int size, bool strict)
4392 {
4393         struct tnum reg_off;
4394
4395         /* Byte size accesses are always allowed. */
4396         if (!strict || size == 1)
4397                 return 0;
4398
4399         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4400         if (!tnum_is_aligned(reg_off, size)) {
4401                 char tn_buf[48];
4402
4403                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4404                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4405                         pointer_desc, tn_buf, reg->off, off, size);
4406                 return -EACCES;
4407         }
4408
4409         return 0;
4410 }
4411
4412 static int check_ptr_alignment(struct bpf_verifier_env *env,
4413                                const struct bpf_reg_state *reg, int off,
4414                                int size, bool strict_alignment_once)
4415 {
4416         bool strict = env->strict_alignment || strict_alignment_once;
4417         const char *pointer_desc = "";
4418
4419         switch (reg->type) {
4420         case PTR_TO_PACKET:
4421         case PTR_TO_PACKET_META:
4422                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4423                  * right in front, treat it the very same way.
4424                  */
4425                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4426         case PTR_TO_FLOW_KEYS:
4427                 pointer_desc = "flow keys ";
4428                 break;
4429         case PTR_TO_MAP_KEY:
4430                 pointer_desc = "key ";
4431                 break;
4432         case PTR_TO_MAP_VALUE:
4433                 pointer_desc = "value ";
4434                 break;
4435         case PTR_TO_CTX:
4436                 pointer_desc = "context ";
4437                 break;
4438         case PTR_TO_STACK:
4439                 pointer_desc = "stack ";
4440                 /* The stack spill tracking logic in check_stack_write_fixed_off()
4441                  * and check_stack_read_fixed_off() relies on stack accesses being
4442                  * aligned.
4443                  */
4444                 strict = true;
4445                 break;
4446         case PTR_TO_SOCKET:
4447                 pointer_desc = "sock ";
4448                 break;
4449         case PTR_TO_SOCK_COMMON:
4450                 pointer_desc = "sock_common ";
4451                 break;
4452         case PTR_TO_TCP_SOCK:
4453                 pointer_desc = "tcp_sock ";
4454                 break;
4455         case PTR_TO_XDP_SOCK:
4456                 pointer_desc = "xdp_sock ";
4457                 break;
4458         default:
4459                 break;
4460         }
4461         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4462                                            strict);
4463 }
4464
4465 static int update_stack_depth(struct bpf_verifier_env *env,
4466                               const struct bpf_func_state *func,
4467                               int off)
4468 {
4469         u16 stack = env->subprog_info[func->subprogno].stack_depth;
4470
4471         if (stack >= -off)
4472                 return 0;
4473
4474         /* update known max for given subprogram */
4475         env->subprog_info[func->subprogno].stack_depth = -off;
4476         return 0;
4477 }
4478
4479 /* starting from main bpf function walk all instructions of the function
4480  * and recursively walk all callees that given function can call.
4481  * Ignore jump and exit insns.
4482  * Since recursion is prevented by check_cfg() this algorithm
4483  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4484  */
4485 static int check_max_stack_depth(struct bpf_verifier_env *env)
4486 {
4487         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4488         struct bpf_subprog_info *subprog = env->subprog_info;
4489         struct bpf_insn *insn = env->prog->insnsi;
4490         bool tail_call_reachable = false;
4491         int ret_insn[MAX_CALL_FRAMES];
4492         int ret_prog[MAX_CALL_FRAMES];
4493         int j;
4494
4495 process_func:
4496         /* protect against potential stack overflow that might happen when
4497          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4498          * depth for such case down to 256 so that the worst case scenario
4499          * would result in 8k stack size (32 which is tailcall limit * 256 =
4500          * 8k).
4501          *
4502          * To get the idea what might happen, see an example:
4503          * func1 -> sub rsp, 128
4504          *  subfunc1 -> sub rsp, 256
4505          *  tailcall1 -> add rsp, 256
4506          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4507          *   subfunc2 -> sub rsp, 64
4508          *   subfunc22 -> sub rsp, 128
4509          *   tailcall2 -> add rsp, 128
4510          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4511          *
4512          * tailcall will unwind the current stack frame but it will not get rid
4513          * of caller's stack as shown on the example above.
4514          */
4515         if (idx && subprog[idx].has_tail_call && depth >= 256) {
4516                 verbose(env,
4517                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4518                         depth);
4519                 return -EACCES;
4520         }
4521         /* round up to 32-bytes, since this is granularity
4522          * of interpreter stack size
4523          */
4524         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4525         if (depth > MAX_BPF_STACK) {
4526                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4527                         frame + 1, depth);
4528                 return -EACCES;
4529         }
4530 continue_func:
4531         subprog_end = subprog[idx + 1].start;
4532         for (; i < subprog_end; i++) {
4533                 int next_insn;
4534
4535                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4536                         continue;
4537                 /* remember insn and function to return to */
4538                 ret_insn[frame] = i + 1;
4539                 ret_prog[frame] = idx;
4540
4541                 /* find the callee */
4542                 next_insn = i + insn[i].imm + 1;
4543                 idx = find_subprog(env, next_insn);
4544                 if (idx < 0) {
4545                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4546                                   next_insn);
4547                         return -EFAULT;
4548                 }
4549                 if (subprog[idx].is_async_cb) {
4550                         if (subprog[idx].has_tail_call) {
4551                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4552                                 return -EFAULT;
4553                         }
4554                          /* async callbacks don't increase bpf prog stack size */
4555                         continue;
4556                 }
4557                 i = next_insn;
4558
4559                 if (subprog[idx].has_tail_call)
4560                         tail_call_reachable = true;
4561
4562                 frame++;
4563                 if (frame >= MAX_CALL_FRAMES) {
4564                         verbose(env, "the call stack of %d frames is too deep !\n",
4565                                 frame);
4566                         return -E2BIG;
4567                 }
4568                 goto process_func;
4569         }
4570         /* if tail call got detected across bpf2bpf calls then mark each of the
4571          * currently present subprog frames as tail call reachable subprogs;
4572          * this info will be utilized by JIT so that we will be preserving the
4573          * tail call counter throughout bpf2bpf calls combined with tailcalls
4574          */
4575         if (tail_call_reachable)
4576                 for (j = 0; j < frame; j++)
4577                         subprog[ret_prog[j]].tail_call_reachable = true;
4578         if (subprog[0].tail_call_reachable)
4579                 env->prog->aux->tail_call_reachable = true;
4580
4581         /* end of for() loop means the last insn of the 'subprog'
4582          * was reached. Doesn't matter whether it was JA or EXIT
4583          */
4584         if (frame == 0)
4585                 return 0;
4586         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4587         frame--;
4588         i = ret_insn[frame];
4589         idx = ret_prog[frame];
4590         goto continue_func;
4591 }
4592
4593 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4594 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4595                                   const struct bpf_insn *insn, int idx)
4596 {
4597         int start = idx + insn->imm + 1, subprog;
4598
4599         subprog = find_subprog(env, start);
4600         if (subprog < 0) {
4601                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4602                           start);
4603                 return -EFAULT;
4604         }
4605         return env->subprog_info[subprog].stack_depth;
4606 }
4607 #endif
4608
4609 static int __check_buffer_access(struct bpf_verifier_env *env,
4610                                  const char *buf_info,
4611                                  const struct bpf_reg_state *reg,
4612                                  int regno, int off, int size)
4613 {
4614         if (off < 0) {
4615                 verbose(env,
4616                         "R%d invalid %s buffer access: off=%d, size=%d\n",
4617                         regno, buf_info, off, size);
4618                 return -EACCES;
4619         }
4620         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4621                 char tn_buf[48];
4622
4623                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4624                 verbose(env,
4625                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4626                         regno, off, tn_buf);
4627                 return -EACCES;
4628         }
4629
4630         return 0;
4631 }
4632
4633 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4634                                   const struct bpf_reg_state *reg,
4635                                   int regno, int off, int size)
4636 {
4637         int err;
4638
4639         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4640         if (err)
4641                 return err;
4642
4643         if (off + size > env->prog->aux->max_tp_access)
4644                 env->prog->aux->max_tp_access = off + size;
4645
4646         return 0;
4647 }
4648
4649 static int check_buffer_access(struct bpf_verifier_env *env,
4650                                const struct bpf_reg_state *reg,
4651                                int regno, int off, int size,
4652                                bool zero_size_allowed,
4653                                u32 *max_access)
4654 {
4655         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4656         int err;
4657
4658         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4659         if (err)
4660                 return err;
4661
4662         if (off + size > *max_access)
4663                 *max_access = off + size;
4664
4665         return 0;
4666 }
4667
4668 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4669 static void zext_32_to_64(struct bpf_reg_state *reg)
4670 {
4671         reg->var_off = tnum_subreg(reg->var_off);
4672         __reg_assign_32_into_64(reg);
4673 }
4674
4675 /* truncate register to smaller size (in bytes)
4676  * must be called with size < BPF_REG_SIZE
4677  */
4678 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4679 {
4680         u64 mask;
4681
4682         /* clear high bits in bit representation */
4683         reg->var_off = tnum_cast(reg->var_off, size);
4684
4685         /* fix arithmetic bounds */
4686         mask = ((u64)1 << (size * 8)) - 1;
4687         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4688                 reg->umin_value &= mask;
4689                 reg->umax_value &= mask;
4690         } else {
4691                 reg->umin_value = 0;
4692                 reg->umax_value = mask;
4693         }
4694         reg->smin_value = reg->umin_value;
4695         reg->smax_value = reg->umax_value;
4696
4697         /* If size is smaller than 32bit register the 32bit register
4698          * values are also truncated so we push 64-bit bounds into
4699          * 32-bit bounds. Above were truncated < 32-bits already.
4700          */
4701         if (size >= 4)
4702                 return;
4703         __reg_combine_64_into_32(reg);
4704 }
4705
4706 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4707 {
4708         /* A map is considered read-only if the following condition are true:
4709          *
4710          * 1) BPF program side cannot change any of the map content. The
4711          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4712          *    and was set at map creation time.
4713          * 2) The map value(s) have been initialized from user space by a
4714          *    loader and then "frozen", such that no new map update/delete
4715          *    operations from syscall side are possible for the rest of
4716          *    the map's lifetime from that point onwards.
4717          * 3) Any parallel/pending map update/delete operations from syscall
4718          *    side have been completed. Only after that point, it's safe to
4719          *    assume that map value(s) are immutable.
4720          */
4721         return (map->map_flags & BPF_F_RDONLY_PROG) &&
4722                READ_ONCE(map->frozen) &&
4723                !bpf_map_write_active(map);
4724 }
4725
4726 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4727 {
4728         void *ptr;
4729         u64 addr;
4730         int err;
4731
4732         err = map->ops->map_direct_value_addr(map, &addr, off);
4733         if (err)
4734                 return err;
4735         ptr = (void *)(long)addr + off;
4736
4737         switch (size) {
4738         case sizeof(u8):
4739                 *val = (u64)*(u8 *)ptr;
4740                 break;
4741         case sizeof(u16):
4742                 *val = (u64)*(u16 *)ptr;
4743                 break;
4744         case sizeof(u32):
4745                 *val = (u64)*(u32 *)ptr;
4746                 break;
4747         case sizeof(u64):
4748                 *val = *(u64 *)ptr;
4749                 break;
4750         default:
4751                 return -EINVAL;
4752         }
4753         return 0;
4754 }
4755
4756 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4757                                    struct bpf_reg_state *regs,
4758                                    int regno, int off, int size,
4759                                    enum bpf_access_type atype,
4760                                    int value_regno)
4761 {
4762         struct bpf_reg_state *reg = regs + regno;
4763         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4764         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4765         enum bpf_type_flag flag = 0;
4766         u32 btf_id;
4767         int ret;
4768
4769         if (!env->allow_ptr_leaks) {
4770                 verbose(env,
4771                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4772                         tname);
4773                 return -EPERM;
4774         }
4775         if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
4776                 verbose(env,
4777                         "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
4778                         tname);
4779                 return -EINVAL;
4780         }
4781         if (off < 0) {
4782                 verbose(env,
4783                         "R%d is ptr_%s invalid negative access: off=%d\n",
4784                         regno, tname, off);
4785                 return -EACCES;
4786         }
4787         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4788                 char tn_buf[48];
4789
4790                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4791                 verbose(env,
4792                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4793                         regno, tname, off, tn_buf);
4794                 return -EACCES;
4795         }
4796
4797         if (reg->type & MEM_USER) {
4798                 verbose(env,
4799                         "R%d is ptr_%s access user memory: off=%d\n",
4800                         regno, tname, off);
4801                 return -EACCES;
4802         }
4803
4804         if (reg->type & MEM_PERCPU) {
4805                 verbose(env,
4806                         "R%d is ptr_%s access percpu memory: off=%d\n",
4807                         regno, tname, off);
4808                 return -EACCES;
4809         }
4810
4811         if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
4812                 if (!btf_is_kernel(reg->btf)) {
4813                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
4814                         return -EFAULT;
4815                 }
4816                 ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4817         } else {
4818                 /* Writes are permitted with default btf_struct_access for
4819                  * program allocated objects (which always have ref_obj_id > 0),
4820                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
4821                  */
4822                 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
4823                         verbose(env, "only read is supported\n");
4824                         return -EACCES;
4825                 }
4826
4827                 if (type_is_alloc(reg->type) && !reg->ref_obj_id) {
4828                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
4829                         return -EFAULT;
4830                 }
4831
4832                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4833         }
4834
4835         if (ret < 0)
4836                 return ret;
4837
4838         /* If this is an untrusted pointer, all pointers formed by walking it
4839          * also inherit the untrusted flag.
4840          */
4841         if (type_flag(reg->type) & PTR_UNTRUSTED)
4842                 flag |= PTR_UNTRUSTED;
4843
4844         /* By default any pointer obtained from walking a trusted pointer is
4845          * no longer trusted except the rcu case below.
4846          */
4847         flag &= ~PTR_TRUSTED;
4848
4849         if (flag & MEM_RCU) {
4850                 /* Mark value register as MEM_RCU only if it is protected by
4851                  * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU
4852                  * itself can already indicate trustedness inside the rcu
4853                  * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since
4854                  * it could be null in some cases.
4855                  */
4856                 if (!env->cur_state->active_rcu_lock ||
4857                     !(is_trusted_reg(reg) || is_rcu_reg(reg)))
4858                         flag &= ~MEM_RCU;
4859                 else
4860                         flag |= PTR_MAYBE_NULL;
4861         } else if (reg->type & MEM_RCU) {
4862                 /* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged
4863                  * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively.
4864                  */
4865                 flag |= PTR_UNTRUSTED;
4866         }
4867
4868         if (atype == BPF_READ && value_regno >= 0)
4869                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4870
4871         return 0;
4872 }
4873
4874 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4875                                    struct bpf_reg_state *regs,
4876                                    int regno, int off, int size,
4877                                    enum bpf_access_type atype,
4878                                    int value_regno)
4879 {
4880         struct bpf_reg_state *reg = regs + regno;
4881         struct bpf_map *map = reg->map_ptr;
4882         struct bpf_reg_state map_reg;
4883         enum bpf_type_flag flag = 0;
4884         const struct btf_type *t;
4885         const char *tname;
4886         u32 btf_id;
4887         int ret;
4888
4889         if (!btf_vmlinux) {
4890                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4891                 return -ENOTSUPP;
4892         }
4893
4894         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4895                 verbose(env, "map_ptr access not supported for map type %d\n",
4896                         map->map_type);
4897                 return -ENOTSUPP;
4898         }
4899
4900         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4901         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4902
4903         if (!env->allow_ptr_leaks) {
4904                 verbose(env,
4905                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4906                         tname);
4907                 return -EPERM;
4908         }
4909
4910         if (off < 0) {
4911                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4912                         regno, tname, off);
4913                 return -EACCES;
4914         }
4915
4916         if (atype != BPF_READ) {
4917                 verbose(env, "only read from %s is supported\n", tname);
4918                 return -EACCES;
4919         }
4920
4921         /* Simulate access to a PTR_TO_BTF_ID */
4922         memset(&map_reg, 0, sizeof(map_reg));
4923         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
4924         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
4925         if (ret < 0)
4926                 return ret;
4927
4928         if (value_regno >= 0)
4929                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4930
4931         return 0;
4932 }
4933
4934 /* Check that the stack access at the given offset is within bounds. The
4935  * maximum valid offset is -1.
4936  *
4937  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4938  * -state->allocated_stack for reads.
4939  */
4940 static int check_stack_slot_within_bounds(int off,
4941                                           struct bpf_func_state *state,
4942                                           enum bpf_access_type t)
4943 {
4944         int min_valid_off;
4945
4946         if (t == BPF_WRITE)
4947                 min_valid_off = -MAX_BPF_STACK;
4948         else
4949                 min_valid_off = -state->allocated_stack;
4950
4951         if (off < min_valid_off || off > -1)
4952                 return -EACCES;
4953         return 0;
4954 }
4955
4956 /* Check that the stack access at 'regno + off' falls within the maximum stack
4957  * bounds.
4958  *
4959  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4960  */
4961 static int check_stack_access_within_bounds(
4962                 struct bpf_verifier_env *env,
4963                 int regno, int off, int access_size,
4964                 enum bpf_access_src src, enum bpf_access_type type)
4965 {
4966         struct bpf_reg_state *regs = cur_regs(env);
4967         struct bpf_reg_state *reg = regs + regno;
4968         struct bpf_func_state *state = func(env, reg);
4969         int min_off, max_off;
4970         int err;
4971         char *err_extra;
4972
4973         if (src == ACCESS_HELPER)
4974                 /* We don't know if helpers are reading or writing (or both). */
4975                 err_extra = " indirect access to";
4976         else if (type == BPF_READ)
4977                 err_extra = " read from";
4978         else
4979                 err_extra = " write to";
4980
4981         if (tnum_is_const(reg->var_off)) {
4982                 min_off = reg->var_off.value + off;
4983                 if (access_size > 0)
4984                         max_off = min_off + access_size - 1;
4985                 else
4986                         max_off = min_off;
4987         } else {
4988                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4989                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4990                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4991                                 err_extra, regno);
4992                         return -EACCES;
4993                 }
4994                 min_off = reg->smin_value + off;
4995                 if (access_size > 0)
4996                         max_off = reg->smax_value + off + access_size - 1;
4997                 else
4998                         max_off = min_off;
4999         }
5000
5001         err = check_stack_slot_within_bounds(min_off, state, type);
5002         if (!err)
5003                 err = check_stack_slot_within_bounds(max_off, state, type);
5004
5005         if (err) {
5006                 if (tnum_is_const(reg->var_off)) {
5007                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5008                                 err_extra, regno, off, access_size);
5009                 } else {
5010                         char tn_buf[48];
5011
5012                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5013                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5014                                 err_extra, regno, tn_buf, access_size);
5015                 }
5016         }
5017         return err;
5018 }
5019
5020 /* check whether memory at (regno + off) is accessible for t = (read | write)
5021  * if t==write, value_regno is a register which value is stored into memory
5022  * if t==read, value_regno is a register which will receive the value from memory
5023  * if t==write && value_regno==-1, some unknown value is stored into memory
5024  * if t==read && value_regno==-1, don't care what we read from memory
5025  */
5026 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5027                             int off, int bpf_size, enum bpf_access_type t,
5028                             int value_regno, bool strict_alignment_once)
5029 {
5030         struct bpf_reg_state *regs = cur_regs(env);
5031         struct bpf_reg_state *reg = regs + regno;
5032         struct bpf_func_state *state;
5033         int size, err = 0;
5034
5035         size = bpf_size_to_bytes(bpf_size);
5036         if (size < 0)
5037                 return size;
5038
5039         /* alignment checks will add in reg->off themselves */
5040         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5041         if (err)
5042                 return err;
5043
5044         /* for access checks, reg->off is just part of off */
5045         off += reg->off;
5046
5047         if (reg->type == PTR_TO_MAP_KEY) {
5048                 if (t == BPF_WRITE) {
5049                         verbose(env, "write to change key R%d not allowed\n", regno);
5050                         return -EACCES;
5051                 }
5052
5053                 err = check_mem_region_access(env, regno, off, size,
5054                                               reg->map_ptr->key_size, false);
5055                 if (err)
5056                         return err;
5057                 if (value_regno >= 0)
5058                         mark_reg_unknown(env, regs, value_regno);
5059         } else if (reg->type == PTR_TO_MAP_VALUE) {
5060                 struct btf_field *kptr_field = NULL;
5061
5062                 if (t == BPF_WRITE && value_regno >= 0 &&
5063                     is_pointer_value(env, value_regno)) {
5064                         verbose(env, "R%d leaks addr into map\n", value_regno);
5065                         return -EACCES;
5066                 }
5067                 err = check_map_access_type(env, regno, off, size, t);
5068                 if (err)
5069                         return err;
5070                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5071                 if (err)
5072                         return err;
5073                 if (tnum_is_const(reg->var_off))
5074                         kptr_field = btf_record_find(reg->map_ptr->record,
5075                                                      off + reg->var_off.value, BPF_KPTR);
5076                 if (kptr_field) {
5077                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5078                 } else if (t == BPF_READ && value_regno >= 0) {
5079                         struct bpf_map *map = reg->map_ptr;
5080
5081                         /* if map is read-only, track its contents as scalars */
5082                         if (tnum_is_const(reg->var_off) &&
5083                             bpf_map_is_rdonly(map) &&
5084                             map->ops->map_direct_value_addr) {
5085                                 int map_off = off + reg->var_off.value;
5086                                 u64 val = 0;
5087
5088                                 err = bpf_map_direct_read(map, map_off, size,
5089                                                           &val);
5090                                 if (err)
5091                                         return err;
5092
5093                                 regs[value_regno].type = SCALAR_VALUE;
5094                                 __mark_reg_known(&regs[value_regno], val);
5095                         } else {
5096                                 mark_reg_unknown(env, regs, value_regno);
5097                         }
5098                 }
5099         } else if (base_type(reg->type) == PTR_TO_MEM) {
5100                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5101
5102                 if (type_may_be_null(reg->type)) {
5103                         verbose(env, "R%d invalid mem access '%s'\n", regno,
5104                                 reg_type_str(env, reg->type));
5105                         return -EACCES;
5106                 }
5107
5108                 if (t == BPF_WRITE && rdonly_mem) {
5109                         verbose(env, "R%d cannot write into %s\n",
5110                                 regno, reg_type_str(env, reg->type));
5111                         return -EACCES;
5112                 }
5113
5114                 if (t == BPF_WRITE && value_regno >= 0 &&
5115                     is_pointer_value(env, value_regno)) {
5116                         verbose(env, "R%d leaks addr into mem\n", value_regno);
5117                         return -EACCES;
5118                 }
5119
5120                 err = check_mem_region_access(env, regno, off, size,
5121                                               reg->mem_size, false);
5122                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5123                         mark_reg_unknown(env, regs, value_regno);
5124         } else if (reg->type == PTR_TO_CTX) {
5125                 enum bpf_reg_type reg_type = SCALAR_VALUE;
5126                 struct btf *btf = NULL;
5127                 u32 btf_id = 0;
5128
5129                 if (t == BPF_WRITE && value_regno >= 0 &&
5130                     is_pointer_value(env, value_regno)) {
5131                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
5132                         return -EACCES;
5133                 }
5134
5135                 err = check_ptr_off_reg(env, reg, regno);
5136                 if (err < 0)
5137                         return err;
5138
5139                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5140                                        &btf_id);
5141                 if (err)
5142                         verbose_linfo(env, insn_idx, "; ");
5143                 if (!err && t == BPF_READ && value_regno >= 0) {
5144                         /* ctx access returns either a scalar, or a
5145                          * PTR_TO_PACKET[_META,_END]. In the latter
5146                          * case, we know the offset is zero.
5147                          */
5148                         if (reg_type == SCALAR_VALUE) {
5149                                 mark_reg_unknown(env, regs, value_regno);
5150                         } else {
5151                                 mark_reg_known_zero(env, regs,
5152                                                     value_regno);
5153                                 if (type_may_be_null(reg_type))
5154                                         regs[value_regno].id = ++env->id_gen;
5155                                 /* A load of ctx field could have different
5156                                  * actual load size with the one encoded in the
5157                                  * insn. When the dst is PTR, it is for sure not
5158                                  * a sub-register.
5159                                  */
5160                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5161                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
5162                                         regs[value_regno].btf = btf;
5163                                         regs[value_regno].btf_id = btf_id;
5164                                 }
5165                         }
5166                         regs[value_regno].type = reg_type;
5167                 }
5168
5169         } else if (reg->type == PTR_TO_STACK) {
5170                 /* Basic bounds checks. */
5171                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5172                 if (err)
5173                         return err;
5174
5175                 state = func(env, reg);
5176                 err = update_stack_depth(env, state, off);
5177                 if (err)
5178                         return err;
5179
5180                 if (t == BPF_READ)
5181                         err = check_stack_read(env, regno, off, size,
5182                                                value_regno);
5183                 else
5184                         err = check_stack_write(env, regno, off, size,
5185                                                 value_regno, insn_idx);
5186         } else if (reg_is_pkt_pointer(reg)) {
5187                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5188                         verbose(env, "cannot write into packet\n");
5189                         return -EACCES;
5190                 }
5191                 if (t == BPF_WRITE && value_regno >= 0 &&
5192                     is_pointer_value(env, value_regno)) {
5193                         verbose(env, "R%d leaks addr into packet\n",
5194                                 value_regno);
5195                         return -EACCES;
5196                 }
5197                 err = check_packet_access(env, regno, off, size, false);
5198                 if (!err && t == BPF_READ && value_regno >= 0)
5199                         mark_reg_unknown(env, regs, value_regno);
5200         } else if (reg->type == PTR_TO_FLOW_KEYS) {
5201                 if (t == BPF_WRITE && value_regno >= 0 &&
5202                     is_pointer_value(env, value_regno)) {
5203                         verbose(env, "R%d leaks addr into flow keys\n",
5204                                 value_regno);
5205                         return -EACCES;
5206                 }
5207
5208                 err = check_flow_keys_access(env, off, size);
5209                 if (!err && t == BPF_READ && value_regno >= 0)
5210                         mark_reg_unknown(env, regs, value_regno);
5211         } else if (type_is_sk_pointer(reg->type)) {
5212                 if (t == BPF_WRITE) {
5213                         verbose(env, "R%d cannot write into %s\n",
5214                                 regno, reg_type_str(env, reg->type));
5215                         return -EACCES;
5216                 }
5217                 err = check_sock_access(env, insn_idx, regno, off, size, t);
5218                 if (!err && value_regno >= 0)
5219                         mark_reg_unknown(env, regs, value_regno);
5220         } else if (reg->type == PTR_TO_TP_BUFFER) {
5221                 err = check_tp_buffer_access(env, reg, regno, off, size);
5222                 if (!err && t == BPF_READ && value_regno >= 0)
5223                         mark_reg_unknown(env, regs, value_regno);
5224         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5225                    !type_may_be_null(reg->type)) {
5226                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5227                                               value_regno);
5228         } else if (reg->type == CONST_PTR_TO_MAP) {
5229                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5230                                               value_regno);
5231         } else if (base_type(reg->type) == PTR_TO_BUF) {
5232                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5233                 u32 *max_access;
5234
5235                 if (rdonly_mem) {
5236                         if (t == BPF_WRITE) {
5237                                 verbose(env, "R%d cannot write into %s\n",
5238                                         regno, reg_type_str(env, reg->type));
5239                                 return -EACCES;
5240                         }
5241                         max_access = &env->prog->aux->max_rdonly_access;
5242                 } else {
5243                         max_access = &env->prog->aux->max_rdwr_access;
5244                 }
5245
5246                 err = check_buffer_access(env, reg, regno, off, size, false,
5247                                           max_access);
5248
5249                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5250                         mark_reg_unknown(env, regs, value_regno);
5251         } else {
5252                 verbose(env, "R%d invalid mem access '%s'\n", regno,
5253                         reg_type_str(env, reg->type));
5254                 return -EACCES;
5255         }
5256
5257         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5258             regs[value_regno].type == SCALAR_VALUE) {
5259                 /* b/h/w load zero-extends, mark upper bits as known 0 */
5260                 coerce_reg_to_size(&regs[value_regno], size);
5261         }
5262         return err;
5263 }
5264
5265 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5266 {
5267         int load_reg;
5268         int err;
5269
5270         switch (insn->imm) {
5271         case BPF_ADD:
5272         case BPF_ADD | BPF_FETCH:
5273         case BPF_AND:
5274         case BPF_AND | BPF_FETCH:
5275         case BPF_OR:
5276         case BPF_OR | BPF_FETCH:
5277         case BPF_XOR:
5278         case BPF_XOR | BPF_FETCH:
5279         case BPF_XCHG:
5280         case BPF_CMPXCHG:
5281                 break;
5282         default:
5283                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5284                 return -EINVAL;
5285         }
5286
5287         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5288                 verbose(env, "invalid atomic operand size\n");
5289                 return -EINVAL;
5290         }
5291
5292         /* check src1 operand */
5293         err = check_reg_arg(env, insn->src_reg, SRC_OP);
5294         if (err)
5295                 return err;
5296
5297         /* check src2 operand */
5298         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5299         if (err)
5300                 return err;
5301
5302         if (insn->imm == BPF_CMPXCHG) {
5303                 /* Check comparison of R0 with memory location */
5304                 const u32 aux_reg = BPF_REG_0;
5305
5306                 err = check_reg_arg(env, aux_reg, SRC_OP);
5307                 if (err)
5308                         return err;
5309
5310                 if (is_pointer_value(env, aux_reg)) {
5311                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
5312                         return -EACCES;
5313                 }
5314         }
5315
5316         if (is_pointer_value(env, insn->src_reg)) {
5317                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5318                 return -EACCES;
5319         }
5320
5321         if (is_ctx_reg(env, insn->dst_reg) ||
5322             is_pkt_reg(env, insn->dst_reg) ||
5323             is_flow_key_reg(env, insn->dst_reg) ||
5324             is_sk_reg(env, insn->dst_reg)) {
5325                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5326                         insn->dst_reg,
5327                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5328                 return -EACCES;
5329         }
5330
5331         if (insn->imm & BPF_FETCH) {
5332                 if (insn->imm == BPF_CMPXCHG)
5333                         load_reg = BPF_REG_0;
5334                 else
5335                         load_reg = insn->src_reg;
5336
5337                 /* check and record load of old value */
5338                 err = check_reg_arg(env, load_reg, DST_OP);
5339                 if (err)
5340                         return err;
5341         } else {
5342                 /* This instruction accesses a memory location but doesn't
5343                  * actually load it into a register.
5344                  */
5345                 load_reg = -1;
5346         }
5347
5348         /* Check whether we can read the memory, with second call for fetch
5349          * case to simulate the register fill.
5350          */
5351         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5352                                BPF_SIZE(insn->code), BPF_READ, -1, true);
5353         if (!err && load_reg >= 0)
5354                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5355                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
5356                                        true);
5357         if (err)
5358                 return err;
5359
5360         /* Check whether we can write into the same memory. */
5361         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5362                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5363         if (err)
5364                 return err;
5365
5366         return 0;
5367 }
5368
5369 /* When register 'regno' is used to read the stack (either directly or through
5370  * a helper function) make sure that it's within stack boundary and, depending
5371  * on the access type, that all elements of the stack are initialized.
5372  *
5373  * 'off' includes 'regno->off', but not its dynamic part (if any).
5374  *
5375  * All registers that have been spilled on the stack in the slots within the
5376  * read offsets are marked as read.
5377  */
5378 static int check_stack_range_initialized(
5379                 struct bpf_verifier_env *env, int regno, int off,
5380                 int access_size, bool zero_size_allowed,
5381                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5382 {
5383         struct bpf_reg_state *reg = reg_state(env, regno);
5384         struct bpf_func_state *state = func(env, reg);
5385         int err, min_off, max_off, i, j, slot, spi;
5386         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5387         enum bpf_access_type bounds_check_type;
5388         /* Some accesses can write anything into the stack, others are
5389          * read-only.
5390          */
5391         bool clobber = false;
5392
5393         if (access_size == 0 && !zero_size_allowed) {
5394                 verbose(env, "invalid zero-sized read\n");
5395                 return -EACCES;
5396         }
5397
5398         if (type == ACCESS_HELPER) {
5399                 /* The bounds checks for writes are more permissive than for
5400                  * reads. However, if raw_mode is not set, we'll do extra
5401                  * checks below.
5402                  */
5403                 bounds_check_type = BPF_WRITE;
5404                 clobber = true;
5405         } else {
5406                 bounds_check_type = BPF_READ;
5407         }
5408         err = check_stack_access_within_bounds(env, regno, off, access_size,
5409                                                type, bounds_check_type);
5410         if (err)
5411                 return err;
5412
5413
5414         if (tnum_is_const(reg->var_off)) {
5415                 min_off = max_off = reg->var_off.value + off;
5416         } else {
5417                 /* Variable offset is prohibited for unprivileged mode for
5418                  * simplicity since it requires corresponding support in
5419                  * Spectre masking for stack ALU.
5420                  * See also retrieve_ptr_limit().
5421                  */
5422                 if (!env->bypass_spec_v1) {
5423                         char tn_buf[48];
5424
5425                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5426                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5427                                 regno, err_extra, tn_buf);
5428                         return -EACCES;
5429                 }
5430                 /* Only initialized buffer on stack is allowed to be accessed
5431                  * with variable offset. With uninitialized buffer it's hard to
5432                  * guarantee that whole memory is marked as initialized on
5433                  * helper return since specific bounds are unknown what may
5434                  * cause uninitialized stack leaking.
5435                  */
5436                 if (meta && meta->raw_mode)
5437                         meta = NULL;
5438
5439                 min_off = reg->smin_value + off;
5440                 max_off = reg->smax_value + off;
5441         }
5442
5443         if (meta && meta->raw_mode) {
5444                 meta->access_size = access_size;
5445                 meta->regno = regno;
5446                 return 0;
5447         }
5448
5449         for (i = min_off; i < max_off + access_size; i++) {
5450                 u8 *stype;
5451
5452                 slot = -i - 1;
5453                 spi = slot / BPF_REG_SIZE;
5454                 if (state->allocated_stack <= slot)
5455                         goto err;
5456                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5457                 if (*stype == STACK_MISC)
5458                         goto mark;
5459                 if (*stype == STACK_ZERO) {
5460                         if (clobber) {
5461                                 /* helper can write anything into the stack */
5462                                 *stype = STACK_MISC;
5463                         }
5464                         goto mark;
5465                 }
5466
5467                 if (is_spilled_reg(&state->stack[spi]) &&
5468                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5469                      env->allow_ptr_leaks)) {
5470                         if (clobber) {
5471                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5472                                 for (j = 0; j < BPF_REG_SIZE; j++)
5473                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5474                         }
5475                         goto mark;
5476                 }
5477
5478 err:
5479                 if (tnum_is_const(reg->var_off)) {
5480                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5481                                 err_extra, regno, min_off, i - min_off, access_size);
5482                 } else {
5483                         char tn_buf[48];
5484
5485                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5486                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5487                                 err_extra, regno, tn_buf, i - min_off, access_size);
5488                 }
5489                 return -EACCES;
5490 mark:
5491                 /* reading any byte out of 8-byte 'spill_slot' will cause
5492                  * the whole slot to be marked as 'read'
5493                  */
5494                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5495                               state->stack[spi].spilled_ptr.parent,
5496                               REG_LIVE_READ64);
5497                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5498                  * be sure that whether stack slot is written to or not. Hence,
5499                  * we must still conservatively propagate reads upwards even if
5500                  * helper may write to the entire memory range.
5501                  */
5502         }
5503         return update_stack_depth(env, state, min_off);
5504 }
5505
5506 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5507                                    int access_size, bool zero_size_allowed,
5508                                    struct bpf_call_arg_meta *meta)
5509 {
5510         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5511         u32 *max_access;
5512
5513         switch (base_type(reg->type)) {
5514         case PTR_TO_PACKET:
5515         case PTR_TO_PACKET_META:
5516                 return check_packet_access(env, regno, reg->off, access_size,
5517                                            zero_size_allowed);
5518         case PTR_TO_MAP_KEY:
5519                 if (meta && meta->raw_mode) {
5520                         verbose(env, "R%d cannot write into %s\n", regno,
5521                                 reg_type_str(env, reg->type));
5522                         return -EACCES;
5523                 }
5524                 return check_mem_region_access(env, regno, reg->off, access_size,
5525                                                reg->map_ptr->key_size, false);
5526         case PTR_TO_MAP_VALUE:
5527                 if (check_map_access_type(env, regno, reg->off, access_size,
5528                                           meta && meta->raw_mode ? BPF_WRITE :
5529                                           BPF_READ))
5530                         return -EACCES;
5531                 return check_map_access(env, regno, reg->off, access_size,
5532                                         zero_size_allowed, ACCESS_HELPER);
5533         case PTR_TO_MEM:
5534                 if (type_is_rdonly_mem(reg->type)) {
5535                         if (meta && meta->raw_mode) {
5536                                 verbose(env, "R%d cannot write into %s\n", regno,
5537                                         reg_type_str(env, reg->type));
5538                                 return -EACCES;
5539                         }
5540                 }
5541                 return check_mem_region_access(env, regno, reg->off,
5542                                                access_size, reg->mem_size,
5543                                                zero_size_allowed);
5544         case PTR_TO_BUF:
5545                 if (type_is_rdonly_mem(reg->type)) {
5546                         if (meta && meta->raw_mode) {
5547                                 verbose(env, "R%d cannot write into %s\n", regno,
5548                                         reg_type_str(env, reg->type));
5549                                 return -EACCES;
5550                         }
5551
5552                         max_access = &env->prog->aux->max_rdonly_access;
5553                 } else {
5554                         max_access = &env->prog->aux->max_rdwr_access;
5555                 }
5556                 return check_buffer_access(env, reg, regno, reg->off,
5557                                            access_size, zero_size_allowed,
5558                                            max_access);
5559         case PTR_TO_STACK:
5560                 return check_stack_range_initialized(
5561                                 env,
5562                                 regno, reg->off, access_size,
5563                                 zero_size_allowed, ACCESS_HELPER, meta);
5564         case PTR_TO_CTX:
5565                 /* in case the function doesn't know how to access the context,
5566                  * (because we are in a program of type SYSCALL for example), we
5567                  * can not statically check its size.
5568                  * Dynamically check it now.
5569                  */
5570                 if (!env->ops->convert_ctx_access) {
5571                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5572                         int offset = access_size - 1;
5573
5574                         /* Allow zero-byte read from PTR_TO_CTX */
5575                         if (access_size == 0)
5576                                 return zero_size_allowed ? 0 : -EACCES;
5577
5578                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5579                                                 atype, -1, false);
5580                 }
5581
5582                 fallthrough;
5583         default: /* scalar_value or invalid ptr */
5584                 /* Allow zero-byte read from NULL, regardless of pointer type */
5585                 if (zero_size_allowed && access_size == 0 &&
5586                     register_is_null(reg))
5587                         return 0;
5588
5589                 verbose(env, "R%d type=%s ", regno,
5590                         reg_type_str(env, reg->type));
5591                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5592                 return -EACCES;
5593         }
5594 }
5595
5596 static int check_mem_size_reg(struct bpf_verifier_env *env,
5597                               struct bpf_reg_state *reg, u32 regno,
5598                               bool zero_size_allowed,
5599                               struct bpf_call_arg_meta *meta)
5600 {
5601         int err;
5602
5603         /* This is used to refine r0 return value bounds for helpers
5604          * that enforce this value as an upper bound on return values.
5605          * See do_refine_retval_range() for helpers that can refine
5606          * the return value. C type of helper is u32 so we pull register
5607          * bound from umax_value however, if negative verifier errors
5608          * out. Only upper bounds can be learned because retval is an
5609          * int type and negative retvals are allowed.
5610          */
5611         meta->msize_max_value = reg->umax_value;
5612
5613         /* The register is SCALAR_VALUE; the access check
5614          * happens using its boundaries.
5615          */
5616         if (!tnum_is_const(reg->var_off))
5617                 /* For unprivileged variable accesses, disable raw
5618                  * mode so that the program is required to
5619                  * initialize all the memory that the helper could
5620                  * just partially fill up.
5621                  */
5622                 meta = NULL;
5623
5624         if (reg->smin_value < 0) {
5625                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5626                         regno);
5627                 return -EACCES;
5628         }
5629
5630         if (reg->umin_value == 0) {
5631                 err = check_helper_mem_access(env, regno - 1, 0,
5632                                               zero_size_allowed,
5633                                               meta);
5634                 if (err)
5635                         return err;
5636         }
5637
5638         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5639                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5640                         regno);
5641                 return -EACCES;
5642         }
5643         err = check_helper_mem_access(env, regno - 1,
5644                                       reg->umax_value,
5645                                       zero_size_allowed, meta);
5646         if (!err)
5647                 err = mark_chain_precision(env, regno);
5648         return err;
5649 }
5650
5651 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5652                    u32 regno, u32 mem_size)
5653 {
5654         bool may_be_null = type_may_be_null(reg->type);
5655         struct bpf_reg_state saved_reg;
5656         struct bpf_call_arg_meta meta;
5657         int err;
5658
5659         if (register_is_null(reg))
5660                 return 0;
5661
5662         memset(&meta, 0, sizeof(meta));
5663         /* Assuming that the register contains a value check if the memory
5664          * access is safe. Temporarily save and restore the register's state as
5665          * the conversion shouldn't be visible to a caller.
5666          */
5667         if (may_be_null) {
5668                 saved_reg = *reg;
5669                 mark_ptr_not_null_reg(reg);
5670         }
5671
5672         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5673         /* Check access for BPF_WRITE */
5674         meta.raw_mode = true;
5675         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5676
5677         if (may_be_null)
5678                 *reg = saved_reg;
5679
5680         return err;
5681 }
5682
5683 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5684                                     u32 regno)
5685 {
5686         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5687         bool may_be_null = type_may_be_null(mem_reg->type);
5688         struct bpf_reg_state saved_reg;
5689         struct bpf_call_arg_meta meta;
5690         int err;
5691
5692         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5693
5694         memset(&meta, 0, sizeof(meta));
5695
5696         if (may_be_null) {
5697                 saved_reg = *mem_reg;
5698                 mark_ptr_not_null_reg(mem_reg);
5699         }
5700
5701         err = check_mem_size_reg(env, reg, regno, true, &meta);
5702         /* Check access for BPF_WRITE */
5703         meta.raw_mode = true;
5704         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5705
5706         if (may_be_null)
5707                 *mem_reg = saved_reg;
5708         return err;
5709 }
5710
5711 /* Implementation details:
5712  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
5713  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
5714  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5715  * Two separate bpf_obj_new will also have different reg->id.
5716  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
5717  * clears reg->id after value_or_null->value transition, since the verifier only
5718  * cares about the range of access to valid map value pointer and doesn't care
5719  * about actual address of the map element.
5720  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5721  * reg->id > 0 after value_or_null->value transition. By doing so
5722  * two bpf_map_lookups will be considered two different pointers that
5723  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
5724  * returned from bpf_obj_new.
5725  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5726  * dead-locks.
5727  * Since only one bpf_spin_lock is allowed the checks are simpler than
5728  * reg_is_refcounted() logic. The verifier needs to remember only
5729  * one spin_lock instead of array of acquired_refs.
5730  * cur_state->active_lock remembers which map value element or allocated
5731  * object got locked and clears it after bpf_spin_unlock.
5732  */
5733 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5734                              bool is_lock)
5735 {
5736         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5737         struct bpf_verifier_state *cur = env->cur_state;
5738         bool is_const = tnum_is_const(reg->var_off);
5739         u64 val = reg->var_off.value;
5740         struct bpf_map *map = NULL;
5741         struct btf *btf = NULL;
5742         struct btf_record *rec;
5743
5744         if (!is_const) {
5745                 verbose(env,
5746                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5747                         regno);
5748                 return -EINVAL;
5749         }
5750         if (reg->type == PTR_TO_MAP_VALUE) {
5751                 map = reg->map_ptr;
5752                 if (!map->btf) {
5753                         verbose(env,
5754                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5755                                 map->name);
5756                         return -EINVAL;
5757                 }
5758         } else {
5759                 btf = reg->btf;
5760         }
5761
5762         rec = reg_btf_record(reg);
5763         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
5764                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
5765                         map ? map->name : "kptr");
5766                 return -EINVAL;
5767         }
5768         if (rec->spin_lock_off != val + reg->off) {
5769                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
5770                         val + reg->off, rec->spin_lock_off);
5771                 return -EINVAL;
5772         }
5773         if (is_lock) {
5774                 if (cur->active_lock.ptr) {
5775                         verbose(env,
5776                                 "Locking two bpf_spin_locks are not allowed\n");
5777                         return -EINVAL;
5778                 }
5779                 if (map)
5780                         cur->active_lock.ptr = map;
5781                 else
5782                         cur->active_lock.ptr = btf;
5783                 cur->active_lock.id = reg->id;
5784         } else {
5785                 struct bpf_func_state *fstate = cur_func(env);
5786                 void *ptr;
5787                 int i;
5788
5789                 if (map)
5790                         ptr = map;
5791                 else
5792                         ptr = btf;
5793
5794                 if (!cur->active_lock.ptr) {
5795                         verbose(env, "bpf_spin_unlock without taking a lock\n");
5796                         return -EINVAL;
5797                 }
5798                 if (cur->active_lock.ptr != ptr ||
5799                     cur->active_lock.id != reg->id) {
5800                         verbose(env, "bpf_spin_unlock of different lock\n");
5801                         return -EINVAL;
5802                 }
5803                 cur->active_lock.ptr = NULL;
5804                 cur->active_lock.id = 0;
5805
5806                 for (i = fstate->acquired_refs - 1; i >= 0; i--) {
5807                         int err;
5808
5809                         /* Complain on error because this reference state cannot
5810                          * be freed before this point, as bpf_spin_lock critical
5811                          * section does not allow functions that release the
5812                          * allocated object immediately.
5813                          */
5814                         if (!fstate->refs[i].release_on_unlock)
5815                                 continue;
5816                         err = release_reference(env, fstate->refs[i].id);
5817                         if (err) {
5818                                 verbose(env, "failed to release release_on_unlock reference");
5819                                 return err;
5820                         }
5821                 }
5822         }
5823         return 0;
5824 }
5825
5826 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5827                               struct bpf_call_arg_meta *meta)
5828 {
5829         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5830         bool is_const = tnum_is_const(reg->var_off);
5831         struct bpf_map *map = reg->map_ptr;
5832         u64 val = reg->var_off.value;
5833
5834         if (!is_const) {
5835                 verbose(env,
5836                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5837                         regno);
5838                 return -EINVAL;
5839         }
5840         if (!map->btf) {
5841                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5842                         map->name);
5843                 return -EINVAL;
5844         }
5845         if (!btf_record_has_field(map->record, BPF_TIMER)) {
5846                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
5847                 return -EINVAL;
5848         }
5849         if (map->record->timer_off != val + reg->off) {
5850                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5851                         val + reg->off, map->record->timer_off);
5852                 return -EINVAL;
5853         }
5854         if (meta->map_ptr) {
5855                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5856                 return -EFAULT;
5857         }
5858         meta->map_uid = reg->map_uid;
5859         meta->map_ptr = map;
5860         return 0;
5861 }
5862
5863 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5864                              struct bpf_call_arg_meta *meta)
5865 {
5866         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5867         struct bpf_map *map_ptr = reg->map_ptr;
5868         struct btf_field *kptr_field;
5869         u32 kptr_off;
5870
5871         if (!tnum_is_const(reg->var_off)) {
5872                 verbose(env,
5873                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5874                         regno);
5875                 return -EINVAL;
5876         }
5877         if (!map_ptr->btf) {
5878                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5879                         map_ptr->name);
5880                 return -EINVAL;
5881         }
5882         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
5883                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5884                 return -EINVAL;
5885         }
5886
5887         meta->map_ptr = map_ptr;
5888         kptr_off = reg->off + reg->var_off.value;
5889         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
5890         if (!kptr_field) {
5891                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5892                 return -EACCES;
5893         }
5894         if (kptr_field->type != BPF_KPTR_REF) {
5895                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5896                 return -EACCES;
5897         }
5898         meta->kptr_field = kptr_field;
5899         return 0;
5900 }
5901
5902 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
5903  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
5904  *
5905  * In both cases we deal with the first 8 bytes, but need to mark the next 8
5906  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
5907  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
5908  *
5909  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
5910  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
5911  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
5912  * mutate the view of the dynptr and also possibly destroy it. In the latter
5913  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
5914  * memory that dynptr points to.
5915  *
5916  * The verifier will keep track both levels of mutation (bpf_dynptr's in
5917  * reg->type and the memory's in reg->dynptr.type), but there is no support for
5918  * readonly dynptr view yet, hence only the first case is tracked and checked.
5919  *
5920  * This is consistent with how C applies the const modifier to a struct object,
5921  * where the pointer itself inside bpf_dynptr becomes const but not what it
5922  * points to.
5923  *
5924  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
5925  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
5926  */
5927 int process_dynptr_func(struct bpf_verifier_env *env, int regno,
5928                         enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
5929 {
5930         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5931
5932         /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
5933          * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
5934          */
5935         if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
5936                 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
5937                 return -EFAULT;
5938         }
5939         /* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
5940          * check_func_arg_reg_off's logic. We only need to check offset
5941          * alignment for PTR_TO_STACK.
5942          */
5943         if (reg->type == PTR_TO_STACK && (reg->off % BPF_REG_SIZE)) {
5944                 verbose(env, "cannot pass in dynptr at an offset=%d\n", reg->off);
5945                 return -EINVAL;
5946         }
5947         /*  MEM_UNINIT - Points to memory that is an appropriate candidate for
5948          *               constructing a mutable bpf_dynptr object.
5949          *
5950          *               Currently, this is only possible with PTR_TO_STACK
5951          *               pointing to a region of at least 16 bytes which doesn't
5952          *               contain an existing bpf_dynptr.
5953          *
5954          *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
5955          *               mutated or destroyed. However, the memory it points to
5956          *               may be mutated.
5957          *
5958          *  None       - Points to a initialized dynptr that can be mutated and
5959          *               destroyed, including mutation of the memory it points
5960          *               to.
5961          */
5962         if (arg_type & MEM_UNINIT) {
5963                 if (!is_dynptr_reg_valid_uninit(env, reg)) {
5964                         verbose(env, "Dynptr has to be an uninitialized dynptr\n");
5965                         return -EINVAL;
5966                 }
5967
5968                 /* We only support one dynptr being uninitialized at the moment,
5969                  * which is sufficient for the helper functions we have right now.
5970                  */
5971                 if (meta->uninit_dynptr_regno) {
5972                         verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
5973                         return -EFAULT;
5974                 }
5975
5976                 meta->uninit_dynptr_regno = regno;
5977         } else /* MEM_RDONLY and None case from above */ {
5978                 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
5979                 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
5980                         verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
5981                         return -EINVAL;
5982                 }
5983
5984                 if (!is_dynptr_reg_valid_init(env, reg)) {
5985                         verbose(env,
5986                                 "Expected an initialized dynptr as arg #%d\n",
5987                                 regno);
5988                         return -EINVAL;
5989                 }
5990
5991                 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
5992                 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
5993                         const char *err_extra = "";
5994
5995                         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
5996                         case DYNPTR_TYPE_LOCAL:
5997                                 err_extra = "local";
5998                                 break;
5999                         case DYNPTR_TYPE_RINGBUF:
6000                                 err_extra = "ringbuf";
6001                                 break;
6002                         default:
6003                                 err_extra = "<unknown>";
6004                                 break;
6005                         }
6006                         verbose(env,
6007                                 "Expected a dynptr of type %s as arg #%d\n",
6008                                 err_extra, regno);
6009                         return -EINVAL;
6010                 }
6011         }
6012         return 0;
6013 }
6014
6015 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6016 {
6017         return type == ARG_CONST_SIZE ||
6018                type == ARG_CONST_SIZE_OR_ZERO;
6019 }
6020
6021 static bool arg_type_is_release(enum bpf_arg_type type)
6022 {
6023         return type & OBJ_RELEASE;
6024 }
6025
6026 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6027 {
6028         return base_type(type) == ARG_PTR_TO_DYNPTR;
6029 }
6030
6031 static int int_ptr_type_to_size(enum bpf_arg_type type)
6032 {
6033         if (type == ARG_PTR_TO_INT)
6034                 return sizeof(u32);
6035         else if (type == ARG_PTR_TO_LONG)
6036                 return sizeof(u64);
6037
6038         return -EINVAL;
6039 }
6040
6041 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6042                                  const struct bpf_call_arg_meta *meta,
6043                                  enum bpf_arg_type *arg_type)
6044 {
6045         if (!meta->map_ptr) {
6046                 /* kernel subsystem misconfigured verifier */
6047                 verbose(env, "invalid map_ptr to access map->type\n");
6048                 return -EACCES;
6049         }
6050
6051         switch (meta->map_ptr->map_type) {
6052         case BPF_MAP_TYPE_SOCKMAP:
6053         case BPF_MAP_TYPE_SOCKHASH:
6054                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6055                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6056                 } else {
6057                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
6058                         return -EINVAL;
6059                 }
6060                 break;
6061         case BPF_MAP_TYPE_BLOOM_FILTER:
6062                 if (meta->func_id == BPF_FUNC_map_peek_elem)
6063                         *arg_type = ARG_PTR_TO_MAP_VALUE;
6064                 break;
6065         default:
6066                 break;
6067         }
6068         return 0;
6069 }
6070
6071 struct bpf_reg_types {
6072         const enum bpf_reg_type types[10];
6073         u32 *btf_id;
6074 };
6075
6076 static const struct bpf_reg_types sock_types = {
6077         .types = {
6078                 PTR_TO_SOCK_COMMON,
6079                 PTR_TO_SOCKET,
6080                 PTR_TO_TCP_SOCK,
6081                 PTR_TO_XDP_SOCK,
6082         },
6083 };
6084
6085 #ifdef CONFIG_NET
6086 static const struct bpf_reg_types btf_id_sock_common_types = {
6087         .types = {
6088                 PTR_TO_SOCK_COMMON,
6089                 PTR_TO_SOCKET,
6090                 PTR_TO_TCP_SOCK,
6091                 PTR_TO_XDP_SOCK,
6092                 PTR_TO_BTF_ID,
6093                 PTR_TO_BTF_ID | PTR_TRUSTED,
6094         },
6095         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6096 };
6097 #endif
6098
6099 static const struct bpf_reg_types mem_types = {
6100         .types = {
6101                 PTR_TO_STACK,
6102                 PTR_TO_PACKET,
6103                 PTR_TO_PACKET_META,
6104                 PTR_TO_MAP_KEY,
6105                 PTR_TO_MAP_VALUE,
6106                 PTR_TO_MEM,
6107                 PTR_TO_MEM | MEM_RINGBUF,
6108                 PTR_TO_BUF,
6109         },
6110 };
6111
6112 static const struct bpf_reg_types int_ptr_types = {
6113         .types = {
6114                 PTR_TO_STACK,
6115                 PTR_TO_PACKET,
6116                 PTR_TO_PACKET_META,
6117                 PTR_TO_MAP_KEY,
6118                 PTR_TO_MAP_VALUE,
6119         },
6120 };
6121
6122 static const struct bpf_reg_types spin_lock_types = {
6123         .types = {
6124                 PTR_TO_MAP_VALUE,
6125                 PTR_TO_BTF_ID | MEM_ALLOC,
6126         }
6127 };
6128
6129 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
6130 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
6131 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
6132 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
6133 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
6134 static const struct bpf_reg_types btf_ptr_types = {
6135         .types = {
6136                 PTR_TO_BTF_ID,
6137                 PTR_TO_BTF_ID | PTR_TRUSTED,
6138                 PTR_TO_BTF_ID | MEM_RCU,
6139         },
6140 };
6141 static const struct bpf_reg_types percpu_btf_ptr_types = {
6142         .types = {
6143                 PTR_TO_BTF_ID | MEM_PERCPU,
6144                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
6145         }
6146 };
6147 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
6148 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
6149 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
6150 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
6151 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
6152 static const struct bpf_reg_types dynptr_types = {
6153         .types = {
6154                 PTR_TO_STACK,
6155                 CONST_PTR_TO_DYNPTR,
6156         }
6157 };
6158
6159 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
6160         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
6161         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
6162         [ARG_CONST_SIZE]                = &scalar_types,
6163         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
6164         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
6165         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
6166         [ARG_PTR_TO_CTX]                = &context_types,
6167         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
6168 #ifdef CONFIG_NET
6169         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
6170 #endif
6171         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
6172         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
6173         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
6174         [ARG_PTR_TO_MEM]                = &mem_types,
6175         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
6176         [ARG_PTR_TO_INT]                = &int_ptr_types,
6177         [ARG_PTR_TO_LONG]               = &int_ptr_types,
6178         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
6179         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
6180         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
6181         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
6182         [ARG_PTR_TO_TIMER]              = &timer_types,
6183         [ARG_PTR_TO_KPTR]               = &kptr_types,
6184         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
6185 };
6186
6187 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6188                           enum bpf_arg_type arg_type,
6189                           const u32 *arg_btf_id,
6190                           struct bpf_call_arg_meta *meta)
6191 {
6192         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6193         enum bpf_reg_type expected, type = reg->type;
6194         const struct bpf_reg_types *compatible;
6195         int i, j;
6196
6197         compatible = compatible_reg_types[base_type(arg_type)];
6198         if (!compatible) {
6199                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6200                 return -EFAULT;
6201         }
6202
6203         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6204          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6205          *
6206          * Same for MAYBE_NULL:
6207          *
6208          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6209          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6210          *
6211          * Therefore we fold these flags depending on the arg_type before comparison.
6212          */
6213         if (arg_type & MEM_RDONLY)
6214                 type &= ~MEM_RDONLY;
6215         if (arg_type & PTR_MAYBE_NULL)
6216                 type &= ~PTR_MAYBE_NULL;
6217
6218         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6219                 expected = compatible->types[i];
6220                 if (expected == NOT_INIT)
6221                         break;
6222
6223                 if (type == expected)
6224                         goto found;
6225         }
6226
6227         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6228         for (j = 0; j + 1 < i; j++)
6229                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6230         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6231         return -EACCES;
6232
6233 found:
6234         if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
6235                 /* For bpf_sk_release, it needs to match against first member
6236                  * 'struct sock_common', hence make an exception for it. This
6237                  * allows bpf_sk_release to work for multiple socket types.
6238                  */
6239                 bool strict_type_match = arg_type_is_release(arg_type) &&
6240                                          meta->func_id != BPF_FUNC_sk_release;
6241
6242                 if (!arg_btf_id) {
6243                         if (!compatible->btf_id) {
6244                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6245                                 return -EFAULT;
6246                         }
6247                         arg_btf_id = compatible->btf_id;
6248                 }
6249
6250                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
6251                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6252                                 return -EACCES;
6253                 } else {
6254                         if (arg_btf_id == BPF_PTR_POISON) {
6255                                 verbose(env, "verifier internal error:");
6256                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6257                                         regno);
6258                                 return -EACCES;
6259                         }
6260
6261                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6262                                                   btf_vmlinux, *arg_btf_id,
6263                                                   strict_type_match)) {
6264                                 verbose(env, "R%d is of type %s but %s is expected\n",
6265                                         regno, kernel_type_name(reg->btf, reg->btf_id),
6266                                         kernel_type_name(btf_vmlinux, *arg_btf_id));
6267                                 return -EACCES;
6268                         }
6269                 }
6270         } else if (type_is_alloc(reg->type)) {
6271                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6272                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6273                         return -EFAULT;
6274                 }
6275         }
6276
6277         return 0;
6278 }
6279
6280 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6281                            const struct bpf_reg_state *reg, int regno,
6282                            enum bpf_arg_type arg_type)
6283 {
6284         u32 type = reg->type;
6285
6286         /* When referenced register is passed to release function, its fixed
6287          * offset must be 0.
6288          *
6289          * We will check arg_type_is_release reg has ref_obj_id when storing
6290          * meta->release_regno.
6291          */
6292         if (arg_type_is_release(arg_type)) {
6293                 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
6294                  * may not directly point to the object being released, but to
6295                  * dynptr pointing to such object, which might be at some offset
6296                  * on the stack. In that case, we simply to fallback to the
6297                  * default handling.
6298                  */
6299                 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
6300                         return 0;
6301                 /* Doing check_ptr_off_reg check for the offset will catch this
6302                  * because fixed_off_ok is false, but checking here allows us
6303                  * to give the user a better error message.
6304                  */
6305                 if (reg->off) {
6306                         verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
6307                                 regno);
6308                         return -EINVAL;
6309                 }
6310                 return __check_ptr_off_reg(env, reg, regno, false);
6311         }
6312
6313         switch (type) {
6314         /* Pointer types where both fixed and variable offset is explicitly allowed: */
6315         case PTR_TO_STACK:
6316         case PTR_TO_PACKET:
6317         case PTR_TO_PACKET_META:
6318         case PTR_TO_MAP_KEY:
6319         case PTR_TO_MAP_VALUE:
6320         case PTR_TO_MEM:
6321         case PTR_TO_MEM | MEM_RDONLY:
6322         case PTR_TO_MEM | MEM_RINGBUF:
6323         case PTR_TO_BUF:
6324         case PTR_TO_BUF | MEM_RDONLY:
6325         case SCALAR_VALUE:
6326                 return 0;
6327         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6328          * fixed offset.
6329          */
6330         case PTR_TO_BTF_ID:
6331         case PTR_TO_BTF_ID | MEM_ALLOC:
6332         case PTR_TO_BTF_ID | PTR_TRUSTED:
6333         case PTR_TO_BTF_ID | MEM_RCU:
6334         case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6335                 /* When referenced PTR_TO_BTF_ID is passed to release function,
6336                  * its fixed offset must be 0. In the other cases, fixed offset
6337                  * can be non-zero. This was already checked above. So pass
6338                  * fixed_off_ok as true to allow fixed offset for all other
6339                  * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
6340                  * still need to do checks instead of returning.
6341                  */
6342                 return __check_ptr_off_reg(env, reg, regno, true);
6343         default:
6344                 return __check_ptr_off_reg(env, reg, regno, false);
6345         }
6346 }
6347
6348 static u32 dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6349 {
6350         struct bpf_func_state *state = func(env, reg);
6351         int spi;
6352
6353         if (reg->type == CONST_PTR_TO_DYNPTR)
6354                 return reg->ref_obj_id;
6355
6356         spi = get_spi(reg->off);
6357         return state->stack[spi].spilled_ptr.ref_obj_id;
6358 }
6359
6360 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6361                           struct bpf_call_arg_meta *meta,
6362                           const struct bpf_func_proto *fn)
6363 {
6364         u32 regno = BPF_REG_1 + arg;
6365         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6366         enum bpf_arg_type arg_type = fn->arg_type[arg];
6367         enum bpf_reg_type type = reg->type;
6368         u32 *arg_btf_id = NULL;
6369         int err = 0;
6370
6371         if (arg_type == ARG_DONTCARE)
6372                 return 0;
6373
6374         err = check_reg_arg(env, regno, SRC_OP);
6375         if (err)
6376                 return err;
6377
6378         if (arg_type == ARG_ANYTHING) {
6379                 if (is_pointer_value(env, regno)) {
6380                         verbose(env, "R%d leaks addr into helper function\n",
6381                                 regno);
6382                         return -EACCES;
6383                 }
6384                 return 0;
6385         }
6386
6387         if (type_is_pkt_pointer(type) &&
6388             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6389                 verbose(env, "helper access to the packet is not allowed\n");
6390                 return -EACCES;
6391         }
6392
6393         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6394                 err = resolve_map_arg_type(env, meta, &arg_type);
6395                 if (err)
6396                         return err;
6397         }
6398
6399         if (register_is_null(reg) && type_may_be_null(arg_type))
6400                 /* A NULL register has a SCALAR_VALUE type, so skip
6401                  * type checking.
6402                  */
6403                 goto skip_type_check;
6404
6405         /* arg_btf_id and arg_size are in a union. */
6406         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6407             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6408                 arg_btf_id = fn->arg_btf_id[arg];
6409
6410         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6411         if (err)
6412                 return err;
6413
6414         err = check_func_arg_reg_off(env, reg, regno, arg_type);
6415         if (err)
6416                 return err;
6417
6418 skip_type_check:
6419         if (arg_type_is_release(arg_type)) {
6420                 if (arg_type_is_dynptr(arg_type)) {
6421                         struct bpf_func_state *state = func(env, reg);
6422                         int spi;
6423
6424                         /* Only dynptr created on stack can be released, thus
6425                          * the get_spi and stack state checks for spilled_ptr
6426                          * should only be done before process_dynptr_func for
6427                          * PTR_TO_STACK.
6428                          */
6429                         if (reg->type == PTR_TO_STACK) {
6430                                 spi = get_spi(reg->off);
6431                                 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6432                                     !state->stack[spi].spilled_ptr.ref_obj_id) {
6433                                         verbose(env, "arg %d is an unacquired reference\n", regno);
6434                                         return -EINVAL;
6435                                 }
6436                         } else {
6437                                 verbose(env, "cannot release unowned const bpf_dynptr\n");
6438                                 return -EINVAL;
6439                         }
6440                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6441                         verbose(env, "R%d must be referenced when passed to release function\n",
6442                                 regno);
6443                         return -EINVAL;
6444                 }
6445                 if (meta->release_regno) {
6446                         verbose(env, "verifier internal error: more than one release argument\n");
6447                         return -EFAULT;
6448                 }
6449                 meta->release_regno = regno;
6450         }
6451
6452         if (reg->ref_obj_id) {
6453                 if (meta->ref_obj_id) {
6454                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6455                                 regno, reg->ref_obj_id,
6456                                 meta->ref_obj_id);
6457                         return -EFAULT;
6458                 }
6459                 meta->ref_obj_id = reg->ref_obj_id;
6460         }
6461
6462         switch (base_type(arg_type)) {
6463         case ARG_CONST_MAP_PTR:
6464                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6465                 if (meta->map_ptr) {
6466                         /* Use map_uid (which is unique id of inner map) to reject:
6467                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6468                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6469                          * if (inner_map1 && inner_map2) {
6470                          *     timer = bpf_map_lookup_elem(inner_map1);
6471                          *     if (timer)
6472                          *         // mismatch would have been allowed
6473                          *         bpf_timer_init(timer, inner_map2);
6474                          * }
6475                          *
6476                          * Comparing map_ptr is enough to distinguish normal and outer maps.
6477                          */
6478                         if (meta->map_ptr != reg->map_ptr ||
6479                             meta->map_uid != reg->map_uid) {
6480                                 verbose(env,
6481                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6482                                         meta->map_uid, reg->map_uid);
6483                                 return -EINVAL;
6484                         }
6485                 }
6486                 meta->map_ptr = reg->map_ptr;
6487                 meta->map_uid = reg->map_uid;
6488                 break;
6489         case ARG_PTR_TO_MAP_KEY:
6490                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6491                  * check that [key, key + map->key_size) are within
6492                  * stack limits and initialized
6493                  */
6494                 if (!meta->map_ptr) {
6495                         /* in function declaration map_ptr must come before
6496                          * map_key, so that it's verified and known before
6497                          * we have to check map_key here. Otherwise it means
6498                          * that kernel subsystem misconfigured verifier
6499                          */
6500                         verbose(env, "invalid map_ptr to access map->key\n");
6501                         return -EACCES;
6502                 }
6503                 err = check_helper_mem_access(env, regno,
6504                                               meta->map_ptr->key_size, false,
6505                                               NULL);
6506                 break;
6507         case ARG_PTR_TO_MAP_VALUE:
6508                 if (type_may_be_null(arg_type) && register_is_null(reg))
6509                         return 0;
6510
6511                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6512                  * check [value, value + map->value_size) validity
6513                  */
6514                 if (!meta->map_ptr) {
6515                         /* kernel subsystem misconfigured verifier */
6516                         verbose(env, "invalid map_ptr to access map->value\n");
6517                         return -EACCES;
6518                 }
6519                 meta->raw_mode = arg_type & MEM_UNINIT;
6520                 err = check_helper_mem_access(env, regno,
6521                                               meta->map_ptr->value_size, false,
6522                                               meta);
6523                 break;
6524         case ARG_PTR_TO_PERCPU_BTF_ID:
6525                 if (!reg->btf_id) {
6526                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6527                         return -EACCES;
6528                 }
6529                 meta->ret_btf = reg->btf;
6530                 meta->ret_btf_id = reg->btf_id;
6531                 break;
6532         case ARG_PTR_TO_SPIN_LOCK:
6533                 if (meta->func_id == BPF_FUNC_spin_lock) {
6534                         err = process_spin_lock(env, regno, true);
6535                         if (err)
6536                                 return err;
6537                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6538                         err = process_spin_lock(env, regno, false);
6539                         if (err)
6540                                 return err;
6541                 } else {
6542                         verbose(env, "verifier internal error\n");
6543                         return -EFAULT;
6544                 }
6545                 break;
6546         case ARG_PTR_TO_TIMER:
6547                 err = process_timer_func(env, regno, meta);
6548                 if (err)
6549                         return err;
6550                 break;
6551         case ARG_PTR_TO_FUNC:
6552                 meta->subprogno = reg->subprogno;
6553                 break;
6554         case ARG_PTR_TO_MEM:
6555                 /* The access to this pointer is only checked when we hit the
6556                  * next is_mem_size argument below.
6557                  */
6558                 meta->raw_mode = arg_type & MEM_UNINIT;
6559                 if (arg_type & MEM_FIXED_SIZE) {
6560                         err = check_helper_mem_access(env, regno,
6561                                                       fn->arg_size[arg], false,
6562                                                       meta);
6563                 }
6564                 break;
6565         case ARG_CONST_SIZE:
6566                 err = check_mem_size_reg(env, reg, regno, false, meta);
6567                 break;
6568         case ARG_CONST_SIZE_OR_ZERO:
6569                 err = check_mem_size_reg(env, reg, regno, true, meta);
6570                 break;
6571         case ARG_PTR_TO_DYNPTR:
6572                 err = process_dynptr_func(env, regno, arg_type, meta);
6573                 if (err)
6574                         return err;
6575                 break;
6576         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6577                 if (!tnum_is_const(reg->var_off)) {
6578                         verbose(env, "R%d is not a known constant'\n",
6579                                 regno);
6580                         return -EACCES;
6581                 }
6582                 meta->mem_size = reg->var_off.value;
6583                 err = mark_chain_precision(env, regno);
6584                 if (err)
6585                         return err;
6586                 break;
6587         case ARG_PTR_TO_INT:
6588         case ARG_PTR_TO_LONG:
6589         {
6590                 int size = int_ptr_type_to_size(arg_type);
6591
6592                 err = check_helper_mem_access(env, regno, size, false, meta);
6593                 if (err)
6594                         return err;
6595                 err = check_ptr_alignment(env, reg, 0, size, true);
6596                 break;
6597         }
6598         case ARG_PTR_TO_CONST_STR:
6599         {
6600                 struct bpf_map *map = reg->map_ptr;
6601                 int map_off;
6602                 u64 map_addr;
6603                 char *str_ptr;
6604
6605                 if (!bpf_map_is_rdonly(map)) {
6606                         verbose(env, "R%d does not point to a readonly map'\n", regno);
6607                         return -EACCES;
6608                 }
6609
6610                 if (!tnum_is_const(reg->var_off)) {
6611                         verbose(env, "R%d is not a constant address'\n", regno);
6612                         return -EACCES;
6613                 }
6614
6615                 if (!map->ops->map_direct_value_addr) {
6616                         verbose(env, "no direct value access support for this map type\n");
6617                         return -EACCES;
6618                 }
6619
6620                 err = check_map_access(env, regno, reg->off,
6621                                        map->value_size - reg->off, false,
6622                                        ACCESS_HELPER);
6623                 if (err)
6624                         return err;
6625
6626                 map_off = reg->off + reg->var_off.value;
6627                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6628                 if (err) {
6629                         verbose(env, "direct value access on string failed\n");
6630                         return err;
6631                 }
6632
6633                 str_ptr = (char *)(long)(map_addr);
6634                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6635                         verbose(env, "string is not zero-terminated\n");
6636                         return -EINVAL;
6637                 }
6638                 break;
6639         }
6640         case ARG_PTR_TO_KPTR:
6641                 err = process_kptr_func(env, regno, meta);
6642                 if (err)
6643                         return err;
6644                 break;
6645         }
6646
6647         return err;
6648 }
6649
6650 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6651 {
6652         enum bpf_attach_type eatype = env->prog->expected_attach_type;
6653         enum bpf_prog_type type = resolve_prog_type(env->prog);
6654
6655         if (func_id != BPF_FUNC_map_update_elem)
6656                 return false;
6657
6658         /* It's not possible to get access to a locked struct sock in these
6659          * contexts, so updating is safe.
6660          */
6661         switch (type) {
6662         case BPF_PROG_TYPE_TRACING:
6663                 if (eatype == BPF_TRACE_ITER)
6664                         return true;
6665                 break;
6666         case BPF_PROG_TYPE_SOCKET_FILTER:
6667         case BPF_PROG_TYPE_SCHED_CLS:
6668         case BPF_PROG_TYPE_SCHED_ACT:
6669         case BPF_PROG_TYPE_XDP:
6670         case BPF_PROG_TYPE_SK_REUSEPORT:
6671         case BPF_PROG_TYPE_FLOW_DISSECTOR:
6672         case BPF_PROG_TYPE_SK_LOOKUP:
6673                 return true;
6674         default:
6675                 break;
6676         }
6677
6678         verbose(env, "cannot update sockmap in this context\n");
6679         return false;
6680 }
6681
6682 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6683 {
6684         return env->prog->jit_requested &&
6685                bpf_jit_supports_subprog_tailcalls();
6686 }
6687
6688 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6689                                         struct bpf_map *map, int func_id)
6690 {
6691         if (!map)
6692                 return 0;
6693
6694         /* We need a two way check, first is from map perspective ... */
6695         switch (map->map_type) {
6696         case BPF_MAP_TYPE_PROG_ARRAY:
6697                 if (func_id != BPF_FUNC_tail_call)
6698                         goto error;
6699                 break;
6700         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6701                 if (func_id != BPF_FUNC_perf_event_read &&
6702                     func_id != BPF_FUNC_perf_event_output &&
6703                     func_id != BPF_FUNC_skb_output &&
6704                     func_id != BPF_FUNC_perf_event_read_value &&
6705                     func_id != BPF_FUNC_xdp_output)
6706                         goto error;
6707                 break;
6708         case BPF_MAP_TYPE_RINGBUF:
6709                 if (func_id != BPF_FUNC_ringbuf_output &&
6710                     func_id != BPF_FUNC_ringbuf_reserve &&
6711                     func_id != BPF_FUNC_ringbuf_query &&
6712                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6713                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6714                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
6715                         goto error;
6716                 break;
6717         case BPF_MAP_TYPE_USER_RINGBUF:
6718                 if (func_id != BPF_FUNC_user_ringbuf_drain)
6719                         goto error;
6720                 break;
6721         case BPF_MAP_TYPE_STACK_TRACE:
6722                 if (func_id != BPF_FUNC_get_stackid)
6723                         goto error;
6724                 break;
6725         case BPF_MAP_TYPE_CGROUP_ARRAY:
6726                 if (func_id != BPF_FUNC_skb_under_cgroup &&
6727                     func_id != BPF_FUNC_current_task_under_cgroup)
6728                         goto error;
6729                 break;
6730         case BPF_MAP_TYPE_CGROUP_STORAGE:
6731         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6732                 if (func_id != BPF_FUNC_get_local_storage)
6733                         goto error;
6734                 break;
6735         case BPF_MAP_TYPE_DEVMAP:
6736         case BPF_MAP_TYPE_DEVMAP_HASH:
6737                 if (func_id != BPF_FUNC_redirect_map &&
6738                     func_id != BPF_FUNC_map_lookup_elem)
6739                         goto error;
6740                 break;
6741         /* Restrict bpf side of cpumap and xskmap, open when use-cases
6742          * appear.
6743          */
6744         case BPF_MAP_TYPE_CPUMAP:
6745                 if (func_id != BPF_FUNC_redirect_map)
6746                         goto error;
6747                 break;
6748         case BPF_MAP_TYPE_XSKMAP:
6749                 if (func_id != BPF_FUNC_redirect_map &&
6750                     func_id != BPF_FUNC_map_lookup_elem)
6751                         goto error;
6752                 break;
6753         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6754         case BPF_MAP_TYPE_HASH_OF_MAPS:
6755                 if (func_id != BPF_FUNC_map_lookup_elem)
6756                         goto error;
6757                 break;
6758         case BPF_MAP_TYPE_SOCKMAP:
6759                 if (func_id != BPF_FUNC_sk_redirect_map &&
6760                     func_id != BPF_FUNC_sock_map_update &&
6761                     func_id != BPF_FUNC_map_delete_elem &&
6762                     func_id != BPF_FUNC_msg_redirect_map &&
6763                     func_id != BPF_FUNC_sk_select_reuseport &&
6764                     func_id != BPF_FUNC_map_lookup_elem &&
6765                     !may_update_sockmap(env, func_id))
6766                         goto error;
6767                 break;
6768         case BPF_MAP_TYPE_SOCKHASH:
6769                 if (func_id != BPF_FUNC_sk_redirect_hash &&
6770                     func_id != BPF_FUNC_sock_hash_update &&
6771                     func_id != BPF_FUNC_map_delete_elem &&
6772                     func_id != BPF_FUNC_msg_redirect_hash &&
6773                     func_id != BPF_FUNC_sk_select_reuseport &&
6774                     func_id != BPF_FUNC_map_lookup_elem &&
6775                     !may_update_sockmap(env, func_id))
6776                         goto error;
6777                 break;
6778         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6779                 if (func_id != BPF_FUNC_sk_select_reuseport)
6780                         goto error;
6781                 break;
6782         case BPF_MAP_TYPE_QUEUE:
6783         case BPF_MAP_TYPE_STACK:
6784                 if (func_id != BPF_FUNC_map_peek_elem &&
6785                     func_id != BPF_FUNC_map_pop_elem &&
6786                     func_id != BPF_FUNC_map_push_elem)
6787                         goto error;
6788                 break;
6789         case BPF_MAP_TYPE_SK_STORAGE:
6790                 if (func_id != BPF_FUNC_sk_storage_get &&
6791                     func_id != BPF_FUNC_sk_storage_delete)
6792                         goto error;
6793                 break;
6794         case BPF_MAP_TYPE_INODE_STORAGE:
6795                 if (func_id != BPF_FUNC_inode_storage_get &&
6796                     func_id != BPF_FUNC_inode_storage_delete)
6797                         goto error;
6798                 break;
6799         case BPF_MAP_TYPE_TASK_STORAGE:
6800                 if (func_id != BPF_FUNC_task_storage_get &&
6801                     func_id != BPF_FUNC_task_storage_delete)
6802                         goto error;
6803                 break;
6804         case BPF_MAP_TYPE_CGRP_STORAGE:
6805                 if (func_id != BPF_FUNC_cgrp_storage_get &&
6806                     func_id != BPF_FUNC_cgrp_storage_delete)
6807                         goto error;
6808                 break;
6809         case BPF_MAP_TYPE_BLOOM_FILTER:
6810                 if (func_id != BPF_FUNC_map_peek_elem &&
6811                     func_id != BPF_FUNC_map_push_elem)
6812                         goto error;
6813                 break;
6814         default:
6815                 break;
6816         }
6817
6818         /* ... and second from the function itself. */
6819         switch (func_id) {
6820         case BPF_FUNC_tail_call:
6821                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6822                         goto error;
6823                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6824                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6825                         return -EINVAL;
6826                 }
6827                 break;
6828         case BPF_FUNC_perf_event_read:
6829         case BPF_FUNC_perf_event_output:
6830         case BPF_FUNC_perf_event_read_value:
6831         case BPF_FUNC_skb_output:
6832         case BPF_FUNC_xdp_output:
6833                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6834                         goto error;
6835                 break;
6836         case BPF_FUNC_ringbuf_output:
6837         case BPF_FUNC_ringbuf_reserve:
6838         case BPF_FUNC_ringbuf_query:
6839         case BPF_FUNC_ringbuf_reserve_dynptr:
6840         case BPF_FUNC_ringbuf_submit_dynptr:
6841         case BPF_FUNC_ringbuf_discard_dynptr:
6842                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6843                         goto error;
6844                 break;
6845         case BPF_FUNC_user_ringbuf_drain:
6846                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6847                         goto error;
6848                 break;
6849         case BPF_FUNC_get_stackid:
6850                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6851                         goto error;
6852                 break;
6853         case BPF_FUNC_current_task_under_cgroup:
6854         case BPF_FUNC_skb_under_cgroup:
6855                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6856                         goto error;
6857                 break;
6858         case BPF_FUNC_redirect_map:
6859                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6860                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6861                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
6862                     map->map_type != BPF_MAP_TYPE_XSKMAP)
6863                         goto error;
6864                 break;
6865         case BPF_FUNC_sk_redirect_map:
6866         case BPF_FUNC_msg_redirect_map:
6867         case BPF_FUNC_sock_map_update:
6868                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6869                         goto error;
6870                 break;
6871         case BPF_FUNC_sk_redirect_hash:
6872         case BPF_FUNC_msg_redirect_hash:
6873         case BPF_FUNC_sock_hash_update:
6874                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6875                         goto error;
6876                 break;
6877         case BPF_FUNC_get_local_storage:
6878                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6879                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6880                         goto error;
6881                 break;
6882         case BPF_FUNC_sk_select_reuseport:
6883                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6884                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6885                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
6886                         goto error;
6887                 break;
6888         case BPF_FUNC_map_pop_elem:
6889                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6890                     map->map_type != BPF_MAP_TYPE_STACK)
6891                         goto error;
6892                 break;
6893         case BPF_FUNC_map_peek_elem:
6894         case BPF_FUNC_map_push_elem:
6895                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6896                     map->map_type != BPF_MAP_TYPE_STACK &&
6897                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6898                         goto error;
6899                 break;
6900         case BPF_FUNC_map_lookup_percpu_elem:
6901                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6902                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6903                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6904                         goto error;
6905                 break;
6906         case BPF_FUNC_sk_storage_get:
6907         case BPF_FUNC_sk_storage_delete:
6908                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6909                         goto error;
6910                 break;
6911         case BPF_FUNC_inode_storage_get:
6912         case BPF_FUNC_inode_storage_delete:
6913                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6914                         goto error;
6915                 break;
6916         case BPF_FUNC_task_storage_get:
6917         case BPF_FUNC_task_storage_delete:
6918                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6919                         goto error;
6920                 break;
6921         case BPF_FUNC_cgrp_storage_get:
6922         case BPF_FUNC_cgrp_storage_delete:
6923                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
6924                         goto error;
6925                 break;
6926         default:
6927                 break;
6928         }
6929
6930         return 0;
6931 error:
6932         verbose(env, "cannot pass map_type %d into func %s#%d\n",
6933                 map->map_type, func_id_name(func_id), func_id);
6934         return -EINVAL;
6935 }
6936
6937 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6938 {
6939         int count = 0;
6940
6941         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6942                 count++;
6943         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6944                 count++;
6945         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6946                 count++;
6947         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6948                 count++;
6949         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6950                 count++;
6951
6952         /* We only support one arg being in raw mode at the moment,
6953          * which is sufficient for the helper functions we have
6954          * right now.
6955          */
6956         return count <= 1;
6957 }
6958
6959 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6960 {
6961         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6962         bool has_size = fn->arg_size[arg] != 0;
6963         bool is_next_size = false;
6964
6965         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6966                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6967
6968         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6969                 return is_next_size;
6970
6971         return has_size == is_next_size || is_next_size == is_fixed;
6972 }
6973
6974 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6975 {
6976         /* bpf_xxx(..., buf, len) call will access 'len'
6977          * bytes from memory 'buf'. Both arg types need
6978          * to be paired, so make sure there's no buggy
6979          * helper function specification.
6980          */
6981         if (arg_type_is_mem_size(fn->arg1_type) ||
6982             check_args_pair_invalid(fn, 0) ||
6983             check_args_pair_invalid(fn, 1) ||
6984             check_args_pair_invalid(fn, 2) ||
6985             check_args_pair_invalid(fn, 3) ||
6986             check_args_pair_invalid(fn, 4))
6987                 return false;
6988
6989         return true;
6990 }
6991
6992 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6993 {
6994         int i;
6995
6996         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6997                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
6998                         return !!fn->arg_btf_id[i];
6999                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
7000                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
7001                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
7002                     /* arg_btf_id and arg_size are in a union. */
7003                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
7004                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
7005                         return false;
7006         }
7007
7008         return true;
7009 }
7010
7011 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
7012 {
7013         return check_raw_mode_ok(fn) &&
7014                check_arg_pair_ok(fn) &&
7015                check_btf_id_ok(fn) ? 0 : -EINVAL;
7016 }
7017
7018 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
7019  * are now invalid, so turn them into unknown SCALAR_VALUE.
7020  */
7021 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
7022 {
7023         struct bpf_func_state *state;
7024         struct bpf_reg_state *reg;
7025
7026         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7027                 if (reg_is_pkt_pointer_any(reg))
7028                         __mark_reg_unknown(env, reg);
7029         }));
7030 }
7031
7032 enum {
7033         AT_PKT_END = -1,
7034         BEYOND_PKT_END = -2,
7035 };
7036
7037 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
7038 {
7039         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7040         struct bpf_reg_state *reg = &state->regs[regn];
7041
7042         if (reg->type != PTR_TO_PACKET)
7043                 /* PTR_TO_PACKET_META is not supported yet */
7044                 return;
7045
7046         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
7047          * How far beyond pkt_end it goes is unknown.
7048          * if (!range_open) it's the case of pkt >= pkt_end
7049          * if (range_open) it's the case of pkt > pkt_end
7050          * hence this pointer is at least 1 byte bigger than pkt_end
7051          */
7052         if (range_open)
7053                 reg->range = BEYOND_PKT_END;
7054         else
7055                 reg->range = AT_PKT_END;
7056 }
7057
7058 /* The pointer with the specified id has released its reference to kernel
7059  * resources. Identify all copies of the same pointer and clear the reference.
7060  */
7061 static int release_reference(struct bpf_verifier_env *env,
7062                              int ref_obj_id)
7063 {
7064         struct bpf_func_state *state;
7065         struct bpf_reg_state *reg;
7066         int err;
7067
7068         err = release_reference_state(cur_func(env), ref_obj_id);
7069         if (err)
7070                 return err;
7071
7072         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7073                 if (reg->ref_obj_id == ref_obj_id) {
7074                         if (!env->allow_ptr_leaks)
7075                                 __mark_reg_not_init(env, reg);
7076                         else
7077                                 __mark_reg_unknown(env, reg);
7078                 }
7079         }));
7080
7081         return 0;
7082 }
7083
7084 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
7085                                     struct bpf_reg_state *regs)
7086 {
7087         int i;
7088
7089         /* after the call registers r0 - r5 were scratched */
7090         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7091                 mark_reg_not_init(env, regs, caller_saved[i]);
7092                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7093         }
7094 }
7095
7096 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
7097                                    struct bpf_func_state *caller,
7098                                    struct bpf_func_state *callee,
7099                                    int insn_idx);
7100
7101 static int set_callee_state(struct bpf_verifier_env *env,
7102                             struct bpf_func_state *caller,
7103                             struct bpf_func_state *callee, int insn_idx);
7104
7105 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7106                              int *insn_idx, int subprog,
7107                              set_callee_state_fn set_callee_state_cb)
7108 {
7109         struct bpf_verifier_state *state = env->cur_state;
7110         struct bpf_func_info_aux *func_info_aux;
7111         struct bpf_func_state *caller, *callee;
7112         int err;
7113         bool is_global = false;
7114
7115         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
7116                 verbose(env, "the call stack of %d frames is too deep\n",
7117                         state->curframe + 2);
7118                 return -E2BIG;
7119         }
7120
7121         caller = state->frame[state->curframe];
7122         if (state->frame[state->curframe + 1]) {
7123                 verbose(env, "verifier bug. Frame %d already allocated\n",
7124                         state->curframe + 1);
7125                 return -EFAULT;
7126         }
7127
7128         func_info_aux = env->prog->aux->func_info_aux;
7129         if (func_info_aux)
7130                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
7131         err = btf_check_subprog_call(env, subprog, caller->regs);
7132         if (err == -EFAULT)
7133                 return err;
7134         if (is_global) {
7135                 if (err) {
7136                         verbose(env, "Caller passes invalid args into func#%d\n",
7137                                 subprog);
7138                         return err;
7139                 } else {
7140                         if (env->log.level & BPF_LOG_LEVEL)
7141                                 verbose(env,
7142                                         "Func#%d is global and valid. Skipping.\n",
7143                                         subprog);
7144                         clear_caller_saved_regs(env, caller->regs);
7145
7146                         /* All global functions return a 64-bit SCALAR_VALUE */
7147                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
7148                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7149
7150                         /* continue with next insn after call */
7151                         return 0;
7152                 }
7153         }
7154
7155         /* set_callee_state is used for direct subprog calls, but we are
7156          * interested in validating only BPF helpers that can call subprogs as
7157          * callbacks
7158          */
7159         if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
7160                 verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
7161                         func_id_name(insn->imm), insn->imm);
7162                 return -EFAULT;
7163         }
7164
7165         if (insn->code == (BPF_JMP | BPF_CALL) &&
7166             insn->src_reg == 0 &&
7167             insn->imm == BPF_FUNC_timer_set_callback) {
7168                 struct bpf_verifier_state *async_cb;
7169
7170                 /* there is no real recursion here. timer callbacks are async */
7171                 env->subprog_info[subprog].is_async_cb = true;
7172                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7173                                          *insn_idx, subprog);
7174                 if (!async_cb)
7175                         return -EFAULT;
7176                 callee = async_cb->frame[0];
7177                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
7178
7179                 /* Convert bpf_timer_set_callback() args into timer callback args */
7180                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
7181                 if (err)
7182                         return err;
7183
7184                 clear_caller_saved_regs(env, caller->regs);
7185                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
7186                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7187                 /* continue with next insn after call */
7188                 return 0;
7189         }
7190
7191         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7192         if (!callee)
7193                 return -ENOMEM;
7194         state->frame[state->curframe + 1] = callee;
7195
7196         /* callee cannot access r0, r6 - r9 for reading and has to write
7197          * into its own stack before reading from it.
7198          * callee can read/write into caller's stack
7199          */
7200         init_func_state(env, callee,
7201                         /* remember the callsite, it will be used by bpf_exit */
7202                         *insn_idx /* callsite */,
7203                         state->curframe + 1 /* frameno within this callchain */,
7204                         subprog /* subprog number within this prog */);
7205
7206         /* Transfer references to the callee */
7207         err = copy_reference_state(callee, caller);
7208         if (err)
7209                 goto err_out;
7210
7211         err = set_callee_state_cb(env, caller, callee, *insn_idx);
7212         if (err)
7213                 goto err_out;
7214
7215         clear_caller_saved_regs(env, caller->regs);
7216
7217         /* only increment it after check_reg_arg() finished */
7218         state->curframe++;
7219
7220         /* and go analyze first insn of the callee */
7221         *insn_idx = env->subprog_info[subprog].start - 1;
7222
7223         if (env->log.level & BPF_LOG_LEVEL) {
7224                 verbose(env, "caller:\n");
7225                 print_verifier_state(env, caller, true);
7226                 verbose(env, "callee:\n");
7227                 print_verifier_state(env, callee, true);
7228         }
7229         return 0;
7230
7231 err_out:
7232         free_func_state(callee);
7233         state->frame[state->curframe + 1] = NULL;
7234         return err;
7235 }
7236
7237 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7238                                    struct bpf_func_state *caller,
7239                                    struct bpf_func_state *callee)
7240 {
7241         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7242          *      void *callback_ctx, u64 flags);
7243          * callback_fn(struct bpf_map *map, void *key, void *value,
7244          *      void *callback_ctx);
7245          */
7246         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7247
7248         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7249         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7250         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7251
7252         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7253         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7254         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7255
7256         /* pointer to stack or null */
7257         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7258
7259         /* unused */
7260         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7261         return 0;
7262 }
7263
7264 static int set_callee_state(struct bpf_verifier_env *env,
7265                             struct bpf_func_state *caller,
7266                             struct bpf_func_state *callee, int insn_idx)
7267 {
7268         int i;
7269
7270         /* copy r1 - r5 args that callee can access.  The copy includes parent
7271          * pointers, which connects us up to the liveness chain
7272          */
7273         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7274                 callee->regs[i] = caller->regs[i];
7275         return 0;
7276 }
7277
7278 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7279                            int *insn_idx)
7280 {
7281         int subprog, target_insn;
7282
7283         target_insn = *insn_idx + insn->imm + 1;
7284         subprog = find_subprog(env, target_insn);
7285         if (subprog < 0) {
7286                 verbose(env, "verifier bug. No program starts at insn %d\n",
7287                         target_insn);
7288                 return -EFAULT;
7289         }
7290
7291         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7292 }
7293
7294 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7295                                        struct bpf_func_state *caller,
7296                                        struct bpf_func_state *callee,
7297                                        int insn_idx)
7298 {
7299         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7300         struct bpf_map *map;
7301         int err;
7302
7303         if (bpf_map_ptr_poisoned(insn_aux)) {
7304                 verbose(env, "tail_call abusing map_ptr\n");
7305                 return -EINVAL;
7306         }
7307
7308         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7309         if (!map->ops->map_set_for_each_callback_args ||
7310             !map->ops->map_for_each_callback) {
7311                 verbose(env, "callback function not allowed for map\n");
7312                 return -ENOTSUPP;
7313         }
7314
7315         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7316         if (err)
7317                 return err;
7318
7319         callee->in_callback_fn = true;
7320         callee->callback_ret_range = tnum_range(0, 1);
7321         return 0;
7322 }
7323
7324 static int set_loop_callback_state(struct bpf_verifier_env *env,
7325                                    struct bpf_func_state *caller,
7326                                    struct bpf_func_state *callee,
7327                                    int insn_idx)
7328 {
7329         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7330          *          u64 flags);
7331          * callback_fn(u32 index, void *callback_ctx);
7332          */
7333         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7334         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7335
7336         /* unused */
7337         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7338         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7339         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7340
7341         callee->in_callback_fn = true;
7342         callee->callback_ret_range = tnum_range(0, 1);
7343         return 0;
7344 }
7345
7346 static int set_timer_callback_state(struct bpf_verifier_env *env,
7347                                     struct bpf_func_state *caller,
7348                                     struct bpf_func_state *callee,
7349                                     int insn_idx)
7350 {
7351         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7352
7353         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7354          * callback_fn(struct bpf_map *map, void *key, void *value);
7355          */
7356         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7357         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7358         callee->regs[BPF_REG_1].map_ptr = map_ptr;
7359
7360         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7361         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7362         callee->regs[BPF_REG_2].map_ptr = map_ptr;
7363
7364         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7365         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7366         callee->regs[BPF_REG_3].map_ptr = map_ptr;
7367
7368         /* unused */
7369         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7370         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7371         callee->in_async_callback_fn = true;
7372         callee->callback_ret_range = tnum_range(0, 1);
7373         return 0;
7374 }
7375
7376 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7377                                        struct bpf_func_state *caller,
7378                                        struct bpf_func_state *callee,
7379                                        int insn_idx)
7380 {
7381         /* bpf_find_vma(struct task_struct *task, u64 addr,
7382          *               void *callback_fn, void *callback_ctx, u64 flags)
7383          * (callback_fn)(struct task_struct *task,
7384          *               struct vm_area_struct *vma, void *callback_ctx);
7385          */
7386         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7387
7388         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7389         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7390         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7391         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7392
7393         /* pointer to stack or null */
7394         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7395
7396         /* unused */
7397         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7398         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7399         callee->in_callback_fn = true;
7400         callee->callback_ret_range = tnum_range(0, 1);
7401         return 0;
7402 }
7403
7404 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7405                                            struct bpf_func_state *caller,
7406                                            struct bpf_func_state *callee,
7407                                            int insn_idx)
7408 {
7409         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7410          *                        callback_ctx, u64 flags);
7411          * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
7412          */
7413         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7414         mark_dynptr_cb_reg(&callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
7415         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7416
7417         /* unused */
7418         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7419         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7420         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7421
7422         callee->in_callback_fn = true;
7423         callee->callback_ret_range = tnum_range(0, 1);
7424         return 0;
7425 }
7426
7427 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7428 {
7429         struct bpf_verifier_state *state = env->cur_state;
7430         struct bpf_func_state *caller, *callee;
7431         struct bpf_reg_state *r0;
7432         int err;
7433
7434         callee = state->frame[state->curframe];
7435         r0 = &callee->regs[BPF_REG_0];
7436         if (r0->type == PTR_TO_STACK) {
7437                 /* technically it's ok to return caller's stack pointer
7438                  * (or caller's caller's pointer) back to the caller,
7439                  * since these pointers are valid. Only current stack
7440                  * pointer will be invalid as soon as function exits,
7441                  * but let's be conservative
7442                  */
7443                 verbose(env, "cannot return stack pointer to the caller\n");
7444                 return -EINVAL;
7445         }
7446
7447         caller = state->frame[state->curframe - 1];
7448         if (callee->in_callback_fn) {
7449                 /* enforce R0 return value range [0, 1]. */
7450                 struct tnum range = callee->callback_ret_range;
7451
7452                 if (r0->type != SCALAR_VALUE) {
7453                         verbose(env, "R0 not a scalar value\n");
7454                         return -EACCES;
7455                 }
7456                 if (!tnum_in(range, r0->var_off)) {
7457                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7458                         return -EINVAL;
7459                 }
7460         } else {
7461                 /* return to the caller whatever r0 had in the callee */
7462                 caller->regs[BPF_REG_0] = *r0;
7463         }
7464
7465         /* callback_fn frame should have released its own additions to parent's
7466          * reference state at this point, or check_reference_leak would
7467          * complain, hence it must be the same as the caller. There is no need
7468          * to copy it back.
7469          */
7470         if (!callee->in_callback_fn) {
7471                 /* Transfer references to the caller */
7472                 err = copy_reference_state(caller, callee);
7473                 if (err)
7474                         return err;
7475         }
7476
7477         *insn_idx = callee->callsite + 1;
7478         if (env->log.level & BPF_LOG_LEVEL) {
7479                 verbose(env, "returning from callee:\n");
7480                 print_verifier_state(env, callee, true);
7481                 verbose(env, "to caller at %d:\n", *insn_idx);
7482                 print_verifier_state(env, caller, true);
7483         }
7484         /* clear everything in the callee */
7485         free_func_state(callee);
7486         state->frame[state->curframe--] = NULL;
7487         return 0;
7488 }
7489
7490 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7491                                    int func_id,
7492                                    struct bpf_call_arg_meta *meta)
7493 {
7494         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7495
7496         if (ret_type != RET_INTEGER ||
7497             (func_id != BPF_FUNC_get_stack &&
7498              func_id != BPF_FUNC_get_task_stack &&
7499              func_id != BPF_FUNC_probe_read_str &&
7500              func_id != BPF_FUNC_probe_read_kernel_str &&
7501              func_id != BPF_FUNC_probe_read_user_str))
7502                 return;
7503
7504         ret_reg->smax_value = meta->msize_max_value;
7505         ret_reg->s32_max_value = meta->msize_max_value;
7506         ret_reg->smin_value = -MAX_ERRNO;
7507         ret_reg->s32_min_value = -MAX_ERRNO;
7508         reg_bounds_sync(ret_reg);
7509 }
7510
7511 static int
7512 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7513                 int func_id, int insn_idx)
7514 {
7515         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7516         struct bpf_map *map = meta->map_ptr;
7517
7518         if (func_id != BPF_FUNC_tail_call &&
7519             func_id != BPF_FUNC_map_lookup_elem &&
7520             func_id != BPF_FUNC_map_update_elem &&
7521             func_id != BPF_FUNC_map_delete_elem &&
7522             func_id != BPF_FUNC_map_push_elem &&
7523             func_id != BPF_FUNC_map_pop_elem &&
7524             func_id != BPF_FUNC_map_peek_elem &&
7525             func_id != BPF_FUNC_for_each_map_elem &&
7526             func_id != BPF_FUNC_redirect_map &&
7527             func_id != BPF_FUNC_map_lookup_percpu_elem)
7528                 return 0;
7529
7530         if (map == NULL) {
7531                 verbose(env, "kernel subsystem misconfigured verifier\n");
7532                 return -EINVAL;
7533         }
7534
7535         /* In case of read-only, some additional restrictions
7536          * need to be applied in order to prevent altering the
7537          * state of the map from program side.
7538          */
7539         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7540             (func_id == BPF_FUNC_map_delete_elem ||
7541              func_id == BPF_FUNC_map_update_elem ||
7542              func_id == BPF_FUNC_map_push_elem ||
7543              func_id == BPF_FUNC_map_pop_elem)) {
7544                 verbose(env, "write into map forbidden\n");
7545                 return -EACCES;
7546         }
7547
7548         if (!BPF_MAP_PTR(aux->map_ptr_state))
7549                 bpf_map_ptr_store(aux, meta->map_ptr,
7550                                   !meta->map_ptr->bypass_spec_v1);
7551         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7552                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7553                                   !meta->map_ptr->bypass_spec_v1);
7554         return 0;
7555 }
7556
7557 static int
7558 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7559                 int func_id, int insn_idx)
7560 {
7561         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7562         struct bpf_reg_state *regs = cur_regs(env), *reg;
7563         struct bpf_map *map = meta->map_ptr;
7564         u64 val, max;
7565         int err;
7566
7567         if (func_id != BPF_FUNC_tail_call)
7568                 return 0;
7569         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7570                 verbose(env, "kernel subsystem misconfigured verifier\n");
7571                 return -EINVAL;
7572         }
7573
7574         reg = &regs[BPF_REG_3];
7575         val = reg->var_off.value;
7576         max = map->max_entries;
7577
7578         if (!(register_is_const(reg) && val < max)) {
7579                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7580                 return 0;
7581         }
7582
7583         err = mark_chain_precision(env, BPF_REG_3);
7584         if (err)
7585                 return err;
7586         if (bpf_map_key_unseen(aux))
7587                 bpf_map_key_store(aux, val);
7588         else if (!bpf_map_key_poisoned(aux) &&
7589                   bpf_map_key_immediate(aux) != val)
7590                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7591         return 0;
7592 }
7593
7594 static int check_reference_leak(struct bpf_verifier_env *env)
7595 {
7596         struct bpf_func_state *state = cur_func(env);
7597         bool refs_lingering = false;
7598         int i;
7599
7600         if (state->frameno && !state->in_callback_fn)
7601                 return 0;
7602
7603         for (i = 0; i < state->acquired_refs; i++) {
7604                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7605                         continue;
7606                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7607                         state->refs[i].id, state->refs[i].insn_idx);
7608                 refs_lingering = true;
7609         }
7610         return refs_lingering ? -EINVAL : 0;
7611 }
7612
7613 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7614                                    struct bpf_reg_state *regs)
7615 {
7616         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7617         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7618         struct bpf_map *fmt_map = fmt_reg->map_ptr;
7619         struct bpf_bprintf_data data = {};
7620         int err, fmt_map_off, num_args;
7621         u64 fmt_addr;
7622         char *fmt;
7623
7624         /* data must be an array of u64 */
7625         if (data_len_reg->var_off.value % 8)
7626                 return -EINVAL;
7627         num_args = data_len_reg->var_off.value / 8;
7628
7629         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7630          * and map_direct_value_addr is set.
7631          */
7632         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7633         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7634                                                   fmt_map_off);
7635         if (err) {
7636                 verbose(env, "verifier bug\n");
7637                 return -EFAULT;
7638         }
7639         fmt = (char *)(long)fmt_addr + fmt_map_off;
7640
7641         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7642          * can focus on validating the format specifiers.
7643          */
7644         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
7645         if (err < 0)
7646                 verbose(env, "Invalid format string\n");
7647
7648         return err;
7649 }
7650
7651 static int check_get_func_ip(struct bpf_verifier_env *env)
7652 {
7653         enum bpf_prog_type type = resolve_prog_type(env->prog);
7654         int func_id = BPF_FUNC_get_func_ip;
7655
7656         if (type == BPF_PROG_TYPE_TRACING) {
7657                 if (!bpf_prog_has_trampoline(env->prog)) {
7658                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7659                                 func_id_name(func_id), func_id);
7660                         return -ENOTSUPP;
7661                 }
7662                 return 0;
7663         } else if (type == BPF_PROG_TYPE_KPROBE) {
7664                 return 0;
7665         }
7666
7667         verbose(env, "func %s#%d not supported for program type %d\n",
7668                 func_id_name(func_id), func_id, type);
7669         return -ENOTSUPP;
7670 }
7671
7672 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7673 {
7674         return &env->insn_aux_data[env->insn_idx];
7675 }
7676
7677 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7678 {
7679         struct bpf_reg_state *regs = cur_regs(env);
7680         struct bpf_reg_state *reg = &regs[BPF_REG_4];
7681         bool reg_is_null = register_is_null(reg);
7682
7683         if (reg_is_null)
7684                 mark_chain_precision(env, BPF_REG_4);
7685
7686         return reg_is_null;
7687 }
7688
7689 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7690 {
7691         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7692
7693         if (!state->initialized) {
7694                 state->initialized = 1;
7695                 state->fit_for_inline = loop_flag_is_zero(env);
7696                 state->callback_subprogno = subprogno;
7697                 return;
7698         }
7699
7700         if (!state->fit_for_inline)
7701                 return;
7702
7703         state->fit_for_inline = (loop_flag_is_zero(env) &&
7704                                  state->callback_subprogno == subprogno);
7705 }
7706
7707 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7708                              int *insn_idx_p)
7709 {
7710         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7711         const struct bpf_func_proto *fn = NULL;
7712         enum bpf_return_type ret_type;
7713         enum bpf_type_flag ret_flag;
7714         struct bpf_reg_state *regs;
7715         struct bpf_call_arg_meta meta;
7716         int insn_idx = *insn_idx_p;
7717         bool changes_data;
7718         int i, err, func_id;
7719
7720         /* find function prototype */
7721         func_id = insn->imm;
7722         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7723                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7724                         func_id);
7725                 return -EINVAL;
7726         }
7727
7728         if (env->ops->get_func_proto)
7729                 fn = env->ops->get_func_proto(func_id, env->prog);
7730         if (!fn) {
7731                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7732                         func_id);
7733                 return -EINVAL;
7734         }
7735
7736         /* eBPF programs must be GPL compatible to use GPL-ed functions */
7737         if (!env->prog->gpl_compatible && fn->gpl_only) {
7738                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7739                 return -EINVAL;
7740         }
7741
7742         if (fn->allowed && !fn->allowed(env->prog)) {
7743                 verbose(env, "helper call is not allowed in probe\n");
7744                 return -EINVAL;
7745         }
7746
7747         if (!env->prog->aux->sleepable && fn->might_sleep) {
7748                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
7749                 return -EINVAL;
7750         }
7751
7752         /* With LD_ABS/IND some JITs save/restore skb from r1. */
7753         changes_data = bpf_helper_changes_pkt_data(fn->func);
7754         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7755                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7756                         func_id_name(func_id), func_id);
7757                 return -EINVAL;
7758         }
7759
7760         memset(&meta, 0, sizeof(meta));
7761         meta.pkt_access = fn->pkt_access;
7762
7763         err = check_func_proto(fn, func_id);
7764         if (err) {
7765                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7766                         func_id_name(func_id), func_id);
7767                 return err;
7768         }
7769
7770         if (env->cur_state->active_rcu_lock) {
7771                 if (fn->might_sleep) {
7772                         verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
7773                                 func_id_name(func_id), func_id);
7774                         return -EINVAL;
7775                 }
7776
7777                 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
7778                         env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
7779         }
7780
7781         meta.func_id = func_id;
7782         /* check args */
7783         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7784                 err = check_func_arg(env, i, &meta, fn);
7785                 if (err)
7786                         return err;
7787         }
7788
7789         err = record_func_map(env, &meta, func_id, insn_idx);
7790         if (err)
7791                 return err;
7792
7793         err = record_func_key(env, &meta, func_id, insn_idx);
7794         if (err)
7795                 return err;
7796
7797         /* Mark slots with STACK_MISC in case of raw mode, stack offset
7798          * is inferred from register state.
7799          */
7800         for (i = 0; i < meta.access_size; i++) {
7801                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7802                                        BPF_WRITE, -1, false);
7803                 if (err)
7804                         return err;
7805         }
7806
7807         regs = cur_regs(env);
7808
7809         /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
7810          * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr
7811          * is safe to do directly.
7812          */
7813         if (meta.uninit_dynptr_regno) {
7814                 if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) {
7815                         verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n");
7816                         return -EFAULT;
7817                 }
7818                 /* we write BPF_DW bits (8 bytes) at a time */
7819                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7820                         err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7821                                                i, BPF_DW, BPF_WRITE, -1, false);
7822                         if (err)
7823                                 return err;
7824                 }
7825
7826                 err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7827                                               fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7828                                               insn_idx);
7829                 if (err)
7830                         return err;
7831         }
7832
7833         if (meta.release_regno) {
7834                 err = -EINVAL;
7835                 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
7836                  * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
7837                  * is safe to do directly.
7838                  */
7839                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
7840                         if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
7841                                 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
7842                                 return -EFAULT;
7843                         }
7844                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7845                 } else if (meta.ref_obj_id) {
7846                         err = release_reference(env, meta.ref_obj_id);
7847                 } else if (register_is_null(&regs[meta.release_regno])) {
7848                         /* meta.ref_obj_id can only be 0 if register that is meant to be
7849                          * released is NULL, which must be > R0.
7850                          */
7851                         err = 0;
7852                 }
7853                 if (err) {
7854                         verbose(env, "func %s#%d reference has not been acquired before\n",
7855                                 func_id_name(func_id), func_id);
7856                         return err;
7857                 }
7858         }
7859
7860         switch (func_id) {
7861         case BPF_FUNC_tail_call:
7862                 err = check_reference_leak(env);
7863                 if (err) {
7864                         verbose(env, "tail_call would lead to reference leak\n");
7865                         return err;
7866                 }
7867                 break;
7868         case BPF_FUNC_get_local_storage:
7869                 /* check that flags argument in get_local_storage(map, flags) is 0,
7870                  * this is required because get_local_storage() can't return an error.
7871                  */
7872                 if (!register_is_null(&regs[BPF_REG_2])) {
7873                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7874                         return -EINVAL;
7875                 }
7876                 break;
7877         case BPF_FUNC_for_each_map_elem:
7878                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7879                                         set_map_elem_callback_state);
7880                 break;
7881         case BPF_FUNC_timer_set_callback:
7882                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7883                                         set_timer_callback_state);
7884                 break;
7885         case BPF_FUNC_find_vma:
7886                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7887                                         set_find_vma_callback_state);
7888                 break;
7889         case BPF_FUNC_snprintf:
7890                 err = check_bpf_snprintf_call(env, regs);
7891                 break;
7892         case BPF_FUNC_loop:
7893                 update_loop_inline_state(env, meta.subprogno);
7894                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7895                                         set_loop_callback_state);
7896                 break;
7897         case BPF_FUNC_dynptr_from_mem:
7898                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7899                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7900                                 reg_type_str(env, regs[BPF_REG_1].type));
7901                         return -EACCES;
7902                 }
7903                 break;
7904         case BPF_FUNC_set_retval:
7905                 if (prog_type == BPF_PROG_TYPE_LSM &&
7906                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7907                         if (!env->prog->aux->attach_func_proto->type) {
7908                                 /* Make sure programs that attach to void
7909                                  * hooks don't try to modify return value.
7910                                  */
7911                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7912                                 return -EINVAL;
7913                         }
7914                 }
7915                 break;
7916         case BPF_FUNC_dynptr_data:
7917                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7918                         if (arg_type_is_dynptr(fn->arg_type[i])) {
7919                                 struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7920
7921                                 if (meta.ref_obj_id) {
7922                                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7923                                         return -EFAULT;
7924                                 }
7925
7926                                 meta.ref_obj_id = dynptr_ref_obj_id(env, reg);
7927                                 break;
7928                         }
7929                 }
7930                 if (i == MAX_BPF_FUNC_REG_ARGS) {
7931                         verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7932                         return -EFAULT;
7933                 }
7934                 break;
7935         case BPF_FUNC_user_ringbuf_drain:
7936                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7937                                         set_user_ringbuf_callback_state);
7938                 break;
7939         }
7940
7941         if (err)
7942                 return err;
7943
7944         /* reset caller saved regs */
7945         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7946                 mark_reg_not_init(env, regs, caller_saved[i]);
7947                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7948         }
7949
7950         /* helper call returns 64-bit value. */
7951         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7952
7953         /* update return register (already marked as written above) */
7954         ret_type = fn->ret_type;
7955         ret_flag = type_flag(ret_type);
7956
7957         switch (base_type(ret_type)) {
7958         case RET_INTEGER:
7959                 /* sets type to SCALAR_VALUE */
7960                 mark_reg_unknown(env, regs, BPF_REG_0);
7961                 break;
7962         case RET_VOID:
7963                 regs[BPF_REG_0].type = NOT_INIT;
7964                 break;
7965         case RET_PTR_TO_MAP_VALUE:
7966                 /* There is no offset yet applied, variable or fixed */
7967                 mark_reg_known_zero(env, regs, BPF_REG_0);
7968                 /* remember map_ptr, so that check_map_access()
7969                  * can check 'value_size' boundary of memory access
7970                  * to map element returned from bpf_map_lookup_elem()
7971                  */
7972                 if (meta.map_ptr == NULL) {
7973                         verbose(env,
7974                                 "kernel subsystem misconfigured verifier\n");
7975                         return -EINVAL;
7976                 }
7977                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7978                 regs[BPF_REG_0].map_uid = meta.map_uid;
7979                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7980                 if (!type_may_be_null(ret_type) &&
7981                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
7982                         regs[BPF_REG_0].id = ++env->id_gen;
7983                 }
7984                 break;
7985         case RET_PTR_TO_SOCKET:
7986                 mark_reg_known_zero(env, regs, BPF_REG_0);
7987                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7988                 break;
7989         case RET_PTR_TO_SOCK_COMMON:
7990                 mark_reg_known_zero(env, regs, BPF_REG_0);
7991                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7992                 break;
7993         case RET_PTR_TO_TCP_SOCK:
7994                 mark_reg_known_zero(env, regs, BPF_REG_0);
7995                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7996                 break;
7997         case RET_PTR_TO_MEM:
7998                 mark_reg_known_zero(env, regs, BPF_REG_0);
7999                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8000                 regs[BPF_REG_0].mem_size = meta.mem_size;
8001                 break;
8002         case RET_PTR_TO_MEM_OR_BTF_ID:
8003         {
8004                 const struct btf_type *t;
8005
8006                 mark_reg_known_zero(env, regs, BPF_REG_0);
8007                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
8008                 if (!btf_type_is_struct(t)) {
8009                         u32 tsize;
8010                         const struct btf_type *ret;
8011                         const char *tname;
8012
8013                         /* resolve the type size of ksym. */
8014                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
8015                         if (IS_ERR(ret)) {
8016                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
8017                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
8018                                         tname, PTR_ERR(ret));
8019                                 return -EINVAL;
8020                         }
8021                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8022                         regs[BPF_REG_0].mem_size = tsize;
8023                 } else {
8024                         /* MEM_RDONLY may be carried from ret_flag, but it
8025                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
8026                          * it will confuse the check of PTR_TO_BTF_ID in
8027                          * check_mem_access().
8028                          */
8029                         ret_flag &= ~MEM_RDONLY;
8030
8031                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8032                         regs[BPF_REG_0].btf = meta.ret_btf;
8033                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8034                 }
8035                 break;
8036         }
8037         case RET_PTR_TO_BTF_ID:
8038         {
8039                 struct btf *ret_btf;
8040                 int ret_btf_id;
8041
8042                 mark_reg_known_zero(env, regs, BPF_REG_0);
8043                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8044                 if (func_id == BPF_FUNC_kptr_xchg) {
8045                         ret_btf = meta.kptr_field->kptr.btf;
8046                         ret_btf_id = meta.kptr_field->kptr.btf_id;
8047                 } else {
8048                         if (fn->ret_btf_id == BPF_PTR_POISON) {
8049                                 verbose(env, "verifier internal error:");
8050                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
8051                                         func_id_name(func_id));
8052                                 return -EINVAL;
8053                         }
8054                         ret_btf = btf_vmlinux;
8055                         ret_btf_id = *fn->ret_btf_id;
8056                 }
8057                 if (ret_btf_id == 0) {
8058                         verbose(env, "invalid return type %u of func %s#%d\n",
8059                                 base_type(ret_type), func_id_name(func_id),
8060                                 func_id);
8061                         return -EINVAL;
8062                 }
8063                 regs[BPF_REG_0].btf = ret_btf;
8064                 regs[BPF_REG_0].btf_id = ret_btf_id;
8065                 break;
8066         }
8067         default:
8068                 verbose(env, "unknown return type %u of func %s#%d\n",
8069                         base_type(ret_type), func_id_name(func_id), func_id);
8070                 return -EINVAL;
8071         }
8072
8073         if (type_may_be_null(regs[BPF_REG_0].type))
8074                 regs[BPF_REG_0].id = ++env->id_gen;
8075
8076         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
8077                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
8078                         func_id_name(func_id), func_id);
8079                 return -EFAULT;
8080         }
8081
8082         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
8083                 /* For release_reference() */
8084                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8085         } else if (is_acquire_function(func_id, meta.map_ptr)) {
8086                 int id = acquire_reference_state(env, insn_idx);
8087
8088                 if (id < 0)
8089                         return id;
8090                 /* For mark_ptr_or_null_reg() */
8091                 regs[BPF_REG_0].id = id;
8092                 /* For release_reference() */
8093                 regs[BPF_REG_0].ref_obj_id = id;
8094         }
8095
8096         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
8097
8098         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
8099         if (err)
8100                 return err;
8101
8102         if ((func_id == BPF_FUNC_get_stack ||
8103              func_id == BPF_FUNC_get_task_stack) &&
8104             !env->prog->has_callchain_buf) {
8105                 const char *err_str;
8106
8107 #ifdef CONFIG_PERF_EVENTS
8108                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
8109                 err_str = "cannot get callchain buffer for func %s#%d\n";
8110 #else
8111                 err = -ENOTSUPP;
8112                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
8113 #endif
8114                 if (err) {
8115                         verbose(env, err_str, func_id_name(func_id), func_id);
8116                         return err;
8117                 }
8118
8119                 env->prog->has_callchain_buf = true;
8120         }
8121
8122         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
8123                 env->prog->call_get_stack = true;
8124
8125         if (func_id == BPF_FUNC_get_func_ip) {
8126                 if (check_get_func_ip(env))
8127                         return -ENOTSUPP;
8128                 env->prog->call_get_func_ip = true;
8129         }
8130
8131         if (changes_data)
8132                 clear_all_pkt_pointers(env);
8133         return 0;
8134 }
8135
8136 /* mark_btf_func_reg_size() is used when the reg size is determined by
8137  * the BTF func_proto's return value size and argument.
8138  */
8139 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
8140                                    size_t reg_size)
8141 {
8142         struct bpf_reg_state *reg = &cur_regs(env)[regno];
8143
8144         if (regno == BPF_REG_0) {
8145                 /* Function return value */
8146                 reg->live |= REG_LIVE_WRITTEN;
8147                 reg->subreg_def = reg_size == sizeof(u64) ?
8148                         DEF_NOT_SUBREG : env->insn_idx + 1;
8149         } else {
8150                 /* Function argument */
8151                 if (reg_size == sizeof(u64)) {
8152                         mark_insn_zext(env, reg);
8153                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
8154                 } else {
8155                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
8156                 }
8157         }
8158 }
8159
8160 struct bpf_kfunc_call_arg_meta {
8161         /* In parameters */
8162         struct btf *btf;
8163         u32 func_id;
8164         u32 kfunc_flags;
8165         const struct btf_type *func_proto;
8166         const char *func_name;
8167         /* Out parameters */
8168         u32 ref_obj_id;
8169         u8 release_regno;
8170         bool r0_rdonly;
8171         u32 ret_btf_id;
8172         u64 r0_size;
8173         struct {
8174                 u64 value;
8175                 bool found;
8176         } arg_constant;
8177         struct {
8178                 struct btf *btf;
8179                 u32 btf_id;
8180         } arg_obj_drop;
8181         struct {
8182                 struct btf_field *field;
8183         } arg_list_head;
8184 };
8185
8186 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8187 {
8188         return meta->kfunc_flags & KF_ACQUIRE;
8189 }
8190
8191 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8192 {
8193         return meta->kfunc_flags & KF_RET_NULL;
8194 }
8195
8196 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8197 {
8198         return meta->kfunc_flags & KF_RELEASE;
8199 }
8200
8201 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8202 {
8203         return meta->kfunc_flags & KF_TRUSTED_ARGS;
8204 }
8205
8206 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8207 {
8208         return meta->kfunc_flags & KF_SLEEPABLE;
8209 }
8210
8211 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8212 {
8213         return meta->kfunc_flags & KF_DESTRUCTIVE;
8214 }
8215
8216 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8217 {
8218         return meta->kfunc_flags & KF_RCU;
8219 }
8220
8221 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8222 {
8223         return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8224 }
8225
8226 static bool __kfunc_param_match_suffix(const struct btf *btf,
8227                                        const struct btf_param *arg,
8228                                        const char *suffix)
8229 {
8230         int suffix_len = strlen(suffix), len;
8231         const char *param_name;
8232
8233         /* In the future, this can be ported to use BTF tagging */
8234         param_name = btf_name_by_offset(btf, arg->name_off);
8235         if (str_is_empty(param_name))
8236                 return false;
8237         len = strlen(param_name);
8238         if (len < suffix_len)
8239                 return false;
8240         param_name += len - suffix_len;
8241         return !strncmp(param_name, suffix, suffix_len);
8242 }
8243
8244 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8245                                   const struct btf_param *arg,
8246                                   const struct bpf_reg_state *reg)
8247 {
8248         const struct btf_type *t;
8249
8250         t = btf_type_skip_modifiers(btf, arg->type, NULL);
8251         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8252                 return false;
8253
8254         return __kfunc_param_match_suffix(btf, arg, "__sz");
8255 }
8256
8257 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8258 {
8259         return __kfunc_param_match_suffix(btf, arg, "__k");
8260 }
8261
8262 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8263 {
8264         return __kfunc_param_match_suffix(btf, arg, "__ign");
8265 }
8266
8267 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8268 {
8269         return __kfunc_param_match_suffix(btf, arg, "__alloc");
8270 }
8271
8272 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8273                                           const struct btf_param *arg,
8274                                           const char *name)
8275 {
8276         int len, target_len = strlen(name);
8277         const char *param_name;
8278
8279         param_name = btf_name_by_offset(btf, arg->name_off);
8280         if (str_is_empty(param_name))
8281                 return false;
8282         len = strlen(param_name);
8283         if (len != target_len)
8284                 return false;
8285         if (strcmp(param_name, name))
8286                 return false;
8287
8288         return true;
8289 }
8290
8291 enum {
8292         KF_ARG_DYNPTR_ID,
8293         KF_ARG_LIST_HEAD_ID,
8294         KF_ARG_LIST_NODE_ID,
8295 };
8296
8297 BTF_ID_LIST(kf_arg_btf_ids)
8298 BTF_ID(struct, bpf_dynptr_kern)
8299 BTF_ID(struct, bpf_list_head)
8300 BTF_ID(struct, bpf_list_node)
8301
8302 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8303                                     const struct btf_param *arg, int type)
8304 {
8305         const struct btf_type *t;
8306         u32 res_id;
8307
8308         t = btf_type_skip_modifiers(btf, arg->type, NULL);
8309         if (!t)
8310                 return false;
8311         if (!btf_type_is_ptr(t))
8312                 return false;
8313         t = btf_type_skip_modifiers(btf, t->type, &res_id);
8314         if (!t)
8315                 return false;
8316         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8317 }
8318
8319 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8320 {
8321         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8322 }
8323
8324 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8325 {
8326         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8327 }
8328
8329 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8330 {
8331         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8332 }
8333
8334 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8335 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8336                                         const struct btf *btf,
8337                                         const struct btf_type *t, int rec)
8338 {
8339         const struct btf_type *member_type;
8340         const struct btf_member *member;
8341         u32 i;
8342
8343         if (!btf_type_is_struct(t))
8344                 return false;
8345
8346         for_each_member(i, t, member) {
8347                 const struct btf_array *array;
8348
8349                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8350                 if (btf_type_is_struct(member_type)) {
8351                         if (rec >= 3) {
8352                                 verbose(env, "max struct nesting depth exceeded\n");
8353                                 return false;
8354                         }
8355                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8356                                 return false;
8357                         continue;
8358                 }
8359                 if (btf_type_is_array(member_type)) {
8360                         array = btf_array(member_type);
8361                         if (!array->nelems)
8362                                 return false;
8363                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8364                         if (!btf_type_is_scalar(member_type))
8365                                 return false;
8366                         continue;
8367                 }
8368                 if (!btf_type_is_scalar(member_type))
8369                         return false;
8370         }
8371         return true;
8372 }
8373
8374
8375 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8376 #ifdef CONFIG_NET
8377         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8378         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8379         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8380 #endif
8381 };
8382
8383 enum kfunc_ptr_arg_type {
8384         KF_ARG_PTR_TO_CTX,
8385         KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
8386         KF_ARG_PTR_TO_KPTR,          /* PTR_TO_KPTR but type specific */
8387         KF_ARG_PTR_TO_DYNPTR,
8388         KF_ARG_PTR_TO_LIST_HEAD,
8389         KF_ARG_PTR_TO_LIST_NODE,
8390         KF_ARG_PTR_TO_BTF_ID,        /* Also covers reg2btf_ids conversions */
8391         KF_ARG_PTR_TO_MEM,
8392         KF_ARG_PTR_TO_MEM_SIZE,      /* Size derived from next argument, skip it */
8393 };
8394
8395 enum special_kfunc_type {
8396         KF_bpf_obj_new_impl,
8397         KF_bpf_obj_drop_impl,
8398         KF_bpf_list_push_front,
8399         KF_bpf_list_push_back,
8400         KF_bpf_list_pop_front,
8401         KF_bpf_list_pop_back,
8402         KF_bpf_cast_to_kern_ctx,
8403         KF_bpf_rdonly_cast,
8404         KF_bpf_rcu_read_lock,
8405         KF_bpf_rcu_read_unlock,
8406 };
8407
8408 BTF_SET_START(special_kfunc_set)
8409 BTF_ID(func, bpf_obj_new_impl)
8410 BTF_ID(func, bpf_obj_drop_impl)
8411 BTF_ID(func, bpf_list_push_front)
8412 BTF_ID(func, bpf_list_push_back)
8413 BTF_ID(func, bpf_list_pop_front)
8414 BTF_ID(func, bpf_list_pop_back)
8415 BTF_ID(func, bpf_cast_to_kern_ctx)
8416 BTF_ID(func, bpf_rdonly_cast)
8417 BTF_SET_END(special_kfunc_set)
8418
8419 BTF_ID_LIST(special_kfunc_list)
8420 BTF_ID(func, bpf_obj_new_impl)
8421 BTF_ID(func, bpf_obj_drop_impl)
8422 BTF_ID(func, bpf_list_push_front)
8423 BTF_ID(func, bpf_list_push_back)
8424 BTF_ID(func, bpf_list_pop_front)
8425 BTF_ID(func, bpf_list_pop_back)
8426 BTF_ID(func, bpf_cast_to_kern_ctx)
8427 BTF_ID(func, bpf_rdonly_cast)
8428 BTF_ID(func, bpf_rcu_read_lock)
8429 BTF_ID(func, bpf_rcu_read_unlock)
8430
8431 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
8432 {
8433         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
8434 }
8435
8436 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
8437 {
8438         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
8439 }
8440
8441 static enum kfunc_ptr_arg_type
8442 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8443                        struct bpf_kfunc_call_arg_meta *meta,
8444                        const struct btf_type *t, const struct btf_type *ref_t,
8445                        const char *ref_tname, const struct btf_param *args,
8446                        int argno, int nargs)
8447 {
8448         u32 regno = argno + 1;
8449         struct bpf_reg_state *regs = cur_regs(env);
8450         struct bpf_reg_state *reg = &regs[regno];
8451         bool arg_mem_size = false;
8452
8453         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8454                 return KF_ARG_PTR_TO_CTX;
8455
8456         /* In this function, we verify the kfunc's BTF as per the argument type,
8457          * leaving the rest of the verification with respect to the register
8458          * type to our caller. When a set of conditions hold in the BTF type of
8459          * arguments, we resolve it to a known kfunc_ptr_arg_type.
8460          */
8461         if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8462                 return KF_ARG_PTR_TO_CTX;
8463
8464         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8465                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8466
8467         if (is_kfunc_arg_kptr_get(meta, argno)) {
8468                 if (!btf_type_is_ptr(ref_t)) {
8469                         verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8470                         return -EINVAL;
8471                 }
8472                 ref_t = btf_type_by_id(meta->btf, ref_t->type);
8473                 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8474                 if (!btf_type_is_struct(ref_t)) {
8475                         verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8476                                 meta->func_name, btf_type_str(ref_t), ref_tname);
8477                         return -EINVAL;
8478                 }
8479                 return KF_ARG_PTR_TO_KPTR;
8480         }
8481
8482         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8483                 return KF_ARG_PTR_TO_DYNPTR;
8484
8485         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8486                 return KF_ARG_PTR_TO_LIST_HEAD;
8487
8488         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8489                 return KF_ARG_PTR_TO_LIST_NODE;
8490
8491         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8492                 if (!btf_type_is_struct(ref_t)) {
8493                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8494                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8495                         return -EINVAL;
8496                 }
8497                 return KF_ARG_PTR_TO_BTF_ID;
8498         }
8499
8500         if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]))
8501                 arg_mem_size = true;
8502
8503         /* This is the catch all argument type of register types supported by
8504          * check_helper_mem_access. However, we only allow when argument type is
8505          * pointer to scalar, or struct composed (recursively) of scalars. When
8506          * arg_mem_size is true, the pointer can be void *.
8507          */
8508         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8509             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8510                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
8511                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
8512                 return -EINVAL;
8513         }
8514         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
8515 }
8516
8517 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
8518                                         struct bpf_reg_state *reg,
8519                                         const struct btf_type *ref_t,
8520                                         const char *ref_tname, u32 ref_id,
8521                                         struct bpf_kfunc_call_arg_meta *meta,
8522                                         int argno)
8523 {
8524         const struct btf_type *reg_ref_t;
8525         bool strict_type_match = false;
8526         const struct btf *reg_btf;
8527         const char *reg_ref_tname;
8528         u32 reg_ref_id;
8529
8530         if (base_type(reg->type) == PTR_TO_BTF_ID) {
8531                 reg_btf = reg->btf;
8532                 reg_ref_id = reg->btf_id;
8533         } else {
8534                 reg_btf = btf_vmlinux;
8535                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
8536         }
8537
8538         if (is_kfunc_trusted_args(meta) || (is_kfunc_release(meta) && reg->ref_obj_id))
8539                 strict_type_match = true;
8540
8541         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
8542         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
8543         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
8544                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
8545                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
8546                         btf_type_str(reg_ref_t), reg_ref_tname);
8547                 return -EINVAL;
8548         }
8549         return 0;
8550 }
8551
8552 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
8553                                       struct bpf_reg_state *reg,
8554                                       const struct btf_type *ref_t,
8555                                       const char *ref_tname,
8556                                       struct bpf_kfunc_call_arg_meta *meta,
8557                                       int argno)
8558 {
8559         struct btf_field *kptr_field;
8560
8561         /* check_func_arg_reg_off allows var_off for
8562          * PTR_TO_MAP_VALUE, but we need fixed offset to find
8563          * off_desc.
8564          */
8565         if (!tnum_is_const(reg->var_off)) {
8566                 verbose(env, "arg#0 must have constant offset\n");
8567                 return -EINVAL;
8568         }
8569
8570         kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
8571         if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
8572                 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
8573                         reg->off + reg->var_off.value);
8574                 return -EINVAL;
8575         }
8576
8577         if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
8578                                   kptr_field->kptr.btf_id, true)) {
8579                 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
8580                         meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8581                 return -EINVAL;
8582         }
8583         return 0;
8584 }
8585
8586 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id)
8587 {
8588         struct bpf_func_state *state = cur_func(env);
8589         struct bpf_reg_state *reg;
8590         int i;
8591
8592         /* bpf_spin_lock only allows calling list_push and list_pop, no BPF
8593          * subprogs, no global functions. This means that the references would
8594          * not be released inside the critical section but they may be added to
8595          * the reference state, and the acquired_refs are never copied out for a
8596          * different frame as BPF to BPF calls don't work in bpf_spin_lock
8597          * critical sections.
8598          */
8599         if (!ref_obj_id) {
8600                 verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n");
8601                 return -EFAULT;
8602         }
8603         for (i = 0; i < state->acquired_refs; i++) {
8604                 if (state->refs[i].id == ref_obj_id) {
8605                         if (state->refs[i].release_on_unlock) {
8606                                 verbose(env, "verifier internal error: expected false release_on_unlock");
8607                                 return -EFAULT;
8608                         }
8609                         state->refs[i].release_on_unlock = true;
8610                         /* Now mark everyone sharing same ref_obj_id as untrusted */
8611                         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8612                                 if (reg->ref_obj_id == ref_obj_id)
8613                                         reg->type |= PTR_UNTRUSTED;
8614                         }));
8615                         return 0;
8616                 }
8617         }
8618         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
8619         return -EFAULT;
8620 }
8621
8622 /* Implementation details:
8623  *
8624  * Each register points to some region of memory, which we define as an
8625  * allocation. Each allocation may embed a bpf_spin_lock which protects any
8626  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
8627  * allocation. The lock and the data it protects are colocated in the same
8628  * memory region.
8629  *
8630  * Hence, everytime a register holds a pointer value pointing to such
8631  * allocation, the verifier preserves a unique reg->id for it.
8632  *
8633  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
8634  * bpf_spin_lock is called.
8635  *
8636  * To enable this, lock state in the verifier captures two values:
8637  *      active_lock.ptr = Register's type specific pointer
8638  *      active_lock.id  = A unique ID for each register pointer value
8639  *
8640  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
8641  * supported register types.
8642  *
8643  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
8644  * allocated objects is the reg->btf pointer.
8645  *
8646  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
8647  * can establish the provenance of the map value statically for each distinct
8648  * lookup into such maps. They always contain a single map value hence unique
8649  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
8650  *
8651  * So, in case of global variables, they use array maps with max_entries = 1,
8652  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
8653  * into the same map value as max_entries is 1, as described above).
8654  *
8655  * In case of inner map lookups, the inner map pointer has same map_ptr as the
8656  * outer map pointer (in verifier context), but each lookup into an inner map
8657  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
8658  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
8659  * will get different reg->id assigned to each lookup, hence different
8660  * active_lock.id.
8661  *
8662  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
8663  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
8664  * returned from bpf_obj_new. Each allocation receives a new reg->id.
8665  */
8666 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8667 {
8668         void *ptr;
8669         u32 id;
8670
8671         switch ((int)reg->type) {
8672         case PTR_TO_MAP_VALUE:
8673                 ptr = reg->map_ptr;
8674                 break;
8675         case PTR_TO_BTF_ID | MEM_ALLOC:
8676         case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
8677                 ptr = reg->btf;
8678                 break;
8679         default:
8680                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
8681                 return -EFAULT;
8682         }
8683         id = reg->id;
8684
8685         if (!env->cur_state->active_lock.ptr)
8686                 return -EINVAL;
8687         if (env->cur_state->active_lock.ptr != ptr ||
8688             env->cur_state->active_lock.id != id) {
8689                 verbose(env, "held lock and object are not in the same allocation\n");
8690                 return -EINVAL;
8691         }
8692         return 0;
8693 }
8694
8695 static bool is_bpf_list_api_kfunc(u32 btf_id)
8696 {
8697         return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
8698                btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
8699                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8700                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
8701 }
8702
8703 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8704                                            struct bpf_reg_state *reg, u32 regno,
8705                                            struct bpf_kfunc_call_arg_meta *meta)
8706 {
8707         struct btf_field *field;
8708         struct btf_record *rec;
8709         u32 list_head_off;
8710
8711         if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) {
8712                 verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n");
8713                 return -EFAULT;
8714         }
8715
8716         if (!tnum_is_const(reg->var_off)) {
8717                 verbose(env,
8718                         "R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n",
8719                         regno);
8720                 return -EINVAL;
8721         }
8722
8723         rec = reg_btf_record(reg);
8724         list_head_off = reg->off + reg->var_off.value;
8725         field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD);
8726         if (!field) {
8727                 verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off);
8728                 return -EINVAL;
8729         }
8730
8731         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
8732         if (check_reg_allocation_locked(env, reg)) {
8733                 verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n",
8734                         rec->spin_lock_off);
8735                 return -EINVAL;
8736         }
8737
8738         if (meta->arg_list_head.field) {
8739                 verbose(env, "verifier internal error: repeating bpf_list_head arg\n");
8740                 return -EFAULT;
8741         }
8742         meta->arg_list_head.field = field;
8743         return 0;
8744 }
8745
8746 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
8747                                            struct bpf_reg_state *reg, u32 regno,
8748                                            struct bpf_kfunc_call_arg_meta *meta)
8749 {
8750         const struct btf_type *et, *t;
8751         struct btf_field *field;
8752         struct btf_record *rec;
8753         u32 list_node_off;
8754
8755         if (meta->btf != btf_vmlinux ||
8756             (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] &&
8757              meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) {
8758                 verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n");
8759                 return -EFAULT;
8760         }
8761
8762         if (!tnum_is_const(reg->var_off)) {
8763                 verbose(env,
8764                         "R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n",
8765                         regno);
8766                 return -EINVAL;
8767         }
8768
8769         rec = reg_btf_record(reg);
8770         list_node_off = reg->off + reg->var_off.value;
8771         field = btf_record_find(rec, list_node_off, BPF_LIST_NODE);
8772         if (!field || field->offset != list_node_off) {
8773                 verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off);
8774                 return -EINVAL;
8775         }
8776
8777         field = meta->arg_list_head.field;
8778
8779         et = btf_type_by_id(field->list_head.btf, field->list_head.value_btf_id);
8780         t = btf_type_by_id(reg->btf, reg->btf_id);
8781         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->list_head.btf,
8782                                   field->list_head.value_btf_id, true)) {
8783                 verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d "
8784                         "in struct %s, but arg is at offset=%d in struct %s\n",
8785                         field->list_head.node_offset, btf_name_by_offset(field->list_head.btf, et->name_off),
8786                         list_node_off, btf_name_by_offset(reg->btf, t->name_off));
8787                 return -EINVAL;
8788         }
8789
8790         if (list_node_off != field->list_head.node_offset) {
8791                 verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n",
8792                         list_node_off, field->list_head.node_offset,
8793                         btf_name_by_offset(field->list_head.btf, et->name_off));
8794                 return -EINVAL;
8795         }
8796         /* Set arg#1 for expiration after unlock */
8797         return ref_set_release_on_unlock(env, reg->ref_obj_id);
8798 }
8799
8800 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
8801 {
8802         const char *func_name = meta->func_name, *ref_tname;
8803         const struct btf *btf = meta->btf;
8804         const struct btf_param *args;
8805         u32 i, nargs;
8806         int ret;
8807
8808         args = (const struct btf_param *)(meta->func_proto + 1);
8809         nargs = btf_type_vlen(meta->func_proto);
8810         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
8811                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
8812                         MAX_BPF_FUNC_REG_ARGS);
8813                 return -EINVAL;
8814         }
8815
8816         /* Check that BTF function arguments match actual types that the
8817          * verifier sees.
8818          */
8819         for (i = 0; i < nargs; i++) {
8820                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
8821                 const struct btf_type *t, *ref_t, *resolve_ret;
8822                 enum bpf_arg_type arg_type = ARG_DONTCARE;
8823                 u32 regno = i + 1, ref_id, type_size;
8824                 bool is_ret_buf_sz = false;
8825                 int kf_arg_type;
8826
8827                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
8828
8829                 if (is_kfunc_arg_ignore(btf, &args[i]))
8830                         continue;
8831
8832                 if (btf_type_is_scalar(t)) {
8833                         if (reg->type != SCALAR_VALUE) {
8834                                 verbose(env, "R%d is not a scalar\n", regno);
8835                                 return -EINVAL;
8836                         }
8837
8838                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
8839                                 if (meta->arg_constant.found) {
8840                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
8841                                         return -EFAULT;
8842                                 }
8843                                 if (!tnum_is_const(reg->var_off)) {
8844                                         verbose(env, "R%d must be a known constant\n", regno);
8845                                         return -EINVAL;
8846                                 }
8847                                 ret = mark_chain_precision(env, regno);
8848                                 if (ret < 0)
8849                                         return ret;
8850                                 meta->arg_constant.found = true;
8851                                 meta->arg_constant.value = reg->var_off.value;
8852                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
8853                                 meta->r0_rdonly = true;
8854                                 is_ret_buf_sz = true;
8855                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
8856                                 is_ret_buf_sz = true;
8857                         }
8858
8859                         if (is_ret_buf_sz) {
8860                                 if (meta->r0_size) {
8861                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
8862                                         return -EINVAL;
8863                                 }
8864
8865                                 if (!tnum_is_const(reg->var_off)) {
8866                                         verbose(env, "R%d is not a const\n", regno);
8867                                         return -EINVAL;
8868                                 }
8869
8870                                 meta->r0_size = reg->var_off.value;
8871                                 ret = mark_chain_precision(env, regno);
8872                                 if (ret)
8873                                         return ret;
8874                         }
8875                         continue;
8876                 }
8877
8878                 if (!btf_type_is_ptr(t)) {
8879                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
8880                         return -EINVAL;
8881                 }
8882
8883                 if (reg->ref_obj_id) {
8884                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
8885                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8886                                         regno, reg->ref_obj_id,
8887                                         meta->ref_obj_id);
8888                                 return -EFAULT;
8889                         }
8890                         meta->ref_obj_id = reg->ref_obj_id;
8891                         if (is_kfunc_release(meta))
8892                                 meta->release_regno = regno;
8893                 }
8894
8895                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
8896                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
8897
8898                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
8899                 if (kf_arg_type < 0)
8900                         return kf_arg_type;
8901
8902                 switch (kf_arg_type) {
8903                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8904                 case KF_ARG_PTR_TO_BTF_ID:
8905                         if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
8906                                 break;
8907
8908                         if (!is_trusted_reg(reg)) {
8909                                 if (!is_kfunc_rcu(meta)) {
8910                                         verbose(env, "R%d must be referenced or trusted\n", regno);
8911                                         return -EINVAL;
8912                                 }
8913                                 if (!is_rcu_reg(reg)) {
8914                                         verbose(env, "R%d must be a rcu pointer\n", regno);
8915                                         return -EINVAL;
8916                                 }
8917                         }
8918
8919                         fallthrough;
8920                 case KF_ARG_PTR_TO_CTX:
8921                         /* Trusted arguments have the same offset checks as release arguments */
8922                         arg_type |= OBJ_RELEASE;
8923                         break;
8924                 case KF_ARG_PTR_TO_KPTR:
8925                 case KF_ARG_PTR_TO_DYNPTR:
8926                 case KF_ARG_PTR_TO_LIST_HEAD:
8927                 case KF_ARG_PTR_TO_LIST_NODE:
8928                 case KF_ARG_PTR_TO_MEM:
8929                 case KF_ARG_PTR_TO_MEM_SIZE:
8930                         /* Trusted by default */
8931                         break;
8932                 default:
8933                         WARN_ON_ONCE(1);
8934                         return -EFAULT;
8935                 }
8936
8937                 if (is_kfunc_release(meta) && reg->ref_obj_id)
8938                         arg_type |= OBJ_RELEASE;
8939                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
8940                 if (ret < 0)
8941                         return ret;
8942
8943                 switch (kf_arg_type) {
8944                 case KF_ARG_PTR_TO_CTX:
8945                         if (reg->type != PTR_TO_CTX) {
8946                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
8947                                 return -EINVAL;
8948                         }
8949
8950                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8951                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
8952                                 if (ret < 0)
8953                                         return -EINVAL;
8954                                 meta->ret_btf_id  = ret;
8955                         }
8956                         break;
8957                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8958                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8959                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
8960                                 return -EINVAL;
8961                         }
8962                         if (!reg->ref_obj_id) {
8963                                 verbose(env, "allocated object must be referenced\n");
8964                                 return -EINVAL;
8965                         }
8966                         if (meta->btf == btf_vmlinux &&
8967                             meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8968                                 meta->arg_obj_drop.btf = reg->btf;
8969                                 meta->arg_obj_drop.btf_id = reg->btf_id;
8970                         }
8971                         break;
8972                 case KF_ARG_PTR_TO_KPTR:
8973                         if (reg->type != PTR_TO_MAP_VALUE) {
8974                                 verbose(env, "arg#0 expected pointer to map value\n");
8975                                 return -EINVAL;
8976                         }
8977                         ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
8978                         if (ret < 0)
8979                                 return ret;
8980                         break;
8981                 case KF_ARG_PTR_TO_DYNPTR:
8982                         if (reg->type != PTR_TO_STACK &&
8983                             reg->type != CONST_PTR_TO_DYNPTR) {
8984                                 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
8985                                 return -EINVAL;
8986                         }
8987
8988                         ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL);
8989                         if (ret < 0)
8990                                 return ret;
8991                         break;
8992                 case KF_ARG_PTR_TO_LIST_HEAD:
8993                         if (reg->type != PTR_TO_MAP_VALUE &&
8994                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8995                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
8996                                 return -EINVAL;
8997                         }
8998                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
8999                                 verbose(env, "allocated object must be referenced\n");
9000                                 return -EINVAL;
9001                         }
9002                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
9003                         if (ret < 0)
9004                                 return ret;
9005                         break;
9006                 case KF_ARG_PTR_TO_LIST_NODE:
9007                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9008                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
9009                                 return -EINVAL;
9010                         }
9011                         if (!reg->ref_obj_id) {
9012                                 verbose(env, "allocated object must be referenced\n");
9013                                 return -EINVAL;
9014                         }
9015                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
9016                         if (ret < 0)
9017                                 return ret;
9018                         break;
9019                 case KF_ARG_PTR_TO_BTF_ID:
9020                         /* Only base_type is checked, further checks are done here */
9021                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
9022                              (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
9023                             !reg2btf_ids[base_type(reg->type)]) {
9024                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
9025                                 verbose(env, "expected %s or socket\n",
9026                                         reg_type_str(env, base_type(reg->type) |
9027                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
9028                                 return -EINVAL;
9029                         }
9030                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
9031                         if (ret < 0)
9032                                 return ret;
9033                         break;
9034                 case KF_ARG_PTR_TO_MEM:
9035                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
9036                         if (IS_ERR(resolve_ret)) {
9037                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
9038                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
9039                                 return -EINVAL;
9040                         }
9041                         ret = check_mem_reg(env, reg, regno, type_size);
9042                         if (ret < 0)
9043                                 return ret;
9044                         break;
9045                 case KF_ARG_PTR_TO_MEM_SIZE:
9046                         ret = check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1);
9047                         if (ret < 0) {
9048                                 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
9049                                 return ret;
9050                         }
9051                         /* Skip next '__sz' argument */
9052                         i++;
9053                         break;
9054                 }
9055         }
9056
9057         if (is_kfunc_release(meta) && !meta->release_regno) {
9058                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
9059                         func_name);
9060                 return -EINVAL;
9061         }
9062
9063         return 0;
9064 }
9065
9066 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9067                             int *insn_idx_p)
9068 {
9069         const struct btf_type *t, *func, *func_proto, *ptr_type;
9070         struct bpf_reg_state *regs = cur_regs(env);
9071         const char *func_name, *ptr_type_name;
9072         bool sleepable, rcu_lock, rcu_unlock;
9073         struct bpf_kfunc_call_arg_meta meta;
9074         u32 i, nargs, func_id, ptr_type_id;
9075         int err, insn_idx = *insn_idx_p;
9076         const struct btf_param *args;
9077         const struct btf_type *ret_t;
9078         struct btf *desc_btf;
9079         u32 *kfunc_flags;
9080
9081         /* skip for now, but return error when we find this in fixup_kfunc_call */
9082         if (!insn->imm)
9083                 return 0;
9084
9085         desc_btf = find_kfunc_desc_btf(env, insn->off);
9086         if (IS_ERR(desc_btf))
9087                 return PTR_ERR(desc_btf);
9088
9089         func_id = insn->imm;
9090         func = btf_type_by_id(desc_btf, func_id);
9091         func_name = btf_name_by_offset(desc_btf, func->name_off);
9092         func_proto = btf_type_by_id(desc_btf, func->type);
9093
9094         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
9095         if (!kfunc_flags) {
9096                 verbose(env, "calling kernel function %s is not allowed\n",
9097                         func_name);
9098                 return -EACCES;
9099         }
9100
9101         /* Prepare kfunc call metadata */
9102         memset(&meta, 0, sizeof(meta));
9103         meta.btf = desc_btf;
9104         meta.func_id = func_id;
9105         meta.kfunc_flags = *kfunc_flags;
9106         meta.func_proto = func_proto;
9107         meta.func_name = func_name;
9108
9109         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
9110                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
9111                 return -EACCES;
9112         }
9113
9114         sleepable = is_kfunc_sleepable(&meta);
9115         if (sleepable && !env->prog->aux->sleepable) {
9116                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
9117                 return -EACCES;
9118         }
9119
9120         rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
9121         rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
9122         if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) {
9123                 verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name);
9124                 return -EACCES;
9125         }
9126
9127         if (env->cur_state->active_rcu_lock) {
9128                 struct bpf_func_state *state;
9129                 struct bpf_reg_state *reg;
9130
9131                 if (rcu_lock) {
9132                         verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
9133                         return -EINVAL;
9134                 } else if (rcu_unlock) {
9135                         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9136                                 if (reg->type & MEM_RCU) {
9137                                         reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9138                                         reg->type |= PTR_UNTRUSTED;
9139                                 }
9140                         }));
9141                         env->cur_state->active_rcu_lock = false;
9142                 } else if (sleepable) {
9143                         verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
9144                         return -EACCES;
9145                 }
9146         } else if (rcu_lock) {
9147                 env->cur_state->active_rcu_lock = true;
9148         } else if (rcu_unlock) {
9149                 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
9150                 return -EINVAL;
9151         }
9152
9153         /* Check the arguments */
9154         err = check_kfunc_args(env, &meta);
9155         if (err < 0)
9156                 return err;
9157         /* In case of release function, we get register number of refcounted
9158          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
9159          */
9160         if (meta.release_regno) {
9161                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
9162                 if (err) {
9163                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9164                                 func_name, func_id);
9165                         return err;
9166                 }
9167         }
9168
9169         for (i = 0; i < CALLER_SAVED_REGS; i++)
9170                 mark_reg_not_init(env, regs, caller_saved[i]);
9171
9172         /* Check return type */
9173         t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
9174
9175         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
9176                 /* Only exception is bpf_obj_new_impl */
9177                 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
9178                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
9179                         return -EINVAL;
9180                 }
9181         }
9182
9183         if (btf_type_is_scalar(t)) {
9184                 mark_reg_unknown(env, regs, BPF_REG_0);
9185                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
9186         } else if (btf_type_is_ptr(t)) {
9187                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
9188
9189                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
9190                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
9191                                 struct btf *ret_btf;
9192                                 u32 ret_btf_id;
9193
9194                                 if (unlikely(!bpf_global_ma_set))
9195                                         return -ENOMEM;
9196
9197                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
9198                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
9199                                         return -EINVAL;
9200                                 }
9201
9202                                 ret_btf = env->prog->aux->btf;
9203                                 ret_btf_id = meta.arg_constant.value;
9204
9205                                 /* This may be NULL due to user not supplying a BTF */
9206                                 if (!ret_btf) {
9207                                         verbose(env, "bpf_obj_new requires prog BTF\n");
9208                                         return -EINVAL;
9209                                 }
9210
9211                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
9212                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
9213                                         verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
9214                                         return -EINVAL;
9215                                 }
9216
9217                                 mark_reg_known_zero(env, regs, BPF_REG_0);
9218                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9219                                 regs[BPF_REG_0].btf = ret_btf;
9220                                 regs[BPF_REG_0].btf_id = ret_btf_id;
9221
9222                                 env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
9223                                 env->insn_aux_data[insn_idx].kptr_struct_meta =
9224                                         btf_find_struct_meta(ret_btf, ret_btf_id);
9225                         } else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9226                                 env->insn_aux_data[insn_idx].kptr_struct_meta =
9227                                         btf_find_struct_meta(meta.arg_obj_drop.btf,
9228                                                              meta.arg_obj_drop.btf_id);
9229                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9230                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
9231                                 struct btf_field *field = meta.arg_list_head.field;
9232
9233                                 mark_reg_known_zero(env, regs, BPF_REG_0);
9234                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9235                                 regs[BPF_REG_0].btf = field->list_head.btf;
9236                                 regs[BPF_REG_0].btf_id = field->list_head.value_btf_id;
9237                                 regs[BPF_REG_0].off = field->list_head.node_offset;
9238                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9239                                 mark_reg_known_zero(env, regs, BPF_REG_0);
9240                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
9241                                 regs[BPF_REG_0].btf = desc_btf;
9242                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9243                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
9244                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
9245                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
9246                                         verbose(env,
9247                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
9248                                         return -EINVAL;
9249                                 }
9250
9251                                 mark_reg_known_zero(env, regs, BPF_REG_0);
9252                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
9253                                 regs[BPF_REG_0].btf = desc_btf;
9254                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
9255                         } else {
9256                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
9257                                         meta.func_name);
9258                                 return -EFAULT;
9259                         }
9260                 } else if (!__btf_type_is_struct(ptr_type)) {
9261                         if (!meta.r0_size) {
9262                                 ptr_type_name = btf_name_by_offset(desc_btf,
9263                                                                    ptr_type->name_off);
9264                                 verbose(env,
9265                                         "kernel function %s returns pointer type %s %s is not supported\n",
9266                                         func_name,
9267                                         btf_type_str(ptr_type),
9268                                         ptr_type_name);
9269                                 return -EINVAL;
9270                         }
9271
9272                         mark_reg_known_zero(env, regs, BPF_REG_0);
9273                         regs[BPF_REG_0].type = PTR_TO_MEM;
9274                         regs[BPF_REG_0].mem_size = meta.r0_size;
9275
9276                         if (meta.r0_rdonly)
9277                                 regs[BPF_REG_0].type |= MEM_RDONLY;
9278
9279                         /* Ensures we don't access the memory after a release_reference() */
9280                         if (meta.ref_obj_id)
9281                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9282                 } else {
9283                         mark_reg_known_zero(env, regs, BPF_REG_0);
9284                         regs[BPF_REG_0].btf = desc_btf;
9285                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
9286                         regs[BPF_REG_0].btf_id = ptr_type_id;
9287                 }
9288
9289                 if (is_kfunc_ret_null(&meta)) {
9290                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
9291                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
9292                         regs[BPF_REG_0].id = ++env->id_gen;
9293                 }
9294                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
9295                 if (is_kfunc_acquire(&meta)) {
9296                         int id = acquire_reference_state(env, insn_idx);
9297
9298                         if (id < 0)
9299                                 return id;
9300                         if (is_kfunc_ret_null(&meta))
9301                                 regs[BPF_REG_0].id = id;
9302                         regs[BPF_REG_0].ref_obj_id = id;
9303                 }
9304                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
9305                         regs[BPF_REG_0].id = ++env->id_gen;
9306         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
9307
9308         nargs = btf_type_vlen(func_proto);
9309         args = (const struct btf_param *)(func_proto + 1);
9310         for (i = 0; i < nargs; i++) {
9311                 u32 regno = i + 1;
9312
9313                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
9314                 if (btf_type_is_ptr(t))
9315                         mark_btf_func_reg_size(env, regno, sizeof(void *));
9316                 else
9317                         /* scalar. ensured by btf_check_kfunc_arg_match() */
9318                         mark_btf_func_reg_size(env, regno, t->size);
9319         }
9320
9321         return 0;
9322 }
9323
9324 static bool signed_add_overflows(s64 a, s64 b)
9325 {
9326         /* Do the add in u64, where overflow is well-defined */
9327         s64 res = (s64)((u64)a + (u64)b);
9328
9329         if (b < 0)
9330                 return res > a;
9331         return res < a;
9332 }
9333
9334 static bool signed_add32_overflows(s32 a, s32 b)
9335 {
9336         /* Do the add in u32, where overflow is well-defined */
9337         s32 res = (s32)((u32)a + (u32)b);
9338
9339         if (b < 0)
9340                 return res > a;
9341         return res < a;
9342 }
9343
9344 static bool signed_sub_overflows(s64 a, s64 b)
9345 {
9346         /* Do the sub in u64, where overflow is well-defined */
9347         s64 res = (s64)((u64)a - (u64)b);
9348
9349         if (b < 0)
9350                 return res < a;
9351         return res > a;
9352 }
9353
9354 static bool signed_sub32_overflows(s32 a, s32 b)
9355 {
9356         /* Do the sub in u32, where overflow is well-defined */
9357         s32 res = (s32)((u32)a - (u32)b);
9358
9359         if (b < 0)
9360                 return res < a;
9361         return res > a;
9362 }
9363
9364 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
9365                                   const struct bpf_reg_state *reg,
9366                                   enum bpf_reg_type type)
9367 {
9368         bool known = tnum_is_const(reg->var_off);
9369         s64 val = reg->var_off.value;
9370         s64 smin = reg->smin_value;
9371
9372         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
9373                 verbose(env, "math between %s pointer and %lld is not allowed\n",
9374                         reg_type_str(env, type), val);
9375                 return false;
9376         }
9377
9378         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
9379                 verbose(env, "%s pointer offset %d is not allowed\n",
9380                         reg_type_str(env, type), reg->off);
9381                 return false;
9382         }
9383
9384         if (smin == S64_MIN) {
9385                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
9386                         reg_type_str(env, type));
9387                 return false;
9388         }
9389
9390         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
9391                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
9392                         smin, reg_type_str(env, type));
9393                 return false;
9394         }
9395
9396         return true;
9397 }
9398
9399 enum {
9400         REASON_BOUNDS   = -1,
9401         REASON_TYPE     = -2,
9402         REASON_PATHS    = -3,
9403         REASON_LIMIT    = -4,
9404         REASON_STACK    = -5,
9405 };
9406
9407 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
9408                               u32 *alu_limit, bool mask_to_left)
9409 {
9410         u32 max = 0, ptr_limit = 0;
9411
9412         switch (ptr_reg->type) {
9413         case PTR_TO_STACK:
9414                 /* Offset 0 is out-of-bounds, but acceptable start for the
9415                  * left direction, see BPF_REG_FP. Also, unknown scalar
9416                  * offset where we would need to deal with min/max bounds is
9417                  * currently prohibited for unprivileged.
9418                  */
9419                 max = MAX_BPF_STACK + mask_to_left;
9420                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
9421                 break;
9422         case PTR_TO_MAP_VALUE:
9423                 max = ptr_reg->map_ptr->value_size;
9424                 ptr_limit = (mask_to_left ?
9425                              ptr_reg->smin_value :
9426                              ptr_reg->umax_value) + ptr_reg->off;
9427                 break;
9428         default:
9429                 return REASON_TYPE;
9430         }
9431
9432         if (ptr_limit >= max)
9433                 return REASON_LIMIT;
9434         *alu_limit = ptr_limit;
9435         return 0;
9436 }
9437
9438 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
9439                                     const struct bpf_insn *insn)
9440 {
9441         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
9442 }
9443
9444 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
9445                                        u32 alu_state, u32 alu_limit)
9446 {
9447         /* If we arrived here from different branches with different
9448          * state or limits to sanitize, then this won't work.
9449          */
9450         if (aux->alu_state &&
9451             (aux->alu_state != alu_state ||
9452              aux->alu_limit != alu_limit))
9453                 return REASON_PATHS;
9454
9455         /* Corresponding fixup done in do_misc_fixups(). */
9456         aux->alu_state = alu_state;
9457         aux->alu_limit = alu_limit;
9458         return 0;
9459 }
9460
9461 static int sanitize_val_alu(struct bpf_verifier_env *env,
9462                             struct bpf_insn *insn)
9463 {
9464         struct bpf_insn_aux_data *aux = cur_aux(env);
9465
9466         if (can_skip_alu_sanitation(env, insn))
9467                 return 0;
9468
9469         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
9470 }
9471
9472 static bool sanitize_needed(u8 opcode)
9473 {
9474         return opcode == BPF_ADD || opcode == BPF_SUB;
9475 }
9476
9477 struct bpf_sanitize_info {
9478         struct bpf_insn_aux_data aux;
9479         bool mask_to_left;
9480 };
9481
9482 static struct bpf_verifier_state *
9483 sanitize_speculative_path(struct bpf_verifier_env *env,
9484                           const struct bpf_insn *insn,
9485                           u32 next_idx, u32 curr_idx)
9486 {
9487         struct bpf_verifier_state *branch;
9488         struct bpf_reg_state *regs;
9489
9490         branch = push_stack(env, next_idx, curr_idx, true);
9491         if (branch && insn) {
9492                 regs = branch->frame[branch->curframe]->regs;
9493                 if (BPF_SRC(insn->code) == BPF_K) {
9494                         mark_reg_unknown(env, regs, insn->dst_reg);
9495                 } else if (BPF_SRC(insn->code) == BPF_X) {
9496                         mark_reg_unknown(env, regs, insn->dst_reg);
9497                         mark_reg_unknown(env, regs, insn->src_reg);
9498                 }
9499         }
9500         return branch;
9501 }
9502
9503 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
9504                             struct bpf_insn *insn,
9505                             const struct bpf_reg_state *ptr_reg,
9506                             const struct bpf_reg_state *off_reg,
9507                             struct bpf_reg_state *dst_reg,
9508                             struct bpf_sanitize_info *info,
9509                             const bool commit_window)
9510 {
9511         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
9512         struct bpf_verifier_state *vstate = env->cur_state;
9513         bool off_is_imm = tnum_is_const(off_reg->var_off);
9514         bool off_is_neg = off_reg->smin_value < 0;
9515         bool ptr_is_dst_reg = ptr_reg == dst_reg;
9516         u8 opcode = BPF_OP(insn->code);
9517         u32 alu_state, alu_limit;
9518         struct bpf_reg_state tmp;
9519         bool ret;
9520         int err;
9521
9522         if (can_skip_alu_sanitation(env, insn))
9523                 return 0;
9524
9525         /* We already marked aux for masking from non-speculative
9526          * paths, thus we got here in the first place. We only care
9527          * to explore bad access from here.
9528          */
9529         if (vstate->speculative)
9530                 goto do_sim;
9531
9532         if (!commit_window) {
9533                 if (!tnum_is_const(off_reg->var_off) &&
9534                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
9535                         return REASON_BOUNDS;
9536
9537                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
9538                                      (opcode == BPF_SUB && !off_is_neg);
9539         }
9540
9541         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
9542         if (err < 0)
9543                 return err;
9544
9545         if (commit_window) {
9546                 /* In commit phase we narrow the masking window based on
9547                  * the observed pointer move after the simulated operation.
9548                  */
9549                 alu_state = info->aux.alu_state;
9550                 alu_limit = abs(info->aux.alu_limit - alu_limit);
9551         } else {
9552                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
9553                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
9554                 alu_state |= ptr_is_dst_reg ?
9555                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
9556
9557                 /* Limit pruning on unknown scalars to enable deep search for
9558                  * potential masking differences from other program paths.
9559                  */
9560                 if (!off_is_imm)
9561                         env->explore_alu_limits = true;
9562         }
9563
9564         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
9565         if (err < 0)
9566                 return err;
9567 do_sim:
9568         /* If we're in commit phase, we're done here given we already
9569          * pushed the truncated dst_reg into the speculative verification
9570          * stack.
9571          *
9572          * Also, when register is a known constant, we rewrite register-based
9573          * operation to immediate-based, and thus do not need masking (and as
9574          * a consequence, do not need to simulate the zero-truncation either).
9575          */
9576         if (commit_window || off_is_imm)
9577                 return 0;
9578
9579         /* Simulate and find potential out-of-bounds access under
9580          * speculative execution from truncation as a result of
9581          * masking when off was not within expected range. If off
9582          * sits in dst, then we temporarily need to move ptr there
9583          * to simulate dst (== 0) +/-= ptr. Needed, for example,
9584          * for cases where we use K-based arithmetic in one direction
9585          * and truncated reg-based in the other in order to explore
9586          * bad access.
9587          */
9588         if (!ptr_is_dst_reg) {
9589                 tmp = *dst_reg;
9590                 *dst_reg = *ptr_reg;
9591         }
9592         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
9593                                         env->insn_idx);
9594         if (!ptr_is_dst_reg && ret)
9595                 *dst_reg = tmp;
9596         return !ret ? REASON_STACK : 0;
9597 }
9598
9599 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
9600 {
9601         struct bpf_verifier_state *vstate = env->cur_state;
9602
9603         /* If we simulate paths under speculation, we don't update the
9604          * insn as 'seen' such that when we verify unreachable paths in
9605          * the non-speculative domain, sanitize_dead_code() can still
9606          * rewrite/sanitize them.
9607          */
9608         if (!vstate->speculative)
9609                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9610 }
9611
9612 static int sanitize_err(struct bpf_verifier_env *env,
9613                         const struct bpf_insn *insn, int reason,
9614                         const struct bpf_reg_state *off_reg,
9615                         const struct bpf_reg_state *dst_reg)
9616 {
9617         static const char *err = "pointer arithmetic with it prohibited for !root";
9618         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
9619         u32 dst = insn->dst_reg, src = insn->src_reg;
9620
9621         switch (reason) {
9622         case REASON_BOUNDS:
9623                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
9624                         off_reg == dst_reg ? dst : src, err);
9625                 break;
9626         case REASON_TYPE:
9627                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
9628                         off_reg == dst_reg ? src : dst, err);
9629                 break;
9630         case REASON_PATHS:
9631                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
9632                         dst, op, err);
9633                 break;
9634         case REASON_LIMIT:
9635                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
9636                         dst, op, err);
9637                 break;
9638         case REASON_STACK:
9639                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
9640                         dst, err);
9641                 break;
9642         default:
9643                 verbose(env, "verifier internal error: unknown reason (%d)\n",
9644                         reason);
9645                 break;
9646         }
9647
9648         return -EACCES;
9649 }
9650
9651 /* check that stack access falls within stack limits and that 'reg' doesn't
9652  * have a variable offset.
9653  *
9654  * Variable offset is prohibited for unprivileged mode for simplicity since it
9655  * requires corresponding support in Spectre masking for stack ALU.  See also
9656  * retrieve_ptr_limit().
9657  *
9658  *
9659  * 'off' includes 'reg->off'.
9660  */
9661 static int check_stack_access_for_ptr_arithmetic(
9662                                 struct bpf_verifier_env *env,
9663                                 int regno,
9664                                 const struct bpf_reg_state *reg,
9665                                 int off)
9666 {
9667         if (!tnum_is_const(reg->var_off)) {
9668                 char tn_buf[48];
9669
9670                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
9671                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
9672                         regno, tn_buf, off);
9673                 return -EACCES;
9674         }
9675
9676         if (off >= 0 || off < -MAX_BPF_STACK) {
9677                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
9678                         "prohibited for !root; off=%d\n", regno, off);
9679                 return -EACCES;
9680         }
9681
9682         return 0;
9683 }
9684
9685 static int sanitize_check_bounds(struct bpf_verifier_env *env,
9686                                  const struct bpf_insn *insn,
9687                                  const struct bpf_reg_state *dst_reg)
9688 {
9689         u32 dst = insn->dst_reg;
9690
9691         /* For unprivileged we require that resulting offset must be in bounds
9692          * in order to be able to sanitize access later on.
9693          */
9694         if (env->bypass_spec_v1)
9695                 return 0;
9696
9697         switch (dst_reg->type) {
9698         case PTR_TO_STACK:
9699                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
9700                                         dst_reg->off + dst_reg->var_off.value))
9701                         return -EACCES;
9702                 break;
9703         case PTR_TO_MAP_VALUE:
9704                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
9705                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
9706                                 "prohibited for !root\n", dst);
9707                         return -EACCES;
9708                 }
9709                 break;
9710         default:
9711                 break;
9712         }
9713
9714         return 0;
9715 }
9716
9717 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
9718  * Caller should also handle BPF_MOV case separately.
9719  * If we return -EACCES, caller may want to try again treating pointer as a
9720  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
9721  */
9722 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
9723                                    struct bpf_insn *insn,
9724                                    const struct bpf_reg_state *ptr_reg,
9725                                    const struct bpf_reg_state *off_reg)
9726 {
9727         struct bpf_verifier_state *vstate = env->cur_state;
9728         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9729         struct bpf_reg_state *regs = state->regs, *dst_reg;
9730         bool known = tnum_is_const(off_reg->var_off);
9731         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
9732             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
9733         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
9734             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9735         struct bpf_sanitize_info info = {};
9736         u8 opcode = BPF_OP(insn->code);
9737         u32 dst = insn->dst_reg;
9738         int ret;
9739
9740         dst_reg = &regs[dst];
9741
9742         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
9743             smin_val > smax_val || umin_val > umax_val) {
9744                 /* Taint dst register if offset had invalid bounds derived from
9745                  * e.g. dead branches.
9746                  */
9747                 __mark_reg_unknown(env, dst_reg);
9748                 return 0;
9749         }
9750
9751         if (BPF_CLASS(insn->code) != BPF_ALU64) {
9752                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
9753                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9754                         __mark_reg_unknown(env, dst_reg);
9755                         return 0;
9756                 }
9757
9758                 verbose(env,
9759                         "R%d 32-bit pointer arithmetic prohibited\n",
9760                         dst);
9761                 return -EACCES;
9762         }
9763
9764         if (ptr_reg->type & PTR_MAYBE_NULL) {
9765                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
9766                         dst, reg_type_str(env, ptr_reg->type));
9767                 return -EACCES;
9768         }
9769
9770         switch (base_type(ptr_reg->type)) {
9771         case CONST_PTR_TO_MAP:
9772                 /* smin_val represents the known value */
9773                 if (known && smin_val == 0 && opcode == BPF_ADD)
9774                         break;
9775                 fallthrough;
9776         case PTR_TO_PACKET_END:
9777         case PTR_TO_SOCKET:
9778         case PTR_TO_SOCK_COMMON:
9779         case PTR_TO_TCP_SOCK:
9780         case PTR_TO_XDP_SOCK:
9781                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
9782                         dst, reg_type_str(env, ptr_reg->type));
9783                 return -EACCES;
9784         default:
9785                 break;
9786         }
9787
9788         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
9789          * The id may be overwritten later if we create a new variable offset.
9790          */
9791         dst_reg->type = ptr_reg->type;
9792         dst_reg->id = ptr_reg->id;
9793
9794         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
9795             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
9796                 return -EINVAL;
9797
9798         /* pointer types do not carry 32-bit bounds at the moment. */
9799         __mark_reg32_unbounded(dst_reg);
9800
9801         if (sanitize_needed(opcode)) {
9802                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
9803                                        &info, false);
9804                 if (ret < 0)
9805                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
9806         }
9807
9808         switch (opcode) {
9809         case BPF_ADD:
9810                 /* We can take a fixed offset as long as it doesn't overflow
9811                  * the s32 'off' field
9812                  */
9813                 if (known && (ptr_reg->off + smin_val ==
9814                               (s64)(s32)(ptr_reg->off + smin_val))) {
9815                         /* pointer += K.  Accumulate it into fixed offset */
9816                         dst_reg->smin_value = smin_ptr;
9817                         dst_reg->smax_value = smax_ptr;
9818                         dst_reg->umin_value = umin_ptr;
9819                         dst_reg->umax_value = umax_ptr;
9820                         dst_reg->var_off = ptr_reg->var_off;
9821                         dst_reg->off = ptr_reg->off + smin_val;
9822                         dst_reg->raw = ptr_reg->raw;
9823                         break;
9824                 }
9825                 /* A new variable offset is created.  Note that off_reg->off
9826                  * == 0, since it's a scalar.
9827                  * dst_reg gets the pointer type and since some positive
9828                  * integer value was added to the pointer, give it a new 'id'
9829                  * if it's a PTR_TO_PACKET.
9830                  * this creates a new 'base' pointer, off_reg (variable) gets
9831                  * added into the variable offset, and we copy the fixed offset
9832                  * from ptr_reg.
9833                  */
9834                 if (signed_add_overflows(smin_ptr, smin_val) ||
9835                     signed_add_overflows(smax_ptr, smax_val)) {
9836                         dst_reg->smin_value = S64_MIN;
9837                         dst_reg->smax_value = S64_MAX;
9838                 } else {
9839                         dst_reg->smin_value = smin_ptr + smin_val;
9840                         dst_reg->smax_value = smax_ptr + smax_val;
9841                 }
9842                 if (umin_ptr + umin_val < umin_ptr ||
9843                     umax_ptr + umax_val < umax_ptr) {
9844                         dst_reg->umin_value = 0;
9845                         dst_reg->umax_value = U64_MAX;
9846                 } else {
9847                         dst_reg->umin_value = umin_ptr + umin_val;
9848                         dst_reg->umax_value = umax_ptr + umax_val;
9849                 }
9850                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
9851                 dst_reg->off = ptr_reg->off;
9852                 dst_reg->raw = ptr_reg->raw;
9853                 if (reg_is_pkt_pointer(ptr_reg)) {
9854                         dst_reg->id = ++env->id_gen;
9855                         /* something was added to pkt_ptr, set range to zero */
9856                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9857                 }
9858                 break;
9859         case BPF_SUB:
9860                 if (dst_reg == off_reg) {
9861                         /* scalar -= pointer.  Creates an unknown scalar */
9862                         verbose(env, "R%d tried to subtract pointer from scalar\n",
9863                                 dst);
9864                         return -EACCES;
9865                 }
9866                 /* We don't allow subtraction from FP, because (according to
9867                  * test_verifier.c test "invalid fp arithmetic", JITs might not
9868                  * be able to deal with it.
9869                  */
9870                 if (ptr_reg->type == PTR_TO_STACK) {
9871                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
9872                                 dst);
9873                         return -EACCES;
9874                 }
9875                 if (known && (ptr_reg->off - smin_val ==
9876                               (s64)(s32)(ptr_reg->off - smin_val))) {
9877                         /* pointer -= K.  Subtract it from fixed offset */
9878                         dst_reg->smin_value = smin_ptr;
9879                         dst_reg->smax_value = smax_ptr;
9880                         dst_reg->umin_value = umin_ptr;
9881                         dst_reg->umax_value = umax_ptr;
9882                         dst_reg->var_off = ptr_reg->var_off;
9883                         dst_reg->id = ptr_reg->id;
9884                         dst_reg->off = ptr_reg->off - smin_val;
9885                         dst_reg->raw = ptr_reg->raw;
9886                         break;
9887                 }
9888                 /* A new variable offset is created.  If the subtrahend is known
9889                  * nonnegative, then any reg->range we had before is still good.
9890                  */
9891                 if (signed_sub_overflows(smin_ptr, smax_val) ||
9892                     signed_sub_overflows(smax_ptr, smin_val)) {
9893                         /* Overflow possible, we know nothing */
9894                         dst_reg->smin_value = S64_MIN;
9895                         dst_reg->smax_value = S64_MAX;
9896                 } else {
9897                         dst_reg->smin_value = smin_ptr - smax_val;
9898                         dst_reg->smax_value = smax_ptr - smin_val;
9899                 }
9900                 if (umin_ptr < umax_val) {
9901                         /* Overflow possible, we know nothing */
9902                         dst_reg->umin_value = 0;
9903                         dst_reg->umax_value = U64_MAX;
9904                 } else {
9905                         /* Cannot overflow (as long as bounds are consistent) */
9906                         dst_reg->umin_value = umin_ptr - umax_val;
9907                         dst_reg->umax_value = umax_ptr - umin_val;
9908                 }
9909                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
9910                 dst_reg->off = ptr_reg->off;
9911                 dst_reg->raw = ptr_reg->raw;
9912                 if (reg_is_pkt_pointer(ptr_reg)) {
9913                         dst_reg->id = ++env->id_gen;
9914                         /* something was added to pkt_ptr, set range to zero */
9915                         if (smin_val < 0)
9916                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9917                 }
9918                 break;
9919         case BPF_AND:
9920         case BPF_OR:
9921         case BPF_XOR:
9922                 /* bitwise ops on pointers are troublesome, prohibit. */
9923                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
9924                         dst, bpf_alu_string[opcode >> 4]);
9925                 return -EACCES;
9926         default:
9927                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
9928                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
9929                         dst, bpf_alu_string[opcode >> 4]);
9930                 return -EACCES;
9931         }
9932
9933         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
9934                 return -EINVAL;
9935         reg_bounds_sync(dst_reg);
9936         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
9937                 return -EACCES;
9938         if (sanitize_needed(opcode)) {
9939                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
9940                                        &info, true);
9941                 if (ret < 0)
9942                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
9943         }
9944
9945         return 0;
9946 }
9947
9948 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
9949                                  struct bpf_reg_state *src_reg)
9950 {
9951         s32 smin_val = src_reg->s32_min_value;
9952         s32 smax_val = src_reg->s32_max_value;
9953         u32 umin_val = src_reg->u32_min_value;
9954         u32 umax_val = src_reg->u32_max_value;
9955
9956         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
9957             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
9958                 dst_reg->s32_min_value = S32_MIN;
9959                 dst_reg->s32_max_value = S32_MAX;
9960         } else {
9961                 dst_reg->s32_min_value += smin_val;
9962                 dst_reg->s32_max_value += smax_val;
9963         }
9964         if (dst_reg->u32_min_value + umin_val < umin_val ||
9965             dst_reg->u32_max_value + umax_val < umax_val) {
9966                 dst_reg->u32_min_value = 0;
9967                 dst_reg->u32_max_value = U32_MAX;
9968         } else {
9969                 dst_reg->u32_min_value += umin_val;
9970                 dst_reg->u32_max_value += umax_val;
9971         }
9972 }
9973
9974 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
9975                                struct bpf_reg_state *src_reg)
9976 {
9977         s64 smin_val = src_reg->smin_value;
9978         s64 smax_val = src_reg->smax_value;
9979         u64 umin_val = src_reg->umin_value;
9980         u64 umax_val = src_reg->umax_value;
9981
9982         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
9983             signed_add_overflows(dst_reg->smax_value, smax_val)) {
9984                 dst_reg->smin_value = S64_MIN;
9985                 dst_reg->smax_value = S64_MAX;
9986         } else {
9987                 dst_reg->smin_value += smin_val;
9988                 dst_reg->smax_value += smax_val;
9989         }
9990         if (dst_reg->umin_value + umin_val < umin_val ||
9991             dst_reg->umax_value + umax_val < umax_val) {
9992                 dst_reg->umin_value = 0;
9993                 dst_reg->umax_value = U64_MAX;
9994         } else {
9995                 dst_reg->umin_value += umin_val;
9996                 dst_reg->umax_value += umax_val;
9997         }
9998 }
9999
10000 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
10001                                  struct bpf_reg_state *src_reg)
10002 {
10003         s32 smin_val = src_reg->s32_min_value;
10004         s32 smax_val = src_reg->s32_max_value;
10005         u32 umin_val = src_reg->u32_min_value;
10006         u32 umax_val = src_reg->u32_max_value;
10007
10008         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
10009             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
10010                 /* Overflow possible, we know nothing */
10011                 dst_reg->s32_min_value = S32_MIN;
10012                 dst_reg->s32_max_value = S32_MAX;
10013         } else {
10014                 dst_reg->s32_min_value -= smax_val;
10015                 dst_reg->s32_max_value -= smin_val;
10016         }
10017         if (dst_reg->u32_min_value < umax_val) {
10018                 /* Overflow possible, we know nothing */
10019                 dst_reg->u32_min_value = 0;
10020                 dst_reg->u32_max_value = U32_MAX;
10021         } else {
10022                 /* Cannot overflow (as long as bounds are consistent) */
10023                 dst_reg->u32_min_value -= umax_val;
10024                 dst_reg->u32_max_value -= umin_val;
10025         }
10026 }
10027
10028 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
10029                                struct bpf_reg_state *src_reg)
10030 {
10031         s64 smin_val = src_reg->smin_value;
10032         s64 smax_val = src_reg->smax_value;
10033         u64 umin_val = src_reg->umin_value;
10034         u64 umax_val = src_reg->umax_value;
10035
10036         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
10037             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
10038                 /* Overflow possible, we know nothing */
10039                 dst_reg->smin_value = S64_MIN;
10040                 dst_reg->smax_value = S64_MAX;
10041         } else {
10042                 dst_reg->smin_value -= smax_val;
10043                 dst_reg->smax_value -= smin_val;
10044         }
10045         if (dst_reg->umin_value < umax_val) {
10046                 /* Overflow possible, we know nothing */
10047                 dst_reg->umin_value = 0;
10048                 dst_reg->umax_value = U64_MAX;
10049         } else {
10050                 /* Cannot overflow (as long as bounds are consistent) */
10051                 dst_reg->umin_value -= umax_val;
10052                 dst_reg->umax_value -= umin_val;
10053         }
10054 }
10055
10056 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
10057                                  struct bpf_reg_state *src_reg)
10058 {
10059         s32 smin_val = src_reg->s32_min_value;
10060         u32 umin_val = src_reg->u32_min_value;
10061         u32 umax_val = src_reg->u32_max_value;
10062
10063         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
10064                 /* Ain't nobody got time to multiply that sign */
10065                 __mark_reg32_unbounded(dst_reg);
10066                 return;
10067         }
10068         /* Both values are positive, so we can work with unsigned and
10069          * copy the result to signed (unless it exceeds S32_MAX).
10070          */
10071         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
10072                 /* Potential overflow, we know nothing */
10073                 __mark_reg32_unbounded(dst_reg);
10074                 return;
10075         }
10076         dst_reg->u32_min_value *= umin_val;
10077         dst_reg->u32_max_value *= umax_val;
10078         if (dst_reg->u32_max_value > S32_MAX) {
10079                 /* Overflow possible, we know nothing */
10080                 dst_reg->s32_min_value = S32_MIN;
10081                 dst_reg->s32_max_value = S32_MAX;
10082         } else {
10083                 dst_reg->s32_min_value = dst_reg->u32_min_value;
10084                 dst_reg->s32_max_value = dst_reg->u32_max_value;
10085         }
10086 }
10087
10088 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
10089                                struct bpf_reg_state *src_reg)
10090 {
10091         s64 smin_val = src_reg->smin_value;
10092         u64 umin_val = src_reg->umin_value;
10093         u64 umax_val = src_reg->umax_value;
10094
10095         if (smin_val < 0 || dst_reg->smin_value < 0) {
10096                 /* Ain't nobody got time to multiply that sign */
10097                 __mark_reg64_unbounded(dst_reg);
10098                 return;
10099         }
10100         /* Both values are positive, so we can work with unsigned and
10101          * copy the result to signed (unless it exceeds S64_MAX).
10102          */
10103         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
10104                 /* Potential overflow, we know nothing */
10105                 __mark_reg64_unbounded(dst_reg);
10106                 return;
10107         }
10108         dst_reg->umin_value *= umin_val;
10109         dst_reg->umax_value *= umax_val;
10110         if (dst_reg->umax_value > S64_MAX) {
10111                 /* Overflow possible, we know nothing */
10112                 dst_reg->smin_value = S64_MIN;
10113                 dst_reg->smax_value = S64_MAX;
10114         } else {
10115                 dst_reg->smin_value = dst_reg->umin_value;
10116                 dst_reg->smax_value = dst_reg->umax_value;
10117         }
10118 }
10119
10120 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
10121                                  struct bpf_reg_state *src_reg)
10122 {
10123         bool src_known = tnum_subreg_is_const(src_reg->var_off);
10124         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10125         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10126         s32 smin_val = src_reg->s32_min_value;
10127         u32 umax_val = src_reg->u32_max_value;
10128
10129         if (src_known && dst_known) {
10130                 __mark_reg32_known(dst_reg, var32_off.value);
10131                 return;
10132         }
10133
10134         /* We get our minimum from the var_off, since that's inherently
10135          * bitwise.  Our maximum is the minimum of the operands' maxima.
10136          */
10137         dst_reg->u32_min_value = var32_off.value;
10138         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
10139         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10140                 /* Lose signed bounds when ANDing negative numbers,
10141                  * ain't nobody got time for that.
10142                  */
10143                 dst_reg->s32_min_value = S32_MIN;
10144                 dst_reg->s32_max_value = S32_MAX;
10145         } else {
10146                 /* ANDing two positives gives a positive, so safe to
10147                  * cast result into s64.
10148                  */
10149                 dst_reg->s32_min_value = dst_reg->u32_min_value;
10150                 dst_reg->s32_max_value = dst_reg->u32_max_value;
10151         }
10152 }
10153
10154 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
10155                                struct bpf_reg_state *src_reg)
10156 {
10157         bool src_known = tnum_is_const(src_reg->var_off);
10158         bool dst_known = tnum_is_const(dst_reg->var_off);
10159         s64 smin_val = src_reg->smin_value;
10160         u64 umax_val = src_reg->umax_value;
10161
10162         if (src_known && dst_known) {
10163                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
10164                 return;
10165         }
10166
10167         /* We get our minimum from the var_off, since that's inherently
10168          * bitwise.  Our maximum is the minimum of the operands' maxima.
10169          */
10170         dst_reg->umin_value = dst_reg->var_off.value;
10171         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
10172         if (dst_reg->smin_value < 0 || smin_val < 0) {
10173                 /* Lose signed bounds when ANDing negative numbers,
10174                  * ain't nobody got time for that.
10175                  */
10176                 dst_reg->smin_value = S64_MIN;
10177                 dst_reg->smax_value = S64_MAX;
10178         } else {
10179                 /* ANDing two positives gives a positive, so safe to
10180                  * cast result into s64.
10181                  */
10182                 dst_reg->smin_value = dst_reg->umin_value;
10183                 dst_reg->smax_value = dst_reg->umax_value;
10184         }
10185         /* We may learn something more from the var_off */
10186         __update_reg_bounds(dst_reg);
10187 }
10188
10189 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
10190                                 struct bpf_reg_state *src_reg)
10191 {
10192         bool src_known = tnum_subreg_is_const(src_reg->var_off);
10193         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10194         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10195         s32 smin_val = src_reg->s32_min_value;
10196         u32 umin_val = src_reg->u32_min_value;
10197
10198         if (src_known && dst_known) {
10199                 __mark_reg32_known(dst_reg, var32_off.value);
10200                 return;
10201         }
10202
10203         /* We get our maximum from the var_off, and our minimum is the
10204          * maximum of the operands' minima
10205          */
10206         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
10207         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10208         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10209                 /* Lose signed bounds when ORing negative numbers,
10210                  * ain't nobody got time for that.
10211                  */
10212                 dst_reg->s32_min_value = S32_MIN;
10213                 dst_reg->s32_max_value = S32_MAX;
10214         } else {
10215                 /* ORing two positives gives a positive, so safe to
10216                  * cast result into s64.
10217                  */
10218                 dst_reg->s32_min_value = dst_reg->u32_min_value;
10219                 dst_reg->s32_max_value = dst_reg->u32_max_value;
10220         }
10221 }
10222
10223 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
10224                               struct bpf_reg_state *src_reg)
10225 {
10226         bool src_known = tnum_is_const(src_reg->var_off);
10227         bool dst_known = tnum_is_const(dst_reg->var_off);
10228         s64 smin_val = src_reg->smin_value;
10229         u64 umin_val = src_reg->umin_value;
10230
10231         if (src_known && dst_known) {
10232                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
10233                 return;
10234         }
10235
10236         /* We get our maximum from the var_off, and our minimum is the
10237          * maximum of the operands' minima
10238          */
10239         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
10240         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10241         if (dst_reg->smin_value < 0 || smin_val < 0) {
10242                 /* Lose signed bounds when ORing negative numbers,
10243                  * ain't nobody got time for that.
10244                  */
10245                 dst_reg->smin_value = S64_MIN;
10246                 dst_reg->smax_value = S64_MAX;
10247         } else {
10248                 /* ORing two positives gives a positive, so safe to
10249                  * cast result into s64.
10250                  */
10251                 dst_reg->smin_value = dst_reg->umin_value;
10252                 dst_reg->smax_value = dst_reg->umax_value;
10253         }
10254         /* We may learn something more from the var_off */
10255         __update_reg_bounds(dst_reg);
10256 }
10257
10258 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
10259                                  struct bpf_reg_state *src_reg)
10260 {
10261         bool src_known = tnum_subreg_is_const(src_reg->var_off);
10262         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10263         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10264         s32 smin_val = src_reg->s32_min_value;
10265
10266         if (src_known && dst_known) {
10267                 __mark_reg32_known(dst_reg, var32_off.value);
10268                 return;
10269         }
10270
10271         /* We get both minimum and maximum from the var32_off. */
10272         dst_reg->u32_min_value = var32_off.value;
10273         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10274
10275         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
10276                 /* XORing two positive sign numbers gives a positive,
10277                  * so safe to cast u32 result into s32.
10278                  */
10279                 dst_reg->s32_min_value = dst_reg->u32_min_value;
10280                 dst_reg->s32_max_value = dst_reg->u32_max_value;
10281         } else {
10282                 dst_reg->s32_min_value = S32_MIN;
10283                 dst_reg->s32_max_value = S32_MAX;
10284         }
10285 }
10286
10287 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
10288                                struct bpf_reg_state *src_reg)
10289 {
10290         bool src_known = tnum_is_const(src_reg->var_off);
10291         bool dst_known = tnum_is_const(dst_reg->var_off);
10292         s64 smin_val = src_reg->smin_value;
10293
10294         if (src_known && dst_known) {
10295                 /* dst_reg->var_off.value has been updated earlier */
10296                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
10297                 return;
10298         }
10299
10300         /* We get both minimum and maximum from the var_off. */
10301         dst_reg->umin_value = dst_reg->var_off.value;
10302         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10303
10304         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
10305                 /* XORing two positive sign numbers gives a positive,
10306                  * so safe to cast u64 result into s64.
10307                  */
10308                 dst_reg->smin_value = dst_reg->umin_value;
10309                 dst_reg->smax_value = dst_reg->umax_value;
10310         } else {
10311                 dst_reg->smin_value = S64_MIN;
10312                 dst_reg->smax_value = S64_MAX;
10313         }
10314
10315         __update_reg_bounds(dst_reg);
10316 }
10317
10318 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10319                                    u64 umin_val, u64 umax_val)
10320 {
10321         /* We lose all sign bit information (except what we can pick
10322          * up from var_off)
10323          */
10324         dst_reg->s32_min_value = S32_MIN;
10325         dst_reg->s32_max_value = S32_MAX;
10326         /* If we might shift our top bit out, then we know nothing */
10327         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
10328                 dst_reg->u32_min_value = 0;
10329                 dst_reg->u32_max_value = U32_MAX;
10330         } else {
10331                 dst_reg->u32_min_value <<= umin_val;
10332                 dst_reg->u32_max_value <<= umax_val;
10333         }
10334 }
10335
10336 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10337                                  struct bpf_reg_state *src_reg)
10338 {
10339         u32 umax_val = src_reg->u32_max_value;
10340         u32 umin_val = src_reg->u32_min_value;
10341         /* u32 alu operation will zext upper bits */
10342         struct tnum subreg = tnum_subreg(dst_reg->var_off);
10343
10344         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10345         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
10346         /* Not required but being careful mark reg64 bounds as unknown so
10347          * that we are forced to pick them up from tnum and zext later and
10348          * if some path skips this step we are still safe.
10349          */
10350         __mark_reg64_unbounded(dst_reg);
10351         __update_reg32_bounds(dst_reg);
10352 }
10353
10354 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
10355                                    u64 umin_val, u64 umax_val)
10356 {
10357         /* Special case <<32 because it is a common compiler pattern to sign
10358          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
10359          * positive we know this shift will also be positive so we can track
10360          * bounds correctly. Otherwise we lose all sign bit information except
10361          * what we can pick up from var_off. Perhaps we can generalize this
10362          * later to shifts of any length.
10363          */
10364         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
10365                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
10366         else
10367                 dst_reg->smax_value = S64_MAX;
10368
10369         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
10370                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
10371         else
10372                 dst_reg->smin_value = S64_MIN;
10373
10374         /* If we might shift our top bit out, then we know nothing */
10375         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
10376                 dst_reg->umin_value = 0;
10377                 dst_reg->umax_value = U64_MAX;
10378         } else {
10379                 dst_reg->umin_value <<= umin_val;
10380                 dst_reg->umax_value <<= umax_val;
10381         }
10382 }
10383
10384 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
10385                                struct bpf_reg_state *src_reg)
10386 {
10387         u64 umax_val = src_reg->umax_value;
10388         u64 umin_val = src_reg->umin_value;
10389
10390         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
10391         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
10392         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10393
10394         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
10395         /* We may learn something more from the var_off */
10396         __update_reg_bounds(dst_reg);
10397 }
10398
10399 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
10400                                  struct bpf_reg_state *src_reg)
10401 {
10402         struct tnum subreg = tnum_subreg(dst_reg->var_off);
10403         u32 umax_val = src_reg->u32_max_value;
10404         u32 umin_val = src_reg->u32_min_value;
10405
10406         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10407          * be negative, then either:
10408          * 1) src_reg might be zero, so the sign bit of the result is
10409          *    unknown, so we lose our signed bounds
10410          * 2) it's known negative, thus the unsigned bounds capture the
10411          *    signed bounds
10412          * 3) the signed bounds cross zero, so they tell us nothing
10413          *    about the result
10414          * If the value in dst_reg is known nonnegative, then again the
10415          * unsigned bounds capture the signed bounds.
10416          * Thus, in all cases it suffices to blow away our signed bounds
10417          * and rely on inferring new ones from the unsigned bounds and
10418          * var_off of the result.
10419          */
10420         dst_reg->s32_min_value = S32_MIN;
10421         dst_reg->s32_max_value = S32_MAX;
10422
10423         dst_reg->var_off = tnum_rshift(subreg, umin_val);
10424         dst_reg->u32_min_value >>= umax_val;
10425         dst_reg->u32_max_value >>= umin_val;
10426
10427         __mark_reg64_unbounded(dst_reg);
10428         __update_reg32_bounds(dst_reg);
10429 }
10430
10431 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
10432                                struct bpf_reg_state *src_reg)
10433 {
10434         u64 umax_val = src_reg->umax_value;
10435         u64 umin_val = src_reg->umin_value;
10436
10437         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10438          * be negative, then either:
10439          * 1) src_reg might be zero, so the sign bit of the result is
10440          *    unknown, so we lose our signed bounds
10441          * 2) it's known negative, thus the unsigned bounds capture the
10442          *    signed bounds
10443          * 3) the signed bounds cross zero, so they tell us nothing
10444          *    about the result
10445          * If the value in dst_reg is known nonnegative, then again the
10446          * unsigned bounds capture the signed bounds.
10447          * Thus, in all cases it suffices to blow away our signed bounds
10448          * and rely on inferring new ones from the unsigned bounds and
10449          * var_off of the result.
10450          */
10451         dst_reg->smin_value = S64_MIN;
10452         dst_reg->smax_value = S64_MAX;
10453         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
10454         dst_reg->umin_value >>= umax_val;
10455         dst_reg->umax_value >>= umin_val;
10456
10457         /* Its not easy to operate on alu32 bounds here because it depends
10458          * on bits being shifted in. Take easy way out and mark unbounded
10459          * so we can recalculate later from tnum.
10460          */
10461         __mark_reg32_unbounded(dst_reg);
10462         __update_reg_bounds(dst_reg);
10463 }
10464
10465 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
10466                                   struct bpf_reg_state *src_reg)
10467 {
10468         u64 umin_val = src_reg->u32_min_value;
10469
10470         /* Upon reaching here, src_known is true and
10471          * umax_val is equal to umin_val.
10472          */
10473         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
10474         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
10475
10476         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
10477
10478         /* blow away the dst_reg umin_value/umax_value and rely on
10479          * dst_reg var_off to refine the result.
10480          */
10481         dst_reg->u32_min_value = 0;
10482         dst_reg->u32_max_value = U32_MAX;
10483
10484         __mark_reg64_unbounded(dst_reg);
10485         __update_reg32_bounds(dst_reg);
10486 }
10487
10488 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
10489                                 struct bpf_reg_state *src_reg)
10490 {
10491         u64 umin_val = src_reg->umin_value;
10492
10493         /* Upon reaching here, src_known is true and umax_val is equal
10494          * to umin_val.
10495          */
10496         dst_reg->smin_value >>= umin_val;
10497         dst_reg->smax_value >>= umin_val;
10498
10499         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
10500
10501         /* blow away the dst_reg umin_value/umax_value and rely on
10502          * dst_reg var_off to refine the result.
10503          */
10504         dst_reg->umin_value = 0;
10505         dst_reg->umax_value = U64_MAX;
10506
10507         /* Its not easy to operate on alu32 bounds here because it depends
10508          * on bits being shifted in from upper 32-bits. Take easy way out
10509          * and mark unbounded so we can recalculate later from tnum.
10510          */
10511         __mark_reg32_unbounded(dst_reg);
10512         __update_reg_bounds(dst_reg);
10513 }
10514
10515 /* WARNING: This function does calculations on 64-bit values, but the actual
10516  * execution may occur on 32-bit values. Therefore, things like bitshifts
10517  * need extra checks in the 32-bit case.
10518  */
10519 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
10520                                       struct bpf_insn *insn,
10521                                       struct bpf_reg_state *dst_reg,
10522                                       struct bpf_reg_state src_reg)
10523 {
10524         struct bpf_reg_state *regs = cur_regs(env);
10525         u8 opcode = BPF_OP(insn->code);
10526         bool src_known;
10527         s64 smin_val, smax_val;
10528         u64 umin_val, umax_val;
10529         s32 s32_min_val, s32_max_val;
10530         u32 u32_min_val, u32_max_val;
10531         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
10532         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
10533         int ret;
10534
10535         smin_val = src_reg.smin_value;
10536         smax_val = src_reg.smax_value;
10537         umin_val = src_reg.umin_value;
10538         umax_val = src_reg.umax_value;
10539
10540         s32_min_val = src_reg.s32_min_value;
10541         s32_max_val = src_reg.s32_max_value;
10542         u32_min_val = src_reg.u32_min_value;
10543         u32_max_val = src_reg.u32_max_value;
10544
10545         if (alu32) {
10546                 src_known = tnum_subreg_is_const(src_reg.var_off);
10547                 if ((src_known &&
10548                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
10549                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
10550                         /* Taint dst register if offset had invalid bounds
10551                          * derived from e.g. dead branches.
10552                          */
10553                         __mark_reg_unknown(env, dst_reg);
10554                         return 0;
10555                 }
10556         } else {
10557                 src_known = tnum_is_const(src_reg.var_off);
10558                 if ((src_known &&
10559                      (smin_val != smax_val || umin_val != umax_val)) ||
10560                     smin_val > smax_val || umin_val > umax_val) {
10561                         /* Taint dst register if offset had invalid bounds
10562                          * derived from e.g. dead branches.
10563                          */
10564                         __mark_reg_unknown(env, dst_reg);
10565                         return 0;
10566                 }
10567         }
10568
10569         if (!src_known &&
10570             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
10571                 __mark_reg_unknown(env, dst_reg);
10572                 return 0;
10573         }
10574
10575         if (sanitize_needed(opcode)) {
10576                 ret = sanitize_val_alu(env, insn);
10577                 if (ret < 0)
10578                         return sanitize_err(env, insn, ret, NULL, NULL);
10579         }
10580
10581         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
10582          * There are two classes of instructions: The first class we track both
10583          * alu32 and alu64 sign/unsigned bounds independently this provides the
10584          * greatest amount of precision when alu operations are mixed with jmp32
10585          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
10586          * and BPF_OR. This is possible because these ops have fairly easy to
10587          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
10588          * See alu32 verifier tests for examples. The second class of
10589          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
10590          * with regards to tracking sign/unsigned bounds because the bits may
10591          * cross subreg boundaries in the alu64 case. When this happens we mark
10592          * the reg unbounded in the subreg bound space and use the resulting
10593          * tnum to calculate an approximation of the sign/unsigned bounds.
10594          */
10595         switch (opcode) {
10596         case BPF_ADD:
10597                 scalar32_min_max_add(dst_reg, &src_reg);
10598                 scalar_min_max_add(dst_reg, &src_reg);
10599                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
10600                 break;
10601         case BPF_SUB:
10602                 scalar32_min_max_sub(dst_reg, &src_reg);
10603                 scalar_min_max_sub(dst_reg, &src_reg);
10604                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
10605                 break;
10606         case BPF_MUL:
10607                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
10608                 scalar32_min_max_mul(dst_reg, &src_reg);
10609                 scalar_min_max_mul(dst_reg, &src_reg);
10610                 break;
10611         case BPF_AND:
10612                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
10613                 scalar32_min_max_and(dst_reg, &src_reg);
10614                 scalar_min_max_and(dst_reg, &src_reg);
10615                 break;
10616         case BPF_OR:
10617                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
10618                 scalar32_min_max_or(dst_reg, &src_reg);
10619                 scalar_min_max_or(dst_reg, &src_reg);
10620                 break;
10621         case BPF_XOR:
10622                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
10623                 scalar32_min_max_xor(dst_reg, &src_reg);
10624                 scalar_min_max_xor(dst_reg, &src_reg);
10625                 break;
10626         case BPF_LSH:
10627                 if (umax_val >= insn_bitness) {
10628                         /* Shifts greater than 31 or 63 are undefined.
10629                          * This includes shifts by a negative number.
10630                          */
10631                         mark_reg_unknown(env, regs, insn->dst_reg);
10632                         break;
10633                 }
10634                 if (alu32)
10635                         scalar32_min_max_lsh(dst_reg, &src_reg);
10636                 else
10637                         scalar_min_max_lsh(dst_reg, &src_reg);
10638                 break;
10639         case BPF_RSH:
10640                 if (umax_val >= insn_bitness) {
10641                         /* Shifts greater than 31 or 63 are undefined.
10642                          * This includes shifts by a negative number.
10643                          */
10644                         mark_reg_unknown(env, regs, insn->dst_reg);
10645                         break;
10646                 }
10647                 if (alu32)
10648                         scalar32_min_max_rsh(dst_reg, &src_reg);
10649                 else
10650                         scalar_min_max_rsh(dst_reg, &src_reg);
10651                 break;
10652         case BPF_ARSH:
10653                 if (umax_val >= insn_bitness) {
10654                         /* Shifts greater than 31 or 63 are undefined.
10655                          * This includes shifts by a negative number.
10656                          */
10657                         mark_reg_unknown(env, regs, insn->dst_reg);
10658                         break;
10659                 }
10660                 if (alu32)
10661                         scalar32_min_max_arsh(dst_reg, &src_reg);
10662                 else
10663                         scalar_min_max_arsh(dst_reg, &src_reg);
10664                 break;
10665         default:
10666                 mark_reg_unknown(env, regs, insn->dst_reg);
10667                 break;
10668         }
10669
10670         /* ALU32 ops are zero extended into 64bit register */
10671         if (alu32)
10672                 zext_32_to_64(dst_reg);
10673         reg_bounds_sync(dst_reg);
10674         return 0;
10675 }
10676
10677 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
10678  * and var_off.
10679  */
10680 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
10681                                    struct bpf_insn *insn)
10682 {
10683         struct bpf_verifier_state *vstate = env->cur_state;
10684         struct bpf_func_state *state = vstate->frame[vstate->curframe];
10685         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
10686         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
10687         u8 opcode = BPF_OP(insn->code);
10688         int err;
10689
10690         dst_reg = &regs[insn->dst_reg];
10691         src_reg = NULL;
10692         if (dst_reg->type != SCALAR_VALUE)
10693                 ptr_reg = dst_reg;
10694         else
10695                 /* Make sure ID is cleared otherwise dst_reg min/max could be
10696                  * incorrectly propagated into other registers by find_equal_scalars()
10697                  */
10698                 dst_reg->id = 0;
10699         if (BPF_SRC(insn->code) == BPF_X) {
10700                 src_reg = &regs[insn->src_reg];
10701                 if (src_reg->type != SCALAR_VALUE) {
10702                         if (dst_reg->type != SCALAR_VALUE) {
10703                                 /* Combining two pointers by any ALU op yields
10704                                  * an arbitrary scalar. Disallow all math except
10705                                  * pointer subtraction
10706                                  */
10707                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10708                                         mark_reg_unknown(env, regs, insn->dst_reg);
10709                                         return 0;
10710                                 }
10711                                 verbose(env, "R%d pointer %s pointer prohibited\n",
10712                                         insn->dst_reg,
10713                                         bpf_alu_string[opcode >> 4]);
10714                                 return -EACCES;
10715                         } else {
10716                                 /* scalar += pointer
10717                                  * This is legal, but we have to reverse our
10718                                  * src/dest handling in computing the range
10719                                  */
10720                                 err = mark_chain_precision(env, insn->dst_reg);
10721                                 if (err)
10722                                         return err;
10723                                 return adjust_ptr_min_max_vals(env, insn,
10724                                                                src_reg, dst_reg);
10725                         }
10726                 } else if (ptr_reg) {
10727                         /* pointer += scalar */
10728                         err = mark_chain_precision(env, insn->src_reg);
10729                         if (err)
10730                                 return err;
10731                         return adjust_ptr_min_max_vals(env, insn,
10732                                                        dst_reg, src_reg);
10733                 } else if (dst_reg->precise) {
10734                         /* if dst_reg is precise, src_reg should be precise as well */
10735                         err = mark_chain_precision(env, insn->src_reg);
10736                         if (err)
10737                                 return err;
10738                 }
10739         } else {
10740                 /* Pretend the src is a reg with a known value, since we only
10741                  * need to be able to read from this state.
10742                  */
10743                 off_reg.type = SCALAR_VALUE;
10744                 __mark_reg_known(&off_reg, insn->imm);
10745                 src_reg = &off_reg;
10746                 if (ptr_reg) /* pointer += K */
10747                         return adjust_ptr_min_max_vals(env, insn,
10748                                                        ptr_reg, src_reg);
10749         }
10750
10751         /* Got here implies adding two SCALAR_VALUEs */
10752         if (WARN_ON_ONCE(ptr_reg)) {
10753                 print_verifier_state(env, state, true);
10754                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
10755                 return -EINVAL;
10756         }
10757         if (WARN_ON(!src_reg)) {
10758                 print_verifier_state(env, state, true);
10759                 verbose(env, "verifier internal error: no src_reg\n");
10760                 return -EINVAL;
10761         }
10762         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
10763 }
10764
10765 /* check validity of 32-bit and 64-bit arithmetic operations */
10766 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
10767 {
10768         struct bpf_reg_state *regs = cur_regs(env);
10769         u8 opcode = BPF_OP(insn->code);
10770         int err;
10771
10772         if (opcode == BPF_END || opcode == BPF_NEG) {
10773                 if (opcode == BPF_NEG) {
10774                         if (BPF_SRC(insn->code) != BPF_K ||
10775                             insn->src_reg != BPF_REG_0 ||
10776                             insn->off != 0 || insn->imm != 0) {
10777                                 verbose(env, "BPF_NEG uses reserved fields\n");
10778                                 return -EINVAL;
10779                         }
10780                 } else {
10781                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
10782                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
10783                             BPF_CLASS(insn->code) == BPF_ALU64) {
10784                                 verbose(env, "BPF_END uses reserved fields\n");
10785                                 return -EINVAL;
10786                         }
10787                 }
10788
10789                 /* check src operand */
10790                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10791                 if (err)
10792                         return err;
10793
10794                 if (is_pointer_value(env, insn->dst_reg)) {
10795                         verbose(env, "R%d pointer arithmetic prohibited\n",
10796                                 insn->dst_reg);
10797                         return -EACCES;
10798                 }
10799
10800                 /* check dest operand */
10801                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10802                 if (err)
10803                         return err;
10804
10805         } else if (opcode == BPF_MOV) {
10806
10807                 if (BPF_SRC(insn->code) == BPF_X) {
10808                         if (insn->imm != 0 || insn->off != 0) {
10809                                 verbose(env, "BPF_MOV uses reserved fields\n");
10810                                 return -EINVAL;
10811                         }
10812
10813                         /* check src operand */
10814                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10815                         if (err)
10816                                 return err;
10817                 } else {
10818                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10819                                 verbose(env, "BPF_MOV uses reserved fields\n");
10820                                 return -EINVAL;
10821                         }
10822                 }
10823
10824                 /* check dest operand, mark as required later */
10825                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10826                 if (err)
10827                         return err;
10828
10829                 if (BPF_SRC(insn->code) == BPF_X) {
10830                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
10831                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
10832
10833                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
10834                                 /* case: R1 = R2
10835                                  * copy register state to dest reg
10836                                  */
10837                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
10838                                         /* Assign src and dst registers the same ID
10839                                          * that will be used by find_equal_scalars()
10840                                          * to propagate min/max range.
10841                                          */
10842                                         src_reg->id = ++env->id_gen;
10843                                 *dst_reg = *src_reg;
10844                                 dst_reg->live |= REG_LIVE_WRITTEN;
10845                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
10846                         } else {
10847                                 /* R1 = (u32) R2 */
10848                                 if (is_pointer_value(env, insn->src_reg)) {
10849                                         verbose(env,
10850                                                 "R%d partial copy of pointer\n",
10851                                                 insn->src_reg);
10852                                         return -EACCES;
10853                                 } else if (src_reg->type == SCALAR_VALUE) {
10854                                         *dst_reg = *src_reg;
10855                                         /* Make sure ID is cleared otherwise
10856                                          * dst_reg min/max could be incorrectly
10857                                          * propagated into src_reg by find_equal_scalars()
10858                                          */
10859                                         dst_reg->id = 0;
10860                                         dst_reg->live |= REG_LIVE_WRITTEN;
10861                                         dst_reg->subreg_def = env->insn_idx + 1;
10862                                 } else {
10863                                         mark_reg_unknown(env, regs,
10864                                                          insn->dst_reg);
10865                                 }
10866                                 zext_32_to_64(dst_reg);
10867                                 reg_bounds_sync(dst_reg);
10868                         }
10869                 } else {
10870                         /* case: R = imm
10871                          * remember the value we stored into this reg
10872                          */
10873                         /* clear any state __mark_reg_known doesn't set */
10874                         mark_reg_unknown(env, regs, insn->dst_reg);
10875                         regs[insn->dst_reg].type = SCALAR_VALUE;
10876                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
10877                                 __mark_reg_known(regs + insn->dst_reg,
10878                                                  insn->imm);
10879                         } else {
10880                                 __mark_reg_known(regs + insn->dst_reg,
10881                                                  (u32)insn->imm);
10882                         }
10883                 }
10884
10885         } else if (opcode > BPF_END) {
10886                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
10887                 return -EINVAL;
10888
10889         } else {        /* all other ALU ops: and, sub, xor, add, ... */
10890
10891                 if (BPF_SRC(insn->code) == BPF_X) {
10892                         if (insn->imm != 0 || insn->off != 0) {
10893                                 verbose(env, "BPF_ALU uses reserved fields\n");
10894                                 return -EINVAL;
10895                         }
10896                         /* check src1 operand */
10897                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10898                         if (err)
10899                                 return err;
10900                 } else {
10901                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10902                                 verbose(env, "BPF_ALU uses reserved fields\n");
10903                                 return -EINVAL;
10904                         }
10905                 }
10906
10907                 /* check src2 operand */
10908                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10909                 if (err)
10910                         return err;
10911
10912                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
10913                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
10914                         verbose(env, "div by zero\n");
10915                         return -EINVAL;
10916                 }
10917
10918                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
10919                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
10920                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
10921
10922                         if (insn->imm < 0 || insn->imm >= size) {
10923                                 verbose(env, "invalid shift %d\n", insn->imm);
10924                                 return -EINVAL;
10925                         }
10926                 }
10927
10928                 /* check dest operand */
10929                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10930                 if (err)
10931                         return err;
10932
10933                 return adjust_reg_min_max_vals(env, insn);
10934         }
10935
10936         return 0;
10937 }
10938
10939 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
10940                                    struct bpf_reg_state *dst_reg,
10941                                    enum bpf_reg_type type,
10942                                    bool range_right_open)
10943 {
10944         struct bpf_func_state *state;
10945         struct bpf_reg_state *reg;
10946         int new_range;
10947
10948         if (dst_reg->off < 0 ||
10949             (dst_reg->off == 0 && range_right_open))
10950                 /* This doesn't give us any range */
10951                 return;
10952
10953         if (dst_reg->umax_value > MAX_PACKET_OFF ||
10954             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
10955                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
10956                  * than pkt_end, but that's because it's also less than pkt.
10957                  */
10958                 return;
10959
10960         new_range = dst_reg->off;
10961         if (range_right_open)
10962                 new_range++;
10963
10964         /* Examples for register markings:
10965          *
10966          * pkt_data in dst register:
10967          *
10968          *   r2 = r3;
10969          *   r2 += 8;
10970          *   if (r2 > pkt_end) goto <handle exception>
10971          *   <access okay>
10972          *
10973          *   r2 = r3;
10974          *   r2 += 8;
10975          *   if (r2 < pkt_end) goto <access okay>
10976          *   <handle exception>
10977          *
10978          *   Where:
10979          *     r2 == dst_reg, pkt_end == src_reg
10980          *     r2=pkt(id=n,off=8,r=0)
10981          *     r3=pkt(id=n,off=0,r=0)
10982          *
10983          * pkt_data in src register:
10984          *
10985          *   r2 = r3;
10986          *   r2 += 8;
10987          *   if (pkt_end >= r2) goto <access okay>
10988          *   <handle exception>
10989          *
10990          *   r2 = r3;
10991          *   r2 += 8;
10992          *   if (pkt_end <= r2) goto <handle exception>
10993          *   <access okay>
10994          *
10995          *   Where:
10996          *     pkt_end == dst_reg, r2 == src_reg
10997          *     r2=pkt(id=n,off=8,r=0)
10998          *     r3=pkt(id=n,off=0,r=0)
10999          *
11000          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
11001          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
11002          * and [r3, r3 + 8-1) respectively is safe to access depending on
11003          * the check.
11004          */
11005
11006         /* If our ids match, then we must have the same max_value.  And we
11007          * don't care about the other reg's fixed offset, since if it's too big
11008          * the range won't allow anything.
11009          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
11010          */
11011         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11012                 if (reg->type == type && reg->id == dst_reg->id)
11013                         /* keep the maximum range already checked */
11014                         reg->range = max(reg->range, new_range);
11015         }));
11016 }
11017
11018 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
11019 {
11020         struct tnum subreg = tnum_subreg(reg->var_off);
11021         s32 sval = (s32)val;
11022
11023         switch (opcode) {
11024         case BPF_JEQ:
11025                 if (tnum_is_const(subreg))
11026                         return !!tnum_equals_const(subreg, val);
11027                 break;
11028         case BPF_JNE:
11029                 if (tnum_is_const(subreg))
11030                         return !tnum_equals_const(subreg, val);
11031                 break;
11032         case BPF_JSET:
11033                 if ((~subreg.mask & subreg.value) & val)
11034                         return 1;
11035                 if (!((subreg.mask | subreg.value) & val))
11036                         return 0;
11037                 break;
11038         case BPF_JGT:
11039                 if (reg->u32_min_value > val)
11040                         return 1;
11041                 else if (reg->u32_max_value <= val)
11042                         return 0;
11043                 break;
11044         case BPF_JSGT:
11045                 if (reg->s32_min_value > sval)
11046                         return 1;
11047                 else if (reg->s32_max_value <= sval)
11048                         return 0;
11049                 break;
11050         case BPF_JLT:
11051                 if (reg->u32_max_value < val)
11052                         return 1;
11053                 else if (reg->u32_min_value >= val)
11054                         return 0;
11055                 break;
11056         case BPF_JSLT:
11057                 if (reg->s32_max_value < sval)
11058                         return 1;
11059                 else if (reg->s32_min_value >= sval)
11060                         return 0;
11061                 break;
11062         case BPF_JGE:
11063                 if (reg->u32_min_value >= val)
11064                         return 1;
11065                 else if (reg->u32_max_value < val)
11066                         return 0;
11067                 break;
11068         case BPF_JSGE:
11069                 if (reg->s32_min_value >= sval)
11070                         return 1;
11071                 else if (reg->s32_max_value < sval)
11072                         return 0;
11073                 break;
11074         case BPF_JLE:
11075                 if (reg->u32_max_value <= val)
11076                         return 1;
11077                 else if (reg->u32_min_value > val)
11078                         return 0;
11079                 break;
11080         case BPF_JSLE:
11081                 if (reg->s32_max_value <= sval)
11082                         return 1;
11083                 else if (reg->s32_min_value > sval)
11084                         return 0;
11085                 break;
11086         }
11087
11088         return -1;
11089 }
11090
11091
11092 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
11093 {
11094         s64 sval = (s64)val;
11095
11096         switch (opcode) {
11097         case BPF_JEQ:
11098                 if (tnum_is_const(reg->var_off))
11099                         return !!tnum_equals_const(reg->var_off, val);
11100                 break;
11101         case BPF_JNE:
11102                 if (tnum_is_const(reg->var_off))
11103                         return !tnum_equals_const(reg->var_off, val);
11104                 break;
11105         case BPF_JSET:
11106                 if ((~reg->var_off.mask & reg->var_off.value) & val)
11107                         return 1;
11108                 if (!((reg->var_off.mask | reg->var_off.value) & val))
11109                         return 0;
11110                 break;
11111         case BPF_JGT:
11112                 if (reg->umin_value > val)
11113                         return 1;
11114                 else if (reg->umax_value <= val)
11115                         return 0;
11116                 break;
11117         case BPF_JSGT:
11118                 if (reg->smin_value > sval)
11119                         return 1;
11120                 else if (reg->smax_value <= sval)
11121                         return 0;
11122                 break;
11123         case BPF_JLT:
11124                 if (reg->umax_value < val)
11125                         return 1;
11126                 else if (reg->umin_value >= val)
11127                         return 0;
11128                 break;
11129         case BPF_JSLT:
11130                 if (reg->smax_value < sval)
11131                         return 1;
11132                 else if (reg->smin_value >= sval)
11133                         return 0;
11134                 break;
11135         case BPF_JGE:
11136                 if (reg->umin_value >= val)
11137                         return 1;
11138                 else if (reg->umax_value < val)
11139                         return 0;
11140                 break;
11141         case BPF_JSGE:
11142                 if (reg->smin_value >= sval)
11143                         return 1;
11144                 else if (reg->smax_value < sval)
11145                         return 0;
11146                 break;
11147         case BPF_JLE:
11148                 if (reg->umax_value <= val)
11149                         return 1;
11150                 else if (reg->umin_value > val)
11151                         return 0;
11152                 break;
11153         case BPF_JSLE:
11154                 if (reg->smax_value <= sval)
11155                         return 1;
11156                 else if (reg->smin_value > sval)
11157                         return 0;
11158                 break;
11159         }
11160
11161         return -1;
11162 }
11163
11164 /* compute branch direction of the expression "if (reg opcode val) goto target;"
11165  * and return:
11166  *  1 - branch will be taken and "goto target" will be executed
11167  *  0 - branch will not be taken and fall-through to next insn
11168  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
11169  *      range [0,10]
11170  */
11171 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
11172                            bool is_jmp32)
11173 {
11174         if (__is_pointer_value(false, reg)) {
11175                 if (!reg_type_not_null(reg->type))
11176                         return -1;
11177
11178                 /* If pointer is valid tests against zero will fail so we can
11179                  * use this to direct branch taken.
11180                  */
11181                 if (val != 0)
11182                         return -1;
11183
11184                 switch (opcode) {
11185                 case BPF_JEQ:
11186                         return 0;
11187                 case BPF_JNE:
11188                         return 1;
11189                 default:
11190                         return -1;
11191                 }
11192         }
11193
11194         if (is_jmp32)
11195                 return is_branch32_taken(reg, val, opcode);
11196         return is_branch64_taken(reg, val, opcode);
11197 }
11198
11199 static int flip_opcode(u32 opcode)
11200 {
11201         /* How can we transform "a <op> b" into "b <op> a"? */
11202         static const u8 opcode_flip[16] = {
11203                 /* these stay the same */
11204                 [BPF_JEQ  >> 4] = BPF_JEQ,
11205                 [BPF_JNE  >> 4] = BPF_JNE,
11206                 [BPF_JSET >> 4] = BPF_JSET,
11207                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
11208                 [BPF_JGE  >> 4] = BPF_JLE,
11209                 [BPF_JGT  >> 4] = BPF_JLT,
11210                 [BPF_JLE  >> 4] = BPF_JGE,
11211                 [BPF_JLT  >> 4] = BPF_JGT,
11212                 [BPF_JSGE >> 4] = BPF_JSLE,
11213                 [BPF_JSGT >> 4] = BPF_JSLT,
11214                 [BPF_JSLE >> 4] = BPF_JSGE,
11215                 [BPF_JSLT >> 4] = BPF_JSGT
11216         };
11217         return opcode_flip[opcode >> 4];
11218 }
11219
11220 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
11221                                    struct bpf_reg_state *src_reg,
11222                                    u8 opcode)
11223 {
11224         struct bpf_reg_state *pkt;
11225
11226         if (src_reg->type == PTR_TO_PACKET_END) {
11227                 pkt = dst_reg;
11228         } else if (dst_reg->type == PTR_TO_PACKET_END) {
11229                 pkt = src_reg;
11230                 opcode = flip_opcode(opcode);
11231         } else {
11232                 return -1;
11233         }
11234
11235         if (pkt->range >= 0)
11236                 return -1;
11237
11238         switch (opcode) {
11239         case BPF_JLE:
11240                 /* pkt <= pkt_end */
11241                 fallthrough;
11242         case BPF_JGT:
11243                 /* pkt > pkt_end */
11244                 if (pkt->range == BEYOND_PKT_END)
11245                         /* pkt has at last one extra byte beyond pkt_end */
11246                         return opcode == BPF_JGT;
11247                 break;
11248         case BPF_JLT:
11249                 /* pkt < pkt_end */
11250                 fallthrough;
11251         case BPF_JGE:
11252                 /* pkt >= pkt_end */
11253                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
11254                         return opcode == BPF_JGE;
11255                 break;
11256         }
11257         return -1;
11258 }
11259
11260 /* Adjusts the register min/max values in the case that the dst_reg is the
11261  * variable register that we are working on, and src_reg is a constant or we're
11262  * simply doing a BPF_K check.
11263  * In JEQ/JNE cases we also adjust the var_off values.
11264  */
11265 static void reg_set_min_max(struct bpf_reg_state *true_reg,
11266                             struct bpf_reg_state *false_reg,
11267                             u64 val, u32 val32,
11268                             u8 opcode, bool is_jmp32)
11269 {
11270         struct tnum false_32off = tnum_subreg(false_reg->var_off);
11271         struct tnum false_64off = false_reg->var_off;
11272         struct tnum true_32off = tnum_subreg(true_reg->var_off);
11273         struct tnum true_64off = true_reg->var_off;
11274         s64 sval = (s64)val;
11275         s32 sval32 = (s32)val32;
11276
11277         /* If the dst_reg is a pointer, we can't learn anything about its
11278          * variable offset from the compare (unless src_reg were a pointer into
11279          * the same object, but we don't bother with that.
11280          * Since false_reg and true_reg have the same type by construction, we
11281          * only need to check one of them for pointerness.
11282          */
11283         if (__is_pointer_value(false, false_reg))
11284                 return;
11285
11286         switch (opcode) {
11287         /* JEQ/JNE comparison doesn't change the register equivalence.
11288          *
11289          * r1 = r2;
11290          * if (r1 == 42) goto label;
11291          * ...
11292          * label: // here both r1 and r2 are known to be 42.
11293          *
11294          * Hence when marking register as known preserve it's ID.
11295          */
11296         case BPF_JEQ:
11297                 if (is_jmp32) {
11298                         __mark_reg32_known(true_reg, val32);
11299                         true_32off = tnum_subreg(true_reg->var_off);
11300                 } else {
11301                         ___mark_reg_known(true_reg, val);
11302                         true_64off = true_reg->var_off;
11303                 }
11304                 break;
11305         case BPF_JNE:
11306                 if (is_jmp32) {
11307                         __mark_reg32_known(false_reg, val32);
11308                         false_32off = tnum_subreg(false_reg->var_off);
11309                 } else {
11310                         ___mark_reg_known(false_reg, val);
11311                         false_64off = false_reg->var_off;
11312                 }
11313                 break;
11314         case BPF_JSET:
11315                 if (is_jmp32) {
11316                         false_32off = tnum_and(false_32off, tnum_const(~val32));
11317                         if (is_power_of_2(val32))
11318                                 true_32off = tnum_or(true_32off,
11319                                                      tnum_const(val32));
11320                 } else {
11321                         false_64off = tnum_and(false_64off, tnum_const(~val));
11322                         if (is_power_of_2(val))
11323                                 true_64off = tnum_or(true_64off,
11324                                                      tnum_const(val));
11325                 }
11326                 break;
11327         case BPF_JGE:
11328         case BPF_JGT:
11329         {
11330                 if (is_jmp32) {
11331                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
11332                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
11333
11334                         false_reg->u32_max_value = min(false_reg->u32_max_value,
11335                                                        false_umax);
11336                         true_reg->u32_min_value = max(true_reg->u32_min_value,
11337                                                       true_umin);
11338                 } else {
11339                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
11340                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
11341
11342                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
11343                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
11344                 }
11345                 break;
11346         }
11347         case BPF_JSGE:
11348         case BPF_JSGT:
11349         {
11350                 if (is_jmp32) {
11351                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
11352                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
11353
11354                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
11355                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
11356                 } else {
11357                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
11358                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
11359
11360                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
11361                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
11362                 }
11363                 break;
11364         }
11365         case BPF_JLE:
11366         case BPF_JLT:
11367         {
11368                 if (is_jmp32) {
11369                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
11370                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
11371
11372                         false_reg->u32_min_value = max(false_reg->u32_min_value,
11373                                                        false_umin);
11374                         true_reg->u32_max_value = min(true_reg->u32_max_value,
11375                                                       true_umax);
11376                 } else {
11377                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
11378                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
11379
11380                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
11381                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
11382                 }
11383                 break;
11384         }
11385         case BPF_JSLE:
11386         case BPF_JSLT:
11387         {
11388                 if (is_jmp32) {
11389                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
11390                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
11391
11392                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
11393                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
11394                 } else {
11395                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
11396                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
11397
11398                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
11399                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
11400                 }
11401                 break;
11402         }
11403         default:
11404                 return;
11405         }
11406
11407         if (is_jmp32) {
11408                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
11409                                              tnum_subreg(false_32off));
11410                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
11411                                             tnum_subreg(true_32off));
11412                 __reg_combine_32_into_64(false_reg);
11413                 __reg_combine_32_into_64(true_reg);
11414         } else {
11415                 false_reg->var_off = false_64off;
11416                 true_reg->var_off = true_64off;
11417                 __reg_combine_64_into_32(false_reg);
11418                 __reg_combine_64_into_32(true_reg);
11419         }
11420 }
11421
11422 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
11423  * the variable reg.
11424  */
11425 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
11426                                 struct bpf_reg_state *false_reg,
11427                                 u64 val, u32 val32,
11428                                 u8 opcode, bool is_jmp32)
11429 {
11430         opcode = flip_opcode(opcode);
11431         /* This uses zero as "not present in table"; luckily the zero opcode,
11432          * BPF_JA, can't get here.
11433          */
11434         if (opcode)
11435                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
11436 }
11437
11438 /* Regs are known to be equal, so intersect their min/max/var_off */
11439 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
11440                                   struct bpf_reg_state *dst_reg)
11441 {
11442         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
11443                                                         dst_reg->umin_value);
11444         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
11445                                                         dst_reg->umax_value);
11446         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
11447                                                         dst_reg->smin_value);
11448         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
11449                                                         dst_reg->smax_value);
11450         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
11451                                                              dst_reg->var_off);
11452         reg_bounds_sync(src_reg);
11453         reg_bounds_sync(dst_reg);
11454 }
11455
11456 static void reg_combine_min_max(struct bpf_reg_state *true_src,
11457                                 struct bpf_reg_state *true_dst,
11458                                 struct bpf_reg_state *false_src,
11459                                 struct bpf_reg_state *false_dst,
11460                                 u8 opcode)
11461 {
11462         switch (opcode) {
11463         case BPF_JEQ:
11464                 __reg_combine_min_max(true_src, true_dst);
11465                 break;
11466         case BPF_JNE:
11467                 __reg_combine_min_max(false_src, false_dst);
11468                 break;
11469         }
11470 }
11471
11472 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
11473                                  struct bpf_reg_state *reg, u32 id,
11474                                  bool is_null)
11475 {
11476         if (type_may_be_null(reg->type) && reg->id == id &&
11477             (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
11478                 /* Old offset (both fixed and variable parts) should have been
11479                  * known-zero, because we don't allow pointer arithmetic on
11480                  * pointers that might be NULL. If we see this happening, don't
11481                  * convert the register.
11482                  *
11483                  * But in some cases, some helpers that return local kptrs
11484                  * advance offset for the returned pointer. In those cases, it
11485                  * is fine to expect to see reg->off.
11486                  */
11487                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
11488                         return;
11489                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off))
11490                         return;
11491                 if (is_null) {
11492                         reg->type = SCALAR_VALUE;
11493                         /* We don't need id and ref_obj_id from this point
11494                          * onwards anymore, thus we should better reset it,
11495                          * so that state pruning has chances to take effect.
11496                          */
11497                         reg->id = 0;
11498                         reg->ref_obj_id = 0;
11499
11500                         return;
11501                 }
11502
11503                 mark_ptr_not_null_reg(reg);
11504
11505                 if (!reg_may_point_to_spin_lock(reg)) {
11506                         /* For not-NULL ptr, reg->ref_obj_id will be reset
11507                          * in release_reference().
11508                          *
11509                          * reg->id is still used by spin_lock ptr. Other
11510                          * than spin_lock ptr type, reg->id can be reset.
11511                          */
11512                         reg->id = 0;
11513                 }
11514         }
11515 }
11516
11517 /* The logic is similar to find_good_pkt_pointers(), both could eventually
11518  * be folded together at some point.
11519  */
11520 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
11521                                   bool is_null)
11522 {
11523         struct bpf_func_state *state = vstate->frame[vstate->curframe];
11524         struct bpf_reg_state *regs = state->regs, *reg;
11525         u32 ref_obj_id = regs[regno].ref_obj_id;
11526         u32 id = regs[regno].id;
11527
11528         if (ref_obj_id && ref_obj_id == id && is_null)
11529                 /* regs[regno] is in the " == NULL" branch.
11530                  * No one could have freed the reference state before
11531                  * doing the NULL check.
11532                  */
11533                 WARN_ON_ONCE(release_reference_state(state, id));
11534
11535         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11536                 mark_ptr_or_null_reg(state, reg, id, is_null);
11537         }));
11538 }
11539
11540 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
11541                                    struct bpf_reg_state *dst_reg,
11542                                    struct bpf_reg_state *src_reg,
11543                                    struct bpf_verifier_state *this_branch,
11544                                    struct bpf_verifier_state *other_branch)
11545 {
11546         if (BPF_SRC(insn->code) != BPF_X)
11547                 return false;
11548
11549         /* Pointers are always 64-bit. */
11550         if (BPF_CLASS(insn->code) == BPF_JMP32)
11551                 return false;
11552
11553         switch (BPF_OP(insn->code)) {
11554         case BPF_JGT:
11555                 if ((dst_reg->type == PTR_TO_PACKET &&
11556                      src_reg->type == PTR_TO_PACKET_END) ||
11557                     (dst_reg->type == PTR_TO_PACKET_META &&
11558                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11559                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
11560                         find_good_pkt_pointers(this_branch, dst_reg,
11561                                                dst_reg->type, false);
11562                         mark_pkt_end(other_branch, insn->dst_reg, true);
11563                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11564                             src_reg->type == PTR_TO_PACKET) ||
11565                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11566                             src_reg->type == PTR_TO_PACKET_META)) {
11567                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
11568                         find_good_pkt_pointers(other_branch, src_reg,
11569                                                src_reg->type, true);
11570                         mark_pkt_end(this_branch, insn->src_reg, false);
11571                 } else {
11572                         return false;
11573                 }
11574                 break;
11575         case BPF_JLT:
11576                 if ((dst_reg->type == PTR_TO_PACKET &&
11577                      src_reg->type == PTR_TO_PACKET_END) ||
11578                     (dst_reg->type == PTR_TO_PACKET_META &&
11579                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11580                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
11581                         find_good_pkt_pointers(other_branch, dst_reg,
11582                                                dst_reg->type, true);
11583                         mark_pkt_end(this_branch, insn->dst_reg, false);
11584                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11585                             src_reg->type == PTR_TO_PACKET) ||
11586                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11587                             src_reg->type == PTR_TO_PACKET_META)) {
11588                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
11589                         find_good_pkt_pointers(this_branch, src_reg,
11590                                                src_reg->type, false);
11591                         mark_pkt_end(other_branch, insn->src_reg, true);
11592                 } else {
11593                         return false;
11594                 }
11595                 break;
11596         case BPF_JGE:
11597                 if ((dst_reg->type == PTR_TO_PACKET &&
11598                      src_reg->type == PTR_TO_PACKET_END) ||
11599                     (dst_reg->type == PTR_TO_PACKET_META &&
11600                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11601                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
11602                         find_good_pkt_pointers(this_branch, dst_reg,
11603                                                dst_reg->type, true);
11604                         mark_pkt_end(other_branch, insn->dst_reg, false);
11605                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11606                             src_reg->type == PTR_TO_PACKET) ||
11607                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11608                             src_reg->type == PTR_TO_PACKET_META)) {
11609                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
11610                         find_good_pkt_pointers(other_branch, src_reg,
11611                                                src_reg->type, false);
11612                         mark_pkt_end(this_branch, insn->src_reg, true);
11613                 } else {
11614                         return false;
11615                 }
11616                 break;
11617         case BPF_JLE:
11618                 if ((dst_reg->type == PTR_TO_PACKET &&
11619                      src_reg->type == PTR_TO_PACKET_END) ||
11620                     (dst_reg->type == PTR_TO_PACKET_META &&
11621                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11622                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
11623                         find_good_pkt_pointers(other_branch, dst_reg,
11624                                                dst_reg->type, false);
11625                         mark_pkt_end(this_branch, insn->dst_reg, true);
11626                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11627                             src_reg->type == PTR_TO_PACKET) ||
11628                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11629                             src_reg->type == PTR_TO_PACKET_META)) {
11630                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
11631                         find_good_pkt_pointers(this_branch, src_reg,
11632                                                src_reg->type, true);
11633                         mark_pkt_end(other_branch, insn->src_reg, false);
11634                 } else {
11635                         return false;
11636                 }
11637                 break;
11638         default:
11639                 return false;
11640         }
11641
11642         return true;
11643 }
11644
11645 static void find_equal_scalars(struct bpf_verifier_state *vstate,
11646                                struct bpf_reg_state *known_reg)
11647 {
11648         struct bpf_func_state *state;
11649         struct bpf_reg_state *reg;
11650
11651         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11652                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
11653                         *reg = *known_reg;
11654         }));
11655 }
11656
11657 static int check_cond_jmp_op(struct bpf_verifier_env *env,
11658                              struct bpf_insn *insn, int *insn_idx)
11659 {
11660         struct bpf_verifier_state *this_branch = env->cur_state;
11661         struct bpf_verifier_state *other_branch;
11662         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
11663         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
11664         struct bpf_reg_state *eq_branch_regs;
11665         u8 opcode = BPF_OP(insn->code);
11666         bool is_jmp32;
11667         int pred = -1;
11668         int err;
11669
11670         /* Only conditional jumps are expected to reach here. */
11671         if (opcode == BPF_JA || opcode > BPF_JSLE) {
11672                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
11673                 return -EINVAL;
11674         }
11675
11676         if (BPF_SRC(insn->code) == BPF_X) {
11677                 if (insn->imm != 0) {
11678                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11679                         return -EINVAL;
11680                 }
11681
11682                 /* check src1 operand */
11683                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
11684                 if (err)
11685                         return err;
11686
11687                 if (is_pointer_value(env, insn->src_reg)) {
11688                         verbose(env, "R%d pointer comparison prohibited\n",
11689                                 insn->src_reg);
11690                         return -EACCES;
11691                 }
11692                 src_reg = &regs[insn->src_reg];
11693         } else {
11694                 if (insn->src_reg != BPF_REG_0) {
11695                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11696                         return -EINVAL;
11697                 }
11698         }
11699
11700         /* check src2 operand */
11701         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11702         if (err)
11703                 return err;
11704
11705         dst_reg = &regs[insn->dst_reg];
11706         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
11707
11708         if (BPF_SRC(insn->code) == BPF_K) {
11709                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
11710         } else if (src_reg->type == SCALAR_VALUE &&
11711                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
11712                 pred = is_branch_taken(dst_reg,
11713                                        tnum_subreg(src_reg->var_off).value,
11714                                        opcode,
11715                                        is_jmp32);
11716         } else if (src_reg->type == SCALAR_VALUE &&
11717                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
11718                 pred = is_branch_taken(dst_reg,
11719                                        src_reg->var_off.value,
11720                                        opcode,
11721                                        is_jmp32);
11722         } else if (reg_is_pkt_pointer_any(dst_reg) &&
11723                    reg_is_pkt_pointer_any(src_reg) &&
11724                    !is_jmp32) {
11725                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
11726         }
11727
11728         if (pred >= 0) {
11729                 /* If we get here with a dst_reg pointer type it is because
11730                  * above is_branch_taken() special cased the 0 comparison.
11731                  */
11732                 if (!__is_pointer_value(false, dst_reg))
11733                         err = mark_chain_precision(env, insn->dst_reg);
11734                 if (BPF_SRC(insn->code) == BPF_X && !err &&
11735                     !__is_pointer_value(false, src_reg))
11736                         err = mark_chain_precision(env, insn->src_reg);
11737                 if (err)
11738                         return err;
11739         }
11740
11741         if (pred == 1) {
11742                 /* Only follow the goto, ignore fall-through. If needed, push
11743                  * the fall-through branch for simulation under speculative
11744                  * execution.
11745                  */
11746                 if (!env->bypass_spec_v1 &&
11747                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
11748                                                *insn_idx))
11749                         return -EFAULT;
11750                 *insn_idx += insn->off;
11751                 return 0;
11752         } else if (pred == 0) {
11753                 /* Only follow the fall-through branch, since that's where the
11754                  * program will go. If needed, push the goto branch for
11755                  * simulation under speculative execution.
11756                  */
11757                 if (!env->bypass_spec_v1 &&
11758                     !sanitize_speculative_path(env, insn,
11759                                                *insn_idx + insn->off + 1,
11760                                                *insn_idx))
11761                         return -EFAULT;
11762                 return 0;
11763         }
11764
11765         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
11766                                   false);
11767         if (!other_branch)
11768                 return -EFAULT;
11769         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
11770
11771         /* detect if we are comparing against a constant value so we can adjust
11772          * our min/max values for our dst register.
11773          * this is only legit if both are scalars (or pointers to the same
11774          * object, I suppose, see the PTR_MAYBE_NULL related if block below),
11775          * because otherwise the different base pointers mean the offsets aren't
11776          * comparable.
11777          */
11778         if (BPF_SRC(insn->code) == BPF_X) {
11779                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
11780
11781                 if (dst_reg->type == SCALAR_VALUE &&
11782                     src_reg->type == SCALAR_VALUE) {
11783                         if (tnum_is_const(src_reg->var_off) ||
11784                             (is_jmp32 &&
11785                              tnum_is_const(tnum_subreg(src_reg->var_off))))
11786                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
11787                                                 dst_reg,
11788                                                 src_reg->var_off.value,
11789                                                 tnum_subreg(src_reg->var_off).value,
11790                                                 opcode, is_jmp32);
11791                         else if (tnum_is_const(dst_reg->var_off) ||
11792                                  (is_jmp32 &&
11793                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
11794                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
11795                                                     src_reg,
11796                                                     dst_reg->var_off.value,
11797                                                     tnum_subreg(dst_reg->var_off).value,
11798                                                     opcode, is_jmp32);
11799                         else if (!is_jmp32 &&
11800                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
11801                                 /* Comparing for equality, we can combine knowledge */
11802                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
11803                                                     &other_branch_regs[insn->dst_reg],
11804                                                     src_reg, dst_reg, opcode);
11805                         if (src_reg->id &&
11806                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
11807                                 find_equal_scalars(this_branch, src_reg);
11808                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
11809                         }
11810
11811                 }
11812         } else if (dst_reg->type == SCALAR_VALUE) {
11813                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
11814                                         dst_reg, insn->imm, (u32)insn->imm,
11815                                         opcode, is_jmp32);
11816         }
11817
11818         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
11819             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
11820                 find_equal_scalars(this_branch, dst_reg);
11821                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
11822         }
11823
11824         /* if one pointer register is compared to another pointer
11825          * register check if PTR_MAYBE_NULL could be lifted.
11826          * E.g. register A - maybe null
11827          *      register B - not null
11828          * for JNE A, B, ... - A is not null in the false branch;
11829          * for JEQ A, B, ... - A is not null in the true branch.
11830          */
11831         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
11832             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
11833             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type)) {
11834                 eq_branch_regs = NULL;
11835                 switch (opcode) {
11836                 case BPF_JEQ:
11837                         eq_branch_regs = other_branch_regs;
11838                         break;
11839                 case BPF_JNE:
11840                         eq_branch_regs = regs;
11841                         break;
11842                 default:
11843                         /* do nothing */
11844                         break;
11845                 }
11846                 if (eq_branch_regs) {
11847                         if (type_may_be_null(src_reg->type))
11848                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
11849                         else
11850                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
11851                 }
11852         }
11853
11854         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
11855          * NOTE: these optimizations below are related with pointer comparison
11856          *       which will never be JMP32.
11857          */
11858         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
11859             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
11860             type_may_be_null(dst_reg->type)) {
11861                 /* Mark all identical registers in each branch as either
11862                  * safe or unknown depending R == 0 or R != 0 conditional.
11863                  */
11864                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
11865                                       opcode == BPF_JNE);
11866                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
11867                                       opcode == BPF_JEQ);
11868         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
11869                                            this_branch, other_branch) &&
11870                    is_pointer_value(env, insn->dst_reg)) {
11871                 verbose(env, "R%d pointer comparison prohibited\n",
11872                         insn->dst_reg);
11873                 return -EACCES;
11874         }
11875         if (env->log.level & BPF_LOG_LEVEL)
11876                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
11877         return 0;
11878 }
11879
11880 /* verify BPF_LD_IMM64 instruction */
11881 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
11882 {
11883         struct bpf_insn_aux_data *aux = cur_aux(env);
11884         struct bpf_reg_state *regs = cur_regs(env);
11885         struct bpf_reg_state *dst_reg;
11886         struct bpf_map *map;
11887         int err;
11888
11889         if (BPF_SIZE(insn->code) != BPF_DW) {
11890                 verbose(env, "invalid BPF_LD_IMM insn\n");
11891                 return -EINVAL;
11892         }
11893         if (insn->off != 0) {
11894                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
11895                 return -EINVAL;
11896         }
11897
11898         err = check_reg_arg(env, insn->dst_reg, DST_OP);
11899         if (err)
11900                 return err;
11901
11902         dst_reg = &regs[insn->dst_reg];
11903         if (insn->src_reg == 0) {
11904                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
11905
11906                 dst_reg->type = SCALAR_VALUE;
11907                 __mark_reg_known(&regs[insn->dst_reg], imm);
11908                 return 0;
11909         }
11910
11911         /* All special src_reg cases are listed below. From this point onwards
11912          * we either succeed and assign a corresponding dst_reg->type after
11913          * zeroing the offset, or fail and reject the program.
11914          */
11915         mark_reg_known_zero(env, regs, insn->dst_reg);
11916
11917         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
11918                 dst_reg->type = aux->btf_var.reg_type;
11919                 switch (base_type(dst_reg->type)) {
11920                 case PTR_TO_MEM:
11921                         dst_reg->mem_size = aux->btf_var.mem_size;
11922                         break;
11923                 case PTR_TO_BTF_ID:
11924                         dst_reg->btf = aux->btf_var.btf;
11925                         dst_reg->btf_id = aux->btf_var.btf_id;
11926                         break;
11927                 default:
11928                         verbose(env, "bpf verifier is misconfigured\n");
11929                         return -EFAULT;
11930                 }
11931                 return 0;
11932         }
11933
11934         if (insn->src_reg == BPF_PSEUDO_FUNC) {
11935                 struct bpf_prog_aux *aux = env->prog->aux;
11936                 u32 subprogno = find_subprog(env,
11937                                              env->insn_idx + insn->imm + 1);
11938
11939                 if (!aux->func_info) {
11940                         verbose(env, "missing btf func_info\n");
11941                         return -EINVAL;
11942                 }
11943                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
11944                         verbose(env, "callback function not static\n");
11945                         return -EINVAL;
11946                 }
11947
11948                 dst_reg->type = PTR_TO_FUNC;
11949                 dst_reg->subprogno = subprogno;
11950                 return 0;
11951         }
11952
11953         map = env->used_maps[aux->map_index];
11954         dst_reg->map_ptr = map;
11955
11956         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
11957             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
11958                 dst_reg->type = PTR_TO_MAP_VALUE;
11959                 dst_reg->off = aux->map_off;
11960                 WARN_ON_ONCE(map->max_entries != 1);
11961                 /* We want reg->id to be same (0) as map_value is not distinct */
11962         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
11963                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
11964                 dst_reg->type = CONST_PTR_TO_MAP;
11965         } else {
11966                 verbose(env, "bpf verifier is misconfigured\n");
11967                 return -EINVAL;
11968         }
11969
11970         return 0;
11971 }
11972
11973 static bool may_access_skb(enum bpf_prog_type type)
11974 {
11975         switch (type) {
11976         case BPF_PROG_TYPE_SOCKET_FILTER:
11977         case BPF_PROG_TYPE_SCHED_CLS:
11978         case BPF_PROG_TYPE_SCHED_ACT:
11979                 return true;
11980         default:
11981                 return false;
11982         }
11983 }
11984
11985 /* verify safety of LD_ABS|LD_IND instructions:
11986  * - they can only appear in the programs where ctx == skb
11987  * - since they are wrappers of function calls, they scratch R1-R5 registers,
11988  *   preserve R6-R9, and store return value into R0
11989  *
11990  * Implicit input:
11991  *   ctx == skb == R6 == CTX
11992  *
11993  * Explicit input:
11994  *   SRC == any register
11995  *   IMM == 32-bit immediate
11996  *
11997  * Output:
11998  *   R0 - 8/16/32-bit skb data converted to cpu endianness
11999  */
12000 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
12001 {
12002         struct bpf_reg_state *regs = cur_regs(env);
12003         static const int ctx_reg = BPF_REG_6;
12004         u8 mode = BPF_MODE(insn->code);
12005         int i, err;
12006
12007         if (!may_access_skb(resolve_prog_type(env->prog))) {
12008                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
12009                 return -EINVAL;
12010         }
12011
12012         if (!env->ops->gen_ld_abs) {
12013                 verbose(env, "bpf verifier is misconfigured\n");
12014                 return -EINVAL;
12015         }
12016
12017         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
12018             BPF_SIZE(insn->code) == BPF_DW ||
12019             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
12020                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
12021                 return -EINVAL;
12022         }
12023
12024         /* check whether implicit source operand (register R6) is readable */
12025         err = check_reg_arg(env, ctx_reg, SRC_OP);
12026         if (err)
12027                 return err;
12028
12029         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
12030          * gen_ld_abs() may terminate the program at runtime, leading to
12031          * reference leak.
12032          */
12033         err = check_reference_leak(env);
12034         if (err) {
12035                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
12036                 return err;
12037         }
12038
12039         if (env->cur_state->active_lock.ptr) {
12040                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
12041                 return -EINVAL;
12042         }
12043
12044         if (env->cur_state->active_rcu_lock) {
12045                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
12046                 return -EINVAL;
12047         }
12048
12049         if (regs[ctx_reg].type != PTR_TO_CTX) {
12050                 verbose(env,
12051                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
12052                 return -EINVAL;
12053         }
12054
12055         if (mode == BPF_IND) {
12056                 /* check explicit source operand */
12057                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12058                 if (err)
12059                         return err;
12060         }
12061
12062         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
12063         if (err < 0)
12064                 return err;
12065
12066         /* reset caller saved regs to unreadable */
12067         for (i = 0; i < CALLER_SAVED_REGS; i++) {
12068                 mark_reg_not_init(env, regs, caller_saved[i]);
12069                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
12070         }
12071
12072         /* mark destination R0 register as readable, since it contains
12073          * the value fetched from the packet.
12074          * Already marked as written above.
12075          */
12076         mark_reg_unknown(env, regs, BPF_REG_0);
12077         /* ld_abs load up to 32-bit skb data. */
12078         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
12079         return 0;
12080 }
12081
12082 static int check_return_code(struct bpf_verifier_env *env)
12083 {
12084         struct tnum enforce_attach_type_range = tnum_unknown;
12085         const struct bpf_prog *prog = env->prog;
12086         struct bpf_reg_state *reg;
12087         struct tnum range = tnum_range(0, 1);
12088         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12089         int err;
12090         struct bpf_func_state *frame = env->cur_state->frame[0];
12091         const bool is_subprog = frame->subprogno;
12092
12093         /* LSM and struct_ops func-ptr's return type could be "void" */
12094         if (!is_subprog) {
12095                 switch (prog_type) {
12096                 case BPF_PROG_TYPE_LSM:
12097                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
12098                                 /* See below, can be 0 or 0-1 depending on hook. */
12099                                 break;
12100                         fallthrough;
12101                 case BPF_PROG_TYPE_STRUCT_OPS:
12102                         if (!prog->aux->attach_func_proto->type)
12103                                 return 0;
12104                         break;
12105                 default:
12106                         break;
12107                 }
12108         }
12109
12110         /* eBPF calling convention is such that R0 is used
12111          * to return the value from eBPF program.
12112          * Make sure that it's readable at this time
12113          * of bpf_exit, which means that program wrote
12114          * something into it earlier
12115          */
12116         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
12117         if (err)
12118                 return err;
12119
12120         if (is_pointer_value(env, BPF_REG_0)) {
12121                 verbose(env, "R0 leaks addr as return value\n");
12122                 return -EACCES;
12123         }
12124
12125         reg = cur_regs(env) + BPF_REG_0;
12126
12127         if (frame->in_async_callback_fn) {
12128                 /* enforce return zero from async callbacks like timer */
12129                 if (reg->type != SCALAR_VALUE) {
12130                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
12131                                 reg_type_str(env, reg->type));
12132                         return -EINVAL;
12133                 }
12134
12135                 if (!tnum_in(tnum_const(0), reg->var_off)) {
12136                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
12137                         return -EINVAL;
12138                 }
12139                 return 0;
12140         }
12141
12142         if (is_subprog) {
12143                 if (reg->type != SCALAR_VALUE) {
12144                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
12145                                 reg_type_str(env, reg->type));
12146                         return -EINVAL;
12147                 }
12148                 return 0;
12149         }
12150
12151         switch (prog_type) {
12152         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
12153                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
12154                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
12155                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
12156                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
12157                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
12158                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
12159                         range = tnum_range(1, 1);
12160                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
12161                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
12162                         range = tnum_range(0, 3);
12163                 break;
12164         case BPF_PROG_TYPE_CGROUP_SKB:
12165                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
12166                         range = tnum_range(0, 3);
12167                         enforce_attach_type_range = tnum_range(2, 3);
12168                 }
12169                 break;
12170         case BPF_PROG_TYPE_CGROUP_SOCK:
12171         case BPF_PROG_TYPE_SOCK_OPS:
12172         case BPF_PROG_TYPE_CGROUP_DEVICE:
12173         case BPF_PROG_TYPE_CGROUP_SYSCTL:
12174         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
12175                 break;
12176         case BPF_PROG_TYPE_RAW_TRACEPOINT:
12177                 if (!env->prog->aux->attach_btf_id)
12178                         return 0;
12179                 range = tnum_const(0);
12180                 break;
12181         case BPF_PROG_TYPE_TRACING:
12182                 switch (env->prog->expected_attach_type) {
12183                 case BPF_TRACE_FENTRY:
12184                 case BPF_TRACE_FEXIT:
12185                         range = tnum_const(0);
12186                         break;
12187                 case BPF_TRACE_RAW_TP:
12188                 case BPF_MODIFY_RETURN:
12189                         return 0;
12190                 case BPF_TRACE_ITER:
12191                         break;
12192                 default:
12193                         return -ENOTSUPP;
12194                 }
12195                 break;
12196         case BPF_PROG_TYPE_SK_LOOKUP:
12197                 range = tnum_range(SK_DROP, SK_PASS);
12198                 break;
12199
12200         case BPF_PROG_TYPE_LSM:
12201                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
12202                         /* Regular BPF_PROG_TYPE_LSM programs can return
12203                          * any value.
12204                          */
12205                         return 0;
12206                 }
12207                 if (!env->prog->aux->attach_func_proto->type) {
12208                         /* Make sure programs that attach to void
12209                          * hooks don't try to modify return value.
12210                          */
12211                         range = tnum_range(1, 1);
12212                 }
12213                 break;
12214
12215         case BPF_PROG_TYPE_EXT:
12216                 /* freplace program can return anything as its return value
12217                  * depends on the to-be-replaced kernel func or bpf program.
12218                  */
12219         default:
12220                 return 0;
12221         }
12222
12223         if (reg->type != SCALAR_VALUE) {
12224                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
12225                         reg_type_str(env, reg->type));
12226                 return -EINVAL;
12227         }
12228
12229         if (!tnum_in(range, reg->var_off)) {
12230                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
12231                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
12232                     prog_type == BPF_PROG_TYPE_LSM &&
12233                     !prog->aux->attach_func_proto->type)
12234                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12235                 return -EINVAL;
12236         }
12237
12238         if (!tnum_is_unknown(enforce_attach_type_range) &&
12239             tnum_in(enforce_attach_type_range, reg->var_off))
12240                 env->prog->enforce_expected_attach_type = 1;
12241         return 0;
12242 }
12243
12244 /* non-recursive DFS pseudo code
12245  * 1  procedure DFS-iterative(G,v):
12246  * 2      label v as discovered
12247  * 3      let S be a stack
12248  * 4      S.push(v)
12249  * 5      while S is not empty
12250  * 6            t <- S.peek()
12251  * 7            if t is what we're looking for:
12252  * 8                return t
12253  * 9            for all edges e in G.adjacentEdges(t) do
12254  * 10               if edge e is already labelled
12255  * 11                   continue with the next edge
12256  * 12               w <- G.adjacentVertex(t,e)
12257  * 13               if vertex w is not discovered and not explored
12258  * 14                   label e as tree-edge
12259  * 15                   label w as discovered
12260  * 16                   S.push(w)
12261  * 17                   continue at 5
12262  * 18               else if vertex w is discovered
12263  * 19                   label e as back-edge
12264  * 20               else
12265  * 21                   // vertex w is explored
12266  * 22                   label e as forward- or cross-edge
12267  * 23           label t as explored
12268  * 24           S.pop()
12269  *
12270  * convention:
12271  * 0x10 - discovered
12272  * 0x11 - discovered and fall-through edge labelled
12273  * 0x12 - discovered and fall-through and branch edges labelled
12274  * 0x20 - explored
12275  */
12276
12277 enum {
12278         DISCOVERED = 0x10,
12279         EXPLORED = 0x20,
12280         FALLTHROUGH = 1,
12281         BRANCH = 2,
12282 };
12283
12284 static u32 state_htab_size(struct bpf_verifier_env *env)
12285 {
12286         return env->prog->len;
12287 }
12288
12289 static struct bpf_verifier_state_list **explored_state(
12290                                         struct bpf_verifier_env *env,
12291                                         int idx)
12292 {
12293         struct bpf_verifier_state *cur = env->cur_state;
12294         struct bpf_func_state *state = cur->frame[cur->curframe];
12295
12296         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
12297 }
12298
12299 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
12300 {
12301         env->insn_aux_data[idx].prune_point = true;
12302 }
12303
12304 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
12305 {
12306         return env->insn_aux_data[insn_idx].prune_point;
12307 }
12308
12309 enum {
12310         DONE_EXPLORING = 0,
12311         KEEP_EXPLORING = 1,
12312 };
12313
12314 /* t, w, e - match pseudo-code above:
12315  * t - index of current instruction
12316  * w - next instruction
12317  * e - edge
12318  */
12319 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
12320                      bool loop_ok)
12321 {
12322         int *insn_stack = env->cfg.insn_stack;
12323         int *insn_state = env->cfg.insn_state;
12324
12325         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
12326                 return DONE_EXPLORING;
12327
12328         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
12329                 return DONE_EXPLORING;
12330
12331         if (w < 0 || w >= env->prog->len) {
12332                 verbose_linfo(env, t, "%d: ", t);
12333                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
12334                 return -EINVAL;
12335         }
12336
12337         if (e == BRANCH) {
12338                 /* mark branch target for state pruning */
12339                 mark_prune_point(env, w);
12340                 mark_jmp_point(env, w);
12341         }
12342
12343         if (insn_state[w] == 0) {
12344                 /* tree-edge */
12345                 insn_state[t] = DISCOVERED | e;
12346                 insn_state[w] = DISCOVERED;
12347                 if (env->cfg.cur_stack >= env->prog->len)
12348                         return -E2BIG;
12349                 insn_stack[env->cfg.cur_stack++] = w;
12350                 return KEEP_EXPLORING;
12351         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
12352                 if (loop_ok && env->bpf_capable)
12353                         return DONE_EXPLORING;
12354                 verbose_linfo(env, t, "%d: ", t);
12355                 verbose_linfo(env, w, "%d: ", w);
12356                 verbose(env, "back-edge from insn %d to %d\n", t, w);
12357                 return -EINVAL;
12358         } else if (insn_state[w] == EXPLORED) {
12359                 /* forward- or cross-edge */
12360                 insn_state[t] = DISCOVERED | e;
12361         } else {
12362                 verbose(env, "insn state internal bug\n");
12363                 return -EFAULT;
12364         }
12365         return DONE_EXPLORING;
12366 }
12367
12368 static int visit_func_call_insn(int t, struct bpf_insn *insns,
12369                                 struct bpf_verifier_env *env,
12370                                 bool visit_callee)
12371 {
12372         int ret;
12373
12374         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
12375         if (ret)
12376                 return ret;
12377
12378         mark_prune_point(env, t + 1);
12379         /* when we exit from subprog, we need to record non-linear history */
12380         mark_jmp_point(env, t + 1);
12381
12382         if (visit_callee) {
12383                 mark_prune_point(env, t);
12384                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
12385                                 /* It's ok to allow recursion from CFG point of
12386                                  * view. __check_func_call() will do the actual
12387                                  * check.
12388                                  */
12389                                 bpf_pseudo_func(insns + t));
12390         }
12391         return ret;
12392 }
12393
12394 /* Visits the instruction at index t and returns one of the following:
12395  *  < 0 - an error occurred
12396  *  DONE_EXPLORING - the instruction was fully explored
12397  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
12398  */
12399 static int visit_insn(int t, struct bpf_verifier_env *env)
12400 {
12401         struct bpf_insn *insns = env->prog->insnsi;
12402         int ret;
12403
12404         if (bpf_pseudo_func(insns + t))
12405                 return visit_func_call_insn(t, insns, env, true);
12406
12407         /* All non-branch instructions have a single fall-through edge. */
12408         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
12409             BPF_CLASS(insns[t].code) != BPF_JMP32)
12410                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
12411
12412         switch (BPF_OP(insns[t].code)) {
12413         case BPF_EXIT:
12414                 return DONE_EXPLORING;
12415
12416         case BPF_CALL:
12417                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
12418                         /* Mark this call insn as a prune point to trigger
12419                          * is_state_visited() check before call itself is
12420                          * processed by __check_func_call(). Otherwise new
12421                          * async state will be pushed for further exploration.
12422                          */
12423                         mark_prune_point(env, t);
12424                 return visit_func_call_insn(t, insns, env,
12425                                             insns[t].src_reg == BPF_PSEUDO_CALL);
12426
12427         case BPF_JA:
12428                 if (BPF_SRC(insns[t].code) != BPF_K)
12429                         return -EINVAL;
12430
12431                 /* unconditional jump with single edge */
12432                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
12433                                 true);
12434                 if (ret)
12435                         return ret;
12436
12437                 mark_prune_point(env, t + insns[t].off + 1);
12438                 mark_jmp_point(env, t + insns[t].off + 1);
12439
12440                 return ret;
12441
12442         default:
12443                 /* conditional jump with two edges */
12444                 mark_prune_point(env, t);
12445
12446                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
12447                 if (ret)
12448                         return ret;
12449
12450                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
12451         }
12452 }
12453
12454 /* non-recursive depth-first-search to detect loops in BPF program
12455  * loop == back-edge in directed graph
12456  */
12457 static int check_cfg(struct bpf_verifier_env *env)
12458 {
12459         int insn_cnt = env->prog->len;
12460         int *insn_stack, *insn_state;
12461         int ret = 0;
12462         int i;
12463
12464         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12465         if (!insn_state)
12466                 return -ENOMEM;
12467
12468         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12469         if (!insn_stack) {
12470                 kvfree(insn_state);
12471                 return -ENOMEM;
12472         }
12473
12474         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
12475         insn_stack[0] = 0; /* 0 is the first instruction */
12476         env->cfg.cur_stack = 1;
12477
12478         while (env->cfg.cur_stack > 0) {
12479                 int t = insn_stack[env->cfg.cur_stack - 1];
12480
12481                 ret = visit_insn(t, env);
12482                 switch (ret) {
12483                 case DONE_EXPLORING:
12484                         insn_state[t] = EXPLORED;
12485                         env->cfg.cur_stack--;
12486                         break;
12487                 case KEEP_EXPLORING:
12488                         break;
12489                 default:
12490                         if (ret > 0) {
12491                                 verbose(env, "visit_insn internal bug\n");
12492                                 ret = -EFAULT;
12493                         }
12494                         goto err_free;
12495                 }
12496         }
12497
12498         if (env->cfg.cur_stack < 0) {
12499                 verbose(env, "pop stack internal bug\n");
12500                 ret = -EFAULT;
12501                 goto err_free;
12502         }
12503
12504         for (i = 0; i < insn_cnt; i++) {
12505                 if (insn_state[i] != EXPLORED) {
12506                         verbose(env, "unreachable insn %d\n", i);
12507                         ret = -EINVAL;
12508                         goto err_free;
12509                 }
12510         }
12511         ret = 0; /* cfg looks good */
12512
12513 err_free:
12514         kvfree(insn_state);
12515         kvfree(insn_stack);
12516         env->cfg.insn_state = env->cfg.insn_stack = NULL;
12517         return ret;
12518 }
12519
12520 static int check_abnormal_return(struct bpf_verifier_env *env)
12521 {
12522         int i;
12523
12524         for (i = 1; i < env->subprog_cnt; i++) {
12525                 if (env->subprog_info[i].has_ld_abs) {
12526                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
12527                         return -EINVAL;
12528                 }
12529                 if (env->subprog_info[i].has_tail_call) {
12530                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
12531                         return -EINVAL;
12532                 }
12533         }
12534         return 0;
12535 }
12536
12537 /* The minimum supported BTF func info size */
12538 #define MIN_BPF_FUNCINFO_SIZE   8
12539 #define MAX_FUNCINFO_REC_SIZE   252
12540
12541 static int check_btf_func(struct bpf_verifier_env *env,
12542                           const union bpf_attr *attr,
12543                           bpfptr_t uattr)
12544 {
12545         const struct btf_type *type, *func_proto, *ret_type;
12546         u32 i, nfuncs, urec_size, min_size;
12547         u32 krec_size = sizeof(struct bpf_func_info);
12548         struct bpf_func_info *krecord;
12549         struct bpf_func_info_aux *info_aux = NULL;
12550         struct bpf_prog *prog;
12551         const struct btf *btf;
12552         bpfptr_t urecord;
12553         u32 prev_offset = 0;
12554         bool scalar_return;
12555         int ret = -ENOMEM;
12556
12557         nfuncs = attr->func_info_cnt;
12558         if (!nfuncs) {
12559                 if (check_abnormal_return(env))
12560                         return -EINVAL;
12561                 return 0;
12562         }
12563
12564         if (nfuncs != env->subprog_cnt) {
12565                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
12566                 return -EINVAL;
12567         }
12568
12569         urec_size = attr->func_info_rec_size;
12570         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
12571             urec_size > MAX_FUNCINFO_REC_SIZE ||
12572             urec_size % sizeof(u32)) {
12573                 verbose(env, "invalid func info rec size %u\n", urec_size);
12574                 return -EINVAL;
12575         }
12576
12577         prog = env->prog;
12578         btf = prog->aux->btf;
12579
12580         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
12581         min_size = min_t(u32, krec_size, urec_size);
12582
12583         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
12584         if (!krecord)
12585                 return -ENOMEM;
12586         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
12587         if (!info_aux)
12588                 goto err_free;
12589
12590         for (i = 0; i < nfuncs; i++) {
12591                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
12592                 if (ret) {
12593                         if (ret == -E2BIG) {
12594                                 verbose(env, "nonzero tailing record in func info");
12595                                 /* set the size kernel expects so loader can zero
12596                                  * out the rest of the record.
12597                                  */
12598                                 if (copy_to_bpfptr_offset(uattr,
12599                                                           offsetof(union bpf_attr, func_info_rec_size),
12600                                                           &min_size, sizeof(min_size)))
12601                                         ret = -EFAULT;
12602                         }
12603                         goto err_free;
12604                 }
12605
12606                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
12607                         ret = -EFAULT;
12608                         goto err_free;
12609                 }
12610
12611                 /* check insn_off */
12612                 ret = -EINVAL;
12613                 if (i == 0) {
12614                         if (krecord[i].insn_off) {
12615                                 verbose(env,
12616                                         "nonzero insn_off %u for the first func info record",
12617                                         krecord[i].insn_off);
12618                                 goto err_free;
12619                         }
12620                 } else if (krecord[i].insn_off <= prev_offset) {
12621                         verbose(env,
12622                                 "same or smaller insn offset (%u) than previous func info record (%u)",
12623                                 krecord[i].insn_off, prev_offset);
12624                         goto err_free;
12625                 }
12626
12627                 if (env->subprog_info[i].start != krecord[i].insn_off) {
12628                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
12629                         goto err_free;
12630                 }
12631
12632                 /* check type_id */
12633                 type = btf_type_by_id(btf, krecord[i].type_id);
12634                 if (!type || !btf_type_is_func(type)) {
12635                         verbose(env, "invalid type id %d in func info",
12636                                 krecord[i].type_id);
12637                         goto err_free;
12638                 }
12639                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
12640
12641                 func_proto = btf_type_by_id(btf, type->type);
12642                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
12643                         /* btf_func_check() already verified it during BTF load */
12644                         goto err_free;
12645                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
12646                 scalar_return =
12647                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
12648                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
12649                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
12650                         goto err_free;
12651                 }
12652                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
12653                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
12654                         goto err_free;
12655                 }
12656
12657                 prev_offset = krecord[i].insn_off;
12658                 bpfptr_add(&urecord, urec_size);
12659         }
12660
12661         prog->aux->func_info = krecord;
12662         prog->aux->func_info_cnt = nfuncs;
12663         prog->aux->func_info_aux = info_aux;
12664         return 0;
12665
12666 err_free:
12667         kvfree(krecord);
12668         kfree(info_aux);
12669         return ret;
12670 }
12671
12672 static void adjust_btf_func(struct bpf_verifier_env *env)
12673 {
12674         struct bpf_prog_aux *aux = env->prog->aux;
12675         int i;
12676
12677         if (!aux->func_info)
12678                 return;
12679
12680         for (i = 0; i < env->subprog_cnt; i++)
12681                 aux->func_info[i].insn_off = env->subprog_info[i].start;
12682 }
12683
12684 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
12685 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
12686
12687 static int check_btf_line(struct bpf_verifier_env *env,
12688                           const union bpf_attr *attr,
12689                           bpfptr_t uattr)
12690 {
12691         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
12692         struct bpf_subprog_info *sub;
12693         struct bpf_line_info *linfo;
12694         struct bpf_prog *prog;
12695         const struct btf *btf;
12696         bpfptr_t ulinfo;
12697         int err;
12698
12699         nr_linfo = attr->line_info_cnt;
12700         if (!nr_linfo)
12701                 return 0;
12702         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
12703                 return -EINVAL;
12704
12705         rec_size = attr->line_info_rec_size;
12706         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
12707             rec_size > MAX_LINEINFO_REC_SIZE ||
12708             rec_size & (sizeof(u32) - 1))
12709                 return -EINVAL;
12710
12711         /* Need to zero it in case the userspace may
12712          * pass in a smaller bpf_line_info object.
12713          */
12714         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
12715                          GFP_KERNEL | __GFP_NOWARN);
12716         if (!linfo)
12717                 return -ENOMEM;
12718
12719         prog = env->prog;
12720         btf = prog->aux->btf;
12721
12722         s = 0;
12723         sub = env->subprog_info;
12724         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
12725         expected_size = sizeof(struct bpf_line_info);
12726         ncopy = min_t(u32, expected_size, rec_size);
12727         for (i = 0; i < nr_linfo; i++) {
12728                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
12729                 if (err) {
12730                         if (err == -E2BIG) {
12731                                 verbose(env, "nonzero tailing record in line_info");
12732                                 if (copy_to_bpfptr_offset(uattr,
12733                                                           offsetof(union bpf_attr, line_info_rec_size),
12734                                                           &expected_size, sizeof(expected_size)))
12735                                         err = -EFAULT;
12736                         }
12737                         goto err_free;
12738                 }
12739
12740                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
12741                         err = -EFAULT;
12742                         goto err_free;
12743                 }
12744
12745                 /*
12746                  * Check insn_off to ensure
12747                  * 1) strictly increasing AND
12748                  * 2) bounded by prog->len
12749                  *
12750                  * The linfo[0].insn_off == 0 check logically falls into
12751                  * the later "missing bpf_line_info for func..." case
12752                  * because the first linfo[0].insn_off must be the
12753                  * first sub also and the first sub must have
12754                  * subprog_info[0].start == 0.
12755                  */
12756                 if ((i && linfo[i].insn_off <= prev_offset) ||
12757                     linfo[i].insn_off >= prog->len) {
12758                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
12759                                 i, linfo[i].insn_off, prev_offset,
12760                                 prog->len);
12761                         err = -EINVAL;
12762                         goto err_free;
12763                 }
12764
12765                 if (!prog->insnsi[linfo[i].insn_off].code) {
12766                         verbose(env,
12767                                 "Invalid insn code at line_info[%u].insn_off\n",
12768                                 i);
12769                         err = -EINVAL;
12770                         goto err_free;
12771                 }
12772
12773                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
12774                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
12775                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
12776                         err = -EINVAL;
12777                         goto err_free;
12778                 }
12779
12780                 if (s != env->subprog_cnt) {
12781                         if (linfo[i].insn_off == sub[s].start) {
12782                                 sub[s].linfo_idx = i;
12783                                 s++;
12784                         } else if (sub[s].start < linfo[i].insn_off) {
12785                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
12786                                 err = -EINVAL;
12787                                 goto err_free;
12788                         }
12789                 }
12790
12791                 prev_offset = linfo[i].insn_off;
12792                 bpfptr_add(&ulinfo, rec_size);
12793         }
12794
12795         if (s != env->subprog_cnt) {
12796                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
12797                         env->subprog_cnt - s, s);
12798                 err = -EINVAL;
12799                 goto err_free;
12800         }
12801
12802         prog->aux->linfo = linfo;
12803         prog->aux->nr_linfo = nr_linfo;
12804
12805         return 0;
12806
12807 err_free:
12808         kvfree(linfo);
12809         return err;
12810 }
12811
12812 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
12813 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
12814
12815 static int check_core_relo(struct bpf_verifier_env *env,
12816                            const union bpf_attr *attr,
12817                            bpfptr_t uattr)
12818 {
12819         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
12820         struct bpf_core_relo core_relo = {};
12821         struct bpf_prog *prog = env->prog;
12822         const struct btf *btf = prog->aux->btf;
12823         struct bpf_core_ctx ctx = {
12824                 .log = &env->log,
12825                 .btf = btf,
12826         };
12827         bpfptr_t u_core_relo;
12828         int err;
12829
12830         nr_core_relo = attr->core_relo_cnt;
12831         if (!nr_core_relo)
12832                 return 0;
12833         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
12834                 return -EINVAL;
12835
12836         rec_size = attr->core_relo_rec_size;
12837         if (rec_size < MIN_CORE_RELO_SIZE ||
12838             rec_size > MAX_CORE_RELO_SIZE ||
12839             rec_size % sizeof(u32))
12840                 return -EINVAL;
12841
12842         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
12843         expected_size = sizeof(struct bpf_core_relo);
12844         ncopy = min_t(u32, expected_size, rec_size);
12845
12846         /* Unlike func_info and line_info, copy and apply each CO-RE
12847          * relocation record one at a time.
12848          */
12849         for (i = 0; i < nr_core_relo; i++) {
12850                 /* future proofing when sizeof(bpf_core_relo) changes */
12851                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
12852                 if (err) {
12853                         if (err == -E2BIG) {
12854                                 verbose(env, "nonzero tailing record in core_relo");
12855                                 if (copy_to_bpfptr_offset(uattr,
12856                                                           offsetof(union bpf_attr, core_relo_rec_size),
12857                                                           &expected_size, sizeof(expected_size)))
12858                                         err = -EFAULT;
12859                         }
12860                         break;
12861                 }
12862
12863                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
12864                         err = -EFAULT;
12865                         break;
12866                 }
12867
12868                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
12869                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
12870                                 i, core_relo.insn_off, prog->len);
12871                         err = -EINVAL;
12872                         break;
12873                 }
12874
12875                 err = bpf_core_apply(&ctx, &core_relo, i,
12876                                      &prog->insnsi[core_relo.insn_off / 8]);
12877                 if (err)
12878                         break;
12879                 bpfptr_add(&u_core_relo, rec_size);
12880         }
12881         return err;
12882 }
12883
12884 static int check_btf_info(struct bpf_verifier_env *env,
12885                           const union bpf_attr *attr,
12886                           bpfptr_t uattr)
12887 {
12888         struct btf *btf;
12889         int err;
12890
12891         if (!attr->func_info_cnt && !attr->line_info_cnt) {
12892                 if (check_abnormal_return(env))
12893                         return -EINVAL;
12894                 return 0;
12895         }
12896
12897         btf = btf_get_by_fd(attr->prog_btf_fd);
12898         if (IS_ERR(btf))
12899                 return PTR_ERR(btf);
12900         if (btf_is_kernel(btf)) {
12901                 btf_put(btf);
12902                 return -EACCES;
12903         }
12904         env->prog->aux->btf = btf;
12905
12906         err = check_btf_func(env, attr, uattr);
12907         if (err)
12908                 return err;
12909
12910         err = check_btf_line(env, attr, uattr);
12911         if (err)
12912                 return err;
12913
12914         err = check_core_relo(env, attr, uattr);
12915         if (err)
12916                 return err;
12917
12918         return 0;
12919 }
12920
12921 /* check %cur's range satisfies %old's */
12922 static bool range_within(struct bpf_reg_state *old,
12923                          struct bpf_reg_state *cur)
12924 {
12925         return old->umin_value <= cur->umin_value &&
12926                old->umax_value >= cur->umax_value &&
12927                old->smin_value <= cur->smin_value &&
12928                old->smax_value >= cur->smax_value &&
12929                old->u32_min_value <= cur->u32_min_value &&
12930                old->u32_max_value >= cur->u32_max_value &&
12931                old->s32_min_value <= cur->s32_min_value &&
12932                old->s32_max_value >= cur->s32_max_value;
12933 }
12934
12935 /* If in the old state two registers had the same id, then they need to have
12936  * the same id in the new state as well.  But that id could be different from
12937  * the old state, so we need to track the mapping from old to new ids.
12938  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
12939  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
12940  * regs with a different old id could still have new id 9, we don't care about
12941  * that.
12942  * So we look through our idmap to see if this old id has been seen before.  If
12943  * so, we require the new id to match; otherwise, we add the id pair to the map.
12944  */
12945 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
12946 {
12947         unsigned int i;
12948
12949         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
12950                 if (!idmap[i].old) {
12951                         /* Reached an empty slot; haven't seen this id before */
12952                         idmap[i].old = old_id;
12953                         idmap[i].cur = cur_id;
12954                         return true;
12955                 }
12956                 if (idmap[i].old == old_id)
12957                         return idmap[i].cur == cur_id;
12958         }
12959         /* We ran out of idmap slots, which should be impossible */
12960         WARN_ON_ONCE(1);
12961         return false;
12962 }
12963
12964 static void clean_func_state(struct bpf_verifier_env *env,
12965                              struct bpf_func_state *st)
12966 {
12967         enum bpf_reg_liveness live;
12968         int i, j;
12969
12970         for (i = 0; i < BPF_REG_FP; i++) {
12971                 live = st->regs[i].live;
12972                 /* liveness must not touch this register anymore */
12973                 st->regs[i].live |= REG_LIVE_DONE;
12974                 if (!(live & REG_LIVE_READ))
12975                         /* since the register is unused, clear its state
12976                          * to make further comparison simpler
12977                          */
12978                         __mark_reg_not_init(env, &st->regs[i]);
12979         }
12980
12981         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
12982                 live = st->stack[i].spilled_ptr.live;
12983                 /* liveness must not touch this stack slot anymore */
12984                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
12985                 if (!(live & REG_LIVE_READ)) {
12986                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
12987                         for (j = 0; j < BPF_REG_SIZE; j++)
12988                                 st->stack[i].slot_type[j] = STACK_INVALID;
12989                 }
12990         }
12991 }
12992
12993 static void clean_verifier_state(struct bpf_verifier_env *env,
12994                                  struct bpf_verifier_state *st)
12995 {
12996         int i;
12997
12998         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
12999                 /* all regs in this state in all frames were already marked */
13000                 return;
13001
13002         for (i = 0; i <= st->curframe; i++)
13003                 clean_func_state(env, st->frame[i]);
13004 }
13005
13006 /* the parentage chains form a tree.
13007  * the verifier states are added to state lists at given insn and
13008  * pushed into state stack for future exploration.
13009  * when the verifier reaches bpf_exit insn some of the verifer states
13010  * stored in the state lists have their final liveness state already,
13011  * but a lot of states will get revised from liveness point of view when
13012  * the verifier explores other branches.
13013  * Example:
13014  * 1: r0 = 1
13015  * 2: if r1 == 100 goto pc+1
13016  * 3: r0 = 2
13017  * 4: exit
13018  * when the verifier reaches exit insn the register r0 in the state list of
13019  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
13020  * of insn 2 and goes exploring further. At the insn 4 it will walk the
13021  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
13022  *
13023  * Since the verifier pushes the branch states as it sees them while exploring
13024  * the program the condition of walking the branch instruction for the second
13025  * time means that all states below this branch were already explored and
13026  * their final liveness marks are already propagated.
13027  * Hence when the verifier completes the search of state list in is_state_visited()
13028  * we can call this clean_live_states() function to mark all liveness states
13029  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
13030  * will not be used.
13031  * This function also clears the registers and stack for states that !READ
13032  * to simplify state merging.
13033  *
13034  * Important note here that walking the same branch instruction in the callee
13035  * doesn't meant that the states are DONE. The verifier has to compare
13036  * the callsites
13037  */
13038 static void clean_live_states(struct bpf_verifier_env *env, int insn,
13039                               struct bpf_verifier_state *cur)
13040 {
13041         struct bpf_verifier_state_list *sl;
13042         int i;
13043
13044         sl = *explored_state(env, insn);
13045         while (sl) {
13046                 if (sl->state.branches)
13047                         goto next;
13048                 if (sl->state.insn_idx != insn ||
13049                     sl->state.curframe != cur->curframe)
13050                         goto next;
13051                 for (i = 0; i <= cur->curframe; i++)
13052                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
13053                                 goto next;
13054                 clean_verifier_state(env, &sl->state);
13055 next:
13056                 sl = sl->next;
13057         }
13058 }
13059
13060 /* Returns true if (rold safe implies rcur safe) */
13061 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
13062                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
13063 {
13064         bool equal;
13065
13066         if (!(rold->live & REG_LIVE_READ))
13067                 /* explored state didn't use this */
13068                 return true;
13069
13070         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
13071
13072         if (rold->type == NOT_INIT)
13073                 /* explored state can't have used this */
13074                 return true;
13075         if (rcur->type == NOT_INIT)
13076                 return false;
13077
13078         /* Enforce that register types have to match exactly, including their
13079          * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
13080          * rule.
13081          *
13082          * One can make a point that using a pointer register as unbounded
13083          * SCALAR would be technically acceptable, but this could lead to
13084          * pointer leaks because scalars are allowed to leak while pointers
13085          * are not. We could make this safe in special cases if root is
13086          * calling us, but it's probably not worth the hassle.
13087          *
13088          * Also, register types that are *not* MAYBE_NULL could technically be
13089          * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
13090          * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
13091          * to the same map).
13092          * However, if the old MAYBE_NULL register then got NULL checked,
13093          * doing so could have affected others with the same id, and we can't
13094          * check for that because we lost the id when we converted to
13095          * a non-MAYBE_NULL variant.
13096          * So, as a general rule we don't allow mixing MAYBE_NULL and
13097          * non-MAYBE_NULL registers as well.
13098          */
13099         if (rold->type != rcur->type)
13100                 return false;
13101
13102         switch (base_type(rold->type)) {
13103         case SCALAR_VALUE:
13104                 if (equal)
13105                         return true;
13106                 if (env->explore_alu_limits)
13107                         return false;
13108                 if (!rold->precise)
13109                         return true;
13110                 /* new val must satisfy old val knowledge */
13111                 return range_within(rold, rcur) &&
13112                        tnum_in(rold->var_off, rcur->var_off);
13113         case PTR_TO_MAP_KEY:
13114         case PTR_TO_MAP_VALUE:
13115                 /* If the new min/max/var_off satisfy the old ones and
13116                  * everything else matches, we are OK.
13117                  */
13118                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
13119                        range_within(rold, rcur) &&
13120                        tnum_in(rold->var_off, rcur->var_off) &&
13121                        check_ids(rold->id, rcur->id, idmap);
13122         case PTR_TO_PACKET_META:
13123         case PTR_TO_PACKET:
13124                 /* We must have at least as much range as the old ptr
13125                  * did, so that any accesses which were safe before are
13126                  * still safe.  This is true even if old range < old off,
13127                  * since someone could have accessed through (ptr - k), or
13128                  * even done ptr -= k in a register, to get a safe access.
13129                  */
13130                 if (rold->range > rcur->range)
13131                         return false;
13132                 /* If the offsets don't match, we can't trust our alignment;
13133                  * nor can we be sure that we won't fall out of range.
13134                  */
13135                 if (rold->off != rcur->off)
13136                         return false;
13137                 /* id relations must be preserved */
13138                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
13139                         return false;
13140                 /* new val must satisfy old val knowledge */
13141                 return range_within(rold, rcur) &&
13142                        tnum_in(rold->var_off, rcur->var_off);
13143         case PTR_TO_STACK:
13144                 /* two stack pointers are equal only if they're pointing to
13145                  * the same stack frame, since fp-8 in foo != fp-8 in bar
13146                  */
13147                 return equal && rold->frameno == rcur->frameno;
13148         default:
13149                 /* Only valid matches are exact, which memcmp() */
13150                 return equal;
13151         }
13152
13153         /* Shouldn't get here; if we do, say it's not safe */
13154         WARN_ON_ONCE(1);
13155         return false;
13156 }
13157
13158 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
13159                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
13160 {
13161         int i, spi;
13162
13163         /* walk slots of the explored stack and ignore any additional
13164          * slots in the current stack, since explored(safe) state
13165          * didn't use them
13166          */
13167         for (i = 0; i < old->allocated_stack; i++) {
13168                 spi = i / BPF_REG_SIZE;
13169
13170                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
13171                         i += BPF_REG_SIZE - 1;
13172                         /* explored state didn't use this */
13173                         continue;
13174                 }
13175
13176                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
13177                         continue;
13178
13179                 /* explored stack has more populated slots than current stack
13180                  * and these slots were used
13181                  */
13182                 if (i >= cur->allocated_stack)
13183                         return false;
13184
13185                 /* if old state was safe with misc data in the stack
13186                  * it will be safe with zero-initialized stack.
13187                  * The opposite is not true
13188                  */
13189                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
13190                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
13191                         continue;
13192                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
13193                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
13194                         /* Ex: old explored (safe) state has STACK_SPILL in
13195                          * this stack slot, but current has STACK_MISC ->
13196                          * this verifier states are not equivalent,
13197                          * return false to continue verification of this path
13198                          */
13199                         return false;
13200                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
13201                         continue;
13202                 if (!is_spilled_reg(&old->stack[spi]))
13203                         continue;
13204                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
13205                              &cur->stack[spi].spilled_ptr, idmap))
13206                         /* when explored and current stack slot are both storing
13207                          * spilled registers, check that stored pointers types
13208                          * are the same as well.
13209                          * Ex: explored safe path could have stored
13210                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
13211                          * but current path has stored:
13212                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
13213                          * such verifier states are not equivalent.
13214                          * return false to continue verification of this path
13215                          */
13216                         return false;
13217         }
13218         return true;
13219 }
13220
13221 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
13222                     struct bpf_id_pair *idmap)
13223 {
13224         int i;
13225
13226         if (old->acquired_refs != cur->acquired_refs)
13227                 return false;
13228
13229         for (i = 0; i < old->acquired_refs; i++) {
13230                 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
13231                         return false;
13232         }
13233
13234         return true;
13235 }
13236
13237 /* compare two verifier states
13238  *
13239  * all states stored in state_list are known to be valid, since
13240  * verifier reached 'bpf_exit' instruction through them
13241  *
13242  * this function is called when verifier exploring different branches of
13243  * execution popped from the state stack. If it sees an old state that has
13244  * more strict register state and more strict stack state then this execution
13245  * branch doesn't need to be explored further, since verifier already
13246  * concluded that more strict state leads to valid finish.
13247  *
13248  * Therefore two states are equivalent if register state is more conservative
13249  * and explored stack state is more conservative than the current one.
13250  * Example:
13251  *       explored                   current
13252  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
13253  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
13254  *
13255  * In other words if current stack state (one being explored) has more
13256  * valid slots than old one that already passed validation, it means
13257  * the verifier can stop exploring and conclude that current state is valid too
13258  *
13259  * Similarly with registers. If explored state has register type as invalid
13260  * whereas register type in current state is meaningful, it means that
13261  * the current state will reach 'bpf_exit' instruction safely
13262  */
13263 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
13264                               struct bpf_func_state *cur)
13265 {
13266         int i;
13267
13268         for (i = 0; i < MAX_BPF_REG; i++)
13269                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
13270                              env->idmap_scratch))
13271                         return false;
13272
13273         if (!stacksafe(env, old, cur, env->idmap_scratch))
13274                 return false;
13275
13276         if (!refsafe(old, cur, env->idmap_scratch))
13277                 return false;
13278
13279         return true;
13280 }
13281
13282 static bool states_equal(struct bpf_verifier_env *env,
13283                          struct bpf_verifier_state *old,
13284                          struct bpf_verifier_state *cur)
13285 {
13286         int i;
13287
13288         if (old->curframe != cur->curframe)
13289                 return false;
13290
13291         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
13292
13293         /* Verification state from speculative execution simulation
13294          * must never prune a non-speculative execution one.
13295          */
13296         if (old->speculative && !cur->speculative)
13297                 return false;
13298
13299         if (old->active_lock.ptr != cur->active_lock.ptr)
13300                 return false;
13301
13302         /* Old and cur active_lock's have to be either both present
13303          * or both absent.
13304          */
13305         if (!!old->active_lock.id != !!cur->active_lock.id)
13306                 return false;
13307
13308         if (old->active_lock.id &&
13309             !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
13310                 return false;
13311
13312         if (old->active_rcu_lock != cur->active_rcu_lock)
13313                 return false;
13314
13315         /* for states to be equal callsites have to be the same
13316          * and all frame states need to be equivalent
13317          */
13318         for (i = 0; i <= old->curframe; i++) {
13319                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
13320                         return false;
13321                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
13322                         return false;
13323         }
13324         return true;
13325 }
13326
13327 /* Return 0 if no propagation happened. Return negative error code if error
13328  * happened. Otherwise, return the propagated bit.
13329  */
13330 static int propagate_liveness_reg(struct bpf_verifier_env *env,
13331                                   struct bpf_reg_state *reg,
13332                                   struct bpf_reg_state *parent_reg)
13333 {
13334         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
13335         u8 flag = reg->live & REG_LIVE_READ;
13336         int err;
13337
13338         /* When comes here, read flags of PARENT_REG or REG could be any of
13339          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
13340          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
13341          */
13342         if (parent_flag == REG_LIVE_READ64 ||
13343             /* Or if there is no read flag from REG. */
13344             !flag ||
13345             /* Or if the read flag from REG is the same as PARENT_REG. */
13346             parent_flag == flag)
13347                 return 0;
13348
13349         err = mark_reg_read(env, reg, parent_reg, flag);
13350         if (err)
13351                 return err;
13352
13353         return flag;
13354 }
13355
13356 /* A write screens off any subsequent reads; but write marks come from the
13357  * straight-line code between a state and its parent.  When we arrive at an
13358  * equivalent state (jump target or such) we didn't arrive by the straight-line
13359  * code, so read marks in the state must propagate to the parent regardless
13360  * of the state's write marks. That's what 'parent == state->parent' comparison
13361  * in mark_reg_read() is for.
13362  */
13363 static int propagate_liveness(struct bpf_verifier_env *env,
13364                               const struct bpf_verifier_state *vstate,
13365                               struct bpf_verifier_state *vparent)
13366 {
13367         struct bpf_reg_state *state_reg, *parent_reg;
13368         struct bpf_func_state *state, *parent;
13369         int i, frame, err = 0;
13370
13371         if (vparent->curframe != vstate->curframe) {
13372                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
13373                      vparent->curframe, vstate->curframe);
13374                 return -EFAULT;
13375         }
13376         /* Propagate read liveness of registers... */
13377         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
13378         for (frame = 0; frame <= vstate->curframe; frame++) {
13379                 parent = vparent->frame[frame];
13380                 state = vstate->frame[frame];
13381                 parent_reg = parent->regs;
13382                 state_reg = state->regs;
13383                 /* We don't need to worry about FP liveness, it's read-only */
13384                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
13385                         err = propagate_liveness_reg(env, &state_reg[i],
13386                                                      &parent_reg[i]);
13387                         if (err < 0)
13388                                 return err;
13389                         if (err == REG_LIVE_READ64)
13390                                 mark_insn_zext(env, &parent_reg[i]);
13391                 }
13392
13393                 /* Propagate stack slots. */
13394                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
13395                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
13396                         parent_reg = &parent->stack[i].spilled_ptr;
13397                         state_reg = &state->stack[i].spilled_ptr;
13398                         err = propagate_liveness_reg(env, state_reg,
13399                                                      parent_reg);
13400                         if (err < 0)
13401                                 return err;
13402                 }
13403         }
13404         return 0;
13405 }
13406
13407 /* find precise scalars in the previous equivalent state and
13408  * propagate them into the current state
13409  */
13410 static int propagate_precision(struct bpf_verifier_env *env,
13411                                const struct bpf_verifier_state *old)
13412 {
13413         struct bpf_reg_state *state_reg;
13414         struct bpf_func_state *state;
13415         int i, err = 0, fr;
13416
13417         for (fr = old->curframe; fr >= 0; fr--) {
13418                 state = old->frame[fr];
13419                 state_reg = state->regs;
13420                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
13421                         if (state_reg->type != SCALAR_VALUE ||
13422                             !state_reg->precise)
13423                                 continue;
13424                         if (env->log.level & BPF_LOG_LEVEL2)
13425                                 verbose(env, "frame %d: propagating r%d\n", i, fr);
13426                         err = mark_chain_precision_frame(env, fr, i);
13427                         if (err < 0)
13428                                 return err;
13429                 }
13430
13431                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
13432                         if (!is_spilled_reg(&state->stack[i]))
13433                                 continue;
13434                         state_reg = &state->stack[i].spilled_ptr;
13435                         if (state_reg->type != SCALAR_VALUE ||
13436                             !state_reg->precise)
13437                                 continue;
13438                         if (env->log.level & BPF_LOG_LEVEL2)
13439                                 verbose(env, "frame %d: propagating fp%d\n",
13440                                         (-i - 1) * BPF_REG_SIZE, fr);
13441                         err = mark_chain_precision_stack_frame(env, fr, i);
13442                         if (err < 0)
13443                                 return err;
13444                 }
13445         }
13446         return 0;
13447 }
13448
13449 static bool states_maybe_looping(struct bpf_verifier_state *old,
13450                                  struct bpf_verifier_state *cur)
13451 {
13452         struct bpf_func_state *fold, *fcur;
13453         int i, fr = cur->curframe;
13454
13455         if (old->curframe != fr)
13456                 return false;
13457
13458         fold = old->frame[fr];
13459         fcur = cur->frame[fr];
13460         for (i = 0; i < MAX_BPF_REG; i++)
13461                 if (memcmp(&fold->regs[i], &fcur->regs[i],
13462                            offsetof(struct bpf_reg_state, parent)))
13463                         return false;
13464         return true;
13465 }
13466
13467
13468 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
13469 {
13470         struct bpf_verifier_state_list *new_sl;
13471         struct bpf_verifier_state_list *sl, **pprev;
13472         struct bpf_verifier_state *cur = env->cur_state, *new;
13473         int i, j, err, states_cnt = 0;
13474         bool add_new_state = env->test_state_freq ? true : false;
13475
13476         /* bpf progs typically have pruning point every 4 instructions
13477          * http://vger.kernel.org/bpfconf2019.html#session-1
13478          * Do not add new state for future pruning if the verifier hasn't seen
13479          * at least 2 jumps and at least 8 instructions.
13480          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
13481          * In tests that amounts to up to 50% reduction into total verifier
13482          * memory consumption and 20% verifier time speedup.
13483          */
13484         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
13485             env->insn_processed - env->prev_insn_processed >= 8)
13486                 add_new_state = true;
13487
13488         pprev = explored_state(env, insn_idx);
13489         sl = *pprev;
13490
13491         clean_live_states(env, insn_idx, cur);
13492
13493         while (sl) {
13494                 states_cnt++;
13495                 if (sl->state.insn_idx != insn_idx)
13496                         goto next;
13497
13498                 if (sl->state.branches) {
13499                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
13500
13501                         if (frame->in_async_callback_fn &&
13502                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
13503                                 /* Different async_entry_cnt means that the verifier is
13504                                  * processing another entry into async callback.
13505                                  * Seeing the same state is not an indication of infinite
13506                                  * loop or infinite recursion.
13507                                  * But finding the same state doesn't mean that it's safe
13508                                  * to stop processing the current state. The previous state
13509                                  * hasn't yet reached bpf_exit, since state.branches > 0.
13510                                  * Checking in_async_callback_fn alone is not enough either.
13511                                  * Since the verifier still needs to catch infinite loops
13512                                  * inside async callbacks.
13513                                  */
13514                         } else if (states_maybe_looping(&sl->state, cur) &&
13515                                    states_equal(env, &sl->state, cur)) {
13516                                 verbose_linfo(env, insn_idx, "; ");
13517                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
13518                                 return -EINVAL;
13519                         }
13520                         /* if the verifier is processing a loop, avoid adding new state
13521                          * too often, since different loop iterations have distinct
13522                          * states and may not help future pruning.
13523                          * This threshold shouldn't be too low to make sure that
13524                          * a loop with large bound will be rejected quickly.
13525                          * The most abusive loop will be:
13526                          * r1 += 1
13527                          * if r1 < 1000000 goto pc-2
13528                          * 1M insn_procssed limit / 100 == 10k peak states.
13529                          * This threshold shouldn't be too high either, since states
13530                          * at the end of the loop are likely to be useful in pruning.
13531                          */
13532                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
13533                             env->insn_processed - env->prev_insn_processed < 100)
13534                                 add_new_state = false;
13535                         goto miss;
13536                 }
13537                 if (states_equal(env, &sl->state, cur)) {
13538                         sl->hit_cnt++;
13539                         /* reached equivalent register/stack state,
13540                          * prune the search.
13541                          * Registers read by the continuation are read by us.
13542                          * If we have any write marks in env->cur_state, they
13543                          * will prevent corresponding reads in the continuation
13544                          * from reaching our parent (an explored_state).  Our
13545                          * own state will get the read marks recorded, but
13546                          * they'll be immediately forgotten as we're pruning
13547                          * this state and will pop a new one.
13548                          */
13549                         err = propagate_liveness(env, &sl->state, cur);
13550
13551                         /* if previous state reached the exit with precision and
13552                          * current state is equivalent to it (except precsion marks)
13553                          * the precision needs to be propagated back in
13554                          * the current state.
13555                          */
13556                         err = err ? : push_jmp_history(env, cur);
13557                         err = err ? : propagate_precision(env, &sl->state);
13558                         if (err)
13559                                 return err;
13560                         return 1;
13561                 }
13562 miss:
13563                 /* when new state is not going to be added do not increase miss count.
13564                  * Otherwise several loop iterations will remove the state
13565                  * recorded earlier. The goal of these heuristics is to have
13566                  * states from some iterations of the loop (some in the beginning
13567                  * and some at the end) to help pruning.
13568                  */
13569                 if (add_new_state)
13570                         sl->miss_cnt++;
13571                 /* heuristic to determine whether this state is beneficial
13572                  * to keep checking from state equivalence point of view.
13573                  * Higher numbers increase max_states_per_insn and verification time,
13574                  * but do not meaningfully decrease insn_processed.
13575                  */
13576                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
13577                         /* the state is unlikely to be useful. Remove it to
13578                          * speed up verification
13579                          */
13580                         *pprev = sl->next;
13581                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
13582                                 u32 br = sl->state.branches;
13583
13584                                 WARN_ONCE(br,
13585                                           "BUG live_done but branches_to_explore %d\n",
13586                                           br);
13587                                 free_verifier_state(&sl->state, false);
13588                                 kfree(sl);
13589                                 env->peak_states--;
13590                         } else {
13591                                 /* cannot free this state, since parentage chain may
13592                                  * walk it later. Add it for free_list instead to
13593                                  * be freed at the end of verification
13594                                  */
13595                                 sl->next = env->free_list;
13596                                 env->free_list = sl;
13597                         }
13598                         sl = *pprev;
13599                         continue;
13600                 }
13601 next:
13602                 pprev = &sl->next;
13603                 sl = *pprev;
13604         }
13605
13606         if (env->max_states_per_insn < states_cnt)
13607                 env->max_states_per_insn = states_cnt;
13608
13609         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
13610                 return 0;
13611
13612         if (!add_new_state)
13613                 return 0;
13614
13615         /* There were no equivalent states, remember the current one.
13616          * Technically the current state is not proven to be safe yet,
13617          * but it will either reach outer most bpf_exit (which means it's safe)
13618          * or it will be rejected. When there are no loops the verifier won't be
13619          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
13620          * again on the way to bpf_exit.
13621          * When looping the sl->state.branches will be > 0 and this state
13622          * will not be considered for equivalence until branches == 0.
13623          */
13624         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
13625         if (!new_sl)
13626                 return -ENOMEM;
13627         env->total_states++;
13628         env->peak_states++;
13629         env->prev_jmps_processed = env->jmps_processed;
13630         env->prev_insn_processed = env->insn_processed;
13631
13632         /* forget precise markings we inherited, see __mark_chain_precision */
13633         if (env->bpf_capable)
13634                 mark_all_scalars_imprecise(env, cur);
13635
13636         /* add new state to the head of linked list */
13637         new = &new_sl->state;
13638         err = copy_verifier_state(new, cur);
13639         if (err) {
13640                 free_verifier_state(new, false);
13641                 kfree(new_sl);
13642                 return err;
13643         }
13644         new->insn_idx = insn_idx;
13645         WARN_ONCE(new->branches != 1,
13646                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
13647
13648         cur->parent = new;
13649         cur->first_insn_idx = insn_idx;
13650         clear_jmp_history(cur);
13651         new_sl->next = *explored_state(env, insn_idx);
13652         *explored_state(env, insn_idx) = new_sl;
13653         /* connect new state to parentage chain. Current frame needs all
13654          * registers connected. Only r6 - r9 of the callers are alive (pushed
13655          * to the stack implicitly by JITs) so in callers' frames connect just
13656          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
13657          * the state of the call instruction (with WRITTEN set), and r0 comes
13658          * from callee with its full parentage chain, anyway.
13659          */
13660         /* clear write marks in current state: the writes we did are not writes
13661          * our child did, so they don't screen off its reads from us.
13662          * (There are no read marks in current state, because reads always mark
13663          * their parent and current state never has children yet.  Only
13664          * explored_states can get read marks.)
13665          */
13666         for (j = 0; j <= cur->curframe; j++) {
13667                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
13668                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
13669                 for (i = 0; i < BPF_REG_FP; i++)
13670                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
13671         }
13672
13673         /* all stack frames are accessible from callee, clear them all */
13674         for (j = 0; j <= cur->curframe; j++) {
13675                 struct bpf_func_state *frame = cur->frame[j];
13676                 struct bpf_func_state *newframe = new->frame[j];
13677
13678                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
13679                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
13680                         frame->stack[i].spilled_ptr.parent =
13681                                                 &newframe->stack[i].spilled_ptr;
13682                 }
13683         }
13684         return 0;
13685 }
13686
13687 /* Return true if it's OK to have the same insn return a different type. */
13688 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
13689 {
13690         switch (base_type(type)) {
13691         case PTR_TO_CTX:
13692         case PTR_TO_SOCKET:
13693         case PTR_TO_SOCK_COMMON:
13694         case PTR_TO_TCP_SOCK:
13695         case PTR_TO_XDP_SOCK:
13696         case PTR_TO_BTF_ID:
13697                 return false;
13698         default:
13699                 return true;
13700         }
13701 }
13702
13703 /* If an instruction was previously used with particular pointer types, then we
13704  * need to be careful to avoid cases such as the below, where it may be ok
13705  * for one branch accessing the pointer, but not ok for the other branch:
13706  *
13707  * R1 = sock_ptr
13708  * goto X;
13709  * ...
13710  * R1 = some_other_valid_ptr;
13711  * goto X;
13712  * ...
13713  * R2 = *(u32 *)(R1 + 0);
13714  */
13715 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
13716 {
13717         return src != prev && (!reg_type_mismatch_ok(src) ||
13718                                !reg_type_mismatch_ok(prev));
13719 }
13720
13721 static int do_check(struct bpf_verifier_env *env)
13722 {
13723         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13724         struct bpf_verifier_state *state = env->cur_state;
13725         struct bpf_insn *insns = env->prog->insnsi;
13726         struct bpf_reg_state *regs;
13727         int insn_cnt = env->prog->len;
13728         bool do_print_state = false;
13729         int prev_insn_idx = -1;
13730
13731         for (;;) {
13732                 struct bpf_insn *insn;
13733                 u8 class;
13734                 int err;
13735
13736                 env->prev_insn_idx = prev_insn_idx;
13737                 if (env->insn_idx >= insn_cnt) {
13738                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
13739                                 env->insn_idx, insn_cnt);
13740                         return -EFAULT;
13741                 }
13742
13743                 insn = &insns[env->insn_idx];
13744                 class = BPF_CLASS(insn->code);
13745
13746                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
13747                         verbose(env,
13748                                 "BPF program is too large. Processed %d insn\n",
13749                                 env->insn_processed);
13750                         return -E2BIG;
13751                 }
13752
13753                 state->last_insn_idx = env->prev_insn_idx;
13754
13755                 if (is_prune_point(env, env->insn_idx)) {
13756                         err = is_state_visited(env, env->insn_idx);
13757                         if (err < 0)
13758                                 return err;
13759                         if (err == 1) {
13760                                 /* found equivalent state, can prune the search */
13761                                 if (env->log.level & BPF_LOG_LEVEL) {
13762                                         if (do_print_state)
13763                                                 verbose(env, "\nfrom %d to %d%s: safe\n",
13764                                                         env->prev_insn_idx, env->insn_idx,
13765                                                         env->cur_state->speculative ?
13766                                                         " (speculative execution)" : "");
13767                                         else
13768                                                 verbose(env, "%d: safe\n", env->insn_idx);
13769                                 }
13770                                 goto process_bpf_exit;
13771                         }
13772                 }
13773
13774                 if (is_jmp_point(env, env->insn_idx)) {
13775                         err = push_jmp_history(env, state);
13776                         if (err)
13777                                 return err;
13778                 }
13779
13780                 if (signal_pending(current))
13781                         return -EAGAIN;
13782
13783                 if (need_resched())
13784                         cond_resched();
13785
13786                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
13787                         verbose(env, "\nfrom %d to %d%s:",
13788                                 env->prev_insn_idx, env->insn_idx,
13789                                 env->cur_state->speculative ?
13790                                 " (speculative execution)" : "");
13791                         print_verifier_state(env, state->frame[state->curframe], true);
13792                         do_print_state = false;
13793                 }
13794
13795                 if (env->log.level & BPF_LOG_LEVEL) {
13796                         const struct bpf_insn_cbs cbs = {
13797                                 .cb_call        = disasm_kfunc_name,
13798                                 .cb_print       = verbose,
13799                                 .private_data   = env,
13800                         };
13801
13802                         if (verifier_state_scratched(env))
13803                                 print_insn_state(env, state->frame[state->curframe]);
13804
13805                         verbose_linfo(env, env->insn_idx, "; ");
13806                         env->prev_log_len = env->log.len_used;
13807                         verbose(env, "%d: ", env->insn_idx);
13808                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
13809                         env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
13810                         env->prev_log_len = env->log.len_used;
13811                 }
13812
13813                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
13814                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
13815                                                            env->prev_insn_idx);
13816                         if (err)
13817                                 return err;
13818                 }
13819
13820                 regs = cur_regs(env);
13821                 sanitize_mark_insn_seen(env);
13822                 prev_insn_idx = env->insn_idx;
13823
13824                 if (class == BPF_ALU || class == BPF_ALU64) {
13825                         err = check_alu_op(env, insn);
13826                         if (err)
13827                                 return err;
13828
13829                 } else if (class == BPF_LDX) {
13830                         enum bpf_reg_type *prev_src_type, src_reg_type;
13831
13832                         /* check for reserved fields is already done */
13833
13834                         /* check src operand */
13835                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13836                         if (err)
13837                                 return err;
13838
13839                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13840                         if (err)
13841                                 return err;
13842
13843                         src_reg_type = regs[insn->src_reg].type;
13844
13845                         /* check that memory (src_reg + off) is readable,
13846                          * the state of dst_reg will be updated by this func
13847                          */
13848                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
13849                                                insn->off, BPF_SIZE(insn->code),
13850                                                BPF_READ, insn->dst_reg, false);
13851                         if (err)
13852                                 return err;
13853
13854                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13855
13856                         if (*prev_src_type == NOT_INIT) {
13857                                 /* saw a valid insn
13858                                  * dst_reg = *(u32 *)(src_reg + off)
13859                                  * save type to validate intersecting paths
13860                                  */
13861                                 *prev_src_type = src_reg_type;
13862
13863                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
13864                                 /* ABuser program is trying to use the same insn
13865                                  * dst_reg = *(u32*) (src_reg + off)
13866                                  * with different pointer types:
13867                                  * src_reg == ctx in one branch and
13868                                  * src_reg == stack|map in some other branch.
13869                                  * Reject it.
13870                                  */
13871                                 verbose(env, "same insn cannot be used with different pointers\n");
13872                                 return -EINVAL;
13873                         }
13874
13875                 } else if (class == BPF_STX) {
13876                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
13877
13878                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
13879                                 err = check_atomic(env, env->insn_idx, insn);
13880                                 if (err)
13881                                         return err;
13882                                 env->insn_idx++;
13883                                 continue;
13884                         }
13885
13886                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
13887                                 verbose(env, "BPF_STX uses reserved fields\n");
13888                                 return -EINVAL;
13889                         }
13890
13891                         /* check src1 operand */
13892                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13893                         if (err)
13894                                 return err;
13895                         /* check src2 operand */
13896                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13897                         if (err)
13898                                 return err;
13899
13900                         dst_reg_type = regs[insn->dst_reg].type;
13901
13902                         /* check that memory (dst_reg + off) is writeable */
13903                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13904                                                insn->off, BPF_SIZE(insn->code),
13905                                                BPF_WRITE, insn->src_reg, false);
13906                         if (err)
13907                                 return err;
13908
13909                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13910
13911                         if (*prev_dst_type == NOT_INIT) {
13912                                 *prev_dst_type = dst_reg_type;
13913                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
13914                                 verbose(env, "same insn cannot be used with different pointers\n");
13915                                 return -EINVAL;
13916                         }
13917
13918                 } else if (class == BPF_ST) {
13919                         if (BPF_MODE(insn->code) != BPF_MEM ||
13920                             insn->src_reg != BPF_REG_0) {
13921                                 verbose(env, "BPF_ST uses reserved fields\n");
13922                                 return -EINVAL;
13923                         }
13924                         /* check src operand */
13925                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13926                         if (err)
13927                                 return err;
13928
13929                         if (is_ctx_reg(env, insn->dst_reg)) {
13930                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
13931                                         insn->dst_reg,
13932                                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
13933                                 return -EACCES;
13934                         }
13935
13936                         /* check that memory (dst_reg + off) is writeable */
13937                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13938                                                insn->off, BPF_SIZE(insn->code),
13939                                                BPF_WRITE, -1, false);
13940                         if (err)
13941                                 return err;
13942
13943                 } else if (class == BPF_JMP || class == BPF_JMP32) {
13944                         u8 opcode = BPF_OP(insn->code);
13945
13946                         env->jmps_processed++;
13947                         if (opcode == BPF_CALL) {
13948                                 if (BPF_SRC(insn->code) != BPF_K ||
13949                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
13950                                      && insn->off != 0) ||
13951                                     (insn->src_reg != BPF_REG_0 &&
13952                                      insn->src_reg != BPF_PSEUDO_CALL &&
13953                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
13954                                     insn->dst_reg != BPF_REG_0 ||
13955                                     class == BPF_JMP32) {
13956                                         verbose(env, "BPF_CALL uses reserved fields\n");
13957                                         return -EINVAL;
13958                                 }
13959
13960                                 if (env->cur_state->active_lock.ptr) {
13961                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
13962                                             (insn->src_reg == BPF_PSEUDO_CALL) ||
13963                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
13964                                              (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) {
13965                                                 verbose(env, "function calls are not allowed while holding a lock\n");
13966                                                 return -EINVAL;
13967                                         }
13968                                 }
13969                                 if (insn->src_reg == BPF_PSEUDO_CALL)
13970                                         err = check_func_call(env, insn, &env->insn_idx);
13971                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
13972                                         err = check_kfunc_call(env, insn, &env->insn_idx);
13973                                 else
13974                                         err = check_helper_call(env, insn, &env->insn_idx);
13975                                 if (err)
13976                                         return err;
13977                         } else if (opcode == BPF_JA) {
13978                                 if (BPF_SRC(insn->code) != BPF_K ||
13979                                     insn->imm != 0 ||
13980                                     insn->src_reg != BPF_REG_0 ||
13981                                     insn->dst_reg != BPF_REG_0 ||
13982                                     class == BPF_JMP32) {
13983                                         verbose(env, "BPF_JA uses reserved fields\n");
13984                                         return -EINVAL;
13985                                 }
13986
13987                                 env->insn_idx += insn->off + 1;
13988                                 continue;
13989
13990                         } else if (opcode == BPF_EXIT) {
13991                                 if (BPF_SRC(insn->code) != BPF_K ||
13992                                     insn->imm != 0 ||
13993                                     insn->src_reg != BPF_REG_0 ||
13994                                     insn->dst_reg != BPF_REG_0 ||
13995                                     class == BPF_JMP32) {
13996                                         verbose(env, "BPF_EXIT uses reserved fields\n");
13997                                         return -EINVAL;
13998                                 }
13999
14000                                 if (env->cur_state->active_lock.ptr) {
14001                                         verbose(env, "bpf_spin_unlock is missing\n");
14002                                         return -EINVAL;
14003                                 }
14004
14005                                 if (env->cur_state->active_rcu_lock) {
14006                                         verbose(env, "bpf_rcu_read_unlock is missing\n");
14007                                         return -EINVAL;
14008                                 }
14009
14010                                 /* We must do check_reference_leak here before
14011                                  * prepare_func_exit to handle the case when
14012                                  * state->curframe > 0, it may be a callback
14013                                  * function, for which reference_state must
14014                                  * match caller reference state when it exits.
14015                                  */
14016                                 err = check_reference_leak(env);
14017                                 if (err)
14018                                         return err;
14019
14020                                 if (state->curframe) {
14021                                         /* exit from nested function */
14022                                         err = prepare_func_exit(env, &env->insn_idx);
14023                                         if (err)
14024                                                 return err;
14025                                         do_print_state = true;
14026                                         continue;
14027                                 }
14028
14029                                 err = check_return_code(env);
14030                                 if (err)
14031                                         return err;
14032 process_bpf_exit:
14033                                 mark_verifier_state_scratched(env);
14034                                 update_branch_counts(env, env->cur_state);
14035                                 err = pop_stack(env, &prev_insn_idx,
14036                                                 &env->insn_idx, pop_log);
14037                                 if (err < 0) {
14038                                         if (err != -ENOENT)
14039                                                 return err;
14040                                         break;
14041                                 } else {
14042                                         do_print_state = true;
14043                                         continue;
14044                                 }
14045                         } else {
14046                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
14047                                 if (err)
14048                                         return err;
14049                         }
14050                 } else if (class == BPF_LD) {
14051                         u8 mode = BPF_MODE(insn->code);
14052
14053                         if (mode == BPF_ABS || mode == BPF_IND) {
14054                                 err = check_ld_abs(env, insn);
14055                                 if (err)
14056                                         return err;
14057
14058                         } else if (mode == BPF_IMM) {
14059                                 err = check_ld_imm(env, insn);
14060                                 if (err)
14061                                         return err;
14062
14063                                 env->insn_idx++;
14064                                 sanitize_mark_insn_seen(env);
14065                         } else {
14066                                 verbose(env, "invalid BPF_LD mode\n");
14067                                 return -EINVAL;
14068                         }
14069                 } else {
14070                         verbose(env, "unknown insn class %d\n", class);
14071                         return -EINVAL;
14072                 }
14073
14074                 env->insn_idx++;
14075         }
14076
14077         return 0;
14078 }
14079
14080 static int find_btf_percpu_datasec(struct btf *btf)
14081 {
14082         const struct btf_type *t;
14083         const char *tname;
14084         int i, n;
14085
14086         /*
14087          * Both vmlinux and module each have their own ".data..percpu"
14088          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
14089          * types to look at only module's own BTF types.
14090          */
14091         n = btf_nr_types(btf);
14092         if (btf_is_module(btf))
14093                 i = btf_nr_types(btf_vmlinux);
14094         else
14095                 i = 1;
14096
14097         for(; i < n; i++) {
14098                 t = btf_type_by_id(btf, i);
14099                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
14100                         continue;
14101
14102                 tname = btf_name_by_offset(btf, t->name_off);
14103                 if (!strcmp(tname, ".data..percpu"))
14104                         return i;
14105         }
14106
14107         return -ENOENT;
14108 }
14109
14110 /* replace pseudo btf_id with kernel symbol address */
14111 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
14112                                struct bpf_insn *insn,
14113                                struct bpf_insn_aux_data *aux)
14114 {
14115         const struct btf_var_secinfo *vsi;
14116         const struct btf_type *datasec;
14117         struct btf_mod_pair *btf_mod;
14118         const struct btf_type *t;
14119         const char *sym_name;
14120         bool percpu = false;
14121         u32 type, id = insn->imm;
14122         struct btf *btf;
14123         s32 datasec_id;
14124         u64 addr;
14125         int i, btf_fd, err;
14126
14127         btf_fd = insn[1].imm;
14128         if (btf_fd) {
14129                 btf = btf_get_by_fd(btf_fd);
14130                 if (IS_ERR(btf)) {
14131                         verbose(env, "invalid module BTF object FD specified.\n");
14132                         return -EINVAL;
14133                 }
14134         } else {
14135                 if (!btf_vmlinux) {
14136                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
14137                         return -EINVAL;
14138                 }
14139                 btf = btf_vmlinux;
14140                 btf_get(btf);
14141         }
14142
14143         t = btf_type_by_id(btf, id);
14144         if (!t) {
14145                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
14146                 err = -ENOENT;
14147                 goto err_put;
14148         }
14149
14150         if (!btf_type_is_var(t)) {
14151                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
14152                 err = -EINVAL;
14153                 goto err_put;
14154         }
14155
14156         sym_name = btf_name_by_offset(btf, t->name_off);
14157         addr = kallsyms_lookup_name(sym_name);
14158         if (!addr) {
14159                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
14160                         sym_name);
14161                 err = -ENOENT;
14162                 goto err_put;
14163         }
14164
14165         datasec_id = find_btf_percpu_datasec(btf);
14166         if (datasec_id > 0) {
14167                 datasec = btf_type_by_id(btf, datasec_id);
14168                 for_each_vsi(i, datasec, vsi) {
14169                         if (vsi->type == id) {
14170                                 percpu = true;
14171                                 break;
14172                         }
14173                 }
14174         }
14175
14176         insn[0].imm = (u32)addr;
14177         insn[1].imm = addr >> 32;
14178
14179         type = t->type;
14180         t = btf_type_skip_modifiers(btf, type, NULL);
14181         if (percpu) {
14182                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
14183                 aux->btf_var.btf = btf;
14184                 aux->btf_var.btf_id = type;
14185         } else if (!btf_type_is_struct(t)) {
14186                 const struct btf_type *ret;
14187                 const char *tname;
14188                 u32 tsize;
14189
14190                 /* resolve the type size of ksym. */
14191                 ret = btf_resolve_size(btf, t, &tsize);
14192                 if (IS_ERR(ret)) {
14193                         tname = btf_name_by_offset(btf, t->name_off);
14194                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
14195                                 tname, PTR_ERR(ret));
14196                         err = -EINVAL;
14197                         goto err_put;
14198                 }
14199                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
14200                 aux->btf_var.mem_size = tsize;
14201         } else {
14202                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
14203                 aux->btf_var.btf = btf;
14204                 aux->btf_var.btf_id = type;
14205         }
14206
14207         /* check whether we recorded this BTF (and maybe module) already */
14208         for (i = 0; i < env->used_btf_cnt; i++) {
14209                 if (env->used_btfs[i].btf == btf) {
14210                         btf_put(btf);
14211                         return 0;
14212                 }
14213         }
14214
14215         if (env->used_btf_cnt >= MAX_USED_BTFS) {
14216                 err = -E2BIG;
14217                 goto err_put;
14218         }
14219
14220         btf_mod = &env->used_btfs[env->used_btf_cnt];
14221         btf_mod->btf = btf;
14222         btf_mod->module = NULL;
14223
14224         /* if we reference variables from kernel module, bump its refcount */
14225         if (btf_is_module(btf)) {
14226                 btf_mod->module = btf_try_get_module(btf);
14227                 if (!btf_mod->module) {
14228                         err = -ENXIO;
14229                         goto err_put;
14230                 }
14231         }
14232
14233         env->used_btf_cnt++;
14234
14235         return 0;
14236 err_put:
14237         btf_put(btf);
14238         return err;
14239 }
14240
14241 static bool is_tracing_prog_type(enum bpf_prog_type type)
14242 {
14243         switch (type) {
14244         case BPF_PROG_TYPE_KPROBE:
14245         case BPF_PROG_TYPE_TRACEPOINT:
14246         case BPF_PROG_TYPE_PERF_EVENT:
14247         case BPF_PROG_TYPE_RAW_TRACEPOINT:
14248         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
14249                 return true;
14250         default:
14251                 return false;
14252         }
14253 }
14254
14255 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
14256                                         struct bpf_map *map,
14257                                         struct bpf_prog *prog)
14258
14259 {
14260         enum bpf_prog_type prog_type = resolve_prog_type(prog);
14261
14262         if (btf_record_has_field(map->record, BPF_LIST_HEAD)) {
14263                 if (is_tracing_prog_type(prog_type)) {
14264                         verbose(env, "tracing progs cannot use bpf_list_head yet\n");
14265                         return -EINVAL;
14266                 }
14267         }
14268
14269         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
14270                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
14271                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
14272                         return -EINVAL;
14273                 }
14274
14275                 if (is_tracing_prog_type(prog_type)) {
14276                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
14277                         return -EINVAL;
14278                 }
14279
14280                 if (prog->aux->sleepable) {
14281                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
14282                         return -EINVAL;
14283                 }
14284         }
14285
14286         if (btf_record_has_field(map->record, BPF_TIMER)) {
14287                 if (is_tracing_prog_type(prog_type)) {
14288                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
14289                         return -EINVAL;
14290                 }
14291         }
14292
14293         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
14294             !bpf_offload_prog_map_match(prog, map)) {
14295                 verbose(env, "offload device mismatch between prog and map\n");
14296                 return -EINVAL;
14297         }
14298
14299         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
14300                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
14301                 return -EINVAL;
14302         }
14303
14304         if (prog->aux->sleepable)
14305                 switch (map->map_type) {
14306                 case BPF_MAP_TYPE_HASH:
14307                 case BPF_MAP_TYPE_LRU_HASH:
14308                 case BPF_MAP_TYPE_ARRAY:
14309                 case BPF_MAP_TYPE_PERCPU_HASH:
14310                 case BPF_MAP_TYPE_PERCPU_ARRAY:
14311                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
14312                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
14313                 case BPF_MAP_TYPE_HASH_OF_MAPS:
14314                 case BPF_MAP_TYPE_RINGBUF:
14315                 case BPF_MAP_TYPE_USER_RINGBUF:
14316                 case BPF_MAP_TYPE_INODE_STORAGE:
14317                 case BPF_MAP_TYPE_SK_STORAGE:
14318                 case BPF_MAP_TYPE_TASK_STORAGE:
14319                 case BPF_MAP_TYPE_CGRP_STORAGE:
14320                         break;
14321                 default:
14322                         verbose(env,
14323                                 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
14324                         return -EINVAL;
14325                 }
14326
14327         return 0;
14328 }
14329
14330 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
14331 {
14332         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
14333                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
14334 }
14335
14336 /* find and rewrite pseudo imm in ld_imm64 instructions:
14337  *
14338  * 1. if it accesses map FD, replace it with actual map pointer.
14339  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
14340  *
14341  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
14342  */
14343 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
14344 {
14345         struct bpf_insn *insn = env->prog->insnsi;
14346         int insn_cnt = env->prog->len;
14347         int i, j, err;
14348
14349         err = bpf_prog_calc_tag(env->prog);
14350         if (err)
14351                 return err;
14352
14353         for (i = 0; i < insn_cnt; i++, insn++) {
14354                 if (BPF_CLASS(insn->code) == BPF_LDX &&
14355                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
14356                         verbose(env, "BPF_LDX uses reserved fields\n");
14357                         return -EINVAL;
14358                 }
14359
14360                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
14361                         struct bpf_insn_aux_data *aux;
14362                         struct bpf_map *map;
14363                         struct fd f;
14364                         u64 addr;
14365                         u32 fd;
14366
14367                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
14368                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
14369                             insn[1].off != 0) {
14370                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
14371                                 return -EINVAL;
14372                         }
14373
14374                         if (insn[0].src_reg == 0)
14375                                 /* valid generic load 64-bit imm */
14376                                 goto next_insn;
14377
14378                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
14379                                 aux = &env->insn_aux_data[i];
14380                                 err = check_pseudo_btf_id(env, insn, aux);
14381                                 if (err)
14382                                         return err;
14383                                 goto next_insn;
14384                         }
14385
14386                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
14387                                 aux = &env->insn_aux_data[i];
14388                                 aux->ptr_type = PTR_TO_FUNC;
14389                                 goto next_insn;
14390                         }
14391
14392                         /* In final convert_pseudo_ld_imm64() step, this is
14393                          * converted into regular 64-bit imm load insn.
14394                          */
14395                         switch (insn[0].src_reg) {
14396                         case BPF_PSEUDO_MAP_VALUE:
14397                         case BPF_PSEUDO_MAP_IDX_VALUE:
14398                                 break;
14399                         case BPF_PSEUDO_MAP_FD:
14400                         case BPF_PSEUDO_MAP_IDX:
14401                                 if (insn[1].imm == 0)
14402                                         break;
14403                                 fallthrough;
14404                         default:
14405                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
14406                                 return -EINVAL;
14407                         }
14408
14409                         switch (insn[0].src_reg) {
14410                         case BPF_PSEUDO_MAP_IDX_VALUE:
14411                         case BPF_PSEUDO_MAP_IDX:
14412                                 if (bpfptr_is_null(env->fd_array)) {
14413                                         verbose(env, "fd_idx without fd_array is invalid\n");
14414                                         return -EPROTO;
14415                                 }
14416                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
14417                                                             insn[0].imm * sizeof(fd),
14418                                                             sizeof(fd)))
14419                                         return -EFAULT;
14420                                 break;
14421                         default:
14422                                 fd = insn[0].imm;
14423                                 break;
14424                         }
14425
14426                         f = fdget(fd);
14427                         map = __bpf_map_get(f);
14428                         if (IS_ERR(map)) {
14429                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
14430                                         insn[0].imm);
14431                                 return PTR_ERR(map);
14432                         }
14433
14434                         err = check_map_prog_compatibility(env, map, env->prog);
14435                         if (err) {
14436                                 fdput(f);
14437                                 return err;
14438                         }
14439
14440                         aux = &env->insn_aux_data[i];
14441                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
14442                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
14443                                 addr = (unsigned long)map;
14444                         } else {
14445                                 u32 off = insn[1].imm;
14446
14447                                 if (off >= BPF_MAX_VAR_OFF) {
14448                                         verbose(env, "direct value offset of %u is not allowed\n", off);
14449                                         fdput(f);
14450                                         return -EINVAL;
14451                                 }
14452
14453                                 if (!map->ops->map_direct_value_addr) {
14454                                         verbose(env, "no direct value access support for this map type\n");
14455                                         fdput(f);
14456                                         return -EINVAL;
14457                                 }
14458
14459                                 err = map->ops->map_direct_value_addr(map, &addr, off);
14460                                 if (err) {
14461                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
14462                                                 map->value_size, off);
14463                                         fdput(f);
14464                                         return err;
14465                                 }
14466
14467                                 aux->map_off = off;
14468                                 addr += off;
14469                         }
14470
14471                         insn[0].imm = (u32)addr;
14472                         insn[1].imm = addr >> 32;
14473
14474                         /* check whether we recorded this map already */
14475                         for (j = 0; j < env->used_map_cnt; j++) {
14476                                 if (env->used_maps[j] == map) {
14477                                         aux->map_index = j;
14478                                         fdput(f);
14479                                         goto next_insn;
14480                                 }
14481                         }
14482
14483                         if (env->used_map_cnt >= MAX_USED_MAPS) {
14484                                 fdput(f);
14485                                 return -E2BIG;
14486                         }
14487
14488                         /* hold the map. If the program is rejected by verifier,
14489                          * the map will be released by release_maps() or it
14490                          * will be used by the valid program until it's unloaded
14491                          * and all maps are released in free_used_maps()
14492                          */
14493                         bpf_map_inc(map);
14494
14495                         aux->map_index = env->used_map_cnt;
14496                         env->used_maps[env->used_map_cnt++] = map;
14497
14498                         if (bpf_map_is_cgroup_storage(map) &&
14499                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
14500                                 verbose(env, "only one cgroup storage of each type is allowed\n");
14501                                 fdput(f);
14502                                 return -EBUSY;
14503                         }
14504
14505                         fdput(f);
14506 next_insn:
14507                         insn++;
14508                         i++;
14509                         continue;
14510                 }
14511
14512                 /* Basic sanity check before we invest more work here. */
14513                 if (!bpf_opcode_in_insntable(insn->code)) {
14514                         verbose(env, "unknown opcode %02x\n", insn->code);
14515                         return -EINVAL;
14516                 }
14517         }
14518
14519         /* now all pseudo BPF_LD_IMM64 instructions load valid
14520          * 'struct bpf_map *' into a register instead of user map_fd.
14521          * These pointers will be used later by verifier to validate map access.
14522          */
14523         return 0;
14524 }
14525
14526 /* drop refcnt of maps used by the rejected program */
14527 static void release_maps(struct bpf_verifier_env *env)
14528 {
14529         __bpf_free_used_maps(env->prog->aux, env->used_maps,
14530                              env->used_map_cnt);
14531 }
14532
14533 /* drop refcnt of maps used by the rejected program */
14534 static void release_btfs(struct bpf_verifier_env *env)
14535 {
14536         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
14537                              env->used_btf_cnt);
14538 }
14539
14540 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
14541 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
14542 {
14543         struct bpf_insn *insn = env->prog->insnsi;
14544         int insn_cnt = env->prog->len;
14545         int i;
14546
14547         for (i = 0; i < insn_cnt; i++, insn++) {
14548                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
14549                         continue;
14550                 if (insn->src_reg == BPF_PSEUDO_FUNC)
14551                         continue;
14552                 insn->src_reg = 0;
14553         }
14554 }
14555
14556 /* single env->prog->insni[off] instruction was replaced with the range
14557  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
14558  * [0, off) and [off, end) to new locations, so the patched range stays zero
14559  */
14560 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
14561                                  struct bpf_insn_aux_data *new_data,
14562                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
14563 {
14564         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
14565         struct bpf_insn *insn = new_prog->insnsi;
14566         u32 old_seen = old_data[off].seen;
14567         u32 prog_len;
14568         int i;
14569
14570         /* aux info at OFF always needs adjustment, no matter fast path
14571          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
14572          * original insn at old prog.
14573          */
14574         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
14575
14576         if (cnt == 1)
14577                 return;
14578         prog_len = new_prog->len;
14579
14580         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
14581         memcpy(new_data + off + cnt - 1, old_data + off,
14582                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
14583         for (i = off; i < off + cnt - 1; i++) {
14584                 /* Expand insni[off]'s seen count to the patched range. */
14585                 new_data[i].seen = old_seen;
14586                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
14587         }
14588         env->insn_aux_data = new_data;
14589         vfree(old_data);
14590 }
14591
14592 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
14593 {
14594         int i;
14595
14596         if (len == 1)
14597                 return;
14598         /* NOTE: fake 'exit' subprog should be updated as well. */
14599         for (i = 0; i <= env->subprog_cnt; i++) {
14600                 if (env->subprog_info[i].start <= off)
14601                         continue;
14602                 env->subprog_info[i].start += len - 1;
14603         }
14604 }
14605
14606 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
14607 {
14608         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
14609         int i, sz = prog->aux->size_poke_tab;
14610         struct bpf_jit_poke_descriptor *desc;
14611
14612         for (i = 0; i < sz; i++) {
14613                 desc = &tab[i];
14614                 if (desc->insn_idx <= off)
14615                         continue;
14616                 desc->insn_idx += len - 1;
14617         }
14618 }
14619
14620 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
14621                                             const struct bpf_insn *patch, u32 len)
14622 {
14623         struct bpf_prog *new_prog;
14624         struct bpf_insn_aux_data *new_data = NULL;
14625
14626         if (len > 1) {
14627                 new_data = vzalloc(array_size(env->prog->len + len - 1,
14628                                               sizeof(struct bpf_insn_aux_data)));
14629                 if (!new_data)
14630                         return NULL;
14631         }
14632
14633         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
14634         if (IS_ERR(new_prog)) {
14635                 if (PTR_ERR(new_prog) == -ERANGE)
14636                         verbose(env,
14637                                 "insn %d cannot be patched due to 16-bit range\n",
14638                                 env->insn_aux_data[off].orig_idx);
14639                 vfree(new_data);
14640                 return NULL;
14641         }
14642         adjust_insn_aux_data(env, new_data, new_prog, off, len);
14643         adjust_subprog_starts(env, off, len);
14644         adjust_poke_descs(new_prog, off, len);
14645         return new_prog;
14646 }
14647
14648 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
14649                                               u32 off, u32 cnt)
14650 {
14651         int i, j;
14652
14653         /* find first prog starting at or after off (first to remove) */
14654         for (i = 0; i < env->subprog_cnt; i++)
14655                 if (env->subprog_info[i].start >= off)
14656                         break;
14657         /* find first prog starting at or after off + cnt (first to stay) */
14658         for (j = i; j < env->subprog_cnt; j++)
14659                 if (env->subprog_info[j].start >= off + cnt)
14660                         break;
14661         /* if j doesn't start exactly at off + cnt, we are just removing
14662          * the front of previous prog
14663          */
14664         if (env->subprog_info[j].start != off + cnt)
14665                 j--;
14666
14667         if (j > i) {
14668                 struct bpf_prog_aux *aux = env->prog->aux;
14669                 int move;
14670
14671                 /* move fake 'exit' subprog as well */
14672                 move = env->subprog_cnt + 1 - j;
14673
14674                 memmove(env->subprog_info + i,
14675                         env->subprog_info + j,
14676                         sizeof(*env->subprog_info) * move);
14677                 env->subprog_cnt -= j - i;
14678
14679                 /* remove func_info */
14680                 if (aux->func_info) {
14681                         move = aux->func_info_cnt - j;
14682
14683                         memmove(aux->func_info + i,
14684                                 aux->func_info + j,
14685                                 sizeof(*aux->func_info) * move);
14686                         aux->func_info_cnt -= j - i;
14687                         /* func_info->insn_off is set after all code rewrites,
14688                          * in adjust_btf_func() - no need to adjust
14689                          */
14690                 }
14691         } else {
14692                 /* convert i from "first prog to remove" to "first to adjust" */
14693                 if (env->subprog_info[i].start == off)
14694                         i++;
14695         }
14696
14697         /* update fake 'exit' subprog as well */
14698         for (; i <= env->subprog_cnt; i++)
14699                 env->subprog_info[i].start -= cnt;
14700
14701         return 0;
14702 }
14703
14704 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
14705                                       u32 cnt)
14706 {
14707         struct bpf_prog *prog = env->prog;
14708         u32 i, l_off, l_cnt, nr_linfo;
14709         struct bpf_line_info *linfo;
14710
14711         nr_linfo = prog->aux->nr_linfo;
14712         if (!nr_linfo)
14713                 return 0;
14714
14715         linfo = prog->aux->linfo;
14716
14717         /* find first line info to remove, count lines to be removed */
14718         for (i = 0; i < nr_linfo; i++)
14719                 if (linfo[i].insn_off >= off)
14720                         break;
14721
14722         l_off = i;
14723         l_cnt = 0;
14724         for (; i < nr_linfo; i++)
14725                 if (linfo[i].insn_off < off + cnt)
14726                         l_cnt++;
14727                 else
14728                         break;
14729
14730         /* First live insn doesn't match first live linfo, it needs to "inherit"
14731          * last removed linfo.  prog is already modified, so prog->len == off
14732          * means no live instructions after (tail of the program was removed).
14733          */
14734         if (prog->len != off && l_cnt &&
14735             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
14736                 l_cnt--;
14737                 linfo[--i].insn_off = off + cnt;
14738         }
14739
14740         /* remove the line info which refer to the removed instructions */
14741         if (l_cnt) {
14742                 memmove(linfo + l_off, linfo + i,
14743                         sizeof(*linfo) * (nr_linfo - i));
14744
14745                 prog->aux->nr_linfo -= l_cnt;
14746                 nr_linfo = prog->aux->nr_linfo;
14747         }
14748
14749         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
14750         for (i = l_off; i < nr_linfo; i++)
14751                 linfo[i].insn_off -= cnt;
14752
14753         /* fix up all subprogs (incl. 'exit') which start >= off */
14754         for (i = 0; i <= env->subprog_cnt; i++)
14755                 if (env->subprog_info[i].linfo_idx > l_off) {
14756                         /* program may have started in the removed region but
14757                          * may not be fully removed
14758                          */
14759                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
14760                                 env->subprog_info[i].linfo_idx -= l_cnt;
14761                         else
14762                                 env->subprog_info[i].linfo_idx = l_off;
14763                 }
14764
14765         return 0;
14766 }
14767
14768 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
14769 {
14770         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14771         unsigned int orig_prog_len = env->prog->len;
14772         int err;
14773
14774         if (bpf_prog_is_dev_bound(env->prog->aux))
14775                 bpf_prog_offload_remove_insns(env, off, cnt);
14776
14777         err = bpf_remove_insns(env->prog, off, cnt);
14778         if (err)
14779                 return err;
14780
14781         err = adjust_subprog_starts_after_remove(env, off, cnt);
14782         if (err)
14783                 return err;
14784
14785         err = bpf_adj_linfo_after_remove(env, off, cnt);
14786         if (err)
14787                 return err;
14788
14789         memmove(aux_data + off, aux_data + off + cnt,
14790                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
14791
14792         return 0;
14793 }
14794
14795 /* The verifier does more data flow analysis than llvm and will not
14796  * explore branches that are dead at run time. Malicious programs can
14797  * have dead code too. Therefore replace all dead at-run-time code
14798  * with 'ja -1'.
14799  *
14800  * Just nops are not optimal, e.g. if they would sit at the end of the
14801  * program and through another bug we would manage to jump there, then
14802  * we'd execute beyond program memory otherwise. Returning exception
14803  * code also wouldn't work since we can have subprogs where the dead
14804  * code could be located.
14805  */
14806 static void sanitize_dead_code(struct bpf_verifier_env *env)
14807 {
14808         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14809         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
14810         struct bpf_insn *insn = env->prog->insnsi;
14811         const int insn_cnt = env->prog->len;
14812         int i;
14813
14814         for (i = 0; i < insn_cnt; i++) {
14815                 if (aux_data[i].seen)
14816                         continue;
14817                 memcpy(insn + i, &trap, sizeof(trap));
14818                 aux_data[i].zext_dst = false;
14819         }
14820 }
14821
14822 static bool insn_is_cond_jump(u8 code)
14823 {
14824         u8 op;
14825
14826         if (BPF_CLASS(code) == BPF_JMP32)
14827                 return true;
14828
14829         if (BPF_CLASS(code) != BPF_JMP)
14830                 return false;
14831
14832         op = BPF_OP(code);
14833         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
14834 }
14835
14836 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
14837 {
14838         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14839         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14840         struct bpf_insn *insn = env->prog->insnsi;
14841         const int insn_cnt = env->prog->len;
14842         int i;
14843
14844         for (i = 0; i < insn_cnt; i++, insn++) {
14845                 if (!insn_is_cond_jump(insn->code))
14846                         continue;
14847
14848                 if (!aux_data[i + 1].seen)
14849                         ja.off = insn->off;
14850                 else if (!aux_data[i + 1 + insn->off].seen)
14851                         ja.off = 0;
14852                 else
14853                         continue;
14854
14855                 if (bpf_prog_is_dev_bound(env->prog->aux))
14856                         bpf_prog_offload_replace_insn(env, i, &ja);
14857
14858                 memcpy(insn, &ja, sizeof(ja));
14859         }
14860 }
14861
14862 static int opt_remove_dead_code(struct bpf_verifier_env *env)
14863 {
14864         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14865         int insn_cnt = env->prog->len;
14866         int i, err;
14867
14868         for (i = 0; i < insn_cnt; i++) {
14869                 int j;
14870
14871                 j = 0;
14872                 while (i + j < insn_cnt && !aux_data[i + j].seen)
14873                         j++;
14874                 if (!j)
14875                         continue;
14876
14877                 err = verifier_remove_insns(env, i, j);
14878                 if (err)
14879                         return err;
14880                 insn_cnt = env->prog->len;
14881         }
14882
14883         return 0;
14884 }
14885
14886 static int opt_remove_nops(struct bpf_verifier_env *env)
14887 {
14888         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14889         struct bpf_insn *insn = env->prog->insnsi;
14890         int insn_cnt = env->prog->len;
14891         int i, err;
14892
14893         for (i = 0; i < insn_cnt; i++) {
14894                 if (memcmp(&insn[i], &ja, sizeof(ja)))
14895                         continue;
14896
14897                 err = verifier_remove_insns(env, i, 1);
14898                 if (err)
14899                         return err;
14900                 insn_cnt--;
14901                 i--;
14902         }
14903
14904         return 0;
14905 }
14906
14907 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
14908                                          const union bpf_attr *attr)
14909 {
14910         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
14911         struct bpf_insn_aux_data *aux = env->insn_aux_data;
14912         int i, patch_len, delta = 0, len = env->prog->len;
14913         struct bpf_insn *insns = env->prog->insnsi;
14914         struct bpf_prog *new_prog;
14915         bool rnd_hi32;
14916
14917         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
14918         zext_patch[1] = BPF_ZEXT_REG(0);
14919         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
14920         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
14921         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
14922         for (i = 0; i < len; i++) {
14923                 int adj_idx = i + delta;
14924                 struct bpf_insn insn;
14925                 int load_reg;
14926
14927                 insn = insns[adj_idx];
14928                 load_reg = insn_def_regno(&insn);
14929                 if (!aux[adj_idx].zext_dst) {
14930                         u8 code, class;
14931                         u32 imm_rnd;
14932
14933                         if (!rnd_hi32)
14934                                 continue;
14935
14936                         code = insn.code;
14937                         class = BPF_CLASS(code);
14938                         if (load_reg == -1)
14939                                 continue;
14940
14941                         /* NOTE: arg "reg" (the fourth one) is only used for
14942                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
14943                          *       here.
14944                          */
14945                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
14946                                 if (class == BPF_LD &&
14947                                     BPF_MODE(code) == BPF_IMM)
14948                                         i++;
14949                                 continue;
14950                         }
14951
14952                         /* ctx load could be transformed into wider load. */
14953                         if (class == BPF_LDX &&
14954                             aux[adj_idx].ptr_type == PTR_TO_CTX)
14955                                 continue;
14956
14957                         imm_rnd = get_random_u32();
14958                         rnd_hi32_patch[0] = insn;
14959                         rnd_hi32_patch[1].imm = imm_rnd;
14960                         rnd_hi32_patch[3].dst_reg = load_reg;
14961                         patch = rnd_hi32_patch;
14962                         patch_len = 4;
14963                         goto apply_patch_buffer;
14964                 }
14965
14966                 /* Add in an zero-extend instruction if a) the JIT has requested
14967                  * it or b) it's a CMPXCHG.
14968                  *
14969                  * The latter is because: BPF_CMPXCHG always loads a value into
14970                  * R0, therefore always zero-extends. However some archs'
14971                  * equivalent instruction only does this load when the
14972                  * comparison is successful. This detail of CMPXCHG is
14973                  * orthogonal to the general zero-extension behaviour of the
14974                  * CPU, so it's treated independently of bpf_jit_needs_zext.
14975                  */
14976                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
14977                         continue;
14978
14979                 /* Zero-extension is done by the caller. */
14980                 if (bpf_pseudo_kfunc_call(&insn))
14981                         continue;
14982
14983                 if (WARN_ON(load_reg == -1)) {
14984                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
14985                         return -EFAULT;
14986                 }
14987
14988                 zext_patch[0] = insn;
14989                 zext_patch[1].dst_reg = load_reg;
14990                 zext_patch[1].src_reg = load_reg;
14991                 patch = zext_patch;
14992                 patch_len = 2;
14993 apply_patch_buffer:
14994                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
14995                 if (!new_prog)
14996                         return -ENOMEM;
14997                 env->prog = new_prog;
14998                 insns = new_prog->insnsi;
14999                 aux = env->insn_aux_data;
15000                 delta += patch_len - 1;
15001         }
15002
15003         return 0;
15004 }
15005
15006 /* convert load instructions that access fields of a context type into a
15007  * sequence of instructions that access fields of the underlying structure:
15008  *     struct __sk_buff    -> struct sk_buff
15009  *     struct bpf_sock_ops -> struct sock
15010  */
15011 static int convert_ctx_accesses(struct bpf_verifier_env *env)
15012 {
15013         const struct bpf_verifier_ops *ops = env->ops;
15014         int i, cnt, size, ctx_field_size, delta = 0;
15015         const int insn_cnt = env->prog->len;
15016         struct bpf_insn insn_buf[16], *insn;
15017         u32 target_size, size_default, off;
15018         struct bpf_prog *new_prog;
15019         enum bpf_access_type type;
15020         bool is_narrower_load;
15021
15022         if (ops->gen_prologue || env->seen_direct_write) {
15023                 if (!ops->gen_prologue) {
15024                         verbose(env, "bpf verifier is misconfigured\n");
15025                         return -EINVAL;
15026                 }
15027                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
15028                                         env->prog);
15029                 if (cnt >= ARRAY_SIZE(insn_buf)) {
15030                         verbose(env, "bpf verifier is misconfigured\n");
15031                         return -EINVAL;
15032                 } else if (cnt) {
15033                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
15034                         if (!new_prog)
15035                                 return -ENOMEM;
15036
15037                         env->prog = new_prog;
15038                         delta += cnt - 1;
15039                 }
15040         }
15041
15042         if (bpf_prog_is_dev_bound(env->prog->aux))
15043                 return 0;
15044
15045         insn = env->prog->insnsi + delta;
15046
15047         for (i = 0; i < insn_cnt; i++, insn++) {
15048                 bpf_convert_ctx_access_t convert_ctx_access;
15049                 bool ctx_access;
15050
15051                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
15052                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
15053                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
15054                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
15055                         type = BPF_READ;
15056                         ctx_access = true;
15057                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
15058                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
15059                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
15060                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
15061                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
15062                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
15063                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
15064                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
15065                         type = BPF_WRITE;
15066                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
15067                 } else {
15068                         continue;
15069                 }
15070
15071                 if (type == BPF_WRITE &&
15072                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
15073                         struct bpf_insn patch[] = {
15074                                 *insn,
15075                                 BPF_ST_NOSPEC(),
15076                         };
15077
15078                         cnt = ARRAY_SIZE(patch);
15079                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
15080                         if (!new_prog)
15081                                 return -ENOMEM;
15082
15083                         delta    += cnt - 1;
15084                         env->prog = new_prog;
15085                         insn      = new_prog->insnsi + i + delta;
15086                         continue;
15087                 }
15088
15089                 if (!ctx_access)
15090                         continue;
15091
15092                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
15093                 case PTR_TO_CTX:
15094                         if (!ops->convert_ctx_access)
15095                                 continue;
15096                         convert_ctx_access = ops->convert_ctx_access;
15097                         break;
15098                 case PTR_TO_SOCKET:
15099                 case PTR_TO_SOCK_COMMON:
15100                         convert_ctx_access = bpf_sock_convert_ctx_access;
15101                         break;
15102                 case PTR_TO_TCP_SOCK:
15103                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
15104                         break;
15105                 case PTR_TO_XDP_SOCK:
15106                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
15107                         break;
15108                 case PTR_TO_BTF_ID:
15109                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
15110                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
15111                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
15112                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
15113                  * any faults for loads into such types. BPF_WRITE is disallowed
15114                  * for this case.
15115                  */
15116                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
15117                         if (type == BPF_READ) {
15118                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
15119                                         BPF_SIZE((insn)->code);
15120                                 env->prog->aux->num_exentries++;
15121                         }
15122                         continue;
15123                 default:
15124                         continue;
15125                 }
15126
15127                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
15128                 size = BPF_LDST_BYTES(insn);
15129
15130                 /* If the read access is a narrower load of the field,
15131                  * convert to a 4/8-byte load, to minimum program type specific
15132                  * convert_ctx_access changes. If conversion is successful,
15133                  * we will apply proper mask to the result.
15134                  */
15135                 is_narrower_load = size < ctx_field_size;
15136                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
15137                 off = insn->off;
15138                 if (is_narrower_load) {
15139                         u8 size_code;
15140
15141                         if (type == BPF_WRITE) {
15142                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
15143                                 return -EINVAL;
15144                         }
15145
15146                         size_code = BPF_H;
15147                         if (ctx_field_size == 4)
15148                                 size_code = BPF_W;
15149                         else if (ctx_field_size == 8)
15150                                 size_code = BPF_DW;
15151
15152                         insn->off = off & ~(size_default - 1);
15153                         insn->code = BPF_LDX | BPF_MEM | size_code;
15154                 }
15155
15156                 target_size = 0;
15157                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
15158                                          &target_size);
15159                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
15160                     (ctx_field_size && !target_size)) {
15161                         verbose(env, "bpf verifier is misconfigured\n");
15162                         return -EINVAL;
15163                 }
15164
15165                 if (is_narrower_load && size < target_size) {
15166                         u8 shift = bpf_ctx_narrow_access_offset(
15167                                 off, size, size_default) * 8;
15168                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
15169                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
15170                                 return -EINVAL;
15171                         }
15172                         if (ctx_field_size <= 4) {
15173                                 if (shift)
15174                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
15175                                                                         insn->dst_reg,
15176                                                                         shift);
15177                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
15178                                                                 (1 << size * 8) - 1);
15179                         } else {
15180                                 if (shift)
15181                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
15182                                                                         insn->dst_reg,
15183                                                                         shift);
15184                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
15185                                                                 (1ULL << size * 8) - 1);
15186                         }
15187                 }
15188
15189                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15190                 if (!new_prog)
15191                         return -ENOMEM;
15192
15193                 delta += cnt - 1;
15194
15195                 /* keep walking new program and skip insns we just inserted */
15196                 env->prog = new_prog;
15197                 insn      = new_prog->insnsi + i + delta;
15198         }
15199
15200         return 0;
15201 }
15202
15203 static int jit_subprogs(struct bpf_verifier_env *env)
15204 {
15205         struct bpf_prog *prog = env->prog, **func, *tmp;
15206         int i, j, subprog_start, subprog_end = 0, len, subprog;
15207         struct bpf_map *map_ptr;
15208         struct bpf_insn *insn;
15209         void *old_bpf_func;
15210         int err, num_exentries;
15211
15212         if (env->subprog_cnt <= 1)
15213                 return 0;
15214
15215         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15216                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
15217                         continue;
15218
15219                 /* Upon error here we cannot fall back to interpreter but
15220                  * need a hard reject of the program. Thus -EFAULT is
15221                  * propagated in any case.
15222                  */
15223                 subprog = find_subprog(env, i + insn->imm + 1);
15224                 if (subprog < 0) {
15225                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
15226                                   i + insn->imm + 1);
15227                         return -EFAULT;
15228                 }
15229                 /* temporarily remember subprog id inside insn instead of
15230                  * aux_data, since next loop will split up all insns into funcs
15231                  */
15232                 insn->off = subprog;
15233                 /* remember original imm in case JIT fails and fallback
15234                  * to interpreter will be needed
15235                  */
15236                 env->insn_aux_data[i].call_imm = insn->imm;
15237                 /* point imm to __bpf_call_base+1 from JITs point of view */
15238                 insn->imm = 1;
15239                 if (bpf_pseudo_func(insn))
15240                         /* jit (e.g. x86_64) may emit fewer instructions
15241                          * if it learns a u32 imm is the same as a u64 imm.
15242                          * Force a non zero here.
15243                          */
15244                         insn[1].imm = 1;
15245         }
15246
15247         err = bpf_prog_alloc_jited_linfo(prog);
15248         if (err)
15249                 goto out_undo_insn;
15250
15251         err = -ENOMEM;
15252         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
15253         if (!func)
15254                 goto out_undo_insn;
15255
15256         for (i = 0; i < env->subprog_cnt; i++) {
15257                 subprog_start = subprog_end;
15258                 subprog_end = env->subprog_info[i + 1].start;
15259
15260                 len = subprog_end - subprog_start;
15261                 /* bpf_prog_run() doesn't call subprogs directly,
15262                  * hence main prog stats include the runtime of subprogs.
15263                  * subprogs don't have IDs and not reachable via prog_get_next_id
15264                  * func[i]->stats will never be accessed and stays NULL
15265                  */
15266                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
15267                 if (!func[i])
15268                         goto out_free;
15269                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
15270                        len * sizeof(struct bpf_insn));
15271                 func[i]->type = prog->type;
15272                 func[i]->len = len;
15273                 if (bpf_prog_calc_tag(func[i]))
15274                         goto out_free;
15275                 func[i]->is_func = 1;
15276                 func[i]->aux->func_idx = i;
15277                 /* Below members will be freed only at prog->aux */
15278                 func[i]->aux->btf = prog->aux->btf;
15279                 func[i]->aux->func_info = prog->aux->func_info;
15280                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
15281                 func[i]->aux->poke_tab = prog->aux->poke_tab;
15282                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
15283
15284                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
15285                         struct bpf_jit_poke_descriptor *poke;
15286
15287                         poke = &prog->aux->poke_tab[j];
15288                         if (poke->insn_idx < subprog_end &&
15289                             poke->insn_idx >= subprog_start)
15290                                 poke->aux = func[i]->aux;
15291                 }
15292
15293                 func[i]->aux->name[0] = 'F';
15294                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
15295                 func[i]->jit_requested = 1;
15296                 func[i]->blinding_requested = prog->blinding_requested;
15297                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
15298                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
15299                 func[i]->aux->linfo = prog->aux->linfo;
15300                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
15301                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
15302                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
15303                 num_exentries = 0;
15304                 insn = func[i]->insnsi;
15305                 for (j = 0; j < func[i]->len; j++, insn++) {
15306                         if (BPF_CLASS(insn->code) == BPF_LDX &&
15307                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
15308                                 num_exentries++;
15309                 }
15310                 func[i]->aux->num_exentries = num_exentries;
15311                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
15312                 func[i] = bpf_int_jit_compile(func[i]);
15313                 if (!func[i]->jited) {
15314                         err = -ENOTSUPP;
15315                         goto out_free;
15316                 }
15317                 cond_resched();
15318         }
15319
15320         /* at this point all bpf functions were successfully JITed
15321          * now populate all bpf_calls with correct addresses and
15322          * run last pass of JIT
15323          */
15324         for (i = 0; i < env->subprog_cnt; i++) {
15325                 insn = func[i]->insnsi;
15326                 for (j = 0; j < func[i]->len; j++, insn++) {
15327                         if (bpf_pseudo_func(insn)) {
15328                                 subprog = insn->off;
15329                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
15330                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
15331                                 continue;
15332                         }
15333                         if (!bpf_pseudo_call(insn))
15334                                 continue;
15335                         subprog = insn->off;
15336                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
15337                 }
15338
15339                 /* we use the aux data to keep a list of the start addresses
15340                  * of the JITed images for each function in the program
15341                  *
15342                  * for some architectures, such as powerpc64, the imm field
15343                  * might not be large enough to hold the offset of the start
15344                  * address of the callee's JITed image from __bpf_call_base
15345                  *
15346                  * in such cases, we can lookup the start address of a callee
15347                  * by using its subprog id, available from the off field of
15348                  * the call instruction, as an index for this list
15349                  */
15350                 func[i]->aux->func = func;
15351                 func[i]->aux->func_cnt = env->subprog_cnt;
15352         }
15353         for (i = 0; i < env->subprog_cnt; i++) {
15354                 old_bpf_func = func[i]->bpf_func;
15355                 tmp = bpf_int_jit_compile(func[i]);
15356                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
15357                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
15358                         err = -ENOTSUPP;
15359                         goto out_free;
15360                 }
15361                 cond_resched();
15362         }
15363
15364         /* finally lock prog and jit images for all functions and
15365          * populate kallsysm
15366          */
15367         for (i = 0; i < env->subprog_cnt; i++) {
15368                 bpf_prog_lock_ro(func[i]);
15369                 bpf_prog_kallsyms_add(func[i]);
15370         }
15371
15372         /* Last step: make now unused interpreter insns from main
15373          * prog consistent for later dump requests, so they can
15374          * later look the same as if they were interpreted only.
15375          */
15376         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15377                 if (bpf_pseudo_func(insn)) {
15378                         insn[0].imm = env->insn_aux_data[i].call_imm;
15379                         insn[1].imm = insn->off;
15380                         insn->off = 0;
15381                         continue;
15382                 }
15383                 if (!bpf_pseudo_call(insn))
15384                         continue;
15385                 insn->off = env->insn_aux_data[i].call_imm;
15386                 subprog = find_subprog(env, i + insn->off + 1);
15387                 insn->imm = subprog;
15388         }
15389
15390         prog->jited = 1;
15391         prog->bpf_func = func[0]->bpf_func;
15392         prog->jited_len = func[0]->jited_len;
15393         prog->aux->func = func;
15394         prog->aux->func_cnt = env->subprog_cnt;
15395         bpf_prog_jit_attempt_done(prog);
15396         return 0;
15397 out_free:
15398         /* We failed JIT'ing, so at this point we need to unregister poke
15399          * descriptors from subprogs, so that kernel is not attempting to
15400          * patch it anymore as we're freeing the subprog JIT memory.
15401          */
15402         for (i = 0; i < prog->aux->size_poke_tab; i++) {
15403                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
15404                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
15405         }
15406         /* At this point we're guaranteed that poke descriptors are not
15407          * live anymore. We can just unlink its descriptor table as it's
15408          * released with the main prog.
15409          */
15410         for (i = 0; i < env->subprog_cnt; i++) {
15411                 if (!func[i])
15412                         continue;
15413                 func[i]->aux->poke_tab = NULL;
15414                 bpf_jit_free(func[i]);
15415         }
15416         kfree(func);
15417 out_undo_insn:
15418         /* cleanup main prog to be interpreted */
15419         prog->jit_requested = 0;
15420         prog->blinding_requested = 0;
15421         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15422                 if (!bpf_pseudo_call(insn))
15423                         continue;
15424                 insn->off = 0;
15425                 insn->imm = env->insn_aux_data[i].call_imm;
15426         }
15427         bpf_prog_jit_attempt_done(prog);
15428         return err;
15429 }
15430
15431 static int fixup_call_args(struct bpf_verifier_env *env)
15432 {
15433 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15434         struct bpf_prog *prog = env->prog;
15435         struct bpf_insn *insn = prog->insnsi;
15436         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
15437         int i, depth;
15438 #endif
15439         int err = 0;
15440
15441         if (env->prog->jit_requested &&
15442             !bpf_prog_is_dev_bound(env->prog->aux)) {
15443                 err = jit_subprogs(env);
15444                 if (err == 0)
15445                         return 0;
15446                 if (err == -EFAULT)
15447                         return err;
15448         }
15449 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15450         if (has_kfunc_call) {
15451                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
15452                 return -EINVAL;
15453         }
15454         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
15455                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
15456                  * have to be rejected, since interpreter doesn't support them yet.
15457                  */
15458                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
15459                 return -EINVAL;
15460         }
15461         for (i = 0; i < prog->len; i++, insn++) {
15462                 if (bpf_pseudo_func(insn)) {
15463                         /* When JIT fails the progs with callback calls
15464                          * have to be rejected, since interpreter doesn't support them yet.
15465                          */
15466                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
15467                         return -EINVAL;
15468                 }
15469
15470                 if (!bpf_pseudo_call(insn))
15471                         continue;
15472                 depth = get_callee_stack_depth(env, insn, i);
15473                 if (depth < 0)
15474                         return depth;
15475                 bpf_patch_call_args(insn, depth);
15476         }
15477         err = 0;
15478 #endif
15479         return err;
15480 }
15481
15482 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15483                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
15484 {
15485         const struct bpf_kfunc_desc *desc;
15486
15487         if (!insn->imm) {
15488                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
15489                 return -EINVAL;
15490         }
15491
15492         /* insn->imm has the btf func_id. Replace it with
15493          * an address (relative to __bpf_call_base).
15494          */
15495         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15496         if (!desc) {
15497                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
15498                         insn->imm);
15499                 return -EFAULT;
15500         }
15501
15502         *cnt = 0;
15503         insn->imm = desc->imm;
15504         if (insn->off)
15505                 return 0;
15506         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
15507                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15508                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15509                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
15510
15511                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
15512                 insn_buf[1] = addr[0];
15513                 insn_buf[2] = addr[1];
15514                 insn_buf[3] = *insn;
15515                 *cnt = 4;
15516         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
15517                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15518                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15519
15520                 insn_buf[0] = addr[0];
15521                 insn_buf[1] = addr[1];
15522                 insn_buf[2] = *insn;
15523                 *cnt = 3;
15524         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
15525                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
15526                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
15527                 *cnt = 1;
15528         }
15529         return 0;
15530 }
15531
15532 /* Do various post-verification rewrites in a single program pass.
15533  * These rewrites simplify JIT and interpreter implementations.
15534  */
15535 static int do_misc_fixups(struct bpf_verifier_env *env)
15536 {
15537         struct bpf_prog *prog = env->prog;
15538         enum bpf_attach_type eatype = prog->expected_attach_type;
15539         enum bpf_prog_type prog_type = resolve_prog_type(prog);
15540         struct bpf_insn *insn = prog->insnsi;
15541         const struct bpf_func_proto *fn;
15542         const int insn_cnt = prog->len;
15543         const struct bpf_map_ops *ops;
15544         struct bpf_insn_aux_data *aux;
15545         struct bpf_insn insn_buf[16];
15546         struct bpf_prog *new_prog;
15547         struct bpf_map *map_ptr;
15548         int i, ret, cnt, delta = 0;
15549
15550         for (i = 0; i < insn_cnt; i++, insn++) {
15551                 /* Make divide-by-zero exceptions impossible. */
15552                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
15553                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
15554                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
15555                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
15556                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
15557                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
15558                         struct bpf_insn *patchlet;
15559                         struct bpf_insn chk_and_div[] = {
15560                                 /* [R,W]x div 0 -> 0 */
15561                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15562                                              BPF_JNE | BPF_K, insn->src_reg,
15563                                              0, 2, 0),
15564                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
15565                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15566                                 *insn,
15567                         };
15568                         struct bpf_insn chk_and_mod[] = {
15569                                 /* [R,W]x mod 0 -> [R,W]x */
15570                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15571                                              BPF_JEQ | BPF_K, insn->src_reg,
15572                                              0, 1 + (is64 ? 0 : 1), 0),
15573                                 *insn,
15574                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15575                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
15576                         };
15577
15578                         patchlet = isdiv ? chk_and_div : chk_and_mod;
15579                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
15580                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
15581
15582                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
15583                         if (!new_prog)
15584                                 return -ENOMEM;
15585
15586                         delta    += cnt - 1;
15587                         env->prog = prog = new_prog;
15588                         insn      = new_prog->insnsi + i + delta;
15589                         continue;
15590                 }
15591
15592                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
15593                 if (BPF_CLASS(insn->code) == BPF_LD &&
15594                     (BPF_MODE(insn->code) == BPF_ABS ||
15595                      BPF_MODE(insn->code) == BPF_IND)) {
15596                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
15597                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15598                                 verbose(env, "bpf verifier is misconfigured\n");
15599                                 return -EINVAL;
15600                         }
15601
15602                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15603                         if (!new_prog)
15604                                 return -ENOMEM;
15605
15606                         delta    += cnt - 1;
15607                         env->prog = prog = new_prog;
15608                         insn      = new_prog->insnsi + i + delta;
15609                         continue;
15610                 }
15611
15612                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
15613                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
15614                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
15615                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
15616                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
15617                         struct bpf_insn *patch = &insn_buf[0];
15618                         bool issrc, isneg, isimm;
15619                         u32 off_reg;
15620
15621                         aux = &env->insn_aux_data[i + delta];
15622                         if (!aux->alu_state ||
15623                             aux->alu_state == BPF_ALU_NON_POINTER)
15624                                 continue;
15625
15626                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
15627                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
15628                                 BPF_ALU_SANITIZE_SRC;
15629                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
15630
15631                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
15632                         if (isimm) {
15633                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15634                         } else {
15635                                 if (isneg)
15636                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15637                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15638                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
15639                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
15640                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
15641                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
15642                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
15643                         }
15644                         if (!issrc)
15645                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
15646                         insn->src_reg = BPF_REG_AX;
15647                         if (isneg)
15648                                 insn->code = insn->code == code_add ?
15649                                              code_sub : code_add;
15650                         *patch++ = *insn;
15651                         if (issrc && isneg && !isimm)
15652                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15653                         cnt = patch - insn_buf;
15654
15655                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15656                         if (!new_prog)
15657                                 return -ENOMEM;
15658
15659                         delta    += cnt - 1;
15660                         env->prog = prog = new_prog;
15661                         insn      = new_prog->insnsi + i + delta;
15662                         continue;
15663                 }
15664
15665                 if (insn->code != (BPF_JMP | BPF_CALL))
15666                         continue;
15667                 if (insn->src_reg == BPF_PSEUDO_CALL)
15668                         continue;
15669                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15670                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
15671                         if (ret)
15672                                 return ret;
15673                         if (cnt == 0)
15674                                 continue;
15675
15676                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15677                         if (!new_prog)
15678                                 return -ENOMEM;
15679
15680                         delta    += cnt - 1;
15681                         env->prog = prog = new_prog;
15682                         insn      = new_prog->insnsi + i + delta;
15683                         continue;
15684                 }
15685
15686                 if (insn->imm == BPF_FUNC_get_route_realm)
15687                         prog->dst_needed = 1;
15688                 if (insn->imm == BPF_FUNC_get_prandom_u32)
15689                         bpf_user_rnd_init_once();
15690                 if (insn->imm == BPF_FUNC_override_return)
15691                         prog->kprobe_override = 1;
15692                 if (insn->imm == BPF_FUNC_tail_call) {
15693                         /* If we tail call into other programs, we
15694                          * cannot make any assumptions since they can
15695                          * be replaced dynamically during runtime in
15696                          * the program array.
15697                          */
15698                         prog->cb_access = 1;
15699                         if (!allow_tail_call_in_subprogs(env))
15700                                 prog->aux->stack_depth = MAX_BPF_STACK;
15701                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
15702
15703                         /* mark bpf_tail_call as different opcode to avoid
15704                          * conditional branch in the interpreter for every normal
15705                          * call and to prevent accidental JITing by JIT compiler
15706                          * that doesn't support bpf_tail_call yet
15707                          */
15708                         insn->imm = 0;
15709                         insn->code = BPF_JMP | BPF_TAIL_CALL;
15710
15711                         aux = &env->insn_aux_data[i + delta];
15712                         if (env->bpf_capable && !prog->blinding_requested &&
15713                             prog->jit_requested &&
15714                             !bpf_map_key_poisoned(aux) &&
15715                             !bpf_map_ptr_poisoned(aux) &&
15716                             !bpf_map_ptr_unpriv(aux)) {
15717                                 struct bpf_jit_poke_descriptor desc = {
15718                                         .reason = BPF_POKE_REASON_TAIL_CALL,
15719                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
15720                                         .tail_call.key = bpf_map_key_immediate(aux),
15721                                         .insn_idx = i + delta,
15722                                 };
15723
15724                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
15725                                 if (ret < 0) {
15726                                         verbose(env, "adding tail call poke descriptor failed\n");
15727                                         return ret;
15728                                 }
15729
15730                                 insn->imm = ret + 1;
15731                                 continue;
15732                         }
15733
15734                         if (!bpf_map_ptr_unpriv(aux))
15735                                 continue;
15736
15737                         /* instead of changing every JIT dealing with tail_call
15738                          * emit two extra insns:
15739                          * if (index >= max_entries) goto out;
15740                          * index &= array->index_mask;
15741                          * to avoid out-of-bounds cpu speculation
15742                          */
15743                         if (bpf_map_ptr_poisoned(aux)) {
15744                                 verbose(env, "tail_call abusing map_ptr\n");
15745                                 return -EINVAL;
15746                         }
15747
15748                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15749                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
15750                                                   map_ptr->max_entries, 2);
15751                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
15752                                                     container_of(map_ptr,
15753                                                                  struct bpf_array,
15754                                                                  map)->index_mask);
15755                         insn_buf[2] = *insn;
15756                         cnt = 3;
15757                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15758                         if (!new_prog)
15759                                 return -ENOMEM;
15760
15761                         delta    += cnt - 1;
15762                         env->prog = prog = new_prog;
15763                         insn      = new_prog->insnsi + i + delta;
15764                         continue;
15765                 }
15766
15767                 if (insn->imm == BPF_FUNC_timer_set_callback) {
15768                         /* The verifier will process callback_fn as many times as necessary
15769                          * with different maps and the register states prepared by
15770                          * set_timer_callback_state will be accurate.
15771                          *
15772                          * The following use case is valid:
15773                          *   map1 is shared by prog1, prog2, prog3.
15774                          *   prog1 calls bpf_timer_init for some map1 elements
15775                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
15776                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
15777                          *   prog3 calls bpf_timer_start for some map1 elements.
15778                          *     Those that were not both bpf_timer_init-ed and
15779                          *     bpf_timer_set_callback-ed will return -EINVAL.
15780                          */
15781                         struct bpf_insn ld_addrs[2] = {
15782                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
15783                         };
15784
15785                         insn_buf[0] = ld_addrs[0];
15786                         insn_buf[1] = ld_addrs[1];
15787                         insn_buf[2] = *insn;
15788                         cnt = 3;
15789
15790                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15791                         if (!new_prog)
15792                                 return -ENOMEM;
15793
15794                         delta    += cnt - 1;
15795                         env->prog = prog = new_prog;
15796                         insn      = new_prog->insnsi + i + delta;
15797                         goto patch_call_imm;
15798                 }
15799
15800                 if (is_storage_get_function(insn->imm)) {
15801                         if (!env->prog->aux->sleepable ||
15802                             env->insn_aux_data[i + delta].storage_get_func_atomic)
15803                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
15804                         else
15805                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
15806                         insn_buf[1] = *insn;
15807                         cnt = 2;
15808
15809                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15810                         if (!new_prog)
15811                                 return -ENOMEM;
15812
15813                         delta += cnt - 1;
15814                         env->prog = prog = new_prog;
15815                         insn = new_prog->insnsi + i + delta;
15816                         goto patch_call_imm;
15817                 }
15818
15819                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
15820                  * and other inlining handlers are currently limited to 64 bit
15821                  * only.
15822                  */
15823                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
15824                     (insn->imm == BPF_FUNC_map_lookup_elem ||
15825                      insn->imm == BPF_FUNC_map_update_elem ||
15826                      insn->imm == BPF_FUNC_map_delete_elem ||
15827                      insn->imm == BPF_FUNC_map_push_elem   ||
15828                      insn->imm == BPF_FUNC_map_pop_elem    ||
15829                      insn->imm == BPF_FUNC_map_peek_elem   ||
15830                      insn->imm == BPF_FUNC_redirect_map    ||
15831                      insn->imm == BPF_FUNC_for_each_map_elem ||
15832                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
15833                         aux = &env->insn_aux_data[i + delta];
15834                         if (bpf_map_ptr_poisoned(aux))
15835                                 goto patch_call_imm;
15836
15837                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15838                         ops = map_ptr->ops;
15839                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
15840                             ops->map_gen_lookup) {
15841                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
15842                                 if (cnt == -EOPNOTSUPP)
15843                                         goto patch_map_ops_generic;
15844                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15845                                         verbose(env, "bpf verifier is misconfigured\n");
15846                                         return -EINVAL;
15847                                 }
15848
15849                                 new_prog = bpf_patch_insn_data(env, i + delta,
15850                                                                insn_buf, cnt);
15851                                 if (!new_prog)
15852                                         return -ENOMEM;
15853
15854                                 delta    += cnt - 1;
15855                                 env->prog = prog = new_prog;
15856                                 insn      = new_prog->insnsi + i + delta;
15857                                 continue;
15858                         }
15859
15860                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
15861                                      (void *(*)(struct bpf_map *map, void *key))NULL));
15862                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
15863                                      (int (*)(struct bpf_map *map, void *key))NULL));
15864                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
15865                                      (int (*)(struct bpf_map *map, void *key, void *value,
15866                                               u64 flags))NULL));
15867                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
15868                                      (int (*)(struct bpf_map *map, void *value,
15869                                               u64 flags))NULL));
15870                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
15871                                      (int (*)(struct bpf_map *map, void *value))NULL));
15872                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
15873                                      (int (*)(struct bpf_map *map, void *value))NULL));
15874                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
15875                                      (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
15876                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
15877                                      (int (*)(struct bpf_map *map,
15878                                               bpf_callback_t callback_fn,
15879                                               void *callback_ctx,
15880                                               u64 flags))NULL));
15881                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
15882                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
15883
15884 patch_map_ops_generic:
15885                         switch (insn->imm) {
15886                         case BPF_FUNC_map_lookup_elem:
15887                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
15888                                 continue;
15889                         case BPF_FUNC_map_update_elem:
15890                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
15891                                 continue;
15892                         case BPF_FUNC_map_delete_elem:
15893                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
15894                                 continue;
15895                         case BPF_FUNC_map_push_elem:
15896                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
15897                                 continue;
15898                         case BPF_FUNC_map_pop_elem:
15899                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
15900                                 continue;
15901                         case BPF_FUNC_map_peek_elem:
15902                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
15903                                 continue;
15904                         case BPF_FUNC_redirect_map:
15905                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
15906                                 continue;
15907                         case BPF_FUNC_for_each_map_elem:
15908                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
15909                                 continue;
15910                         case BPF_FUNC_map_lookup_percpu_elem:
15911                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
15912                                 continue;
15913                         }
15914
15915                         goto patch_call_imm;
15916                 }
15917
15918                 /* Implement bpf_jiffies64 inline. */
15919                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
15920                     insn->imm == BPF_FUNC_jiffies64) {
15921                         struct bpf_insn ld_jiffies_addr[2] = {
15922                                 BPF_LD_IMM64(BPF_REG_0,
15923                                              (unsigned long)&jiffies),
15924                         };
15925
15926                         insn_buf[0] = ld_jiffies_addr[0];
15927                         insn_buf[1] = ld_jiffies_addr[1];
15928                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
15929                                                   BPF_REG_0, 0);
15930                         cnt = 3;
15931
15932                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
15933                                                        cnt);
15934                         if (!new_prog)
15935                                 return -ENOMEM;
15936
15937                         delta    += cnt - 1;
15938                         env->prog = prog = new_prog;
15939                         insn      = new_prog->insnsi + i + delta;
15940                         continue;
15941                 }
15942
15943                 /* Implement bpf_get_func_arg inline. */
15944                 if (prog_type == BPF_PROG_TYPE_TRACING &&
15945                     insn->imm == BPF_FUNC_get_func_arg) {
15946                         /* Load nr_args from ctx - 8 */
15947                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15948                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
15949                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
15950                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
15951                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
15952                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15953                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
15954                         insn_buf[7] = BPF_JMP_A(1);
15955                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
15956                         cnt = 9;
15957
15958                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15959                         if (!new_prog)
15960                                 return -ENOMEM;
15961
15962                         delta    += cnt - 1;
15963                         env->prog = prog = new_prog;
15964                         insn      = new_prog->insnsi + i + delta;
15965                         continue;
15966                 }
15967
15968                 /* Implement bpf_get_func_ret inline. */
15969                 if (prog_type == BPF_PROG_TYPE_TRACING &&
15970                     insn->imm == BPF_FUNC_get_func_ret) {
15971                         if (eatype == BPF_TRACE_FEXIT ||
15972                             eatype == BPF_MODIFY_RETURN) {
15973                                 /* Load nr_args from ctx - 8 */
15974                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15975                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
15976                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
15977                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15978                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
15979                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
15980                                 cnt = 6;
15981                         } else {
15982                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
15983                                 cnt = 1;
15984                         }
15985
15986                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15987                         if (!new_prog)
15988                                 return -ENOMEM;
15989
15990                         delta    += cnt - 1;
15991                         env->prog = prog = new_prog;
15992                         insn      = new_prog->insnsi + i + delta;
15993                         continue;
15994                 }
15995
15996                 /* Implement get_func_arg_cnt inline. */
15997                 if (prog_type == BPF_PROG_TYPE_TRACING &&
15998                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
15999                         /* Load nr_args from ctx - 8 */
16000                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
16001
16002                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16003                         if (!new_prog)
16004                                 return -ENOMEM;
16005
16006                         env->prog = prog = new_prog;
16007                         insn      = new_prog->insnsi + i + delta;
16008                         continue;
16009                 }
16010
16011                 /* Implement bpf_get_func_ip inline. */
16012                 if (prog_type == BPF_PROG_TYPE_TRACING &&
16013                     insn->imm == BPF_FUNC_get_func_ip) {
16014                         /* Load IP address from ctx - 16 */
16015                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
16016
16017                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16018                         if (!new_prog)
16019                                 return -ENOMEM;
16020
16021                         env->prog = prog = new_prog;
16022                         insn      = new_prog->insnsi + i + delta;
16023                         continue;
16024                 }
16025
16026 patch_call_imm:
16027                 fn = env->ops->get_func_proto(insn->imm, env->prog);
16028                 /* all functions that have prototype and verifier allowed
16029                  * programs to call them, must be real in-kernel functions
16030                  */
16031                 if (!fn->func) {
16032                         verbose(env,
16033                                 "kernel subsystem misconfigured func %s#%d\n",
16034                                 func_id_name(insn->imm), insn->imm);
16035                         return -EFAULT;
16036                 }
16037                 insn->imm = fn->func - __bpf_call_base;
16038         }
16039
16040         /* Since poke tab is now finalized, publish aux to tracker. */
16041         for (i = 0; i < prog->aux->size_poke_tab; i++) {
16042                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
16043                 if (!map_ptr->ops->map_poke_track ||
16044                     !map_ptr->ops->map_poke_untrack ||
16045                     !map_ptr->ops->map_poke_run) {
16046                         verbose(env, "bpf verifier is misconfigured\n");
16047                         return -EINVAL;
16048                 }
16049
16050                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
16051                 if (ret < 0) {
16052                         verbose(env, "tracking tail call prog failed\n");
16053                         return ret;
16054                 }
16055         }
16056
16057         sort_kfunc_descs_by_imm(env->prog);
16058
16059         return 0;
16060 }
16061
16062 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
16063                                         int position,
16064                                         s32 stack_base,
16065                                         u32 callback_subprogno,
16066                                         u32 *cnt)
16067 {
16068         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
16069         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
16070         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
16071         int reg_loop_max = BPF_REG_6;
16072         int reg_loop_cnt = BPF_REG_7;
16073         int reg_loop_ctx = BPF_REG_8;
16074
16075         struct bpf_prog *new_prog;
16076         u32 callback_start;
16077         u32 call_insn_offset;
16078         s32 callback_offset;
16079
16080         /* This represents an inlined version of bpf_iter.c:bpf_loop,
16081          * be careful to modify this code in sync.
16082          */
16083         struct bpf_insn insn_buf[] = {
16084                 /* Return error and jump to the end of the patch if
16085                  * expected number of iterations is too big.
16086                  */
16087                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
16088                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
16089                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
16090                 /* spill R6, R7, R8 to use these as loop vars */
16091                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
16092                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
16093                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
16094                 /* initialize loop vars */
16095                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
16096                 BPF_MOV32_IMM(reg_loop_cnt, 0),
16097                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
16098                 /* loop header,
16099                  * if reg_loop_cnt >= reg_loop_max skip the loop body
16100                  */
16101                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
16102                 /* callback call,
16103                  * correct callback offset would be set after patching
16104                  */
16105                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
16106                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
16107                 BPF_CALL_REL(0),
16108                 /* increment loop counter */
16109                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
16110                 /* jump to loop header if callback returned 0 */
16111                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
16112                 /* return value of bpf_loop,
16113                  * set R0 to the number of iterations
16114                  */
16115                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
16116                 /* restore original values of R6, R7, R8 */
16117                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
16118                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
16119                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
16120         };
16121
16122         *cnt = ARRAY_SIZE(insn_buf);
16123         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
16124         if (!new_prog)
16125                 return new_prog;
16126
16127         /* callback start is known only after patching */
16128         callback_start = env->subprog_info[callback_subprogno].start;
16129         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
16130         call_insn_offset = position + 12;
16131         callback_offset = callback_start - call_insn_offset - 1;
16132         new_prog->insnsi[call_insn_offset].imm = callback_offset;
16133
16134         return new_prog;
16135 }
16136
16137 static bool is_bpf_loop_call(struct bpf_insn *insn)
16138 {
16139         return insn->code == (BPF_JMP | BPF_CALL) &&
16140                 insn->src_reg == 0 &&
16141                 insn->imm == BPF_FUNC_loop;
16142 }
16143
16144 /* For all sub-programs in the program (including main) check
16145  * insn_aux_data to see if there are bpf_loop calls that require
16146  * inlining. If such calls are found the calls are replaced with a
16147  * sequence of instructions produced by `inline_bpf_loop` function and
16148  * subprog stack_depth is increased by the size of 3 registers.
16149  * This stack space is used to spill values of the R6, R7, R8.  These
16150  * registers are used to store the loop bound, counter and context
16151  * variables.
16152  */
16153 static int optimize_bpf_loop(struct bpf_verifier_env *env)
16154 {
16155         struct bpf_subprog_info *subprogs = env->subprog_info;
16156         int i, cur_subprog = 0, cnt, delta = 0;
16157         struct bpf_insn *insn = env->prog->insnsi;
16158         int insn_cnt = env->prog->len;
16159         u16 stack_depth = subprogs[cur_subprog].stack_depth;
16160         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16161         u16 stack_depth_extra = 0;
16162
16163         for (i = 0; i < insn_cnt; i++, insn++) {
16164                 struct bpf_loop_inline_state *inline_state =
16165                         &env->insn_aux_data[i + delta].loop_inline_state;
16166
16167                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
16168                         struct bpf_prog *new_prog;
16169
16170                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
16171                         new_prog = inline_bpf_loop(env,
16172                                                    i + delta,
16173                                                    -(stack_depth + stack_depth_extra),
16174                                                    inline_state->callback_subprogno,
16175                                                    &cnt);
16176                         if (!new_prog)
16177                                 return -ENOMEM;
16178
16179                         delta     += cnt - 1;
16180                         env->prog  = new_prog;
16181                         insn       = new_prog->insnsi + i + delta;
16182                 }
16183
16184                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
16185                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
16186                         cur_subprog++;
16187                         stack_depth = subprogs[cur_subprog].stack_depth;
16188                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16189                         stack_depth_extra = 0;
16190                 }
16191         }
16192
16193         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16194
16195         return 0;
16196 }
16197
16198 static void free_states(struct bpf_verifier_env *env)
16199 {
16200         struct bpf_verifier_state_list *sl, *sln;
16201         int i;
16202
16203         sl = env->free_list;
16204         while (sl) {
16205                 sln = sl->next;
16206                 free_verifier_state(&sl->state, false);
16207                 kfree(sl);
16208                 sl = sln;
16209         }
16210         env->free_list = NULL;
16211
16212         if (!env->explored_states)
16213                 return;
16214
16215         for (i = 0; i < state_htab_size(env); i++) {
16216                 sl = env->explored_states[i];
16217
16218                 while (sl) {
16219                         sln = sl->next;
16220                         free_verifier_state(&sl->state, false);
16221                         kfree(sl);
16222                         sl = sln;
16223                 }
16224                 env->explored_states[i] = NULL;
16225         }
16226 }
16227
16228 static int do_check_common(struct bpf_verifier_env *env, int subprog)
16229 {
16230         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16231         struct bpf_verifier_state *state;
16232         struct bpf_reg_state *regs;
16233         int ret, i;
16234
16235         env->prev_linfo = NULL;
16236         env->pass_cnt++;
16237
16238         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
16239         if (!state)
16240                 return -ENOMEM;
16241         state->curframe = 0;
16242         state->speculative = false;
16243         state->branches = 1;
16244         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
16245         if (!state->frame[0]) {
16246                 kfree(state);
16247                 return -ENOMEM;
16248         }
16249         env->cur_state = state;
16250         init_func_state(env, state->frame[0],
16251                         BPF_MAIN_FUNC /* callsite */,
16252                         0 /* frameno */,
16253                         subprog);
16254         state->first_insn_idx = env->subprog_info[subprog].start;
16255         state->last_insn_idx = -1;
16256
16257         regs = state->frame[state->curframe]->regs;
16258         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
16259                 ret = btf_prepare_func_args(env, subprog, regs);
16260                 if (ret)
16261                         goto out;
16262                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
16263                         if (regs[i].type == PTR_TO_CTX)
16264                                 mark_reg_known_zero(env, regs, i);
16265                         else if (regs[i].type == SCALAR_VALUE)
16266                                 mark_reg_unknown(env, regs, i);
16267                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
16268                                 const u32 mem_size = regs[i].mem_size;
16269
16270                                 mark_reg_known_zero(env, regs, i);
16271                                 regs[i].mem_size = mem_size;
16272                                 regs[i].id = ++env->id_gen;
16273                         }
16274                 }
16275         } else {
16276                 /* 1st arg to a function */
16277                 regs[BPF_REG_1].type = PTR_TO_CTX;
16278                 mark_reg_known_zero(env, regs, BPF_REG_1);
16279                 ret = btf_check_subprog_arg_match(env, subprog, regs);
16280                 if (ret == -EFAULT)
16281                         /* unlikely verifier bug. abort.
16282                          * ret == 0 and ret < 0 are sadly acceptable for
16283                          * main() function due to backward compatibility.
16284                          * Like socket filter program may be written as:
16285                          * int bpf_prog(struct pt_regs *ctx)
16286                          * and never dereference that ctx in the program.
16287                          * 'struct pt_regs' is a type mismatch for socket
16288                          * filter that should be using 'struct __sk_buff'.
16289                          */
16290                         goto out;
16291         }
16292
16293         ret = do_check(env);
16294 out:
16295         /* check for NULL is necessary, since cur_state can be freed inside
16296          * do_check() under memory pressure.
16297          */
16298         if (env->cur_state) {
16299                 free_verifier_state(env->cur_state, true);
16300                 env->cur_state = NULL;
16301         }
16302         while (!pop_stack(env, NULL, NULL, false));
16303         if (!ret && pop_log)
16304                 bpf_vlog_reset(&env->log, 0);
16305         free_states(env);
16306         return ret;
16307 }
16308
16309 /* Verify all global functions in a BPF program one by one based on their BTF.
16310  * All global functions must pass verification. Otherwise the whole program is rejected.
16311  * Consider:
16312  * int bar(int);
16313  * int foo(int f)
16314  * {
16315  *    return bar(f);
16316  * }
16317  * int bar(int b)
16318  * {
16319  *    ...
16320  * }
16321  * foo() will be verified first for R1=any_scalar_value. During verification it
16322  * will be assumed that bar() already verified successfully and call to bar()
16323  * from foo() will be checked for type match only. Later bar() will be verified
16324  * independently to check that it's safe for R1=any_scalar_value.
16325  */
16326 static int do_check_subprogs(struct bpf_verifier_env *env)
16327 {
16328         struct bpf_prog_aux *aux = env->prog->aux;
16329         int i, ret;
16330
16331         if (!aux->func_info)
16332                 return 0;
16333
16334         for (i = 1; i < env->subprog_cnt; i++) {
16335                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
16336                         continue;
16337                 env->insn_idx = env->subprog_info[i].start;
16338                 WARN_ON_ONCE(env->insn_idx == 0);
16339                 ret = do_check_common(env, i);
16340                 if (ret) {
16341                         return ret;
16342                 } else if (env->log.level & BPF_LOG_LEVEL) {
16343                         verbose(env,
16344                                 "Func#%d is safe for any args that match its prototype\n",
16345                                 i);
16346                 }
16347         }
16348         return 0;
16349 }
16350
16351 static int do_check_main(struct bpf_verifier_env *env)
16352 {
16353         int ret;
16354
16355         env->insn_idx = 0;
16356         ret = do_check_common(env, 0);
16357         if (!ret)
16358                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16359         return ret;
16360 }
16361
16362
16363 static void print_verification_stats(struct bpf_verifier_env *env)
16364 {
16365         int i;
16366
16367         if (env->log.level & BPF_LOG_STATS) {
16368                 verbose(env, "verification time %lld usec\n",
16369                         div_u64(env->verification_time, 1000));
16370                 verbose(env, "stack depth ");
16371                 for (i = 0; i < env->subprog_cnt; i++) {
16372                         u32 depth = env->subprog_info[i].stack_depth;
16373
16374                         verbose(env, "%d", depth);
16375                         if (i + 1 < env->subprog_cnt)
16376                                 verbose(env, "+");
16377                 }
16378                 verbose(env, "\n");
16379         }
16380         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
16381                 "total_states %d peak_states %d mark_read %d\n",
16382                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
16383                 env->max_states_per_insn, env->total_states,
16384                 env->peak_states, env->longest_mark_read_walk);
16385 }
16386
16387 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
16388 {
16389         const struct btf_type *t, *func_proto;
16390         const struct bpf_struct_ops *st_ops;
16391         const struct btf_member *member;
16392         struct bpf_prog *prog = env->prog;
16393         u32 btf_id, member_idx;
16394         const char *mname;
16395
16396         if (!prog->gpl_compatible) {
16397                 verbose(env, "struct ops programs must have a GPL compatible license\n");
16398                 return -EINVAL;
16399         }
16400
16401         btf_id = prog->aux->attach_btf_id;
16402         st_ops = bpf_struct_ops_find(btf_id);
16403         if (!st_ops) {
16404                 verbose(env, "attach_btf_id %u is not a supported struct\n",
16405                         btf_id);
16406                 return -ENOTSUPP;
16407         }
16408
16409         t = st_ops->type;
16410         member_idx = prog->expected_attach_type;
16411         if (member_idx >= btf_type_vlen(t)) {
16412                 verbose(env, "attach to invalid member idx %u of struct %s\n",
16413                         member_idx, st_ops->name);
16414                 return -EINVAL;
16415         }
16416
16417         member = &btf_type_member(t)[member_idx];
16418         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
16419         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
16420                                                NULL);
16421         if (!func_proto) {
16422                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
16423                         mname, member_idx, st_ops->name);
16424                 return -EINVAL;
16425         }
16426
16427         if (st_ops->check_member) {
16428                 int err = st_ops->check_member(t, member);
16429
16430                 if (err) {
16431                         verbose(env, "attach to unsupported member %s of struct %s\n",
16432                                 mname, st_ops->name);
16433                         return err;
16434                 }
16435         }
16436
16437         prog->aux->attach_func_proto = func_proto;
16438         prog->aux->attach_func_name = mname;
16439         env->ops = st_ops->verifier_ops;
16440
16441         return 0;
16442 }
16443 #define SECURITY_PREFIX "security_"
16444
16445 static int check_attach_modify_return(unsigned long addr, const char *func_name)
16446 {
16447         if (within_error_injection_list(addr) ||
16448             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
16449                 return 0;
16450
16451         return -EINVAL;
16452 }
16453
16454 /* list of non-sleepable functions that are otherwise on
16455  * ALLOW_ERROR_INJECTION list
16456  */
16457 BTF_SET_START(btf_non_sleepable_error_inject)
16458 /* Three functions below can be called from sleepable and non-sleepable context.
16459  * Assume non-sleepable from bpf safety point of view.
16460  */
16461 BTF_ID(func, __filemap_add_folio)
16462 BTF_ID(func, should_fail_alloc_page)
16463 BTF_ID(func, should_failslab)
16464 BTF_SET_END(btf_non_sleepable_error_inject)
16465
16466 static int check_non_sleepable_error_inject(u32 btf_id)
16467 {
16468         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
16469 }
16470
16471 int bpf_check_attach_target(struct bpf_verifier_log *log,
16472                             const struct bpf_prog *prog,
16473                             const struct bpf_prog *tgt_prog,
16474                             u32 btf_id,
16475                             struct bpf_attach_target_info *tgt_info)
16476 {
16477         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
16478         const char prefix[] = "btf_trace_";
16479         int ret = 0, subprog = -1, i;
16480         const struct btf_type *t;
16481         bool conservative = true;
16482         const char *tname;
16483         struct btf *btf;
16484         long addr = 0;
16485
16486         if (!btf_id) {
16487                 bpf_log(log, "Tracing programs must provide btf_id\n");
16488                 return -EINVAL;
16489         }
16490         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
16491         if (!btf) {
16492                 bpf_log(log,
16493                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
16494                 return -EINVAL;
16495         }
16496         t = btf_type_by_id(btf, btf_id);
16497         if (!t) {
16498                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
16499                 return -EINVAL;
16500         }
16501         tname = btf_name_by_offset(btf, t->name_off);
16502         if (!tname) {
16503                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
16504                 return -EINVAL;
16505         }
16506         if (tgt_prog) {
16507                 struct bpf_prog_aux *aux = tgt_prog->aux;
16508
16509                 for (i = 0; i < aux->func_info_cnt; i++)
16510                         if (aux->func_info[i].type_id == btf_id) {
16511                                 subprog = i;
16512                                 break;
16513                         }
16514                 if (subprog == -1) {
16515                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
16516                         return -EINVAL;
16517                 }
16518                 conservative = aux->func_info_aux[subprog].unreliable;
16519                 if (prog_extension) {
16520                         if (conservative) {
16521                                 bpf_log(log,
16522                                         "Cannot replace static functions\n");
16523                                 return -EINVAL;
16524                         }
16525                         if (!prog->jit_requested) {
16526                                 bpf_log(log,
16527                                         "Extension programs should be JITed\n");
16528                                 return -EINVAL;
16529                         }
16530                 }
16531                 if (!tgt_prog->jited) {
16532                         bpf_log(log, "Can attach to only JITed progs\n");
16533                         return -EINVAL;
16534                 }
16535                 if (tgt_prog->type == prog->type) {
16536                         /* Cannot fentry/fexit another fentry/fexit program.
16537                          * Cannot attach program extension to another extension.
16538                          * It's ok to attach fentry/fexit to extension program.
16539                          */
16540                         bpf_log(log, "Cannot recursively attach\n");
16541                         return -EINVAL;
16542                 }
16543                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
16544                     prog_extension &&
16545                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
16546                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
16547                         /* Program extensions can extend all program types
16548                          * except fentry/fexit. The reason is the following.
16549                          * The fentry/fexit programs are used for performance
16550                          * analysis, stats and can be attached to any program
16551                          * type except themselves. When extension program is
16552                          * replacing XDP function it is necessary to allow
16553                          * performance analysis of all functions. Both original
16554                          * XDP program and its program extension. Hence
16555                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
16556                          * allowed. If extending of fentry/fexit was allowed it
16557                          * would be possible to create long call chain
16558                          * fentry->extension->fentry->extension beyond
16559                          * reasonable stack size. Hence extending fentry is not
16560                          * allowed.
16561                          */
16562                         bpf_log(log, "Cannot extend fentry/fexit\n");
16563                         return -EINVAL;
16564                 }
16565         } else {
16566                 if (prog_extension) {
16567                         bpf_log(log, "Cannot replace kernel functions\n");
16568                         return -EINVAL;
16569                 }
16570         }
16571
16572         switch (prog->expected_attach_type) {
16573         case BPF_TRACE_RAW_TP:
16574                 if (tgt_prog) {
16575                         bpf_log(log,
16576                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
16577                         return -EINVAL;
16578                 }
16579                 if (!btf_type_is_typedef(t)) {
16580                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
16581                                 btf_id);
16582                         return -EINVAL;
16583                 }
16584                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
16585                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
16586                                 btf_id, tname);
16587                         return -EINVAL;
16588                 }
16589                 tname += sizeof(prefix) - 1;
16590                 t = btf_type_by_id(btf, t->type);
16591                 if (!btf_type_is_ptr(t))
16592                         /* should never happen in valid vmlinux build */
16593                         return -EINVAL;
16594                 t = btf_type_by_id(btf, t->type);
16595                 if (!btf_type_is_func_proto(t))
16596                         /* should never happen in valid vmlinux build */
16597                         return -EINVAL;
16598
16599                 break;
16600         case BPF_TRACE_ITER:
16601                 if (!btf_type_is_func(t)) {
16602                         bpf_log(log, "attach_btf_id %u is not a function\n",
16603                                 btf_id);
16604                         return -EINVAL;
16605                 }
16606                 t = btf_type_by_id(btf, t->type);
16607                 if (!btf_type_is_func_proto(t))
16608                         return -EINVAL;
16609                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16610                 if (ret)
16611                         return ret;
16612                 break;
16613         default:
16614                 if (!prog_extension)
16615                         return -EINVAL;
16616                 fallthrough;
16617         case BPF_MODIFY_RETURN:
16618         case BPF_LSM_MAC:
16619         case BPF_LSM_CGROUP:
16620         case BPF_TRACE_FENTRY:
16621         case BPF_TRACE_FEXIT:
16622                 if (!btf_type_is_func(t)) {
16623                         bpf_log(log, "attach_btf_id %u is not a function\n",
16624                                 btf_id);
16625                         return -EINVAL;
16626                 }
16627                 if (prog_extension &&
16628                     btf_check_type_match(log, prog, btf, t))
16629                         return -EINVAL;
16630                 t = btf_type_by_id(btf, t->type);
16631                 if (!btf_type_is_func_proto(t))
16632                         return -EINVAL;
16633
16634                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
16635                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
16636                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
16637                         return -EINVAL;
16638
16639                 if (tgt_prog && conservative)
16640                         t = NULL;
16641
16642                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16643                 if (ret < 0)
16644                         return ret;
16645
16646                 if (tgt_prog) {
16647                         if (subprog == 0)
16648                                 addr = (long) tgt_prog->bpf_func;
16649                         else
16650                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
16651                 } else {
16652                         addr = kallsyms_lookup_name(tname);
16653                         if (!addr) {
16654                                 bpf_log(log,
16655                                         "The address of function %s cannot be found\n",
16656                                         tname);
16657                                 return -ENOENT;
16658                         }
16659                 }
16660
16661                 if (prog->aux->sleepable) {
16662                         ret = -EINVAL;
16663                         switch (prog->type) {
16664                         case BPF_PROG_TYPE_TRACING:
16665
16666                                 /* fentry/fexit/fmod_ret progs can be sleepable if they are
16667                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
16668                                  */
16669                                 if (!check_non_sleepable_error_inject(btf_id) &&
16670                                     within_error_injection_list(addr))
16671                                         ret = 0;
16672                                 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
16673                                  * in the fmodret id set with the KF_SLEEPABLE flag.
16674                                  */
16675                                 else {
16676                                         u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
16677
16678                                         if (flags && (*flags & KF_SLEEPABLE))
16679                                                 ret = 0;
16680                                 }
16681                                 break;
16682                         case BPF_PROG_TYPE_LSM:
16683                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
16684                                  * Only some of them are sleepable.
16685                                  */
16686                                 if (bpf_lsm_is_sleepable_hook(btf_id))
16687                                         ret = 0;
16688                                 break;
16689                         default:
16690                                 break;
16691                         }
16692                         if (ret) {
16693                                 bpf_log(log, "%s is not sleepable\n", tname);
16694                                 return ret;
16695                         }
16696                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
16697                         if (tgt_prog) {
16698                                 bpf_log(log, "can't modify return codes of BPF programs\n");
16699                                 return -EINVAL;
16700                         }
16701                         ret = -EINVAL;
16702                         if (btf_kfunc_is_modify_return(btf, btf_id) ||
16703                             !check_attach_modify_return(addr, tname))
16704                                 ret = 0;
16705                         if (ret) {
16706                                 bpf_log(log, "%s() is not modifiable\n", tname);
16707                                 return ret;
16708                         }
16709                 }
16710
16711                 break;
16712         }
16713         tgt_info->tgt_addr = addr;
16714         tgt_info->tgt_name = tname;
16715         tgt_info->tgt_type = t;
16716         return 0;
16717 }
16718
16719 BTF_SET_START(btf_id_deny)
16720 BTF_ID_UNUSED
16721 #ifdef CONFIG_SMP
16722 BTF_ID(func, migrate_disable)
16723 BTF_ID(func, migrate_enable)
16724 #endif
16725 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
16726 BTF_ID(func, rcu_read_unlock_strict)
16727 #endif
16728 BTF_SET_END(btf_id_deny)
16729
16730 static int check_attach_btf_id(struct bpf_verifier_env *env)
16731 {
16732         struct bpf_prog *prog = env->prog;
16733         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
16734         struct bpf_attach_target_info tgt_info = {};
16735         u32 btf_id = prog->aux->attach_btf_id;
16736         struct bpf_trampoline *tr;
16737         int ret;
16738         u64 key;
16739
16740         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
16741                 if (prog->aux->sleepable)
16742                         /* attach_btf_id checked to be zero already */
16743                         return 0;
16744                 verbose(env, "Syscall programs can only be sleepable\n");
16745                 return -EINVAL;
16746         }
16747
16748         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
16749             prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
16750                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
16751                 return -EINVAL;
16752         }
16753
16754         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
16755                 return check_struct_ops_btf_id(env);
16756
16757         if (prog->type != BPF_PROG_TYPE_TRACING &&
16758             prog->type != BPF_PROG_TYPE_LSM &&
16759             prog->type != BPF_PROG_TYPE_EXT)
16760                 return 0;
16761
16762         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
16763         if (ret)
16764                 return ret;
16765
16766         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
16767                 /* to make freplace equivalent to their targets, they need to
16768                  * inherit env->ops and expected_attach_type for the rest of the
16769                  * verification
16770                  */
16771                 env->ops = bpf_verifier_ops[tgt_prog->type];
16772                 prog->expected_attach_type = tgt_prog->expected_attach_type;
16773         }
16774
16775         /* store info about the attachment target that will be used later */
16776         prog->aux->attach_func_proto = tgt_info.tgt_type;
16777         prog->aux->attach_func_name = tgt_info.tgt_name;
16778
16779         if (tgt_prog) {
16780                 prog->aux->saved_dst_prog_type = tgt_prog->type;
16781                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
16782         }
16783
16784         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
16785                 prog->aux->attach_btf_trace = true;
16786                 return 0;
16787         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
16788                 if (!bpf_iter_prog_supported(prog))
16789                         return -EINVAL;
16790                 return 0;
16791         }
16792
16793         if (prog->type == BPF_PROG_TYPE_LSM) {
16794                 ret = bpf_lsm_verify_prog(&env->log, prog);
16795                 if (ret < 0)
16796                         return ret;
16797         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
16798                    btf_id_set_contains(&btf_id_deny, btf_id)) {
16799                 return -EINVAL;
16800         }
16801
16802         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
16803         tr = bpf_trampoline_get(key, &tgt_info);
16804         if (!tr)
16805                 return -ENOMEM;
16806
16807         prog->aux->dst_trampoline = tr;
16808         return 0;
16809 }
16810
16811 struct btf *bpf_get_btf_vmlinux(void)
16812 {
16813         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
16814                 mutex_lock(&bpf_verifier_lock);
16815                 if (!btf_vmlinux)
16816                         btf_vmlinux = btf_parse_vmlinux();
16817                 mutex_unlock(&bpf_verifier_lock);
16818         }
16819         return btf_vmlinux;
16820 }
16821
16822 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
16823 {
16824         u64 start_time = ktime_get_ns();
16825         struct bpf_verifier_env *env;
16826         struct bpf_verifier_log *log;
16827         int i, len, ret = -EINVAL;
16828         bool is_priv;
16829
16830         /* no program is valid */
16831         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
16832                 return -EINVAL;
16833
16834         /* 'struct bpf_verifier_env' can be global, but since it's not small,
16835          * allocate/free it every time bpf_check() is called
16836          */
16837         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
16838         if (!env)
16839                 return -ENOMEM;
16840         log = &env->log;
16841
16842         len = (*prog)->len;
16843         env->insn_aux_data =
16844                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
16845         ret = -ENOMEM;
16846         if (!env->insn_aux_data)
16847                 goto err_free_env;
16848         for (i = 0; i < len; i++)
16849                 env->insn_aux_data[i].orig_idx = i;
16850         env->prog = *prog;
16851         env->ops = bpf_verifier_ops[env->prog->type];
16852         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
16853         is_priv = bpf_capable();
16854
16855         bpf_get_btf_vmlinux();
16856
16857         /* grab the mutex to protect few globals used by verifier */
16858         if (!is_priv)
16859                 mutex_lock(&bpf_verifier_lock);
16860
16861         if (attr->log_level || attr->log_buf || attr->log_size) {
16862                 /* user requested verbose verifier output
16863                  * and supplied buffer to store the verification trace
16864                  */
16865                 log->level = attr->log_level;
16866                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
16867                 log->len_total = attr->log_size;
16868
16869                 /* log attributes have to be sane */
16870                 if (!bpf_verifier_log_attr_valid(log)) {
16871                         ret = -EINVAL;
16872                         goto err_unlock;
16873                 }
16874         }
16875
16876         mark_verifier_state_clean(env);
16877
16878         if (IS_ERR(btf_vmlinux)) {
16879                 /* Either gcc or pahole or kernel are broken. */
16880                 verbose(env, "in-kernel BTF is malformed\n");
16881                 ret = PTR_ERR(btf_vmlinux);
16882                 goto skip_full_check;
16883         }
16884
16885         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
16886         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
16887                 env->strict_alignment = true;
16888         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
16889                 env->strict_alignment = false;
16890
16891         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
16892         env->allow_uninit_stack = bpf_allow_uninit_stack();
16893         env->bypass_spec_v1 = bpf_bypass_spec_v1();
16894         env->bypass_spec_v4 = bpf_bypass_spec_v4();
16895         env->bpf_capable = bpf_capable();
16896         env->rcu_tag_supported = btf_vmlinux &&
16897                 btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0;
16898
16899         if (is_priv)
16900                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
16901
16902         env->explored_states = kvcalloc(state_htab_size(env),
16903                                        sizeof(struct bpf_verifier_state_list *),
16904                                        GFP_USER);
16905         ret = -ENOMEM;
16906         if (!env->explored_states)
16907                 goto skip_full_check;
16908
16909         ret = add_subprog_and_kfunc(env);
16910         if (ret < 0)
16911                 goto skip_full_check;
16912
16913         ret = check_subprogs(env);
16914         if (ret < 0)
16915                 goto skip_full_check;
16916
16917         ret = check_btf_info(env, attr, uattr);
16918         if (ret < 0)
16919                 goto skip_full_check;
16920
16921         ret = check_attach_btf_id(env);
16922         if (ret)
16923                 goto skip_full_check;
16924
16925         ret = resolve_pseudo_ldimm64(env);
16926         if (ret < 0)
16927                 goto skip_full_check;
16928
16929         if (bpf_prog_is_dev_bound(env->prog->aux)) {
16930                 ret = bpf_prog_offload_verifier_prep(env->prog);
16931                 if (ret)
16932                         goto skip_full_check;
16933         }
16934
16935         ret = check_cfg(env);
16936         if (ret < 0)
16937                 goto skip_full_check;
16938
16939         ret = do_check_subprogs(env);
16940         ret = ret ?: do_check_main(env);
16941
16942         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
16943                 ret = bpf_prog_offload_finalize(env);
16944
16945 skip_full_check:
16946         kvfree(env->explored_states);
16947
16948         if (ret == 0)
16949                 ret = check_max_stack_depth(env);
16950
16951         /* instruction rewrites happen after this point */
16952         if (ret == 0)
16953                 ret = optimize_bpf_loop(env);
16954
16955         if (is_priv) {
16956                 if (ret == 0)
16957                         opt_hard_wire_dead_code_branches(env);
16958                 if (ret == 0)
16959                         ret = opt_remove_dead_code(env);
16960                 if (ret == 0)
16961                         ret = opt_remove_nops(env);
16962         } else {
16963                 if (ret == 0)
16964                         sanitize_dead_code(env);
16965         }
16966
16967         if (ret == 0)
16968                 /* program is valid, convert *(u32*)(ctx + off) accesses */
16969                 ret = convert_ctx_accesses(env);
16970
16971         if (ret == 0)
16972                 ret = do_misc_fixups(env);
16973
16974         /* do 32-bit optimization after insn patching has done so those patched
16975          * insns could be handled correctly.
16976          */
16977         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
16978                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
16979                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
16980                                                                      : false;
16981         }
16982
16983         if (ret == 0)
16984                 ret = fixup_call_args(env);
16985
16986         env->verification_time = ktime_get_ns() - start_time;
16987         print_verification_stats(env);
16988         env->prog->aux->verified_insns = env->insn_processed;
16989
16990         if (log->level && bpf_verifier_log_full(log))
16991                 ret = -ENOSPC;
16992         if (log->level && !log->ubuf) {
16993                 ret = -EFAULT;
16994                 goto err_release_maps;
16995         }
16996
16997         if (ret)
16998                 goto err_release_maps;
16999
17000         if (env->used_map_cnt) {
17001                 /* if program passed verifier, update used_maps in bpf_prog_info */
17002                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
17003                                                           sizeof(env->used_maps[0]),
17004                                                           GFP_KERNEL);
17005
17006                 if (!env->prog->aux->used_maps) {
17007                         ret = -ENOMEM;
17008                         goto err_release_maps;
17009                 }
17010
17011                 memcpy(env->prog->aux->used_maps, env->used_maps,
17012                        sizeof(env->used_maps[0]) * env->used_map_cnt);
17013                 env->prog->aux->used_map_cnt = env->used_map_cnt;
17014         }
17015         if (env->used_btf_cnt) {
17016                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
17017                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
17018                                                           sizeof(env->used_btfs[0]),
17019                                                           GFP_KERNEL);
17020                 if (!env->prog->aux->used_btfs) {
17021                         ret = -ENOMEM;
17022                         goto err_release_maps;
17023                 }
17024
17025                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
17026                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
17027                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
17028         }
17029         if (env->used_map_cnt || env->used_btf_cnt) {
17030                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
17031                  * bpf_ld_imm64 instructions
17032                  */
17033                 convert_pseudo_ld_imm64(env);
17034         }
17035
17036         adjust_btf_func(env);
17037
17038 err_release_maps:
17039         if (!env->prog->aux->used_maps)
17040                 /* if we didn't copy map pointers into bpf_prog_info, release
17041                  * them now. Otherwise free_used_maps() will release them.
17042                  */
17043                 release_maps(env);
17044         if (!env->prog->aux->used_btfs)
17045                 release_btfs(env);
17046
17047         /* extension progs temporarily inherit the attach_type of their targets
17048            for verification purposes, so set it back to zero before returning
17049          */
17050         if (env->prog->type == BPF_PROG_TYPE_EXT)
17051                 env->prog->expected_attach_type = 0;
17052
17053         *prog = env->prog;
17054 err_unlock:
17055         if (!is_priv)
17056                 mutex_unlock(&bpf_verifier_lock);
17057         vfree(env->insn_aux_data);
17058 err_free_env:
17059         kfree(env);
17060         return ret;
17061 }