bpf: Prevent pointer mismatch in bpf_timer_init.
[linux-2.6-microblaze.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
25
26 #include "disasm.h"
27
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30         [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
34 #undef BPF_PROG_TYPE
35 #undef BPF_MAP_TYPE
36 #undef BPF_LINK_TYPE
37 };
38
39 /* bpf_check() is a static code analyzer that walks eBPF program
40  * instruction by instruction and updates register/stack state.
41  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42  *
43  * The first pass is depth-first-search to check that the program is a DAG.
44  * It rejects the following programs:
45  * - larger than BPF_MAXINSNS insns
46  * - if loop is present (detected via back-edge)
47  * - unreachable insns exist (shouldn't be a forest. program = one function)
48  * - out of bounds or malformed jumps
49  * The second pass is all possible path descent from the 1st insn.
50  * Since it's analyzing all paths through the program, the length of the
51  * analysis is limited to 64k insn, which may be hit even if total number of
52  * insn is less then 4K, but there are too many branches that change stack/regs.
53  * Number of 'branches to be analyzed' is limited to 1k
54  *
55  * On entry to each instruction, each register has a type, and the instruction
56  * changes the types of the registers depending on instruction semantics.
57  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58  * copied to R1.
59  *
60  * All registers are 64-bit.
61  * R0 - return register
62  * R1-R5 argument passing registers
63  * R6-R9 callee saved registers
64  * R10 - frame pointer read-only
65  *
66  * At the start of BPF program the register R1 contains a pointer to bpf_context
67  * and has type PTR_TO_CTX.
68  *
69  * Verifier tracks arithmetic operations on pointers in case:
70  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72  * 1st insn copies R10 (which has FRAME_PTR) type into R1
73  * and 2nd arithmetic instruction is pattern matched to recognize
74  * that it wants to construct a pointer to some element within stack.
75  * So after 2nd insn, the register R1 has type PTR_TO_STACK
76  * (and -20 constant is saved for further stack bounds checking).
77  * Meaning that this reg is a pointer to stack plus known immediate constant.
78  *
79  * Most of the time the registers have SCALAR_VALUE type, which
80  * means the register has some value, but it's not a valid pointer.
81  * (like pointer plus pointer becomes SCALAR_VALUE type)
82  *
83  * When verifier sees load or store instructions the type of base register
84  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85  * four pointer types recognized by check_mem_access() function.
86  *
87  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88  * and the range of [ptr, ptr + map's value_size) is accessible.
89  *
90  * registers used to pass values to function calls are checked against
91  * function argument constraints.
92  *
93  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94  * It means that the register type passed to this function must be
95  * PTR_TO_STACK and it will be used inside the function as
96  * 'pointer to map element key'
97  *
98  * For example the argument constraints for bpf_map_lookup_elem():
99  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100  *   .arg1_type = ARG_CONST_MAP_PTR,
101  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
102  *
103  * ret_type says that this function returns 'pointer to map elem value or null'
104  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105  * 2nd argument should be a pointer to stack, which will be used inside
106  * the helper function as a pointer to map element key.
107  *
108  * On the kernel side the helper function looks like:
109  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110  * {
111  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112  *    void *key = (void *) (unsigned long) r2;
113  *    void *value;
114  *
115  *    here kernel can access 'key' and 'map' pointers safely, knowing that
116  *    [key, key + map->key_size) bytes are valid and were initialized on
117  *    the stack of eBPF program.
118  * }
119  *
120  * Corresponding eBPF program may look like:
121  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
122  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
124  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125  * here verifier looks at prototype of map_lookup_elem() and sees:
126  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128  *
129  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131  * and were initialized prior to this call.
132  * If it's ok, then verifier allows this BPF_CALL insn and looks at
133  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135  * returns either pointer to map value or NULL.
136  *
137  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138  * insn, the register holding that pointer in the true branch changes state to
139  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140  * branch. See check_cond_jmp_op().
141  *
142  * After the call R0 is set to return type of the function and registers R1-R5
143  * are set to NOT_INIT to indicate that they are no longer readable.
144  *
145  * The following reference types represent a potential reference to a kernel
146  * resource which, after first being allocated, must be checked and freed by
147  * the BPF program:
148  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149  *
150  * When the verifier sees a helper call return a reference type, it allocates a
151  * pointer id for the reference and stores it in the current function state.
152  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154  * passes through a NULL-check conditional. For the branch wherein the state is
155  * changed to CONST_IMM, the verifier releases the reference.
156  *
157  * For each helper function that allocates a reference, such as
158  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159  * bpf_sk_release(). When a reference type passes into the release function,
160  * the verifier also releases the reference. If any unchecked or unreleased
161  * reference remains at the end of the program, the verifier rejects it.
162  */
163
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem {
166         /* verifer state is 'st'
167          * before processing instruction 'insn_idx'
168          * and after processing instruction 'prev_insn_idx'
169          */
170         struct bpf_verifier_state st;
171         int insn_idx;
172         int prev_insn_idx;
173         struct bpf_verifier_stack_elem *next;
174         /* length of verifier log at the time this state was pushed on stack */
175         u32 log_pos;
176 };
177
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
179 #define BPF_COMPLEXITY_LIMIT_STATES     64
180
181 #define BPF_MAP_KEY_POISON      (1ULL << 63)
182 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
183
184 #define BPF_MAP_PTR_UNPRIV      1UL
185 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
186                                           POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188
189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190 {
191         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
192 }
193
194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195 {
196         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
197 }
198
199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200                               const struct bpf_map *map, bool unpriv)
201 {
202         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203         unpriv |= bpf_map_ptr_unpriv(aux);
204         aux->map_ptr_state = (unsigned long)map |
205                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206 }
207
208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209 {
210         return aux->map_key_state & BPF_MAP_KEY_POISON;
211 }
212
213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214 {
215         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216 }
217
218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219 {
220         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221 }
222
223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224 {
225         bool poisoned = bpf_map_key_poisoned(aux);
226
227         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
229 }
230
231 static bool bpf_pseudo_call(const struct bpf_insn *insn)
232 {
233         return insn->code == (BPF_JMP | BPF_CALL) &&
234                insn->src_reg == BPF_PSEUDO_CALL;
235 }
236
237 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
238 {
239         return insn->code == (BPF_JMP | BPF_CALL) &&
240                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
241 }
242
243 static bool bpf_pseudo_func(const struct bpf_insn *insn)
244 {
245         return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
246                insn->src_reg == BPF_PSEUDO_FUNC;
247 }
248
249 struct bpf_call_arg_meta {
250         struct bpf_map *map_ptr;
251         bool raw_mode;
252         bool pkt_access;
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 };
266
267 struct btf *btf_vmlinux;
268
269 static DEFINE_MUTEX(bpf_verifier_lock);
270
271 static const struct bpf_line_info *
272 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
273 {
274         const struct bpf_line_info *linfo;
275         const struct bpf_prog *prog;
276         u32 i, nr_linfo;
277
278         prog = env->prog;
279         nr_linfo = prog->aux->nr_linfo;
280
281         if (!nr_linfo || insn_off >= prog->len)
282                 return NULL;
283
284         linfo = prog->aux->linfo;
285         for (i = 1; i < nr_linfo; i++)
286                 if (insn_off < linfo[i].insn_off)
287                         break;
288
289         return &linfo[i - 1];
290 }
291
292 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
293                        va_list args)
294 {
295         unsigned int n;
296
297         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
298
299         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
300                   "verifier log line truncated - local buffer too short\n");
301
302         n = min(log->len_total - log->len_used - 1, n);
303         log->kbuf[n] = '\0';
304
305         if (log->level == BPF_LOG_KERNEL) {
306                 pr_err("BPF:%s\n", log->kbuf);
307                 return;
308         }
309         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
310                 log->len_used += n;
311         else
312                 log->ubuf = NULL;
313 }
314
315 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
316 {
317         char zero = 0;
318
319         if (!bpf_verifier_log_needed(log))
320                 return;
321
322         log->len_used = new_pos;
323         if (put_user(zero, log->ubuf + new_pos))
324                 log->ubuf = NULL;
325 }
326
327 /* log_level controls verbosity level of eBPF verifier.
328  * bpf_verifier_log_write() is used to dump the verification trace to the log,
329  * so the user can figure out what's wrong with the program
330  */
331 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
332                                            const char *fmt, ...)
333 {
334         va_list args;
335
336         if (!bpf_verifier_log_needed(&env->log))
337                 return;
338
339         va_start(args, fmt);
340         bpf_verifier_vlog(&env->log, fmt, args);
341         va_end(args);
342 }
343 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
344
345 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
346 {
347         struct bpf_verifier_env *env = private_data;
348         va_list args;
349
350         if (!bpf_verifier_log_needed(&env->log))
351                 return;
352
353         va_start(args, fmt);
354         bpf_verifier_vlog(&env->log, fmt, args);
355         va_end(args);
356 }
357
358 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
359                             const char *fmt, ...)
360 {
361         va_list args;
362
363         if (!bpf_verifier_log_needed(log))
364                 return;
365
366         va_start(args, fmt);
367         bpf_verifier_vlog(log, fmt, args);
368         va_end(args);
369 }
370
371 static const char *ltrim(const char *s)
372 {
373         while (isspace(*s))
374                 s++;
375
376         return s;
377 }
378
379 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
380                                          u32 insn_off,
381                                          const char *prefix_fmt, ...)
382 {
383         const struct bpf_line_info *linfo;
384
385         if (!bpf_verifier_log_needed(&env->log))
386                 return;
387
388         linfo = find_linfo(env, insn_off);
389         if (!linfo || linfo == env->prev_linfo)
390                 return;
391
392         if (prefix_fmt) {
393                 va_list args;
394
395                 va_start(args, prefix_fmt);
396                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
397                 va_end(args);
398         }
399
400         verbose(env, "%s\n",
401                 ltrim(btf_name_by_offset(env->prog->aux->btf,
402                                          linfo->line_off)));
403
404         env->prev_linfo = linfo;
405 }
406
407 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
408                                    struct bpf_reg_state *reg,
409                                    struct tnum *range, const char *ctx,
410                                    const char *reg_name)
411 {
412         char tn_buf[48];
413
414         verbose(env, "At %s the register %s ", ctx, reg_name);
415         if (!tnum_is_unknown(reg->var_off)) {
416                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
417                 verbose(env, "has value %s", tn_buf);
418         } else {
419                 verbose(env, "has unknown scalar value");
420         }
421         tnum_strn(tn_buf, sizeof(tn_buf), *range);
422         verbose(env, " should have been in %s\n", tn_buf);
423 }
424
425 static bool type_is_pkt_pointer(enum bpf_reg_type type)
426 {
427         return type == PTR_TO_PACKET ||
428                type == PTR_TO_PACKET_META;
429 }
430
431 static bool type_is_sk_pointer(enum bpf_reg_type type)
432 {
433         return type == PTR_TO_SOCKET ||
434                 type == PTR_TO_SOCK_COMMON ||
435                 type == PTR_TO_TCP_SOCK ||
436                 type == PTR_TO_XDP_SOCK;
437 }
438
439 static bool reg_type_not_null(enum bpf_reg_type type)
440 {
441         return type == PTR_TO_SOCKET ||
442                 type == PTR_TO_TCP_SOCK ||
443                 type == PTR_TO_MAP_VALUE ||
444                 type == PTR_TO_MAP_KEY ||
445                 type == PTR_TO_SOCK_COMMON;
446 }
447
448 static bool reg_type_may_be_null(enum bpf_reg_type type)
449 {
450         return type == PTR_TO_MAP_VALUE_OR_NULL ||
451                type == PTR_TO_SOCKET_OR_NULL ||
452                type == PTR_TO_SOCK_COMMON_OR_NULL ||
453                type == PTR_TO_TCP_SOCK_OR_NULL ||
454                type == PTR_TO_BTF_ID_OR_NULL ||
455                type == PTR_TO_MEM_OR_NULL ||
456                type == PTR_TO_RDONLY_BUF_OR_NULL ||
457                type == PTR_TO_RDWR_BUF_OR_NULL;
458 }
459
460 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
461 {
462         return reg->type == PTR_TO_MAP_VALUE &&
463                 map_value_has_spin_lock(reg->map_ptr);
464 }
465
466 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
467 {
468         return type == PTR_TO_SOCKET ||
469                 type == PTR_TO_SOCKET_OR_NULL ||
470                 type == PTR_TO_TCP_SOCK ||
471                 type == PTR_TO_TCP_SOCK_OR_NULL ||
472                 type == PTR_TO_MEM ||
473                 type == PTR_TO_MEM_OR_NULL;
474 }
475
476 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
477 {
478         return type == ARG_PTR_TO_SOCK_COMMON;
479 }
480
481 static bool arg_type_may_be_null(enum bpf_arg_type type)
482 {
483         return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
484                type == ARG_PTR_TO_MEM_OR_NULL ||
485                type == ARG_PTR_TO_CTX_OR_NULL ||
486                type == ARG_PTR_TO_SOCKET_OR_NULL ||
487                type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
488                type == ARG_PTR_TO_STACK_OR_NULL;
489 }
490
491 /* Determine whether the function releases some resources allocated by another
492  * function call. The first reference type argument will be assumed to be
493  * released by release_reference().
494  */
495 static bool is_release_function(enum bpf_func_id func_id)
496 {
497         return func_id == BPF_FUNC_sk_release ||
498                func_id == BPF_FUNC_ringbuf_submit ||
499                func_id == BPF_FUNC_ringbuf_discard;
500 }
501
502 static bool may_be_acquire_function(enum bpf_func_id func_id)
503 {
504         return func_id == BPF_FUNC_sk_lookup_tcp ||
505                 func_id == BPF_FUNC_sk_lookup_udp ||
506                 func_id == BPF_FUNC_skc_lookup_tcp ||
507                 func_id == BPF_FUNC_map_lookup_elem ||
508                 func_id == BPF_FUNC_ringbuf_reserve;
509 }
510
511 static bool is_acquire_function(enum bpf_func_id func_id,
512                                 const struct bpf_map *map)
513 {
514         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
515
516         if (func_id == BPF_FUNC_sk_lookup_tcp ||
517             func_id == BPF_FUNC_sk_lookup_udp ||
518             func_id == BPF_FUNC_skc_lookup_tcp ||
519             func_id == BPF_FUNC_ringbuf_reserve)
520                 return true;
521
522         if (func_id == BPF_FUNC_map_lookup_elem &&
523             (map_type == BPF_MAP_TYPE_SOCKMAP ||
524              map_type == BPF_MAP_TYPE_SOCKHASH))
525                 return true;
526
527         return false;
528 }
529
530 static bool is_ptr_cast_function(enum bpf_func_id func_id)
531 {
532         return func_id == BPF_FUNC_tcp_sock ||
533                 func_id == BPF_FUNC_sk_fullsock ||
534                 func_id == BPF_FUNC_skc_to_tcp_sock ||
535                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
536                 func_id == BPF_FUNC_skc_to_udp6_sock ||
537                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
538                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
539 }
540
541 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
542 {
543         return BPF_CLASS(insn->code) == BPF_STX &&
544                BPF_MODE(insn->code) == BPF_ATOMIC &&
545                insn->imm == BPF_CMPXCHG;
546 }
547
548 /* string representation of 'enum bpf_reg_type' */
549 static const char * const reg_type_str[] = {
550         [NOT_INIT]              = "?",
551         [SCALAR_VALUE]          = "inv",
552         [PTR_TO_CTX]            = "ctx",
553         [CONST_PTR_TO_MAP]      = "map_ptr",
554         [PTR_TO_MAP_VALUE]      = "map_value",
555         [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
556         [PTR_TO_STACK]          = "fp",
557         [PTR_TO_PACKET]         = "pkt",
558         [PTR_TO_PACKET_META]    = "pkt_meta",
559         [PTR_TO_PACKET_END]     = "pkt_end",
560         [PTR_TO_FLOW_KEYS]      = "flow_keys",
561         [PTR_TO_SOCKET]         = "sock",
562         [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
563         [PTR_TO_SOCK_COMMON]    = "sock_common",
564         [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
565         [PTR_TO_TCP_SOCK]       = "tcp_sock",
566         [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
567         [PTR_TO_TP_BUFFER]      = "tp_buffer",
568         [PTR_TO_XDP_SOCK]       = "xdp_sock",
569         [PTR_TO_BTF_ID]         = "ptr_",
570         [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
571         [PTR_TO_PERCPU_BTF_ID]  = "percpu_ptr_",
572         [PTR_TO_MEM]            = "mem",
573         [PTR_TO_MEM_OR_NULL]    = "mem_or_null",
574         [PTR_TO_RDONLY_BUF]     = "rdonly_buf",
575         [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
576         [PTR_TO_RDWR_BUF]       = "rdwr_buf",
577         [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
578         [PTR_TO_FUNC]           = "func",
579         [PTR_TO_MAP_KEY]        = "map_key",
580 };
581
582 static char slot_type_char[] = {
583         [STACK_INVALID] = '?',
584         [STACK_SPILL]   = 'r',
585         [STACK_MISC]    = 'm',
586         [STACK_ZERO]    = '0',
587 };
588
589 static void print_liveness(struct bpf_verifier_env *env,
590                            enum bpf_reg_liveness live)
591 {
592         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
593             verbose(env, "_");
594         if (live & REG_LIVE_READ)
595                 verbose(env, "r");
596         if (live & REG_LIVE_WRITTEN)
597                 verbose(env, "w");
598         if (live & REG_LIVE_DONE)
599                 verbose(env, "D");
600 }
601
602 static struct bpf_func_state *func(struct bpf_verifier_env *env,
603                                    const struct bpf_reg_state *reg)
604 {
605         struct bpf_verifier_state *cur = env->cur_state;
606
607         return cur->frame[reg->frameno];
608 }
609
610 static const char *kernel_type_name(const struct btf* btf, u32 id)
611 {
612         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
613 }
614
615 static void print_verifier_state(struct bpf_verifier_env *env,
616                                  const struct bpf_func_state *state)
617 {
618         const struct bpf_reg_state *reg;
619         enum bpf_reg_type t;
620         int i;
621
622         if (state->frameno)
623                 verbose(env, " frame%d:", state->frameno);
624         for (i = 0; i < MAX_BPF_REG; i++) {
625                 reg = &state->regs[i];
626                 t = reg->type;
627                 if (t == NOT_INIT)
628                         continue;
629                 verbose(env, " R%d", i);
630                 print_liveness(env, reg->live);
631                 verbose(env, "=%s", reg_type_str[t]);
632                 if (t == SCALAR_VALUE && reg->precise)
633                         verbose(env, "P");
634                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
635                     tnum_is_const(reg->var_off)) {
636                         /* reg->off should be 0 for SCALAR_VALUE */
637                         verbose(env, "%lld", reg->var_off.value + reg->off);
638                 } else {
639                         if (t == PTR_TO_BTF_ID ||
640                             t == PTR_TO_BTF_ID_OR_NULL ||
641                             t == PTR_TO_PERCPU_BTF_ID)
642                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
643                         verbose(env, "(id=%d", reg->id);
644                         if (reg_type_may_be_refcounted_or_null(t))
645                                 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
646                         if (t != SCALAR_VALUE)
647                                 verbose(env, ",off=%d", reg->off);
648                         if (type_is_pkt_pointer(t))
649                                 verbose(env, ",r=%d", reg->range);
650                         else if (t == CONST_PTR_TO_MAP ||
651                                  t == PTR_TO_MAP_KEY ||
652                                  t == PTR_TO_MAP_VALUE ||
653                                  t == PTR_TO_MAP_VALUE_OR_NULL)
654                                 verbose(env, ",ks=%d,vs=%d",
655                                         reg->map_ptr->key_size,
656                                         reg->map_ptr->value_size);
657                         if (tnum_is_const(reg->var_off)) {
658                                 /* Typically an immediate SCALAR_VALUE, but
659                                  * could be a pointer whose offset is too big
660                                  * for reg->off
661                                  */
662                                 verbose(env, ",imm=%llx", reg->var_off.value);
663                         } else {
664                                 if (reg->smin_value != reg->umin_value &&
665                                     reg->smin_value != S64_MIN)
666                                         verbose(env, ",smin_value=%lld",
667                                                 (long long)reg->smin_value);
668                                 if (reg->smax_value != reg->umax_value &&
669                                     reg->smax_value != S64_MAX)
670                                         verbose(env, ",smax_value=%lld",
671                                                 (long long)reg->smax_value);
672                                 if (reg->umin_value != 0)
673                                         verbose(env, ",umin_value=%llu",
674                                                 (unsigned long long)reg->umin_value);
675                                 if (reg->umax_value != U64_MAX)
676                                         verbose(env, ",umax_value=%llu",
677                                                 (unsigned long long)reg->umax_value);
678                                 if (!tnum_is_unknown(reg->var_off)) {
679                                         char tn_buf[48];
680
681                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
682                                         verbose(env, ",var_off=%s", tn_buf);
683                                 }
684                                 if (reg->s32_min_value != reg->smin_value &&
685                                     reg->s32_min_value != S32_MIN)
686                                         verbose(env, ",s32_min_value=%d",
687                                                 (int)(reg->s32_min_value));
688                                 if (reg->s32_max_value != reg->smax_value &&
689                                     reg->s32_max_value != S32_MAX)
690                                         verbose(env, ",s32_max_value=%d",
691                                                 (int)(reg->s32_max_value));
692                                 if (reg->u32_min_value != reg->umin_value &&
693                                     reg->u32_min_value != U32_MIN)
694                                         verbose(env, ",u32_min_value=%d",
695                                                 (int)(reg->u32_min_value));
696                                 if (reg->u32_max_value != reg->umax_value &&
697                                     reg->u32_max_value != U32_MAX)
698                                         verbose(env, ",u32_max_value=%d",
699                                                 (int)(reg->u32_max_value));
700                         }
701                         verbose(env, ")");
702                 }
703         }
704         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
705                 char types_buf[BPF_REG_SIZE + 1];
706                 bool valid = false;
707                 int j;
708
709                 for (j = 0; j < BPF_REG_SIZE; j++) {
710                         if (state->stack[i].slot_type[j] != STACK_INVALID)
711                                 valid = true;
712                         types_buf[j] = slot_type_char[
713                                         state->stack[i].slot_type[j]];
714                 }
715                 types_buf[BPF_REG_SIZE] = 0;
716                 if (!valid)
717                         continue;
718                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
719                 print_liveness(env, state->stack[i].spilled_ptr.live);
720                 if (state->stack[i].slot_type[0] == STACK_SPILL) {
721                         reg = &state->stack[i].spilled_ptr;
722                         t = reg->type;
723                         verbose(env, "=%s", reg_type_str[t]);
724                         if (t == SCALAR_VALUE && reg->precise)
725                                 verbose(env, "P");
726                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
727                                 verbose(env, "%lld", reg->var_off.value + reg->off);
728                 } else {
729                         verbose(env, "=%s", types_buf);
730                 }
731         }
732         if (state->acquired_refs && state->refs[0].id) {
733                 verbose(env, " refs=%d", state->refs[0].id);
734                 for (i = 1; i < state->acquired_refs; i++)
735                         if (state->refs[i].id)
736                                 verbose(env, ",%d", state->refs[i].id);
737         }
738         verbose(env, "\n");
739 }
740
741 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
742  * small to hold src. This is different from krealloc since we don't want to preserve
743  * the contents of dst.
744  *
745  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
746  * not be allocated.
747  */
748 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
749 {
750         size_t bytes;
751
752         if (ZERO_OR_NULL_PTR(src))
753                 goto out;
754
755         if (unlikely(check_mul_overflow(n, size, &bytes)))
756                 return NULL;
757
758         if (ksize(dst) < bytes) {
759                 kfree(dst);
760                 dst = kmalloc_track_caller(bytes, flags);
761                 if (!dst)
762                         return NULL;
763         }
764
765         memcpy(dst, src, bytes);
766 out:
767         return dst ? dst : ZERO_SIZE_PTR;
768 }
769
770 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
771  * small to hold new_n items. new items are zeroed out if the array grows.
772  *
773  * Contrary to krealloc_array, does not free arr if new_n is zero.
774  */
775 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
776 {
777         if (!new_n || old_n == new_n)
778                 goto out;
779
780         arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
781         if (!arr)
782                 return NULL;
783
784         if (new_n > old_n)
785                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
786
787 out:
788         return arr ? arr : ZERO_SIZE_PTR;
789 }
790
791 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
792 {
793         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
794                                sizeof(struct bpf_reference_state), GFP_KERNEL);
795         if (!dst->refs)
796                 return -ENOMEM;
797
798         dst->acquired_refs = src->acquired_refs;
799         return 0;
800 }
801
802 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
803 {
804         size_t n = src->allocated_stack / BPF_REG_SIZE;
805
806         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
807                                 GFP_KERNEL);
808         if (!dst->stack)
809                 return -ENOMEM;
810
811         dst->allocated_stack = src->allocated_stack;
812         return 0;
813 }
814
815 static int resize_reference_state(struct bpf_func_state *state, size_t n)
816 {
817         state->refs = realloc_array(state->refs, state->acquired_refs, n,
818                                     sizeof(struct bpf_reference_state));
819         if (!state->refs)
820                 return -ENOMEM;
821
822         state->acquired_refs = n;
823         return 0;
824 }
825
826 static int grow_stack_state(struct bpf_func_state *state, int size)
827 {
828         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
829
830         if (old_n >= n)
831                 return 0;
832
833         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
834         if (!state->stack)
835                 return -ENOMEM;
836
837         state->allocated_stack = size;
838         return 0;
839 }
840
841 /* Acquire a pointer id from the env and update the state->refs to include
842  * this new pointer reference.
843  * On success, returns a valid pointer id to associate with the register
844  * On failure, returns a negative errno.
845  */
846 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
847 {
848         struct bpf_func_state *state = cur_func(env);
849         int new_ofs = state->acquired_refs;
850         int id, err;
851
852         err = resize_reference_state(state, state->acquired_refs + 1);
853         if (err)
854                 return err;
855         id = ++env->id_gen;
856         state->refs[new_ofs].id = id;
857         state->refs[new_ofs].insn_idx = insn_idx;
858
859         return id;
860 }
861
862 /* release function corresponding to acquire_reference_state(). Idempotent. */
863 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
864 {
865         int i, last_idx;
866
867         last_idx = state->acquired_refs - 1;
868         for (i = 0; i < state->acquired_refs; i++) {
869                 if (state->refs[i].id == ptr_id) {
870                         if (last_idx && i != last_idx)
871                                 memcpy(&state->refs[i], &state->refs[last_idx],
872                                        sizeof(*state->refs));
873                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
874                         state->acquired_refs--;
875                         return 0;
876                 }
877         }
878         return -EINVAL;
879 }
880
881 static void free_func_state(struct bpf_func_state *state)
882 {
883         if (!state)
884                 return;
885         kfree(state->refs);
886         kfree(state->stack);
887         kfree(state);
888 }
889
890 static void clear_jmp_history(struct bpf_verifier_state *state)
891 {
892         kfree(state->jmp_history);
893         state->jmp_history = NULL;
894         state->jmp_history_cnt = 0;
895 }
896
897 static void free_verifier_state(struct bpf_verifier_state *state,
898                                 bool free_self)
899 {
900         int i;
901
902         for (i = 0; i <= state->curframe; i++) {
903                 free_func_state(state->frame[i]);
904                 state->frame[i] = NULL;
905         }
906         clear_jmp_history(state);
907         if (free_self)
908                 kfree(state);
909 }
910
911 /* copy verifier state from src to dst growing dst stack space
912  * when necessary to accommodate larger src stack
913  */
914 static int copy_func_state(struct bpf_func_state *dst,
915                            const struct bpf_func_state *src)
916 {
917         int err;
918
919         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
920         err = copy_reference_state(dst, src);
921         if (err)
922                 return err;
923         return copy_stack_state(dst, src);
924 }
925
926 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
927                                const struct bpf_verifier_state *src)
928 {
929         struct bpf_func_state *dst;
930         int i, err;
931
932         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
933                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
934                                             GFP_USER);
935         if (!dst_state->jmp_history)
936                 return -ENOMEM;
937         dst_state->jmp_history_cnt = src->jmp_history_cnt;
938
939         /* if dst has more stack frames then src frame, free them */
940         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
941                 free_func_state(dst_state->frame[i]);
942                 dst_state->frame[i] = NULL;
943         }
944         dst_state->speculative = src->speculative;
945         dst_state->curframe = src->curframe;
946         dst_state->active_spin_lock = src->active_spin_lock;
947         dst_state->branches = src->branches;
948         dst_state->parent = src->parent;
949         dst_state->first_insn_idx = src->first_insn_idx;
950         dst_state->last_insn_idx = src->last_insn_idx;
951         for (i = 0; i <= src->curframe; i++) {
952                 dst = dst_state->frame[i];
953                 if (!dst) {
954                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
955                         if (!dst)
956                                 return -ENOMEM;
957                         dst_state->frame[i] = dst;
958                 }
959                 err = copy_func_state(dst, src->frame[i]);
960                 if (err)
961                         return err;
962         }
963         return 0;
964 }
965
966 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
967 {
968         while (st) {
969                 u32 br = --st->branches;
970
971                 /* WARN_ON(br > 1) technically makes sense here,
972                  * but see comment in push_stack(), hence:
973                  */
974                 WARN_ONCE((int)br < 0,
975                           "BUG update_branch_counts:branches_to_explore=%d\n",
976                           br);
977                 if (br)
978                         break;
979                 st = st->parent;
980         }
981 }
982
983 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
984                      int *insn_idx, bool pop_log)
985 {
986         struct bpf_verifier_state *cur = env->cur_state;
987         struct bpf_verifier_stack_elem *elem, *head = env->head;
988         int err;
989
990         if (env->head == NULL)
991                 return -ENOENT;
992
993         if (cur) {
994                 err = copy_verifier_state(cur, &head->st);
995                 if (err)
996                         return err;
997         }
998         if (pop_log)
999                 bpf_vlog_reset(&env->log, head->log_pos);
1000         if (insn_idx)
1001                 *insn_idx = head->insn_idx;
1002         if (prev_insn_idx)
1003                 *prev_insn_idx = head->prev_insn_idx;
1004         elem = head->next;
1005         free_verifier_state(&head->st, false);
1006         kfree(head);
1007         env->head = elem;
1008         env->stack_size--;
1009         return 0;
1010 }
1011
1012 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1013                                              int insn_idx, int prev_insn_idx,
1014                                              bool speculative)
1015 {
1016         struct bpf_verifier_state *cur = env->cur_state;
1017         struct bpf_verifier_stack_elem *elem;
1018         int err;
1019
1020         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1021         if (!elem)
1022                 goto err;
1023
1024         elem->insn_idx = insn_idx;
1025         elem->prev_insn_idx = prev_insn_idx;
1026         elem->next = env->head;
1027         elem->log_pos = env->log.len_used;
1028         env->head = elem;
1029         env->stack_size++;
1030         err = copy_verifier_state(&elem->st, cur);
1031         if (err)
1032                 goto err;
1033         elem->st.speculative |= speculative;
1034         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1035                 verbose(env, "The sequence of %d jumps is too complex.\n",
1036                         env->stack_size);
1037                 goto err;
1038         }
1039         if (elem->st.parent) {
1040                 ++elem->st.parent->branches;
1041                 /* WARN_ON(branches > 2) technically makes sense here,
1042                  * but
1043                  * 1. speculative states will bump 'branches' for non-branch
1044                  * instructions
1045                  * 2. is_state_visited() heuristics may decide not to create
1046                  * a new state for a sequence of branches and all such current
1047                  * and cloned states will be pointing to a single parent state
1048                  * which might have large 'branches' count.
1049                  */
1050         }
1051         return &elem->st;
1052 err:
1053         free_verifier_state(env->cur_state, true);
1054         env->cur_state = NULL;
1055         /* pop all elements and return */
1056         while (!pop_stack(env, NULL, NULL, false));
1057         return NULL;
1058 }
1059
1060 #define CALLER_SAVED_REGS 6
1061 static const int caller_saved[CALLER_SAVED_REGS] = {
1062         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1063 };
1064
1065 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1066                                 struct bpf_reg_state *reg);
1067
1068 /* This helper doesn't clear reg->id */
1069 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1070 {
1071         reg->var_off = tnum_const(imm);
1072         reg->smin_value = (s64)imm;
1073         reg->smax_value = (s64)imm;
1074         reg->umin_value = imm;
1075         reg->umax_value = imm;
1076
1077         reg->s32_min_value = (s32)imm;
1078         reg->s32_max_value = (s32)imm;
1079         reg->u32_min_value = (u32)imm;
1080         reg->u32_max_value = (u32)imm;
1081 }
1082
1083 /* Mark the unknown part of a register (variable offset or scalar value) as
1084  * known to have the value @imm.
1085  */
1086 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1087 {
1088         /* Clear id, off, and union(map_ptr, range) */
1089         memset(((u8 *)reg) + sizeof(reg->type), 0,
1090                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1091         ___mark_reg_known(reg, imm);
1092 }
1093
1094 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1095 {
1096         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1097         reg->s32_min_value = (s32)imm;
1098         reg->s32_max_value = (s32)imm;
1099         reg->u32_min_value = (u32)imm;
1100         reg->u32_max_value = (u32)imm;
1101 }
1102
1103 /* Mark the 'variable offset' part of a register as zero.  This should be
1104  * used only on registers holding a pointer type.
1105  */
1106 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1107 {
1108         __mark_reg_known(reg, 0);
1109 }
1110
1111 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1112 {
1113         __mark_reg_known(reg, 0);
1114         reg->type = SCALAR_VALUE;
1115 }
1116
1117 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1118                                 struct bpf_reg_state *regs, u32 regno)
1119 {
1120         if (WARN_ON(regno >= MAX_BPF_REG)) {
1121                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1122                 /* Something bad happened, let's kill all regs */
1123                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1124                         __mark_reg_not_init(env, regs + regno);
1125                 return;
1126         }
1127         __mark_reg_known_zero(regs + regno);
1128 }
1129
1130 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1131 {
1132         switch (reg->type) {
1133         case PTR_TO_MAP_VALUE_OR_NULL: {
1134                 const struct bpf_map *map = reg->map_ptr;
1135
1136                 if (map->inner_map_meta) {
1137                         reg->type = CONST_PTR_TO_MAP;
1138                         reg->map_ptr = map->inner_map_meta;
1139                         /* transfer reg's id which is unique for every map_lookup_elem
1140                          * as UID of the inner map.
1141                          */
1142                         reg->map_uid = reg->id;
1143                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1144                         reg->type = PTR_TO_XDP_SOCK;
1145                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1146                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1147                         reg->type = PTR_TO_SOCKET;
1148                 } else {
1149                         reg->type = PTR_TO_MAP_VALUE;
1150                 }
1151                 break;
1152         }
1153         case PTR_TO_SOCKET_OR_NULL:
1154                 reg->type = PTR_TO_SOCKET;
1155                 break;
1156         case PTR_TO_SOCK_COMMON_OR_NULL:
1157                 reg->type = PTR_TO_SOCK_COMMON;
1158                 break;
1159         case PTR_TO_TCP_SOCK_OR_NULL:
1160                 reg->type = PTR_TO_TCP_SOCK;
1161                 break;
1162         case PTR_TO_BTF_ID_OR_NULL:
1163                 reg->type = PTR_TO_BTF_ID;
1164                 break;
1165         case PTR_TO_MEM_OR_NULL:
1166                 reg->type = PTR_TO_MEM;
1167                 break;
1168         case PTR_TO_RDONLY_BUF_OR_NULL:
1169                 reg->type = PTR_TO_RDONLY_BUF;
1170                 break;
1171         case PTR_TO_RDWR_BUF_OR_NULL:
1172                 reg->type = PTR_TO_RDWR_BUF;
1173                 break;
1174         default:
1175                 WARN_ONCE(1, "unknown nullable register type");
1176         }
1177 }
1178
1179 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1180 {
1181         return type_is_pkt_pointer(reg->type);
1182 }
1183
1184 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1185 {
1186         return reg_is_pkt_pointer(reg) ||
1187                reg->type == PTR_TO_PACKET_END;
1188 }
1189
1190 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1191 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1192                                     enum bpf_reg_type which)
1193 {
1194         /* The register can already have a range from prior markings.
1195          * This is fine as long as it hasn't been advanced from its
1196          * origin.
1197          */
1198         return reg->type == which &&
1199                reg->id == 0 &&
1200                reg->off == 0 &&
1201                tnum_equals_const(reg->var_off, 0);
1202 }
1203
1204 /* Reset the min/max bounds of a register */
1205 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1206 {
1207         reg->smin_value = S64_MIN;
1208         reg->smax_value = S64_MAX;
1209         reg->umin_value = 0;
1210         reg->umax_value = U64_MAX;
1211
1212         reg->s32_min_value = S32_MIN;
1213         reg->s32_max_value = S32_MAX;
1214         reg->u32_min_value = 0;
1215         reg->u32_max_value = U32_MAX;
1216 }
1217
1218 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1219 {
1220         reg->smin_value = S64_MIN;
1221         reg->smax_value = S64_MAX;
1222         reg->umin_value = 0;
1223         reg->umax_value = U64_MAX;
1224 }
1225
1226 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1227 {
1228         reg->s32_min_value = S32_MIN;
1229         reg->s32_max_value = S32_MAX;
1230         reg->u32_min_value = 0;
1231         reg->u32_max_value = U32_MAX;
1232 }
1233
1234 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1235 {
1236         struct tnum var32_off = tnum_subreg(reg->var_off);
1237
1238         /* min signed is max(sign bit) | min(other bits) */
1239         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1240                         var32_off.value | (var32_off.mask & S32_MIN));
1241         /* max signed is min(sign bit) | max(other bits) */
1242         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1243                         var32_off.value | (var32_off.mask & S32_MAX));
1244         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1245         reg->u32_max_value = min(reg->u32_max_value,
1246                                  (u32)(var32_off.value | var32_off.mask));
1247 }
1248
1249 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1250 {
1251         /* min signed is max(sign bit) | min(other bits) */
1252         reg->smin_value = max_t(s64, reg->smin_value,
1253                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1254         /* max signed is min(sign bit) | max(other bits) */
1255         reg->smax_value = min_t(s64, reg->smax_value,
1256                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1257         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1258         reg->umax_value = min(reg->umax_value,
1259                               reg->var_off.value | reg->var_off.mask);
1260 }
1261
1262 static void __update_reg_bounds(struct bpf_reg_state *reg)
1263 {
1264         __update_reg32_bounds(reg);
1265         __update_reg64_bounds(reg);
1266 }
1267
1268 /* Uses signed min/max values to inform unsigned, and vice-versa */
1269 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1270 {
1271         /* Learn sign from signed bounds.
1272          * If we cannot cross the sign boundary, then signed and unsigned bounds
1273          * are the same, so combine.  This works even in the negative case, e.g.
1274          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1275          */
1276         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1277                 reg->s32_min_value = reg->u32_min_value =
1278                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1279                 reg->s32_max_value = reg->u32_max_value =
1280                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1281                 return;
1282         }
1283         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1284          * boundary, so we must be careful.
1285          */
1286         if ((s32)reg->u32_max_value >= 0) {
1287                 /* Positive.  We can't learn anything from the smin, but smax
1288                  * is positive, hence safe.
1289                  */
1290                 reg->s32_min_value = reg->u32_min_value;
1291                 reg->s32_max_value = reg->u32_max_value =
1292                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1293         } else if ((s32)reg->u32_min_value < 0) {
1294                 /* Negative.  We can't learn anything from the smax, but smin
1295                  * is negative, hence safe.
1296                  */
1297                 reg->s32_min_value = reg->u32_min_value =
1298                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1299                 reg->s32_max_value = reg->u32_max_value;
1300         }
1301 }
1302
1303 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1304 {
1305         /* Learn sign from signed bounds.
1306          * If we cannot cross the sign boundary, then signed and unsigned bounds
1307          * are the same, so combine.  This works even in the negative case, e.g.
1308          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1309          */
1310         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1311                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1312                                                           reg->umin_value);
1313                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1314                                                           reg->umax_value);
1315                 return;
1316         }
1317         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1318          * boundary, so we must be careful.
1319          */
1320         if ((s64)reg->umax_value >= 0) {
1321                 /* Positive.  We can't learn anything from the smin, but smax
1322                  * is positive, hence safe.
1323                  */
1324                 reg->smin_value = reg->umin_value;
1325                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1326                                                           reg->umax_value);
1327         } else if ((s64)reg->umin_value < 0) {
1328                 /* Negative.  We can't learn anything from the smax, but smin
1329                  * is negative, hence safe.
1330                  */
1331                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1332                                                           reg->umin_value);
1333                 reg->smax_value = reg->umax_value;
1334         }
1335 }
1336
1337 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1338 {
1339         __reg32_deduce_bounds(reg);
1340         __reg64_deduce_bounds(reg);
1341 }
1342
1343 /* Attempts to improve var_off based on unsigned min/max information */
1344 static void __reg_bound_offset(struct bpf_reg_state *reg)
1345 {
1346         struct tnum var64_off = tnum_intersect(reg->var_off,
1347                                                tnum_range(reg->umin_value,
1348                                                           reg->umax_value));
1349         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1350                                                 tnum_range(reg->u32_min_value,
1351                                                            reg->u32_max_value));
1352
1353         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1354 }
1355
1356 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1357 {
1358         reg->umin_value = reg->u32_min_value;
1359         reg->umax_value = reg->u32_max_value;
1360         /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1361          * but must be positive otherwise set to worse case bounds
1362          * and refine later from tnum.
1363          */
1364         if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1365                 reg->smax_value = reg->s32_max_value;
1366         else
1367                 reg->smax_value = U32_MAX;
1368         if (reg->s32_min_value >= 0)
1369                 reg->smin_value = reg->s32_min_value;
1370         else
1371                 reg->smin_value = 0;
1372 }
1373
1374 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1375 {
1376         /* special case when 64-bit register has upper 32-bit register
1377          * zeroed. Typically happens after zext or <<32, >>32 sequence
1378          * allowing us to use 32-bit bounds directly,
1379          */
1380         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1381                 __reg_assign_32_into_64(reg);
1382         } else {
1383                 /* Otherwise the best we can do is push lower 32bit known and
1384                  * unknown bits into register (var_off set from jmp logic)
1385                  * then learn as much as possible from the 64-bit tnum
1386                  * known and unknown bits. The previous smin/smax bounds are
1387                  * invalid here because of jmp32 compare so mark them unknown
1388                  * so they do not impact tnum bounds calculation.
1389                  */
1390                 __mark_reg64_unbounded(reg);
1391                 __update_reg_bounds(reg);
1392         }
1393
1394         /* Intersecting with the old var_off might have improved our bounds
1395          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1396          * then new var_off is (0; 0x7f...fc) which improves our umax.
1397          */
1398         __reg_deduce_bounds(reg);
1399         __reg_bound_offset(reg);
1400         __update_reg_bounds(reg);
1401 }
1402
1403 static bool __reg64_bound_s32(s64 a)
1404 {
1405         return a > S32_MIN && a < S32_MAX;
1406 }
1407
1408 static bool __reg64_bound_u32(u64 a)
1409 {
1410         return a > U32_MIN && a < U32_MAX;
1411 }
1412
1413 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1414 {
1415         __mark_reg32_unbounded(reg);
1416
1417         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1418                 reg->s32_min_value = (s32)reg->smin_value;
1419                 reg->s32_max_value = (s32)reg->smax_value;
1420         }
1421         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1422                 reg->u32_min_value = (u32)reg->umin_value;
1423                 reg->u32_max_value = (u32)reg->umax_value;
1424         }
1425
1426         /* Intersecting with the old var_off might have improved our bounds
1427          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1428          * then new var_off is (0; 0x7f...fc) which improves our umax.
1429          */
1430         __reg_deduce_bounds(reg);
1431         __reg_bound_offset(reg);
1432         __update_reg_bounds(reg);
1433 }
1434
1435 /* Mark a register as having a completely unknown (scalar) value. */
1436 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1437                                struct bpf_reg_state *reg)
1438 {
1439         /*
1440          * Clear type, id, off, and union(map_ptr, range) and
1441          * padding between 'type' and union
1442          */
1443         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1444         reg->type = SCALAR_VALUE;
1445         reg->var_off = tnum_unknown;
1446         reg->frameno = 0;
1447         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1448         __mark_reg_unbounded(reg);
1449 }
1450
1451 static void mark_reg_unknown(struct bpf_verifier_env *env,
1452                              struct bpf_reg_state *regs, u32 regno)
1453 {
1454         if (WARN_ON(regno >= MAX_BPF_REG)) {
1455                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1456                 /* Something bad happened, let's kill all regs except FP */
1457                 for (regno = 0; regno < BPF_REG_FP; regno++)
1458                         __mark_reg_not_init(env, regs + regno);
1459                 return;
1460         }
1461         __mark_reg_unknown(env, regs + regno);
1462 }
1463
1464 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1465                                 struct bpf_reg_state *reg)
1466 {
1467         __mark_reg_unknown(env, reg);
1468         reg->type = NOT_INIT;
1469 }
1470
1471 static void mark_reg_not_init(struct bpf_verifier_env *env,
1472                               struct bpf_reg_state *regs, u32 regno)
1473 {
1474         if (WARN_ON(regno >= MAX_BPF_REG)) {
1475                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1476                 /* Something bad happened, let's kill all regs except FP */
1477                 for (regno = 0; regno < BPF_REG_FP; regno++)
1478                         __mark_reg_not_init(env, regs + regno);
1479                 return;
1480         }
1481         __mark_reg_not_init(env, regs + regno);
1482 }
1483
1484 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1485                             struct bpf_reg_state *regs, u32 regno,
1486                             enum bpf_reg_type reg_type,
1487                             struct btf *btf, u32 btf_id)
1488 {
1489         if (reg_type == SCALAR_VALUE) {
1490                 mark_reg_unknown(env, regs, regno);
1491                 return;
1492         }
1493         mark_reg_known_zero(env, regs, regno);
1494         regs[regno].type = PTR_TO_BTF_ID;
1495         regs[regno].btf = btf;
1496         regs[regno].btf_id = btf_id;
1497 }
1498
1499 #define DEF_NOT_SUBREG  (0)
1500 static void init_reg_state(struct bpf_verifier_env *env,
1501                            struct bpf_func_state *state)
1502 {
1503         struct bpf_reg_state *regs = state->regs;
1504         int i;
1505
1506         for (i = 0; i < MAX_BPF_REG; i++) {
1507                 mark_reg_not_init(env, regs, i);
1508                 regs[i].live = REG_LIVE_NONE;
1509                 regs[i].parent = NULL;
1510                 regs[i].subreg_def = DEF_NOT_SUBREG;
1511         }
1512
1513         /* frame pointer */
1514         regs[BPF_REG_FP].type = PTR_TO_STACK;
1515         mark_reg_known_zero(env, regs, BPF_REG_FP);
1516         regs[BPF_REG_FP].frameno = state->frameno;
1517 }
1518
1519 #define BPF_MAIN_FUNC (-1)
1520 static void init_func_state(struct bpf_verifier_env *env,
1521                             struct bpf_func_state *state,
1522                             int callsite, int frameno, int subprogno)
1523 {
1524         state->callsite = callsite;
1525         state->frameno = frameno;
1526         state->subprogno = subprogno;
1527         init_reg_state(env, state);
1528 }
1529
1530 enum reg_arg_type {
1531         SRC_OP,         /* register is used as source operand */
1532         DST_OP,         /* register is used as destination operand */
1533         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1534 };
1535
1536 static int cmp_subprogs(const void *a, const void *b)
1537 {
1538         return ((struct bpf_subprog_info *)a)->start -
1539                ((struct bpf_subprog_info *)b)->start;
1540 }
1541
1542 static int find_subprog(struct bpf_verifier_env *env, int off)
1543 {
1544         struct bpf_subprog_info *p;
1545
1546         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1547                     sizeof(env->subprog_info[0]), cmp_subprogs);
1548         if (!p)
1549                 return -ENOENT;
1550         return p - env->subprog_info;
1551
1552 }
1553
1554 static int add_subprog(struct bpf_verifier_env *env, int off)
1555 {
1556         int insn_cnt = env->prog->len;
1557         int ret;
1558
1559         if (off >= insn_cnt || off < 0) {
1560                 verbose(env, "call to invalid destination\n");
1561                 return -EINVAL;
1562         }
1563         ret = find_subprog(env, off);
1564         if (ret >= 0)
1565                 return ret;
1566         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1567                 verbose(env, "too many subprograms\n");
1568                 return -E2BIG;
1569         }
1570         /* determine subprog starts. The end is one before the next starts */
1571         env->subprog_info[env->subprog_cnt++].start = off;
1572         sort(env->subprog_info, env->subprog_cnt,
1573              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1574         return env->subprog_cnt - 1;
1575 }
1576
1577 struct bpf_kfunc_desc {
1578         struct btf_func_model func_model;
1579         u32 func_id;
1580         s32 imm;
1581 };
1582
1583 #define MAX_KFUNC_DESCS 256
1584 struct bpf_kfunc_desc_tab {
1585         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1586         u32 nr_descs;
1587 };
1588
1589 static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1590 {
1591         const struct bpf_kfunc_desc *d0 = a;
1592         const struct bpf_kfunc_desc *d1 = b;
1593
1594         /* func_id is not greater than BTF_MAX_TYPE */
1595         return d0->func_id - d1->func_id;
1596 }
1597
1598 static const struct bpf_kfunc_desc *
1599 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1600 {
1601         struct bpf_kfunc_desc desc = {
1602                 .func_id = func_id,
1603         };
1604         struct bpf_kfunc_desc_tab *tab;
1605
1606         tab = prog->aux->kfunc_tab;
1607         return bsearch(&desc, tab->descs, tab->nr_descs,
1608                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1609 }
1610
1611 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1612 {
1613         const struct btf_type *func, *func_proto;
1614         struct bpf_kfunc_desc_tab *tab;
1615         struct bpf_prog_aux *prog_aux;
1616         struct bpf_kfunc_desc *desc;
1617         const char *func_name;
1618         unsigned long addr;
1619         int err;
1620
1621         prog_aux = env->prog->aux;
1622         tab = prog_aux->kfunc_tab;
1623         if (!tab) {
1624                 if (!btf_vmlinux) {
1625                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1626                         return -ENOTSUPP;
1627                 }
1628
1629                 if (!env->prog->jit_requested) {
1630                         verbose(env, "JIT is required for calling kernel function\n");
1631                         return -ENOTSUPP;
1632                 }
1633
1634                 if (!bpf_jit_supports_kfunc_call()) {
1635                         verbose(env, "JIT does not support calling kernel function\n");
1636                         return -ENOTSUPP;
1637                 }
1638
1639                 if (!env->prog->gpl_compatible) {
1640                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1641                         return -EINVAL;
1642                 }
1643
1644                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1645                 if (!tab)
1646                         return -ENOMEM;
1647                 prog_aux->kfunc_tab = tab;
1648         }
1649
1650         if (find_kfunc_desc(env->prog, func_id))
1651                 return 0;
1652
1653         if (tab->nr_descs == MAX_KFUNC_DESCS) {
1654                 verbose(env, "too many different kernel function calls\n");
1655                 return -E2BIG;
1656         }
1657
1658         func = btf_type_by_id(btf_vmlinux, func_id);
1659         if (!func || !btf_type_is_func(func)) {
1660                 verbose(env, "kernel btf_id %u is not a function\n",
1661                         func_id);
1662                 return -EINVAL;
1663         }
1664         func_proto = btf_type_by_id(btf_vmlinux, func->type);
1665         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1666                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1667                         func_id);
1668                 return -EINVAL;
1669         }
1670
1671         func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1672         addr = kallsyms_lookup_name(func_name);
1673         if (!addr) {
1674                 verbose(env, "cannot find address for kernel function %s\n",
1675                         func_name);
1676                 return -EINVAL;
1677         }
1678
1679         desc = &tab->descs[tab->nr_descs++];
1680         desc->func_id = func_id;
1681         desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1682         err = btf_distill_func_proto(&env->log, btf_vmlinux,
1683                                      func_proto, func_name,
1684                                      &desc->func_model);
1685         if (!err)
1686                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1687                      kfunc_desc_cmp_by_id, NULL);
1688         return err;
1689 }
1690
1691 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1692 {
1693         const struct bpf_kfunc_desc *d0 = a;
1694         const struct bpf_kfunc_desc *d1 = b;
1695
1696         if (d0->imm > d1->imm)
1697                 return 1;
1698         else if (d0->imm < d1->imm)
1699                 return -1;
1700         return 0;
1701 }
1702
1703 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1704 {
1705         struct bpf_kfunc_desc_tab *tab;
1706
1707         tab = prog->aux->kfunc_tab;
1708         if (!tab)
1709                 return;
1710
1711         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1712              kfunc_desc_cmp_by_imm, NULL);
1713 }
1714
1715 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1716 {
1717         return !!prog->aux->kfunc_tab;
1718 }
1719
1720 const struct btf_func_model *
1721 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1722                          const struct bpf_insn *insn)
1723 {
1724         const struct bpf_kfunc_desc desc = {
1725                 .imm = insn->imm,
1726         };
1727         const struct bpf_kfunc_desc *res;
1728         struct bpf_kfunc_desc_tab *tab;
1729
1730         tab = prog->aux->kfunc_tab;
1731         res = bsearch(&desc, tab->descs, tab->nr_descs,
1732                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1733
1734         return res ? &res->func_model : NULL;
1735 }
1736
1737 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1738 {
1739         struct bpf_subprog_info *subprog = env->subprog_info;
1740         struct bpf_insn *insn = env->prog->insnsi;
1741         int i, ret, insn_cnt = env->prog->len;
1742
1743         /* Add entry function. */
1744         ret = add_subprog(env, 0);
1745         if (ret)
1746                 return ret;
1747
1748         for (i = 0; i < insn_cnt; i++, insn++) {
1749                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1750                     !bpf_pseudo_kfunc_call(insn))
1751                         continue;
1752
1753                 if (!env->bpf_capable) {
1754                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1755                         return -EPERM;
1756                 }
1757
1758                 if (bpf_pseudo_func(insn)) {
1759                         ret = add_subprog(env, i + insn->imm + 1);
1760                         if (ret >= 0)
1761                                 /* remember subprog */
1762                                 insn[1].imm = ret;
1763                 } else if (bpf_pseudo_call(insn)) {
1764                         ret = add_subprog(env, i + insn->imm + 1);
1765                 } else {
1766                         ret = add_kfunc_call(env, insn->imm);
1767                 }
1768
1769                 if (ret < 0)
1770                         return ret;
1771         }
1772
1773         /* Add a fake 'exit' subprog which could simplify subprog iteration
1774          * logic. 'subprog_cnt' should not be increased.
1775          */
1776         subprog[env->subprog_cnt].start = insn_cnt;
1777
1778         if (env->log.level & BPF_LOG_LEVEL2)
1779                 for (i = 0; i < env->subprog_cnt; i++)
1780                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
1781
1782         return 0;
1783 }
1784
1785 static int check_subprogs(struct bpf_verifier_env *env)
1786 {
1787         int i, subprog_start, subprog_end, off, cur_subprog = 0;
1788         struct bpf_subprog_info *subprog = env->subprog_info;
1789         struct bpf_insn *insn = env->prog->insnsi;
1790         int insn_cnt = env->prog->len;
1791
1792         /* now check that all jumps are within the same subprog */
1793         subprog_start = subprog[cur_subprog].start;
1794         subprog_end = subprog[cur_subprog + 1].start;
1795         for (i = 0; i < insn_cnt; i++) {
1796                 u8 code = insn[i].code;
1797
1798                 if (code == (BPF_JMP | BPF_CALL) &&
1799                     insn[i].imm == BPF_FUNC_tail_call &&
1800                     insn[i].src_reg != BPF_PSEUDO_CALL)
1801                         subprog[cur_subprog].has_tail_call = true;
1802                 if (BPF_CLASS(code) == BPF_LD &&
1803                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1804                         subprog[cur_subprog].has_ld_abs = true;
1805                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1806                         goto next;
1807                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1808                         goto next;
1809                 off = i + insn[i].off + 1;
1810                 if (off < subprog_start || off >= subprog_end) {
1811                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
1812                         return -EINVAL;
1813                 }
1814 next:
1815                 if (i == subprog_end - 1) {
1816                         /* to avoid fall-through from one subprog into another
1817                          * the last insn of the subprog should be either exit
1818                          * or unconditional jump back
1819                          */
1820                         if (code != (BPF_JMP | BPF_EXIT) &&
1821                             code != (BPF_JMP | BPF_JA)) {
1822                                 verbose(env, "last insn is not an exit or jmp\n");
1823                                 return -EINVAL;
1824                         }
1825                         subprog_start = subprog_end;
1826                         cur_subprog++;
1827                         if (cur_subprog < env->subprog_cnt)
1828                                 subprog_end = subprog[cur_subprog + 1].start;
1829                 }
1830         }
1831         return 0;
1832 }
1833
1834 /* Parentage chain of this register (or stack slot) should take care of all
1835  * issues like callee-saved registers, stack slot allocation time, etc.
1836  */
1837 static int mark_reg_read(struct bpf_verifier_env *env,
1838                          const struct bpf_reg_state *state,
1839                          struct bpf_reg_state *parent, u8 flag)
1840 {
1841         bool writes = parent == state->parent; /* Observe write marks */
1842         int cnt = 0;
1843
1844         while (parent) {
1845                 /* if read wasn't screened by an earlier write ... */
1846                 if (writes && state->live & REG_LIVE_WRITTEN)
1847                         break;
1848                 if (parent->live & REG_LIVE_DONE) {
1849                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1850                                 reg_type_str[parent->type],
1851                                 parent->var_off.value, parent->off);
1852                         return -EFAULT;
1853                 }
1854                 /* The first condition is more likely to be true than the
1855                  * second, checked it first.
1856                  */
1857                 if ((parent->live & REG_LIVE_READ) == flag ||
1858                     parent->live & REG_LIVE_READ64)
1859                         /* The parentage chain never changes and
1860                          * this parent was already marked as LIVE_READ.
1861                          * There is no need to keep walking the chain again and
1862                          * keep re-marking all parents as LIVE_READ.
1863                          * This case happens when the same register is read
1864                          * multiple times without writes into it in-between.
1865                          * Also, if parent has the stronger REG_LIVE_READ64 set,
1866                          * then no need to set the weak REG_LIVE_READ32.
1867                          */
1868                         break;
1869                 /* ... then we depend on parent's value */
1870                 parent->live |= flag;
1871                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1872                 if (flag == REG_LIVE_READ64)
1873                         parent->live &= ~REG_LIVE_READ32;
1874                 state = parent;
1875                 parent = state->parent;
1876                 writes = true;
1877                 cnt++;
1878         }
1879
1880         if (env->longest_mark_read_walk < cnt)
1881                 env->longest_mark_read_walk = cnt;
1882         return 0;
1883 }
1884
1885 /* This function is supposed to be used by the following 32-bit optimization
1886  * code only. It returns TRUE if the source or destination register operates
1887  * on 64-bit, otherwise return FALSE.
1888  */
1889 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1890                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1891 {
1892         u8 code, class, op;
1893
1894         code = insn->code;
1895         class = BPF_CLASS(code);
1896         op = BPF_OP(code);
1897         if (class == BPF_JMP) {
1898                 /* BPF_EXIT for "main" will reach here. Return TRUE
1899                  * conservatively.
1900                  */
1901                 if (op == BPF_EXIT)
1902                         return true;
1903                 if (op == BPF_CALL) {
1904                         /* BPF to BPF call will reach here because of marking
1905                          * caller saved clobber with DST_OP_NO_MARK for which we
1906                          * don't care the register def because they are anyway
1907                          * marked as NOT_INIT already.
1908                          */
1909                         if (insn->src_reg == BPF_PSEUDO_CALL)
1910                                 return false;
1911                         /* Helper call will reach here because of arg type
1912                          * check, conservatively return TRUE.
1913                          */
1914                         if (t == SRC_OP)
1915                                 return true;
1916
1917                         return false;
1918                 }
1919         }
1920
1921         if (class == BPF_ALU64 || class == BPF_JMP ||
1922             /* BPF_END always use BPF_ALU class. */
1923             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1924                 return true;
1925
1926         if (class == BPF_ALU || class == BPF_JMP32)
1927                 return false;
1928
1929         if (class == BPF_LDX) {
1930                 if (t != SRC_OP)
1931                         return BPF_SIZE(code) == BPF_DW;
1932                 /* LDX source must be ptr. */
1933                 return true;
1934         }
1935
1936         if (class == BPF_STX) {
1937                 /* BPF_STX (including atomic variants) has multiple source
1938                  * operands, one of which is a ptr. Check whether the caller is
1939                  * asking about it.
1940                  */
1941                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
1942                         return true;
1943                 return BPF_SIZE(code) == BPF_DW;
1944         }
1945
1946         if (class == BPF_LD) {
1947                 u8 mode = BPF_MODE(code);
1948
1949                 /* LD_IMM64 */
1950                 if (mode == BPF_IMM)
1951                         return true;
1952
1953                 /* Both LD_IND and LD_ABS return 32-bit data. */
1954                 if (t != SRC_OP)
1955                         return  false;
1956
1957                 /* Implicit ctx ptr. */
1958                 if (regno == BPF_REG_6)
1959                         return true;
1960
1961                 /* Explicit source could be any width. */
1962                 return true;
1963         }
1964
1965         if (class == BPF_ST)
1966                 /* The only source register for BPF_ST is a ptr. */
1967                 return true;
1968
1969         /* Conservatively return true at default. */
1970         return true;
1971 }
1972
1973 /* Return the regno defined by the insn, or -1. */
1974 static int insn_def_regno(const struct bpf_insn *insn)
1975 {
1976         switch (BPF_CLASS(insn->code)) {
1977         case BPF_JMP:
1978         case BPF_JMP32:
1979         case BPF_ST:
1980                 return -1;
1981         case BPF_STX:
1982                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1983                     (insn->imm & BPF_FETCH)) {
1984                         if (insn->imm == BPF_CMPXCHG)
1985                                 return BPF_REG_0;
1986                         else
1987                                 return insn->src_reg;
1988                 } else {
1989                         return -1;
1990                 }
1991         default:
1992                 return insn->dst_reg;
1993         }
1994 }
1995
1996 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1997 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1998 {
1999         int dst_reg = insn_def_regno(insn);
2000
2001         if (dst_reg == -1)
2002                 return false;
2003
2004         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2005 }
2006
2007 static void mark_insn_zext(struct bpf_verifier_env *env,
2008                            struct bpf_reg_state *reg)
2009 {
2010         s32 def_idx = reg->subreg_def;
2011
2012         if (def_idx == DEF_NOT_SUBREG)
2013                 return;
2014
2015         env->insn_aux_data[def_idx - 1].zext_dst = true;
2016         /* The dst will be zero extended, so won't be sub-register anymore. */
2017         reg->subreg_def = DEF_NOT_SUBREG;
2018 }
2019
2020 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2021                          enum reg_arg_type t)
2022 {
2023         struct bpf_verifier_state *vstate = env->cur_state;
2024         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2025         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2026         struct bpf_reg_state *reg, *regs = state->regs;
2027         bool rw64;
2028
2029         if (regno >= MAX_BPF_REG) {
2030                 verbose(env, "R%d is invalid\n", regno);
2031                 return -EINVAL;
2032         }
2033
2034         reg = &regs[regno];
2035         rw64 = is_reg64(env, insn, regno, reg, t);
2036         if (t == SRC_OP) {
2037                 /* check whether register used as source operand can be read */
2038                 if (reg->type == NOT_INIT) {
2039                         verbose(env, "R%d !read_ok\n", regno);
2040                         return -EACCES;
2041                 }
2042                 /* We don't need to worry about FP liveness because it's read-only */
2043                 if (regno == BPF_REG_FP)
2044                         return 0;
2045
2046                 if (rw64)
2047                         mark_insn_zext(env, reg);
2048
2049                 return mark_reg_read(env, reg, reg->parent,
2050                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2051         } else {
2052                 /* check whether register used as dest operand can be written to */
2053                 if (regno == BPF_REG_FP) {
2054                         verbose(env, "frame pointer is read only\n");
2055                         return -EACCES;
2056                 }
2057                 reg->live |= REG_LIVE_WRITTEN;
2058                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2059                 if (t == DST_OP)
2060                         mark_reg_unknown(env, regs, regno);
2061         }
2062         return 0;
2063 }
2064
2065 /* for any branch, call, exit record the history of jmps in the given state */
2066 static int push_jmp_history(struct bpf_verifier_env *env,
2067                             struct bpf_verifier_state *cur)
2068 {
2069         u32 cnt = cur->jmp_history_cnt;
2070         struct bpf_idx_pair *p;
2071
2072         cnt++;
2073         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2074         if (!p)
2075                 return -ENOMEM;
2076         p[cnt - 1].idx = env->insn_idx;
2077         p[cnt - 1].prev_idx = env->prev_insn_idx;
2078         cur->jmp_history = p;
2079         cur->jmp_history_cnt = cnt;
2080         return 0;
2081 }
2082
2083 /* Backtrack one insn at a time. If idx is not at the top of recorded
2084  * history then previous instruction came from straight line execution.
2085  */
2086 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2087                              u32 *history)
2088 {
2089         u32 cnt = *history;
2090
2091         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2092                 i = st->jmp_history[cnt - 1].prev_idx;
2093                 (*history)--;
2094         } else {
2095                 i--;
2096         }
2097         return i;
2098 }
2099
2100 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2101 {
2102         const struct btf_type *func;
2103
2104         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2105                 return NULL;
2106
2107         func = btf_type_by_id(btf_vmlinux, insn->imm);
2108         return btf_name_by_offset(btf_vmlinux, func->name_off);
2109 }
2110
2111 /* For given verifier state backtrack_insn() is called from the last insn to
2112  * the first insn. Its purpose is to compute a bitmask of registers and
2113  * stack slots that needs precision in the parent verifier state.
2114  */
2115 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2116                           u32 *reg_mask, u64 *stack_mask)
2117 {
2118         const struct bpf_insn_cbs cbs = {
2119                 .cb_call        = disasm_kfunc_name,
2120                 .cb_print       = verbose,
2121                 .private_data   = env,
2122         };
2123         struct bpf_insn *insn = env->prog->insnsi + idx;
2124         u8 class = BPF_CLASS(insn->code);
2125         u8 opcode = BPF_OP(insn->code);
2126         u8 mode = BPF_MODE(insn->code);
2127         u32 dreg = 1u << insn->dst_reg;
2128         u32 sreg = 1u << insn->src_reg;
2129         u32 spi;
2130
2131         if (insn->code == 0)
2132                 return 0;
2133         if (env->log.level & BPF_LOG_LEVEL) {
2134                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2135                 verbose(env, "%d: ", idx);
2136                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2137         }
2138
2139         if (class == BPF_ALU || class == BPF_ALU64) {
2140                 if (!(*reg_mask & dreg))
2141                         return 0;
2142                 if (opcode == BPF_MOV) {
2143                         if (BPF_SRC(insn->code) == BPF_X) {
2144                                 /* dreg = sreg
2145                                  * dreg needs precision after this insn
2146                                  * sreg needs precision before this insn
2147                                  */
2148                                 *reg_mask &= ~dreg;
2149                                 *reg_mask |= sreg;
2150                         } else {
2151                                 /* dreg = K
2152                                  * dreg needs precision after this insn.
2153                                  * Corresponding register is already marked
2154                                  * as precise=true in this verifier state.
2155                                  * No further markings in parent are necessary
2156                                  */
2157                                 *reg_mask &= ~dreg;
2158                         }
2159                 } else {
2160                         if (BPF_SRC(insn->code) == BPF_X) {
2161                                 /* dreg += sreg
2162                                  * both dreg and sreg need precision
2163                                  * before this insn
2164                                  */
2165                                 *reg_mask |= sreg;
2166                         } /* else dreg += K
2167                            * dreg still needs precision before this insn
2168                            */
2169                 }
2170         } else if (class == BPF_LDX) {
2171                 if (!(*reg_mask & dreg))
2172                         return 0;
2173                 *reg_mask &= ~dreg;
2174
2175                 /* scalars can only be spilled into stack w/o losing precision.
2176                  * Load from any other memory can be zero extended.
2177                  * The desire to keep that precision is already indicated
2178                  * by 'precise' mark in corresponding register of this state.
2179                  * No further tracking necessary.
2180                  */
2181                 if (insn->src_reg != BPF_REG_FP)
2182                         return 0;
2183                 if (BPF_SIZE(insn->code) != BPF_DW)
2184                         return 0;
2185
2186                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2187                  * that [fp - off] slot contains scalar that needs to be
2188                  * tracked with precision
2189                  */
2190                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2191                 if (spi >= 64) {
2192                         verbose(env, "BUG spi %d\n", spi);
2193                         WARN_ONCE(1, "verifier backtracking bug");
2194                         return -EFAULT;
2195                 }
2196                 *stack_mask |= 1ull << spi;
2197         } else if (class == BPF_STX || class == BPF_ST) {
2198                 if (*reg_mask & dreg)
2199                         /* stx & st shouldn't be using _scalar_ dst_reg
2200                          * to access memory. It means backtracking
2201                          * encountered a case of pointer subtraction.
2202                          */
2203                         return -ENOTSUPP;
2204                 /* scalars can only be spilled into stack */
2205                 if (insn->dst_reg != BPF_REG_FP)
2206                         return 0;
2207                 if (BPF_SIZE(insn->code) != BPF_DW)
2208                         return 0;
2209                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2210                 if (spi >= 64) {
2211                         verbose(env, "BUG spi %d\n", spi);
2212                         WARN_ONCE(1, "verifier backtracking bug");
2213                         return -EFAULT;
2214                 }
2215                 if (!(*stack_mask & (1ull << spi)))
2216                         return 0;
2217                 *stack_mask &= ~(1ull << spi);
2218                 if (class == BPF_STX)
2219                         *reg_mask |= sreg;
2220         } else if (class == BPF_JMP || class == BPF_JMP32) {
2221                 if (opcode == BPF_CALL) {
2222                         if (insn->src_reg == BPF_PSEUDO_CALL)
2223                                 return -ENOTSUPP;
2224                         /* regular helper call sets R0 */
2225                         *reg_mask &= ~1;
2226                         if (*reg_mask & 0x3f) {
2227                                 /* if backtracing was looking for registers R1-R5
2228                                  * they should have been found already.
2229                                  */
2230                                 verbose(env, "BUG regs %x\n", *reg_mask);
2231                                 WARN_ONCE(1, "verifier backtracking bug");
2232                                 return -EFAULT;
2233                         }
2234                 } else if (opcode == BPF_EXIT) {
2235                         return -ENOTSUPP;
2236                 }
2237         } else if (class == BPF_LD) {
2238                 if (!(*reg_mask & dreg))
2239                         return 0;
2240                 *reg_mask &= ~dreg;
2241                 /* It's ld_imm64 or ld_abs or ld_ind.
2242                  * For ld_imm64 no further tracking of precision
2243                  * into parent is necessary
2244                  */
2245                 if (mode == BPF_IND || mode == BPF_ABS)
2246                         /* to be analyzed */
2247                         return -ENOTSUPP;
2248         }
2249         return 0;
2250 }
2251
2252 /* the scalar precision tracking algorithm:
2253  * . at the start all registers have precise=false.
2254  * . scalar ranges are tracked as normal through alu and jmp insns.
2255  * . once precise value of the scalar register is used in:
2256  *   .  ptr + scalar alu
2257  *   . if (scalar cond K|scalar)
2258  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2259  *   backtrack through the verifier states and mark all registers and
2260  *   stack slots with spilled constants that these scalar regisers
2261  *   should be precise.
2262  * . during state pruning two registers (or spilled stack slots)
2263  *   are equivalent if both are not precise.
2264  *
2265  * Note the verifier cannot simply walk register parentage chain,
2266  * since many different registers and stack slots could have been
2267  * used to compute single precise scalar.
2268  *
2269  * The approach of starting with precise=true for all registers and then
2270  * backtrack to mark a register as not precise when the verifier detects
2271  * that program doesn't care about specific value (e.g., when helper
2272  * takes register as ARG_ANYTHING parameter) is not safe.
2273  *
2274  * It's ok to walk single parentage chain of the verifier states.
2275  * It's possible that this backtracking will go all the way till 1st insn.
2276  * All other branches will be explored for needing precision later.
2277  *
2278  * The backtracking needs to deal with cases like:
2279  *   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)
2280  * r9 -= r8
2281  * r5 = r9
2282  * if r5 > 0x79f goto pc+7
2283  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2284  * r5 += 1
2285  * ...
2286  * call bpf_perf_event_output#25
2287  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2288  *
2289  * and this case:
2290  * r6 = 1
2291  * call foo // uses callee's r6 inside to compute r0
2292  * r0 += r6
2293  * if r0 == 0 goto
2294  *
2295  * to track above reg_mask/stack_mask needs to be independent for each frame.
2296  *
2297  * Also if parent's curframe > frame where backtracking started,
2298  * the verifier need to mark registers in both frames, otherwise callees
2299  * may incorrectly prune callers. This is similar to
2300  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2301  *
2302  * For now backtracking falls back into conservative marking.
2303  */
2304 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2305                                      struct bpf_verifier_state *st)
2306 {
2307         struct bpf_func_state *func;
2308         struct bpf_reg_state *reg;
2309         int i, j;
2310
2311         /* big hammer: mark all scalars precise in this path.
2312          * pop_stack may still get !precise scalars.
2313          */
2314         for (; st; st = st->parent)
2315                 for (i = 0; i <= st->curframe; i++) {
2316                         func = st->frame[i];
2317                         for (j = 0; j < BPF_REG_FP; j++) {
2318                                 reg = &func->regs[j];
2319                                 if (reg->type != SCALAR_VALUE)
2320                                         continue;
2321                                 reg->precise = true;
2322                         }
2323                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2324                                 if (func->stack[j].slot_type[0] != STACK_SPILL)
2325                                         continue;
2326                                 reg = &func->stack[j].spilled_ptr;
2327                                 if (reg->type != SCALAR_VALUE)
2328                                         continue;
2329                                 reg->precise = true;
2330                         }
2331                 }
2332 }
2333
2334 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2335                                   int spi)
2336 {
2337         struct bpf_verifier_state *st = env->cur_state;
2338         int first_idx = st->first_insn_idx;
2339         int last_idx = env->insn_idx;
2340         struct bpf_func_state *func;
2341         struct bpf_reg_state *reg;
2342         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2343         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2344         bool skip_first = true;
2345         bool new_marks = false;
2346         int i, err;
2347
2348         if (!env->bpf_capable)
2349                 return 0;
2350
2351         func = st->frame[st->curframe];
2352         if (regno >= 0) {
2353                 reg = &func->regs[regno];
2354                 if (reg->type != SCALAR_VALUE) {
2355                         WARN_ONCE(1, "backtracing misuse");
2356                         return -EFAULT;
2357                 }
2358                 if (!reg->precise)
2359                         new_marks = true;
2360                 else
2361                         reg_mask = 0;
2362                 reg->precise = true;
2363         }
2364
2365         while (spi >= 0) {
2366                 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2367                         stack_mask = 0;
2368                         break;
2369                 }
2370                 reg = &func->stack[spi].spilled_ptr;
2371                 if (reg->type != SCALAR_VALUE) {
2372                         stack_mask = 0;
2373                         break;
2374                 }
2375                 if (!reg->precise)
2376                         new_marks = true;
2377                 else
2378                         stack_mask = 0;
2379                 reg->precise = true;
2380                 break;
2381         }
2382
2383         if (!new_marks)
2384                 return 0;
2385         if (!reg_mask && !stack_mask)
2386                 return 0;
2387         for (;;) {
2388                 DECLARE_BITMAP(mask, 64);
2389                 u32 history = st->jmp_history_cnt;
2390
2391                 if (env->log.level & BPF_LOG_LEVEL)
2392                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2393                 for (i = last_idx;;) {
2394                         if (skip_first) {
2395                                 err = 0;
2396                                 skip_first = false;
2397                         } else {
2398                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2399                         }
2400                         if (err == -ENOTSUPP) {
2401                                 mark_all_scalars_precise(env, st);
2402                                 return 0;
2403                         } else if (err) {
2404                                 return err;
2405                         }
2406                         if (!reg_mask && !stack_mask)
2407                                 /* Found assignment(s) into tracked register in this state.
2408                                  * Since this state is already marked, just return.
2409                                  * Nothing to be tracked further in the parent state.
2410                                  */
2411                                 return 0;
2412                         if (i == first_idx)
2413                                 break;
2414                         i = get_prev_insn_idx(st, i, &history);
2415                         if (i >= env->prog->len) {
2416                                 /* This can happen if backtracking reached insn 0
2417                                  * and there are still reg_mask or stack_mask
2418                                  * to backtrack.
2419                                  * It means the backtracking missed the spot where
2420                                  * particular register was initialized with a constant.
2421                                  */
2422                                 verbose(env, "BUG backtracking idx %d\n", i);
2423                                 WARN_ONCE(1, "verifier backtracking bug");
2424                                 return -EFAULT;
2425                         }
2426                 }
2427                 st = st->parent;
2428                 if (!st)
2429                         break;
2430
2431                 new_marks = false;
2432                 func = st->frame[st->curframe];
2433                 bitmap_from_u64(mask, reg_mask);
2434                 for_each_set_bit(i, mask, 32) {
2435                         reg = &func->regs[i];
2436                         if (reg->type != SCALAR_VALUE) {
2437                                 reg_mask &= ~(1u << i);
2438                                 continue;
2439                         }
2440                         if (!reg->precise)
2441                                 new_marks = true;
2442                         reg->precise = true;
2443                 }
2444
2445                 bitmap_from_u64(mask, stack_mask);
2446                 for_each_set_bit(i, mask, 64) {
2447                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2448                                 /* the sequence of instructions:
2449                                  * 2: (bf) r3 = r10
2450                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2451                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2452                                  * doesn't contain jmps. It's backtracked
2453                                  * as a single block.
2454                                  * During backtracking insn 3 is not recognized as
2455                                  * stack access, so at the end of backtracking
2456                                  * stack slot fp-8 is still marked in stack_mask.
2457                                  * However the parent state may not have accessed
2458                                  * fp-8 and it's "unallocated" stack space.
2459                                  * In such case fallback to conservative.
2460                                  */
2461                                 mark_all_scalars_precise(env, st);
2462                                 return 0;
2463                         }
2464
2465                         if (func->stack[i].slot_type[0] != STACK_SPILL) {
2466                                 stack_mask &= ~(1ull << i);
2467                                 continue;
2468                         }
2469                         reg = &func->stack[i].spilled_ptr;
2470                         if (reg->type != SCALAR_VALUE) {
2471                                 stack_mask &= ~(1ull << i);
2472                                 continue;
2473                         }
2474                         if (!reg->precise)
2475                                 new_marks = true;
2476                         reg->precise = true;
2477                 }
2478                 if (env->log.level & BPF_LOG_LEVEL) {
2479                         print_verifier_state(env, func);
2480                         verbose(env, "parent %s regs=%x stack=%llx marks\n",
2481                                 new_marks ? "didn't have" : "already had",
2482                                 reg_mask, stack_mask);
2483                 }
2484
2485                 if (!reg_mask && !stack_mask)
2486                         break;
2487                 if (!new_marks)
2488                         break;
2489
2490                 last_idx = st->last_insn_idx;
2491                 first_idx = st->first_insn_idx;
2492         }
2493         return 0;
2494 }
2495
2496 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2497 {
2498         return __mark_chain_precision(env, regno, -1);
2499 }
2500
2501 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2502 {
2503         return __mark_chain_precision(env, -1, spi);
2504 }
2505
2506 static bool is_spillable_regtype(enum bpf_reg_type type)
2507 {
2508         switch (type) {
2509         case PTR_TO_MAP_VALUE:
2510         case PTR_TO_MAP_VALUE_OR_NULL:
2511         case PTR_TO_STACK:
2512         case PTR_TO_CTX:
2513         case PTR_TO_PACKET:
2514         case PTR_TO_PACKET_META:
2515         case PTR_TO_PACKET_END:
2516         case PTR_TO_FLOW_KEYS:
2517         case CONST_PTR_TO_MAP:
2518         case PTR_TO_SOCKET:
2519         case PTR_TO_SOCKET_OR_NULL:
2520         case PTR_TO_SOCK_COMMON:
2521         case PTR_TO_SOCK_COMMON_OR_NULL:
2522         case PTR_TO_TCP_SOCK:
2523         case PTR_TO_TCP_SOCK_OR_NULL:
2524         case PTR_TO_XDP_SOCK:
2525         case PTR_TO_BTF_ID:
2526         case PTR_TO_BTF_ID_OR_NULL:
2527         case PTR_TO_RDONLY_BUF:
2528         case PTR_TO_RDONLY_BUF_OR_NULL:
2529         case PTR_TO_RDWR_BUF:
2530         case PTR_TO_RDWR_BUF_OR_NULL:
2531         case PTR_TO_PERCPU_BTF_ID:
2532         case PTR_TO_MEM:
2533         case PTR_TO_MEM_OR_NULL:
2534         case PTR_TO_FUNC:
2535         case PTR_TO_MAP_KEY:
2536                 return true;
2537         default:
2538                 return false;
2539         }
2540 }
2541
2542 /* Does this register contain a constant zero? */
2543 static bool register_is_null(struct bpf_reg_state *reg)
2544 {
2545         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2546 }
2547
2548 static bool register_is_const(struct bpf_reg_state *reg)
2549 {
2550         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2551 }
2552
2553 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2554 {
2555         return tnum_is_unknown(reg->var_off) &&
2556                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2557                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2558                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2559                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2560 }
2561
2562 static bool register_is_bounded(struct bpf_reg_state *reg)
2563 {
2564         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2565 }
2566
2567 static bool __is_pointer_value(bool allow_ptr_leaks,
2568                                const struct bpf_reg_state *reg)
2569 {
2570         if (allow_ptr_leaks)
2571                 return false;
2572
2573         return reg->type != SCALAR_VALUE;
2574 }
2575
2576 static void save_register_state(struct bpf_func_state *state,
2577                                 int spi, struct bpf_reg_state *reg)
2578 {
2579         int i;
2580
2581         state->stack[spi].spilled_ptr = *reg;
2582         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2583
2584         for (i = 0; i < BPF_REG_SIZE; i++)
2585                 state->stack[spi].slot_type[i] = STACK_SPILL;
2586 }
2587
2588 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2589  * stack boundary and alignment are checked in check_mem_access()
2590  */
2591 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2592                                        /* stack frame we're writing to */
2593                                        struct bpf_func_state *state,
2594                                        int off, int size, int value_regno,
2595                                        int insn_idx)
2596 {
2597         struct bpf_func_state *cur; /* state of the current function */
2598         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2599         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2600         struct bpf_reg_state *reg = NULL;
2601
2602         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2603         if (err)
2604                 return err;
2605         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2606          * so it's aligned access and [off, off + size) are within stack limits
2607          */
2608         if (!env->allow_ptr_leaks &&
2609             state->stack[spi].slot_type[0] == STACK_SPILL &&
2610             size != BPF_REG_SIZE) {
2611                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2612                 return -EACCES;
2613         }
2614
2615         cur = env->cur_state->frame[env->cur_state->curframe];
2616         if (value_regno >= 0)
2617                 reg = &cur->regs[value_regno];
2618
2619         if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2620             !register_is_null(reg) && env->bpf_capable) {
2621                 if (dst_reg != BPF_REG_FP) {
2622                         /* The backtracking logic can only recognize explicit
2623                          * stack slot address like [fp - 8]. Other spill of
2624                          * scalar via different register has to be conservative.
2625                          * Backtrack from here and mark all registers as precise
2626                          * that contributed into 'reg' being a constant.
2627                          */
2628                         err = mark_chain_precision(env, value_regno);
2629                         if (err)
2630                                 return err;
2631                 }
2632                 save_register_state(state, spi, reg);
2633         } else if (reg && is_spillable_regtype(reg->type)) {
2634                 /* register containing pointer is being spilled into stack */
2635                 if (size != BPF_REG_SIZE) {
2636                         verbose_linfo(env, insn_idx, "; ");
2637                         verbose(env, "invalid size of register spill\n");
2638                         return -EACCES;
2639                 }
2640
2641                 if (state != cur && reg->type == PTR_TO_STACK) {
2642                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2643                         return -EINVAL;
2644                 }
2645
2646                 if (!env->bypass_spec_v4) {
2647                         bool sanitize = false;
2648
2649                         if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2650                             register_is_const(&state->stack[spi].spilled_ptr))
2651                                 sanitize = true;
2652                         for (i = 0; i < BPF_REG_SIZE; i++)
2653                                 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2654                                         sanitize = true;
2655                                         break;
2656                                 }
2657                         if (sanitize) {
2658                                 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2659                                 int soff = (-spi - 1) * BPF_REG_SIZE;
2660
2661                                 /* detected reuse of integer stack slot with a pointer
2662                                  * which means either llvm is reusing stack slot or
2663                                  * an attacker is trying to exploit CVE-2018-3639
2664                                  * (speculative store bypass)
2665                                  * Have to sanitize that slot with preemptive
2666                                  * store of zero.
2667                                  */
2668                                 if (*poff && *poff != soff) {
2669                                         /* disallow programs where single insn stores
2670                                          * into two different stack slots, since verifier
2671                                          * cannot sanitize them
2672                                          */
2673                                         verbose(env,
2674                                                 "insn %d cannot access two stack slots fp%d and fp%d",
2675                                                 insn_idx, *poff, soff);
2676                                         return -EINVAL;
2677                                 }
2678                                 *poff = soff;
2679                         }
2680                 }
2681                 save_register_state(state, spi, reg);
2682         } else {
2683                 u8 type = STACK_MISC;
2684
2685                 /* regular write of data into stack destroys any spilled ptr */
2686                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2687                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2688                 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2689                         for (i = 0; i < BPF_REG_SIZE; i++)
2690                                 state->stack[spi].slot_type[i] = STACK_MISC;
2691
2692                 /* only mark the slot as written if all 8 bytes were written
2693                  * otherwise read propagation may incorrectly stop too soon
2694                  * when stack slots are partially written.
2695                  * This heuristic means that read propagation will be
2696                  * conservative, since it will add reg_live_read marks
2697                  * to stack slots all the way to first state when programs
2698                  * writes+reads less than 8 bytes
2699                  */
2700                 if (size == BPF_REG_SIZE)
2701                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2702
2703                 /* when we zero initialize stack slots mark them as such */
2704                 if (reg && register_is_null(reg)) {
2705                         /* backtracking doesn't work for STACK_ZERO yet. */
2706                         err = mark_chain_precision(env, value_regno);
2707                         if (err)
2708                                 return err;
2709                         type = STACK_ZERO;
2710                 }
2711
2712                 /* Mark slots affected by this stack write. */
2713                 for (i = 0; i < size; i++)
2714                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2715                                 type;
2716         }
2717         return 0;
2718 }
2719
2720 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2721  * known to contain a variable offset.
2722  * This function checks whether the write is permitted and conservatively
2723  * tracks the effects of the write, considering that each stack slot in the
2724  * dynamic range is potentially written to.
2725  *
2726  * 'off' includes 'regno->off'.
2727  * 'value_regno' can be -1, meaning that an unknown value is being written to
2728  * the stack.
2729  *
2730  * Spilled pointers in range are not marked as written because we don't know
2731  * what's going to be actually written. This means that read propagation for
2732  * future reads cannot be terminated by this write.
2733  *
2734  * For privileged programs, uninitialized stack slots are considered
2735  * initialized by this write (even though we don't know exactly what offsets
2736  * are going to be written to). The idea is that we don't want the verifier to
2737  * reject future reads that access slots written to through variable offsets.
2738  */
2739 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2740                                      /* func where register points to */
2741                                      struct bpf_func_state *state,
2742                                      int ptr_regno, int off, int size,
2743                                      int value_regno, int insn_idx)
2744 {
2745         struct bpf_func_state *cur; /* state of the current function */
2746         int min_off, max_off;
2747         int i, err;
2748         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2749         bool writing_zero = false;
2750         /* set if the fact that we're writing a zero is used to let any
2751          * stack slots remain STACK_ZERO
2752          */
2753         bool zero_used = false;
2754
2755         cur = env->cur_state->frame[env->cur_state->curframe];
2756         ptr_reg = &cur->regs[ptr_regno];
2757         min_off = ptr_reg->smin_value + off;
2758         max_off = ptr_reg->smax_value + off + size;
2759         if (value_regno >= 0)
2760                 value_reg = &cur->regs[value_regno];
2761         if (value_reg && register_is_null(value_reg))
2762                 writing_zero = true;
2763
2764         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2765         if (err)
2766                 return err;
2767
2768
2769         /* Variable offset writes destroy any spilled pointers in range. */
2770         for (i = min_off; i < max_off; i++) {
2771                 u8 new_type, *stype;
2772                 int slot, spi;
2773
2774                 slot = -i - 1;
2775                 spi = slot / BPF_REG_SIZE;
2776                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2777
2778                 if (!env->allow_ptr_leaks
2779                                 && *stype != NOT_INIT
2780                                 && *stype != SCALAR_VALUE) {
2781                         /* Reject the write if there's are spilled pointers in
2782                          * range. If we didn't reject here, the ptr status
2783                          * would be erased below (even though not all slots are
2784                          * actually overwritten), possibly opening the door to
2785                          * leaks.
2786                          */
2787                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2788                                 insn_idx, i);
2789                         return -EINVAL;
2790                 }
2791
2792                 /* Erase all spilled pointers. */
2793                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2794
2795                 /* Update the slot type. */
2796                 new_type = STACK_MISC;
2797                 if (writing_zero && *stype == STACK_ZERO) {
2798                         new_type = STACK_ZERO;
2799                         zero_used = true;
2800                 }
2801                 /* If the slot is STACK_INVALID, we check whether it's OK to
2802                  * pretend that it will be initialized by this write. The slot
2803                  * might not actually be written to, and so if we mark it as
2804                  * initialized future reads might leak uninitialized memory.
2805                  * For privileged programs, we will accept such reads to slots
2806                  * that may or may not be written because, if we're reject
2807                  * them, the error would be too confusing.
2808                  */
2809                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2810                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2811                                         insn_idx, i);
2812                         return -EINVAL;
2813                 }
2814                 *stype = new_type;
2815         }
2816         if (zero_used) {
2817                 /* backtracking doesn't work for STACK_ZERO yet. */
2818                 err = mark_chain_precision(env, value_regno);
2819                 if (err)
2820                         return err;
2821         }
2822         return 0;
2823 }
2824
2825 /* When register 'dst_regno' is assigned some values from stack[min_off,
2826  * max_off), we set the register's type according to the types of the
2827  * respective stack slots. If all the stack values are known to be zeros, then
2828  * so is the destination reg. Otherwise, the register is considered to be
2829  * SCALAR. This function does not deal with register filling; the caller must
2830  * ensure that all spilled registers in the stack range have been marked as
2831  * read.
2832  */
2833 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2834                                 /* func where src register points to */
2835                                 struct bpf_func_state *ptr_state,
2836                                 int min_off, int max_off, int dst_regno)
2837 {
2838         struct bpf_verifier_state *vstate = env->cur_state;
2839         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2840         int i, slot, spi;
2841         u8 *stype;
2842         int zeros = 0;
2843
2844         for (i = min_off; i < max_off; i++) {
2845                 slot = -i - 1;
2846                 spi = slot / BPF_REG_SIZE;
2847                 stype = ptr_state->stack[spi].slot_type;
2848                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2849                         break;
2850                 zeros++;
2851         }
2852         if (zeros == max_off - min_off) {
2853                 /* any access_size read into register is zero extended,
2854                  * so the whole register == const_zero
2855                  */
2856                 __mark_reg_const_zero(&state->regs[dst_regno]);
2857                 /* backtracking doesn't support STACK_ZERO yet,
2858                  * so mark it precise here, so that later
2859                  * backtracking can stop here.
2860                  * Backtracking may not need this if this register
2861                  * doesn't participate in pointer adjustment.
2862                  * Forward propagation of precise flag is not
2863                  * necessary either. This mark is only to stop
2864                  * backtracking. Any register that contributed
2865                  * to const 0 was marked precise before spill.
2866                  */
2867                 state->regs[dst_regno].precise = true;
2868         } else {
2869                 /* have read misc data from the stack */
2870                 mark_reg_unknown(env, state->regs, dst_regno);
2871         }
2872         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2873 }
2874
2875 /* Read the stack at 'off' and put the results into the register indicated by
2876  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2877  * spilled reg.
2878  *
2879  * 'dst_regno' can be -1, meaning that the read value is not going to a
2880  * register.
2881  *
2882  * The access is assumed to be within the current stack bounds.
2883  */
2884 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2885                                       /* func where src register points to */
2886                                       struct bpf_func_state *reg_state,
2887                                       int off, int size, int dst_regno)
2888 {
2889         struct bpf_verifier_state *vstate = env->cur_state;
2890         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2891         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2892         struct bpf_reg_state *reg;
2893         u8 *stype;
2894
2895         stype = reg_state->stack[spi].slot_type;
2896         reg = &reg_state->stack[spi].spilled_ptr;
2897
2898         if (stype[0] == STACK_SPILL) {
2899                 if (size != BPF_REG_SIZE) {
2900                         if (reg->type != SCALAR_VALUE) {
2901                                 verbose_linfo(env, env->insn_idx, "; ");
2902                                 verbose(env, "invalid size of register fill\n");
2903                                 return -EACCES;
2904                         }
2905                         if (dst_regno >= 0) {
2906                                 mark_reg_unknown(env, state->regs, dst_regno);
2907                                 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2908                         }
2909                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2910                         return 0;
2911                 }
2912                 for (i = 1; i < BPF_REG_SIZE; i++) {
2913                         if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2914                                 verbose(env, "corrupted spill memory\n");
2915                                 return -EACCES;
2916                         }
2917                 }
2918
2919                 if (dst_regno >= 0) {
2920                         /* restore register state from stack */
2921                         state->regs[dst_regno] = *reg;
2922                         /* mark reg as written since spilled pointer state likely
2923                          * has its liveness marks cleared by is_state_visited()
2924                          * which resets stack/reg liveness for state transitions
2925                          */
2926                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2927                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2928                         /* If dst_regno==-1, the caller is asking us whether
2929                          * it is acceptable to use this value as a SCALAR_VALUE
2930                          * (e.g. for XADD).
2931                          * We must not allow unprivileged callers to do that
2932                          * with spilled pointers.
2933                          */
2934                         verbose(env, "leaking pointer from stack off %d\n",
2935                                 off);
2936                         return -EACCES;
2937                 }
2938                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2939         } else {
2940                 u8 type;
2941
2942                 for (i = 0; i < size; i++) {
2943                         type = stype[(slot - i) % BPF_REG_SIZE];
2944                         if (type == STACK_MISC)
2945                                 continue;
2946                         if (type == STACK_ZERO)
2947                                 continue;
2948                         verbose(env, "invalid read from stack off %d+%d size %d\n",
2949                                 off, i, size);
2950                         return -EACCES;
2951                 }
2952                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2953                 if (dst_regno >= 0)
2954                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2955         }
2956         return 0;
2957 }
2958
2959 enum stack_access_src {
2960         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2961         ACCESS_HELPER = 2,  /* the access is performed by a helper */
2962 };
2963
2964 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2965                                          int regno, int off, int access_size,
2966                                          bool zero_size_allowed,
2967                                          enum stack_access_src type,
2968                                          struct bpf_call_arg_meta *meta);
2969
2970 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2971 {
2972         return cur_regs(env) + regno;
2973 }
2974
2975 /* Read the stack at 'ptr_regno + off' and put the result into the register
2976  * 'dst_regno'.
2977  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2978  * but not its variable offset.
2979  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2980  *
2981  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2982  * filling registers (i.e. reads of spilled register cannot be detected when
2983  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2984  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2985  * offset; for a fixed offset check_stack_read_fixed_off should be used
2986  * instead.
2987  */
2988 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2989                                     int ptr_regno, int off, int size, int dst_regno)
2990 {
2991         /* The state of the source register. */
2992         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2993         struct bpf_func_state *ptr_state = func(env, reg);
2994         int err;
2995         int min_off, max_off;
2996
2997         /* Note that we pass a NULL meta, so raw access will not be permitted.
2998          */
2999         err = check_stack_range_initialized(env, ptr_regno, off, size,
3000                                             false, ACCESS_DIRECT, NULL);
3001         if (err)
3002                 return err;
3003
3004         min_off = reg->smin_value + off;
3005         max_off = reg->smax_value + off;
3006         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3007         return 0;
3008 }
3009
3010 /* check_stack_read dispatches to check_stack_read_fixed_off or
3011  * check_stack_read_var_off.
3012  *
3013  * The caller must ensure that the offset falls within the allocated stack
3014  * bounds.
3015  *
3016  * 'dst_regno' is a register which will receive the value from the stack. It
3017  * can be -1, meaning that the read value is not going to a register.
3018  */
3019 static int check_stack_read(struct bpf_verifier_env *env,
3020                             int ptr_regno, int off, int size,
3021                             int dst_regno)
3022 {
3023         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3024         struct bpf_func_state *state = func(env, reg);
3025         int err;
3026         /* Some accesses are only permitted with a static offset. */
3027         bool var_off = !tnum_is_const(reg->var_off);
3028
3029         /* The offset is required to be static when reads don't go to a
3030          * register, in order to not leak pointers (see
3031          * check_stack_read_fixed_off).
3032          */
3033         if (dst_regno < 0 && var_off) {
3034                 char tn_buf[48];
3035
3036                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3037                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3038                         tn_buf, off, size);
3039                 return -EACCES;
3040         }
3041         /* Variable offset is prohibited for unprivileged mode for simplicity
3042          * since it requires corresponding support in Spectre masking for stack
3043          * ALU. See also retrieve_ptr_limit().
3044          */
3045         if (!env->bypass_spec_v1 && var_off) {
3046                 char tn_buf[48];
3047
3048                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3049                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3050                                 ptr_regno, tn_buf);
3051                 return -EACCES;
3052         }
3053
3054         if (!var_off) {
3055                 off += reg->var_off.value;
3056                 err = check_stack_read_fixed_off(env, state, off, size,
3057                                                  dst_regno);
3058         } else {
3059                 /* Variable offset stack reads need more conservative handling
3060                  * than fixed offset ones. Note that dst_regno >= 0 on this
3061                  * branch.
3062                  */
3063                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3064                                                dst_regno);
3065         }
3066         return err;
3067 }
3068
3069
3070 /* check_stack_write dispatches to check_stack_write_fixed_off or
3071  * check_stack_write_var_off.
3072  *
3073  * 'ptr_regno' is the register used as a pointer into the stack.
3074  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3075  * 'value_regno' is the register whose value we're writing to the stack. It can
3076  * be -1, meaning that we're not writing from a register.
3077  *
3078  * The caller must ensure that the offset falls within the maximum stack size.
3079  */
3080 static int check_stack_write(struct bpf_verifier_env *env,
3081                              int ptr_regno, int off, int size,
3082                              int value_regno, int insn_idx)
3083 {
3084         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3085         struct bpf_func_state *state = func(env, reg);
3086         int err;
3087
3088         if (tnum_is_const(reg->var_off)) {
3089                 off += reg->var_off.value;
3090                 err = check_stack_write_fixed_off(env, state, off, size,
3091                                                   value_regno, insn_idx);
3092         } else {
3093                 /* Variable offset stack reads need more conservative handling
3094                  * than fixed offset ones.
3095                  */
3096                 err = check_stack_write_var_off(env, state,
3097                                                 ptr_regno, off, size,
3098                                                 value_regno, insn_idx);
3099         }
3100         return err;
3101 }
3102
3103 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3104                                  int off, int size, enum bpf_access_type type)
3105 {
3106         struct bpf_reg_state *regs = cur_regs(env);
3107         struct bpf_map *map = regs[regno].map_ptr;
3108         u32 cap = bpf_map_flags_to_cap(map);
3109
3110         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3111                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3112                         map->value_size, off, size);
3113                 return -EACCES;
3114         }
3115
3116         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3117                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3118                         map->value_size, off, size);
3119                 return -EACCES;
3120         }
3121
3122         return 0;
3123 }
3124
3125 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3126 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3127                               int off, int size, u32 mem_size,
3128                               bool zero_size_allowed)
3129 {
3130         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3131         struct bpf_reg_state *reg;
3132
3133         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3134                 return 0;
3135
3136         reg = &cur_regs(env)[regno];
3137         switch (reg->type) {
3138         case PTR_TO_MAP_KEY:
3139                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3140                         mem_size, off, size);
3141                 break;
3142         case PTR_TO_MAP_VALUE:
3143                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3144                         mem_size, off, size);
3145                 break;
3146         case PTR_TO_PACKET:
3147         case PTR_TO_PACKET_META:
3148         case PTR_TO_PACKET_END:
3149                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3150                         off, size, regno, reg->id, off, mem_size);
3151                 break;
3152         case PTR_TO_MEM:
3153         default:
3154                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3155                         mem_size, off, size);
3156         }
3157
3158         return -EACCES;
3159 }
3160
3161 /* check read/write into a memory region with possible variable offset */
3162 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3163                                    int off, int size, u32 mem_size,
3164                                    bool zero_size_allowed)
3165 {
3166         struct bpf_verifier_state *vstate = env->cur_state;
3167         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3168         struct bpf_reg_state *reg = &state->regs[regno];
3169         int err;
3170
3171         /* We may have adjusted the register pointing to memory region, so we
3172          * need to try adding each of min_value and max_value to off
3173          * to make sure our theoretical access will be safe.
3174          */
3175         if (env->log.level & BPF_LOG_LEVEL)
3176                 print_verifier_state(env, state);
3177
3178         /* The minimum value is only important with signed
3179          * comparisons where we can't assume the floor of a
3180          * value is 0.  If we are using signed variables for our
3181          * index'es we need to make sure that whatever we use
3182          * will have a set floor within our range.
3183          */
3184         if (reg->smin_value < 0 &&
3185             (reg->smin_value == S64_MIN ||
3186              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3187               reg->smin_value + off < 0)) {
3188                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3189                         regno);
3190                 return -EACCES;
3191         }
3192         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3193                                  mem_size, zero_size_allowed);
3194         if (err) {
3195                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3196                         regno);
3197                 return err;
3198         }
3199
3200         /* If we haven't set a max value then we need to bail since we can't be
3201          * sure we won't do bad things.
3202          * If reg->umax_value + off could overflow, treat that as unbounded too.
3203          */
3204         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3205                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3206                         regno);
3207                 return -EACCES;
3208         }
3209         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3210                                  mem_size, zero_size_allowed);
3211         if (err) {
3212                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3213                         regno);
3214                 return err;
3215         }
3216
3217         return 0;
3218 }
3219
3220 /* check read/write into a map element with possible variable offset */
3221 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3222                             int off, int size, bool zero_size_allowed)
3223 {
3224         struct bpf_verifier_state *vstate = env->cur_state;
3225         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3226         struct bpf_reg_state *reg = &state->regs[regno];
3227         struct bpf_map *map = reg->map_ptr;
3228         int err;
3229
3230         err = check_mem_region_access(env, regno, off, size, map->value_size,
3231                                       zero_size_allowed);
3232         if (err)
3233                 return err;
3234
3235         if (map_value_has_spin_lock(map)) {
3236                 u32 lock = map->spin_lock_off;
3237
3238                 /* if any part of struct bpf_spin_lock can be touched by
3239                  * load/store reject this program.
3240                  * To check that [x1, x2) overlaps with [y1, y2)
3241                  * it is sufficient to check x1 < y2 && y1 < x2.
3242                  */
3243                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3244                      lock < reg->umax_value + off + size) {
3245                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3246                         return -EACCES;
3247                 }
3248         }
3249         if (map_value_has_timer(map)) {
3250                 u32 t = map->timer_off;
3251
3252                 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3253                      t < reg->umax_value + off + size) {
3254                         verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3255                         return -EACCES;
3256                 }
3257         }
3258         return err;
3259 }
3260
3261 #define MAX_PACKET_OFF 0xffff
3262
3263 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3264 {
3265         return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3266 }
3267
3268 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3269                                        const struct bpf_call_arg_meta *meta,
3270                                        enum bpf_access_type t)
3271 {
3272         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3273
3274         switch (prog_type) {
3275         /* Program types only with direct read access go here! */
3276         case BPF_PROG_TYPE_LWT_IN:
3277         case BPF_PROG_TYPE_LWT_OUT:
3278         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3279         case BPF_PROG_TYPE_SK_REUSEPORT:
3280         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3281         case BPF_PROG_TYPE_CGROUP_SKB:
3282                 if (t == BPF_WRITE)
3283                         return false;
3284                 fallthrough;
3285
3286         /* Program types with direct read + write access go here! */
3287         case BPF_PROG_TYPE_SCHED_CLS:
3288         case BPF_PROG_TYPE_SCHED_ACT:
3289         case BPF_PROG_TYPE_XDP:
3290         case BPF_PROG_TYPE_LWT_XMIT:
3291         case BPF_PROG_TYPE_SK_SKB:
3292         case BPF_PROG_TYPE_SK_MSG:
3293                 if (meta)
3294                         return meta->pkt_access;
3295
3296                 env->seen_direct_write = true;
3297                 return true;
3298
3299         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3300                 if (t == BPF_WRITE)
3301                         env->seen_direct_write = true;
3302
3303                 return true;
3304
3305         default:
3306                 return false;
3307         }
3308 }
3309
3310 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3311                                int size, bool zero_size_allowed)
3312 {
3313         struct bpf_reg_state *regs = cur_regs(env);
3314         struct bpf_reg_state *reg = &regs[regno];
3315         int err;
3316
3317         /* We may have added a variable offset to the packet pointer; but any
3318          * reg->range we have comes after that.  We are only checking the fixed
3319          * offset.
3320          */
3321
3322         /* We don't allow negative numbers, because we aren't tracking enough
3323          * detail to prove they're safe.
3324          */
3325         if (reg->smin_value < 0) {
3326                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3327                         regno);
3328                 return -EACCES;
3329         }
3330
3331         err = reg->range < 0 ? -EINVAL :
3332               __check_mem_access(env, regno, off, size, reg->range,
3333                                  zero_size_allowed);
3334         if (err) {
3335                 verbose(env, "R%d offset is outside of the packet\n", regno);
3336                 return err;
3337         }
3338
3339         /* __check_mem_access has made sure "off + size - 1" is within u16.
3340          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3341          * otherwise find_good_pkt_pointers would have refused to set range info
3342          * that __check_mem_access would have rejected this pkt access.
3343          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3344          */
3345         env->prog->aux->max_pkt_offset =
3346                 max_t(u32, env->prog->aux->max_pkt_offset,
3347                       off + reg->umax_value + size - 1);
3348
3349         return err;
3350 }
3351
3352 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3353 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3354                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
3355                             struct btf **btf, u32 *btf_id)
3356 {
3357         struct bpf_insn_access_aux info = {
3358                 .reg_type = *reg_type,
3359                 .log = &env->log,
3360         };
3361
3362         if (env->ops->is_valid_access &&
3363             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3364                 /* A non zero info.ctx_field_size indicates that this field is a
3365                  * candidate for later verifier transformation to load the whole
3366                  * field and then apply a mask when accessed with a narrower
3367                  * access than actual ctx access size. A zero info.ctx_field_size
3368                  * will only allow for whole field access and rejects any other
3369                  * type of narrower access.
3370                  */
3371                 *reg_type = info.reg_type;
3372
3373                 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3374                         *btf = info.btf;
3375                         *btf_id = info.btf_id;
3376                 } else {
3377                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3378                 }
3379                 /* remember the offset of last byte accessed in ctx */
3380                 if (env->prog->aux->max_ctx_offset < off + size)
3381                         env->prog->aux->max_ctx_offset = off + size;
3382                 return 0;
3383         }
3384
3385         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3386         return -EACCES;
3387 }
3388
3389 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3390                                   int size)
3391 {
3392         if (size < 0 || off < 0 ||
3393             (u64)off + size > sizeof(struct bpf_flow_keys)) {
3394                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3395                         off, size);
3396                 return -EACCES;
3397         }
3398         return 0;
3399 }
3400
3401 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3402                              u32 regno, int off, int size,
3403                              enum bpf_access_type t)
3404 {
3405         struct bpf_reg_state *regs = cur_regs(env);
3406         struct bpf_reg_state *reg = &regs[regno];
3407         struct bpf_insn_access_aux info = {};
3408         bool valid;
3409
3410         if (reg->smin_value < 0) {
3411                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3412                         regno);
3413                 return -EACCES;
3414         }
3415
3416         switch (reg->type) {
3417         case PTR_TO_SOCK_COMMON:
3418                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3419                 break;
3420         case PTR_TO_SOCKET:
3421                 valid = bpf_sock_is_valid_access(off, size, t, &info);
3422                 break;
3423         case PTR_TO_TCP_SOCK:
3424                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3425                 break;
3426         case PTR_TO_XDP_SOCK:
3427                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3428                 break;
3429         default:
3430                 valid = false;
3431         }
3432
3433
3434         if (valid) {
3435                 env->insn_aux_data[insn_idx].ctx_field_size =
3436                         info.ctx_field_size;
3437                 return 0;
3438         }
3439
3440         verbose(env, "R%d invalid %s access off=%d size=%d\n",
3441                 regno, reg_type_str[reg->type], off, size);
3442
3443         return -EACCES;
3444 }
3445
3446 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3447 {
3448         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3449 }
3450
3451 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3452 {
3453         const struct bpf_reg_state *reg = reg_state(env, regno);
3454
3455         return reg->type == PTR_TO_CTX;
3456 }
3457
3458 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3459 {
3460         const struct bpf_reg_state *reg = reg_state(env, regno);
3461
3462         return type_is_sk_pointer(reg->type);
3463 }
3464
3465 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3466 {
3467         const struct bpf_reg_state *reg = reg_state(env, regno);
3468
3469         return type_is_pkt_pointer(reg->type);
3470 }
3471
3472 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3473 {
3474         const struct bpf_reg_state *reg = reg_state(env, regno);
3475
3476         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3477         return reg->type == PTR_TO_FLOW_KEYS;
3478 }
3479
3480 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3481                                    const struct bpf_reg_state *reg,
3482                                    int off, int size, bool strict)
3483 {
3484         struct tnum reg_off;
3485         int ip_align;
3486
3487         /* Byte size accesses are always allowed. */
3488         if (!strict || size == 1)
3489                 return 0;
3490
3491         /* For platforms that do not have a Kconfig enabling
3492          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3493          * NET_IP_ALIGN is universally set to '2'.  And on platforms
3494          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3495          * to this code only in strict mode where we want to emulate
3496          * the NET_IP_ALIGN==2 checking.  Therefore use an
3497          * unconditional IP align value of '2'.
3498          */
3499         ip_align = 2;
3500
3501         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3502         if (!tnum_is_aligned(reg_off, size)) {
3503                 char tn_buf[48];
3504
3505                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3506                 verbose(env,
3507                         "misaligned packet access off %d+%s+%d+%d size %d\n",
3508                         ip_align, tn_buf, reg->off, off, size);
3509                 return -EACCES;
3510         }
3511
3512         return 0;
3513 }
3514
3515 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3516                                        const struct bpf_reg_state *reg,
3517                                        const char *pointer_desc,
3518                                        int off, int size, bool strict)
3519 {
3520         struct tnum reg_off;
3521
3522         /* Byte size accesses are always allowed. */
3523         if (!strict || size == 1)
3524                 return 0;
3525
3526         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3527         if (!tnum_is_aligned(reg_off, size)) {
3528                 char tn_buf[48];
3529
3530                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3531                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3532                         pointer_desc, tn_buf, reg->off, off, size);
3533                 return -EACCES;
3534         }
3535
3536         return 0;
3537 }
3538
3539 static int check_ptr_alignment(struct bpf_verifier_env *env,
3540                                const struct bpf_reg_state *reg, int off,
3541                                int size, bool strict_alignment_once)
3542 {
3543         bool strict = env->strict_alignment || strict_alignment_once;
3544         const char *pointer_desc = "";
3545
3546         switch (reg->type) {
3547         case PTR_TO_PACKET:
3548         case PTR_TO_PACKET_META:
3549                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3550                  * right in front, treat it the very same way.
3551                  */
3552                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3553         case PTR_TO_FLOW_KEYS:
3554                 pointer_desc = "flow keys ";
3555                 break;
3556         case PTR_TO_MAP_KEY:
3557                 pointer_desc = "key ";
3558                 break;
3559         case PTR_TO_MAP_VALUE:
3560                 pointer_desc = "value ";
3561                 break;
3562         case PTR_TO_CTX:
3563                 pointer_desc = "context ";
3564                 break;
3565         case PTR_TO_STACK:
3566                 pointer_desc = "stack ";
3567                 /* The stack spill tracking logic in check_stack_write_fixed_off()
3568                  * and check_stack_read_fixed_off() relies on stack accesses being
3569                  * aligned.
3570                  */
3571                 strict = true;
3572                 break;
3573         case PTR_TO_SOCKET:
3574                 pointer_desc = "sock ";
3575                 break;
3576         case PTR_TO_SOCK_COMMON:
3577                 pointer_desc = "sock_common ";
3578                 break;
3579         case PTR_TO_TCP_SOCK:
3580                 pointer_desc = "tcp_sock ";
3581                 break;
3582         case PTR_TO_XDP_SOCK:
3583                 pointer_desc = "xdp_sock ";
3584                 break;
3585         default:
3586                 break;
3587         }
3588         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3589                                            strict);
3590 }
3591
3592 static int update_stack_depth(struct bpf_verifier_env *env,
3593                               const struct bpf_func_state *func,
3594                               int off)
3595 {
3596         u16 stack = env->subprog_info[func->subprogno].stack_depth;
3597
3598         if (stack >= -off)
3599                 return 0;
3600
3601         /* update known max for given subprogram */
3602         env->subprog_info[func->subprogno].stack_depth = -off;
3603         return 0;
3604 }
3605
3606 /* starting from main bpf function walk all instructions of the function
3607  * and recursively walk all callees that given function can call.
3608  * Ignore jump and exit insns.
3609  * Since recursion is prevented by check_cfg() this algorithm
3610  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3611  */
3612 static int check_max_stack_depth(struct bpf_verifier_env *env)
3613 {
3614         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3615         struct bpf_subprog_info *subprog = env->subprog_info;
3616         struct bpf_insn *insn = env->prog->insnsi;
3617         bool tail_call_reachable = false;
3618         int ret_insn[MAX_CALL_FRAMES];
3619         int ret_prog[MAX_CALL_FRAMES];
3620         int j;
3621
3622 process_func:
3623         /* protect against potential stack overflow that might happen when
3624          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3625          * depth for such case down to 256 so that the worst case scenario
3626          * would result in 8k stack size (32 which is tailcall limit * 256 =
3627          * 8k).
3628          *
3629          * To get the idea what might happen, see an example:
3630          * func1 -> sub rsp, 128
3631          *  subfunc1 -> sub rsp, 256
3632          *  tailcall1 -> add rsp, 256
3633          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3634          *   subfunc2 -> sub rsp, 64
3635          *   subfunc22 -> sub rsp, 128
3636          *   tailcall2 -> add rsp, 128
3637          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3638          *
3639          * tailcall will unwind the current stack frame but it will not get rid
3640          * of caller's stack as shown on the example above.
3641          */
3642         if (idx && subprog[idx].has_tail_call && depth >= 256) {
3643                 verbose(env,
3644                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3645                         depth);
3646                 return -EACCES;
3647         }
3648         /* round up to 32-bytes, since this is granularity
3649          * of interpreter stack size
3650          */
3651         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3652         if (depth > MAX_BPF_STACK) {
3653                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3654                         frame + 1, depth);
3655                 return -EACCES;
3656         }
3657 continue_func:
3658         subprog_end = subprog[idx + 1].start;
3659         for (; i < subprog_end; i++) {
3660                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3661                         continue;
3662                 /* remember insn and function to return to */
3663                 ret_insn[frame] = i + 1;
3664                 ret_prog[frame] = idx;
3665
3666                 /* find the callee */
3667                 i = i + insn[i].imm + 1;
3668                 idx = find_subprog(env, i);
3669                 if (idx < 0) {
3670                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3671                                   i);
3672                         return -EFAULT;
3673                 }
3674
3675                 if (subprog[idx].has_tail_call)
3676                         tail_call_reachable = true;
3677
3678                 frame++;
3679                 if (frame >= MAX_CALL_FRAMES) {
3680                         verbose(env, "the call stack of %d frames is too deep !\n",
3681                                 frame);
3682                         return -E2BIG;
3683                 }
3684                 goto process_func;
3685         }
3686         /* if tail call got detected across bpf2bpf calls then mark each of the
3687          * currently present subprog frames as tail call reachable subprogs;
3688          * this info will be utilized by JIT so that we will be preserving the
3689          * tail call counter throughout bpf2bpf calls combined with tailcalls
3690          */
3691         if (tail_call_reachable)
3692                 for (j = 0; j < frame; j++)
3693                         subprog[ret_prog[j]].tail_call_reachable = true;
3694
3695         /* end of for() loop means the last insn of the 'subprog'
3696          * was reached. Doesn't matter whether it was JA or EXIT
3697          */
3698         if (frame == 0)
3699                 return 0;
3700         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3701         frame--;
3702         i = ret_insn[frame];
3703         idx = ret_prog[frame];
3704         goto continue_func;
3705 }
3706
3707 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3708 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3709                                   const struct bpf_insn *insn, int idx)
3710 {
3711         int start = idx + insn->imm + 1, subprog;
3712
3713         subprog = find_subprog(env, start);
3714         if (subprog < 0) {
3715                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3716                           start);
3717                 return -EFAULT;
3718         }
3719         return env->subprog_info[subprog].stack_depth;
3720 }
3721 #endif
3722
3723 int check_ctx_reg(struct bpf_verifier_env *env,
3724                   const struct bpf_reg_state *reg, int regno)
3725 {
3726         /* Access to ctx or passing it to a helper is only allowed in
3727          * its original, unmodified form.
3728          */
3729
3730         if (reg->off) {
3731                 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3732                         regno, reg->off);
3733                 return -EACCES;
3734         }
3735
3736         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3737                 char tn_buf[48];
3738
3739                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3740                 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3741                 return -EACCES;
3742         }
3743
3744         return 0;
3745 }
3746
3747 static int __check_buffer_access(struct bpf_verifier_env *env,
3748                                  const char *buf_info,
3749                                  const struct bpf_reg_state *reg,
3750                                  int regno, int off, int size)
3751 {
3752         if (off < 0) {
3753                 verbose(env,
3754                         "R%d invalid %s buffer access: off=%d, size=%d\n",
3755                         regno, buf_info, off, size);
3756                 return -EACCES;
3757         }
3758         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3759                 char tn_buf[48];
3760
3761                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3762                 verbose(env,
3763                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3764                         regno, off, tn_buf);
3765                 return -EACCES;
3766         }
3767
3768         return 0;
3769 }
3770
3771 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3772                                   const struct bpf_reg_state *reg,
3773                                   int regno, int off, int size)
3774 {
3775         int err;
3776
3777         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3778         if (err)
3779                 return err;
3780
3781         if (off + size > env->prog->aux->max_tp_access)
3782                 env->prog->aux->max_tp_access = off + size;
3783
3784         return 0;
3785 }
3786
3787 static int check_buffer_access(struct bpf_verifier_env *env,
3788                                const struct bpf_reg_state *reg,
3789                                int regno, int off, int size,
3790                                bool zero_size_allowed,
3791                                const char *buf_info,
3792                                u32 *max_access)
3793 {
3794         int err;
3795
3796         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3797         if (err)
3798                 return err;
3799
3800         if (off + size > *max_access)
3801                 *max_access = off + size;
3802
3803         return 0;
3804 }
3805
3806 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3807 static void zext_32_to_64(struct bpf_reg_state *reg)
3808 {
3809         reg->var_off = tnum_subreg(reg->var_off);
3810         __reg_assign_32_into_64(reg);
3811 }
3812
3813 /* truncate register to smaller size (in bytes)
3814  * must be called with size < BPF_REG_SIZE
3815  */
3816 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3817 {
3818         u64 mask;
3819
3820         /* clear high bits in bit representation */
3821         reg->var_off = tnum_cast(reg->var_off, size);
3822
3823         /* fix arithmetic bounds */
3824         mask = ((u64)1 << (size * 8)) - 1;
3825         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3826                 reg->umin_value &= mask;
3827                 reg->umax_value &= mask;
3828         } else {
3829                 reg->umin_value = 0;
3830                 reg->umax_value = mask;
3831         }
3832         reg->smin_value = reg->umin_value;
3833         reg->smax_value = reg->umax_value;
3834
3835         /* If size is smaller than 32bit register the 32bit register
3836          * values are also truncated so we push 64-bit bounds into
3837          * 32-bit bounds. Above were truncated < 32-bits already.
3838          */
3839         if (size >= 4)
3840                 return;
3841         __reg_combine_64_into_32(reg);
3842 }
3843
3844 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3845 {
3846         return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3847 }
3848
3849 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3850 {
3851         void *ptr;
3852         u64 addr;
3853         int err;
3854
3855         err = map->ops->map_direct_value_addr(map, &addr, off);
3856         if (err)
3857                 return err;
3858         ptr = (void *)(long)addr + off;
3859
3860         switch (size) {
3861         case sizeof(u8):
3862                 *val = (u64)*(u8 *)ptr;
3863                 break;
3864         case sizeof(u16):
3865                 *val = (u64)*(u16 *)ptr;
3866                 break;
3867         case sizeof(u32):
3868                 *val = (u64)*(u32 *)ptr;
3869                 break;
3870         case sizeof(u64):
3871                 *val = *(u64 *)ptr;
3872                 break;
3873         default:
3874                 return -EINVAL;
3875         }
3876         return 0;
3877 }
3878
3879 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3880                                    struct bpf_reg_state *regs,
3881                                    int regno, int off, int size,
3882                                    enum bpf_access_type atype,
3883                                    int value_regno)
3884 {
3885         struct bpf_reg_state *reg = regs + regno;
3886         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3887         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3888         u32 btf_id;
3889         int ret;
3890
3891         if (off < 0) {
3892                 verbose(env,
3893                         "R%d is ptr_%s invalid negative access: off=%d\n",
3894                         regno, tname, off);
3895                 return -EACCES;
3896         }
3897         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3898                 char tn_buf[48];
3899
3900                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3901                 verbose(env,
3902                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3903                         regno, tname, off, tn_buf);
3904                 return -EACCES;
3905         }
3906
3907         if (env->ops->btf_struct_access) {
3908                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3909                                                   off, size, atype, &btf_id);
3910         } else {
3911                 if (atype != BPF_READ) {
3912                         verbose(env, "only read is supported\n");
3913                         return -EACCES;
3914                 }
3915
3916                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3917                                         atype, &btf_id);
3918         }
3919
3920         if (ret < 0)
3921                 return ret;
3922
3923         if (atype == BPF_READ && value_regno >= 0)
3924                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3925
3926         return 0;
3927 }
3928
3929 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3930                                    struct bpf_reg_state *regs,
3931                                    int regno, int off, int size,
3932                                    enum bpf_access_type atype,
3933                                    int value_regno)
3934 {
3935         struct bpf_reg_state *reg = regs + regno;
3936         struct bpf_map *map = reg->map_ptr;
3937         const struct btf_type *t;
3938         const char *tname;
3939         u32 btf_id;
3940         int ret;
3941
3942         if (!btf_vmlinux) {
3943                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3944                 return -ENOTSUPP;
3945         }
3946
3947         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3948                 verbose(env, "map_ptr access not supported for map type %d\n",
3949                         map->map_type);
3950                 return -ENOTSUPP;
3951         }
3952
3953         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3954         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3955
3956         if (!env->allow_ptr_to_map_access) {
3957                 verbose(env,
3958                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3959                         tname);
3960                 return -EPERM;
3961         }
3962
3963         if (off < 0) {
3964                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3965                         regno, tname, off);
3966                 return -EACCES;
3967         }
3968
3969         if (atype != BPF_READ) {
3970                 verbose(env, "only read from %s is supported\n", tname);
3971                 return -EACCES;
3972         }
3973
3974         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
3975         if (ret < 0)
3976                 return ret;
3977
3978         if (value_regno >= 0)
3979                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
3980
3981         return 0;
3982 }
3983
3984 /* Check that the stack access at the given offset is within bounds. The
3985  * maximum valid offset is -1.
3986  *
3987  * The minimum valid offset is -MAX_BPF_STACK for writes, and
3988  * -state->allocated_stack for reads.
3989  */
3990 static int check_stack_slot_within_bounds(int off,
3991                                           struct bpf_func_state *state,
3992                                           enum bpf_access_type t)
3993 {
3994         int min_valid_off;
3995
3996         if (t == BPF_WRITE)
3997                 min_valid_off = -MAX_BPF_STACK;
3998         else
3999                 min_valid_off = -state->allocated_stack;
4000
4001         if (off < min_valid_off || off > -1)
4002                 return -EACCES;
4003         return 0;
4004 }
4005
4006 /* Check that the stack access at 'regno + off' falls within the maximum stack
4007  * bounds.
4008  *
4009  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4010  */
4011 static int check_stack_access_within_bounds(
4012                 struct bpf_verifier_env *env,
4013                 int regno, int off, int access_size,
4014                 enum stack_access_src src, enum bpf_access_type type)
4015 {
4016         struct bpf_reg_state *regs = cur_regs(env);
4017         struct bpf_reg_state *reg = regs + regno;
4018         struct bpf_func_state *state = func(env, reg);
4019         int min_off, max_off;
4020         int err;
4021         char *err_extra;
4022
4023         if (src == ACCESS_HELPER)
4024                 /* We don't know if helpers are reading or writing (or both). */
4025                 err_extra = " indirect access to";
4026         else if (type == BPF_READ)
4027                 err_extra = " read from";
4028         else
4029                 err_extra = " write to";
4030
4031         if (tnum_is_const(reg->var_off)) {
4032                 min_off = reg->var_off.value + off;
4033                 if (access_size > 0)
4034                         max_off = min_off + access_size - 1;
4035                 else
4036                         max_off = min_off;
4037         } else {
4038                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4039                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4040                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4041                                 err_extra, regno);
4042                         return -EACCES;
4043                 }
4044                 min_off = reg->smin_value + off;
4045                 if (access_size > 0)
4046                         max_off = reg->smax_value + off + access_size - 1;
4047                 else
4048                         max_off = min_off;
4049         }
4050
4051         err = check_stack_slot_within_bounds(min_off, state, type);
4052         if (!err)
4053                 err = check_stack_slot_within_bounds(max_off, state, type);
4054
4055         if (err) {
4056                 if (tnum_is_const(reg->var_off)) {
4057                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4058                                 err_extra, regno, off, access_size);
4059                 } else {
4060                         char tn_buf[48];
4061
4062                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4063                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4064                                 err_extra, regno, tn_buf, access_size);
4065                 }
4066         }
4067         return err;
4068 }
4069
4070 /* check whether memory at (regno + off) is accessible for t = (read | write)
4071  * if t==write, value_regno is a register which value is stored into memory
4072  * if t==read, value_regno is a register which will receive the value from memory
4073  * if t==write && value_regno==-1, some unknown value is stored into memory
4074  * if t==read && value_regno==-1, don't care what we read from memory
4075  */
4076 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4077                             int off, int bpf_size, enum bpf_access_type t,
4078                             int value_regno, bool strict_alignment_once)
4079 {
4080         struct bpf_reg_state *regs = cur_regs(env);
4081         struct bpf_reg_state *reg = regs + regno;
4082         struct bpf_func_state *state;
4083         int size, err = 0;
4084
4085         size = bpf_size_to_bytes(bpf_size);
4086         if (size < 0)
4087                 return size;
4088
4089         /* alignment checks will add in reg->off themselves */
4090         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4091         if (err)
4092                 return err;
4093
4094         /* for access checks, reg->off is just part of off */
4095         off += reg->off;
4096
4097         if (reg->type == PTR_TO_MAP_KEY) {
4098                 if (t == BPF_WRITE) {
4099                         verbose(env, "write to change key R%d not allowed\n", regno);
4100                         return -EACCES;
4101                 }
4102
4103                 err = check_mem_region_access(env, regno, off, size,
4104                                               reg->map_ptr->key_size, false);
4105                 if (err)
4106                         return err;
4107                 if (value_regno >= 0)
4108                         mark_reg_unknown(env, regs, value_regno);
4109         } else if (reg->type == PTR_TO_MAP_VALUE) {
4110                 if (t == BPF_WRITE && value_regno >= 0 &&
4111                     is_pointer_value(env, value_regno)) {
4112                         verbose(env, "R%d leaks addr into map\n", value_regno);
4113                         return -EACCES;
4114                 }
4115                 err = check_map_access_type(env, regno, off, size, t);
4116                 if (err)
4117                         return err;
4118                 err = check_map_access(env, regno, off, size, false);
4119                 if (!err && t == BPF_READ && value_regno >= 0) {
4120                         struct bpf_map *map = reg->map_ptr;
4121
4122                         /* if map is read-only, track its contents as scalars */
4123                         if (tnum_is_const(reg->var_off) &&
4124                             bpf_map_is_rdonly(map) &&
4125                             map->ops->map_direct_value_addr) {
4126                                 int map_off = off + reg->var_off.value;
4127                                 u64 val = 0;
4128
4129                                 err = bpf_map_direct_read(map, map_off, size,
4130                                                           &val);
4131                                 if (err)
4132                                         return err;
4133
4134                                 regs[value_regno].type = SCALAR_VALUE;
4135                                 __mark_reg_known(&regs[value_regno], val);
4136                         } else {
4137                                 mark_reg_unknown(env, regs, value_regno);
4138                         }
4139                 }
4140         } else if (reg->type == PTR_TO_MEM) {
4141                 if (t == BPF_WRITE && value_regno >= 0 &&
4142                     is_pointer_value(env, value_regno)) {
4143                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4144                         return -EACCES;
4145                 }
4146                 err = check_mem_region_access(env, regno, off, size,
4147                                               reg->mem_size, false);
4148                 if (!err && t == BPF_READ && value_regno >= 0)
4149                         mark_reg_unknown(env, regs, value_regno);
4150         } else if (reg->type == PTR_TO_CTX) {
4151                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4152                 struct btf *btf = NULL;
4153                 u32 btf_id = 0;
4154
4155                 if (t == BPF_WRITE && value_regno >= 0 &&
4156                     is_pointer_value(env, value_regno)) {
4157                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4158                         return -EACCES;
4159                 }
4160
4161                 err = check_ctx_reg(env, reg, regno);
4162                 if (err < 0)
4163                         return err;
4164
4165                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4166                 if (err)
4167                         verbose_linfo(env, insn_idx, "; ");
4168                 if (!err && t == BPF_READ && value_regno >= 0) {
4169                         /* ctx access returns either a scalar, or a
4170                          * PTR_TO_PACKET[_META,_END]. In the latter
4171                          * case, we know the offset is zero.
4172                          */
4173                         if (reg_type == SCALAR_VALUE) {
4174                                 mark_reg_unknown(env, regs, value_regno);
4175                         } else {
4176                                 mark_reg_known_zero(env, regs,
4177                                                     value_regno);
4178                                 if (reg_type_may_be_null(reg_type))
4179                                         regs[value_regno].id = ++env->id_gen;
4180                                 /* A load of ctx field could have different
4181                                  * actual load size with the one encoded in the
4182                                  * insn. When the dst is PTR, it is for sure not
4183                                  * a sub-register.
4184                                  */
4185                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4186                                 if (reg_type == PTR_TO_BTF_ID ||
4187                                     reg_type == PTR_TO_BTF_ID_OR_NULL) {
4188                                         regs[value_regno].btf = btf;
4189                                         regs[value_regno].btf_id = btf_id;
4190                                 }
4191                         }
4192                         regs[value_regno].type = reg_type;
4193                 }
4194
4195         } else if (reg->type == PTR_TO_STACK) {
4196                 /* Basic bounds checks. */
4197                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4198                 if (err)
4199                         return err;
4200
4201                 state = func(env, reg);
4202                 err = update_stack_depth(env, state, off);
4203                 if (err)
4204                         return err;
4205
4206                 if (t == BPF_READ)
4207                         err = check_stack_read(env, regno, off, size,
4208                                                value_regno);
4209                 else
4210                         err = check_stack_write(env, regno, off, size,
4211                                                 value_regno, insn_idx);
4212         } else if (reg_is_pkt_pointer(reg)) {
4213                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4214                         verbose(env, "cannot write into packet\n");
4215                         return -EACCES;
4216                 }
4217                 if (t == BPF_WRITE && value_regno >= 0 &&
4218                     is_pointer_value(env, value_regno)) {
4219                         verbose(env, "R%d leaks addr into packet\n",
4220                                 value_regno);
4221                         return -EACCES;
4222                 }
4223                 err = check_packet_access(env, regno, off, size, false);
4224                 if (!err && t == BPF_READ && value_regno >= 0)
4225                         mark_reg_unknown(env, regs, value_regno);
4226         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4227                 if (t == BPF_WRITE && value_regno >= 0 &&
4228                     is_pointer_value(env, value_regno)) {
4229                         verbose(env, "R%d leaks addr into flow keys\n",
4230                                 value_regno);
4231                         return -EACCES;
4232                 }
4233
4234                 err = check_flow_keys_access(env, off, size);
4235                 if (!err && t == BPF_READ && value_regno >= 0)
4236                         mark_reg_unknown(env, regs, value_regno);
4237         } else if (type_is_sk_pointer(reg->type)) {
4238                 if (t == BPF_WRITE) {
4239                         verbose(env, "R%d cannot write into %s\n",
4240                                 regno, reg_type_str[reg->type]);
4241                         return -EACCES;
4242                 }
4243                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4244                 if (!err && value_regno >= 0)
4245                         mark_reg_unknown(env, regs, value_regno);
4246         } else if (reg->type == PTR_TO_TP_BUFFER) {
4247                 err = check_tp_buffer_access(env, reg, regno, off, size);
4248                 if (!err && t == BPF_READ && value_regno >= 0)
4249                         mark_reg_unknown(env, regs, value_regno);
4250         } else if (reg->type == PTR_TO_BTF_ID) {
4251                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4252                                               value_regno);
4253         } else if (reg->type == CONST_PTR_TO_MAP) {
4254                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4255                                               value_regno);
4256         } else if (reg->type == PTR_TO_RDONLY_BUF) {
4257                 if (t == BPF_WRITE) {
4258                         verbose(env, "R%d cannot write into %s\n",
4259                                 regno, reg_type_str[reg->type]);
4260                         return -EACCES;
4261                 }
4262                 err = check_buffer_access(env, reg, regno, off, size, false,
4263                                           "rdonly",
4264                                           &env->prog->aux->max_rdonly_access);
4265                 if (!err && value_regno >= 0)
4266                         mark_reg_unknown(env, regs, value_regno);
4267         } else if (reg->type == PTR_TO_RDWR_BUF) {
4268                 err = check_buffer_access(env, reg, regno, off, size, false,
4269                                           "rdwr",
4270                                           &env->prog->aux->max_rdwr_access);
4271                 if (!err && t == BPF_READ && value_regno >= 0)
4272                         mark_reg_unknown(env, regs, value_regno);
4273         } else {
4274                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4275                         reg_type_str[reg->type]);
4276                 return -EACCES;
4277         }
4278
4279         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4280             regs[value_regno].type == SCALAR_VALUE) {
4281                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4282                 coerce_reg_to_size(&regs[value_regno], size);
4283         }
4284         return err;
4285 }
4286
4287 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4288 {
4289         int load_reg;
4290         int err;
4291
4292         switch (insn->imm) {
4293         case BPF_ADD:
4294         case BPF_ADD | BPF_FETCH:
4295         case BPF_AND:
4296         case BPF_AND | BPF_FETCH:
4297         case BPF_OR:
4298         case BPF_OR | BPF_FETCH:
4299         case BPF_XOR:
4300         case BPF_XOR | BPF_FETCH:
4301         case BPF_XCHG:
4302         case BPF_CMPXCHG:
4303                 break;
4304         default:
4305                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4306                 return -EINVAL;
4307         }
4308
4309         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4310                 verbose(env, "invalid atomic operand size\n");
4311                 return -EINVAL;
4312         }
4313
4314         /* check src1 operand */
4315         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4316         if (err)
4317                 return err;
4318
4319         /* check src2 operand */
4320         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4321         if (err)
4322                 return err;
4323
4324         if (insn->imm == BPF_CMPXCHG) {
4325                 /* Check comparison of R0 with memory location */
4326                 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4327                 if (err)
4328                         return err;
4329         }
4330
4331         if (is_pointer_value(env, insn->src_reg)) {
4332                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4333                 return -EACCES;
4334         }
4335
4336         if (is_ctx_reg(env, insn->dst_reg) ||
4337             is_pkt_reg(env, insn->dst_reg) ||
4338             is_flow_key_reg(env, insn->dst_reg) ||
4339             is_sk_reg(env, insn->dst_reg)) {
4340                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4341                         insn->dst_reg,
4342                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
4343                 return -EACCES;
4344         }
4345
4346         if (insn->imm & BPF_FETCH) {
4347                 if (insn->imm == BPF_CMPXCHG)
4348                         load_reg = BPF_REG_0;
4349                 else
4350                         load_reg = insn->src_reg;
4351
4352                 /* check and record load of old value */
4353                 err = check_reg_arg(env, load_reg, DST_OP);
4354                 if (err)
4355                         return err;
4356         } else {
4357                 /* This instruction accesses a memory location but doesn't
4358                  * actually load it into a register.
4359                  */
4360                 load_reg = -1;
4361         }
4362
4363         /* check whether we can read the memory */
4364         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4365                                BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4366         if (err)
4367                 return err;
4368
4369         /* check whether we can write into the same memory */
4370         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4371                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4372         if (err)
4373                 return err;
4374
4375         return 0;
4376 }
4377
4378 /* When register 'regno' is used to read the stack (either directly or through
4379  * a helper function) make sure that it's within stack boundary and, depending
4380  * on the access type, that all elements of the stack are initialized.
4381  *
4382  * 'off' includes 'regno->off', but not its dynamic part (if any).
4383  *
4384  * All registers that have been spilled on the stack in the slots within the
4385  * read offsets are marked as read.
4386  */
4387 static int check_stack_range_initialized(
4388                 struct bpf_verifier_env *env, int regno, int off,
4389                 int access_size, bool zero_size_allowed,
4390                 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4391 {
4392         struct bpf_reg_state *reg = reg_state(env, regno);
4393         struct bpf_func_state *state = func(env, reg);
4394         int err, min_off, max_off, i, j, slot, spi;
4395         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4396         enum bpf_access_type bounds_check_type;
4397         /* Some accesses can write anything into the stack, others are
4398          * read-only.
4399          */
4400         bool clobber = false;
4401
4402         if (access_size == 0 && !zero_size_allowed) {
4403                 verbose(env, "invalid zero-sized read\n");
4404                 return -EACCES;
4405         }
4406
4407         if (type == ACCESS_HELPER) {
4408                 /* The bounds checks for writes are more permissive than for
4409                  * reads. However, if raw_mode is not set, we'll do extra
4410                  * checks below.
4411                  */
4412                 bounds_check_type = BPF_WRITE;
4413                 clobber = true;
4414         } else {
4415                 bounds_check_type = BPF_READ;
4416         }
4417         err = check_stack_access_within_bounds(env, regno, off, access_size,
4418                                                type, bounds_check_type);
4419         if (err)
4420                 return err;
4421
4422
4423         if (tnum_is_const(reg->var_off)) {
4424                 min_off = max_off = reg->var_off.value + off;
4425         } else {
4426                 /* Variable offset is prohibited for unprivileged mode for
4427                  * simplicity since it requires corresponding support in
4428                  * Spectre masking for stack ALU.
4429                  * See also retrieve_ptr_limit().
4430                  */
4431                 if (!env->bypass_spec_v1) {
4432                         char tn_buf[48];
4433
4434                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4435                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4436                                 regno, err_extra, tn_buf);
4437                         return -EACCES;
4438                 }
4439                 /* Only initialized buffer on stack is allowed to be accessed
4440                  * with variable offset. With uninitialized buffer it's hard to
4441                  * guarantee that whole memory is marked as initialized on
4442                  * helper return since specific bounds are unknown what may
4443                  * cause uninitialized stack leaking.
4444                  */
4445                 if (meta && meta->raw_mode)
4446                         meta = NULL;
4447
4448                 min_off = reg->smin_value + off;
4449                 max_off = reg->smax_value + off;
4450         }
4451
4452         if (meta && meta->raw_mode) {
4453                 meta->access_size = access_size;
4454                 meta->regno = regno;
4455                 return 0;
4456         }
4457
4458         for (i = min_off; i < max_off + access_size; i++) {
4459                 u8 *stype;
4460
4461                 slot = -i - 1;
4462                 spi = slot / BPF_REG_SIZE;
4463                 if (state->allocated_stack <= slot)
4464                         goto err;
4465                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4466                 if (*stype == STACK_MISC)
4467                         goto mark;
4468                 if (*stype == STACK_ZERO) {
4469                         if (clobber) {
4470                                 /* helper can write anything into the stack */
4471                                 *stype = STACK_MISC;
4472                         }
4473                         goto mark;
4474                 }
4475
4476                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4477                     state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4478                         goto mark;
4479
4480                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4481                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4482                      env->allow_ptr_leaks)) {
4483                         if (clobber) {
4484                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4485                                 for (j = 0; j < BPF_REG_SIZE; j++)
4486                                         state->stack[spi].slot_type[j] = STACK_MISC;
4487                         }
4488                         goto mark;
4489                 }
4490
4491 err:
4492                 if (tnum_is_const(reg->var_off)) {
4493                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4494                                 err_extra, regno, min_off, i - min_off, access_size);
4495                 } else {
4496                         char tn_buf[48];
4497
4498                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4499                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4500                                 err_extra, regno, tn_buf, i - min_off, access_size);
4501                 }
4502                 return -EACCES;
4503 mark:
4504                 /* reading any byte out of 8-byte 'spill_slot' will cause
4505                  * the whole slot to be marked as 'read'
4506                  */
4507                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4508                               state->stack[spi].spilled_ptr.parent,
4509                               REG_LIVE_READ64);
4510         }
4511         return update_stack_depth(env, state, min_off);
4512 }
4513
4514 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4515                                    int access_size, bool zero_size_allowed,
4516                                    struct bpf_call_arg_meta *meta)
4517 {
4518         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4519
4520         switch (reg->type) {
4521         case PTR_TO_PACKET:
4522         case PTR_TO_PACKET_META:
4523                 return check_packet_access(env, regno, reg->off, access_size,
4524                                            zero_size_allowed);
4525         case PTR_TO_MAP_KEY:
4526                 return check_mem_region_access(env, regno, reg->off, access_size,
4527                                                reg->map_ptr->key_size, false);
4528         case PTR_TO_MAP_VALUE:
4529                 if (check_map_access_type(env, regno, reg->off, access_size,
4530                                           meta && meta->raw_mode ? BPF_WRITE :
4531                                           BPF_READ))
4532                         return -EACCES;
4533                 return check_map_access(env, regno, reg->off, access_size,
4534                                         zero_size_allowed);
4535         case PTR_TO_MEM:
4536                 return check_mem_region_access(env, regno, reg->off,
4537                                                access_size, reg->mem_size,
4538                                                zero_size_allowed);
4539         case PTR_TO_RDONLY_BUF:
4540                 if (meta && meta->raw_mode)
4541                         return -EACCES;
4542                 return check_buffer_access(env, reg, regno, reg->off,
4543                                            access_size, zero_size_allowed,
4544                                            "rdonly",
4545                                            &env->prog->aux->max_rdonly_access);
4546         case PTR_TO_RDWR_BUF:
4547                 return check_buffer_access(env, reg, regno, reg->off,
4548                                            access_size, zero_size_allowed,
4549                                            "rdwr",
4550                                            &env->prog->aux->max_rdwr_access);
4551         case PTR_TO_STACK:
4552                 return check_stack_range_initialized(
4553                                 env,
4554                                 regno, reg->off, access_size,
4555                                 zero_size_allowed, ACCESS_HELPER, meta);
4556         default: /* scalar_value or invalid ptr */
4557                 /* Allow zero-byte read from NULL, regardless of pointer type */
4558                 if (zero_size_allowed && access_size == 0 &&
4559                     register_is_null(reg))
4560                         return 0;
4561
4562                 verbose(env, "R%d type=%s expected=%s\n", regno,
4563                         reg_type_str[reg->type],
4564                         reg_type_str[PTR_TO_STACK]);
4565                 return -EACCES;
4566         }
4567 }
4568
4569 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4570                    u32 regno, u32 mem_size)
4571 {
4572         if (register_is_null(reg))
4573                 return 0;
4574
4575         if (reg_type_may_be_null(reg->type)) {
4576                 /* Assuming that the register contains a value check if the memory
4577                  * access is safe. Temporarily save and restore the register's state as
4578                  * the conversion shouldn't be visible to a caller.
4579                  */
4580                 const struct bpf_reg_state saved_reg = *reg;
4581                 int rv;
4582
4583                 mark_ptr_not_null_reg(reg);
4584                 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4585                 *reg = saved_reg;
4586                 return rv;
4587         }
4588
4589         return check_helper_mem_access(env, regno, mem_size, true, NULL);
4590 }
4591
4592 /* Implementation details:
4593  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4594  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4595  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4596  * value_or_null->value transition, since the verifier only cares about
4597  * the range of access to valid map value pointer and doesn't care about actual
4598  * address of the map element.
4599  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4600  * reg->id > 0 after value_or_null->value transition. By doing so
4601  * two bpf_map_lookups will be considered two different pointers that
4602  * point to different bpf_spin_locks.
4603  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4604  * dead-locks.
4605  * Since only one bpf_spin_lock is allowed the checks are simpler than
4606  * reg_is_refcounted() logic. The verifier needs to remember only
4607  * one spin_lock instead of array of acquired_refs.
4608  * cur_state->active_spin_lock remembers which map value element got locked
4609  * and clears it after bpf_spin_unlock.
4610  */
4611 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4612                              bool is_lock)
4613 {
4614         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4615         struct bpf_verifier_state *cur = env->cur_state;
4616         bool is_const = tnum_is_const(reg->var_off);
4617         struct bpf_map *map = reg->map_ptr;
4618         u64 val = reg->var_off.value;
4619
4620         if (!is_const) {
4621                 verbose(env,
4622                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4623                         regno);
4624                 return -EINVAL;
4625         }
4626         if (!map->btf) {
4627                 verbose(env,
4628                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4629                         map->name);
4630                 return -EINVAL;
4631         }
4632         if (!map_value_has_spin_lock(map)) {
4633                 if (map->spin_lock_off == -E2BIG)
4634                         verbose(env,
4635                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4636                                 map->name);
4637                 else if (map->spin_lock_off == -ENOENT)
4638                         verbose(env,
4639                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4640                                 map->name);
4641                 else
4642                         verbose(env,
4643                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4644                                 map->name);
4645                 return -EINVAL;
4646         }
4647         if (map->spin_lock_off != val + reg->off) {
4648                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4649                         val + reg->off);
4650                 return -EINVAL;
4651         }
4652         if (is_lock) {
4653                 if (cur->active_spin_lock) {
4654                         verbose(env,
4655                                 "Locking two bpf_spin_locks are not allowed\n");
4656                         return -EINVAL;
4657                 }
4658                 cur->active_spin_lock = reg->id;
4659         } else {
4660                 if (!cur->active_spin_lock) {
4661                         verbose(env, "bpf_spin_unlock without taking a lock\n");
4662                         return -EINVAL;
4663                 }
4664                 if (cur->active_spin_lock != reg->id) {
4665                         verbose(env, "bpf_spin_unlock of different lock\n");
4666                         return -EINVAL;
4667                 }
4668                 cur->active_spin_lock = 0;
4669         }
4670         return 0;
4671 }
4672
4673 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4674                               struct bpf_call_arg_meta *meta)
4675 {
4676         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4677         bool is_const = tnum_is_const(reg->var_off);
4678         struct bpf_map *map = reg->map_ptr;
4679         u64 val = reg->var_off.value;
4680
4681         if (!is_const) {
4682                 verbose(env,
4683                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
4684                         regno);
4685                 return -EINVAL;
4686         }
4687         if (!map->btf) {
4688                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
4689                         map->name);
4690                 return -EINVAL;
4691         }
4692         if (!map_value_has_timer(map)) {
4693                 if (map->timer_off == -E2BIG)
4694                         verbose(env,
4695                                 "map '%s' has more than one 'struct bpf_timer'\n",
4696                                 map->name);
4697                 else if (map->timer_off == -ENOENT)
4698                         verbose(env,
4699                                 "map '%s' doesn't have 'struct bpf_timer'\n",
4700                                 map->name);
4701                 else
4702                         verbose(env,
4703                                 "map '%s' is not a struct type or bpf_timer is mangled\n",
4704                                 map->name);
4705                 return -EINVAL;
4706         }
4707         if (map->timer_off != val + reg->off) {
4708                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
4709                         val + reg->off, map->timer_off);
4710                 return -EINVAL;
4711         }
4712         if (meta->map_ptr) {
4713                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
4714                 return -EFAULT;
4715         }
4716         meta->map_uid = reg->map_uid;
4717         meta->map_ptr = map;
4718         return 0;
4719 }
4720
4721 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4722 {
4723         return type == ARG_PTR_TO_MEM ||
4724                type == ARG_PTR_TO_MEM_OR_NULL ||
4725                type == ARG_PTR_TO_UNINIT_MEM;
4726 }
4727
4728 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4729 {
4730         return type == ARG_CONST_SIZE ||
4731                type == ARG_CONST_SIZE_OR_ZERO;
4732 }
4733
4734 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4735 {
4736         return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4737 }
4738
4739 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4740 {
4741         return type == ARG_PTR_TO_INT ||
4742                type == ARG_PTR_TO_LONG;
4743 }
4744
4745 static int int_ptr_type_to_size(enum bpf_arg_type type)
4746 {
4747         if (type == ARG_PTR_TO_INT)
4748                 return sizeof(u32);
4749         else if (type == ARG_PTR_TO_LONG)
4750                 return sizeof(u64);
4751
4752         return -EINVAL;
4753 }
4754
4755 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4756                                  const struct bpf_call_arg_meta *meta,
4757                                  enum bpf_arg_type *arg_type)
4758 {
4759         if (!meta->map_ptr) {
4760                 /* kernel subsystem misconfigured verifier */
4761                 verbose(env, "invalid map_ptr to access map->type\n");
4762                 return -EACCES;
4763         }
4764
4765         switch (meta->map_ptr->map_type) {
4766         case BPF_MAP_TYPE_SOCKMAP:
4767         case BPF_MAP_TYPE_SOCKHASH:
4768                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4769                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4770                 } else {
4771                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
4772                         return -EINVAL;
4773                 }
4774                 break;
4775
4776         default:
4777                 break;
4778         }
4779         return 0;
4780 }
4781
4782 struct bpf_reg_types {
4783         const enum bpf_reg_type types[10];
4784         u32 *btf_id;
4785 };
4786
4787 static const struct bpf_reg_types map_key_value_types = {
4788         .types = {
4789                 PTR_TO_STACK,
4790                 PTR_TO_PACKET,
4791                 PTR_TO_PACKET_META,
4792                 PTR_TO_MAP_KEY,
4793                 PTR_TO_MAP_VALUE,
4794         },
4795 };
4796
4797 static const struct bpf_reg_types sock_types = {
4798         .types = {
4799                 PTR_TO_SOCK_COMMON,
4800                 PTR_TO_SOCKET,
4801                 PTR_TO_TCP_SOCK,
4802                 PTR_TO_XDP_SOCK,
4803         },
4804 };
4805
4806 #ifdef CONFIG_NET
4807 static const struct bpf_reg_types btf_id_sock_common_types = {
4808         .types = {
4809                 PTR_TO_SOCK_COMMON,
4810                 PTR_TO_SOCKET,
4811                 PTR_TO_TCP_SOCK,
4812                 PTR_TO_XDP_SOCK,
4813                 PTR_TO_BTF_ID,
4814         },
4815         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4816 };
4817 #endif
4818
4819 static const struct bpf_reg_types mem_types = {
4820         .types = {
4821                 PTR_TO_STACK,
4822                 PTR_TO_PACKET,
4823                 PTR_TO_PACKET_META,
4824                 PTR_TO_MAP_KEY,
4825                 PTR_TO_MAP_VALUE,
4826                 PTR_TO_MEM,
4827                 PTR_TO_RDONLY_BUF,
4828                 PTR_TO_RDWR_BUF,
4829         },
4830 };
4831
4832 static const struct bpf_reg_types int_ptr_types = {
4833         .types = {
4834                 PTR_TO_STACK,
4835                 PTR_TO_PACKET,
4836                 PTR_TO_PACKET_META,
4837                 PTR_TO_MAP_KEY,
4838                 PTR_TO_MAP_VALUE,
4839         },
4840 };
4841
4842 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4843 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4844 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4845 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4846 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4847 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4848 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4849 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4850 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4851 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
4852 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
4853 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
4854
4855 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4856         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
4857         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
4858         [ARG_PTR_TO_UNINIT_MAP_VALUE]   = &map_key_value_types,
4859         [ARG_PTR_TO_MAP_VALUE_OR_NULL]  = &map_key_value_types,
4860         [ARG_CONST_SIZE]                = &scalar_types,
4861         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
4862         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
4863         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
4864         [ARG_PTR_TO_CTX]                = &context_types,
4865         [ARG_PTR_TO_CTX_OR_NULL]        = &context_types,
4866         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
4867 #ifdef CONFIG_NET
4868         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4869 #endif
4870         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
4871         [ARG_PTR_TO_SOCKET_OR_NULL]     = &fullsock_types,
4872         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
4873         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
4874         [ARG_PTR_TO_MEM]                = &mem_types,
4875         [ARG_PTR_TO_MEM_OR_NULL]        = &mem_types,
4876         [ARG_PTR_TO_UNINIT_MEM]         = &mem_types,
4877         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
4878         [ARG_PTR_TO_ALLOC_MEM_OR_NULL]  = &alloc_mem_types,
4879         [ARG_PTR_TO_INT]                = &int_ptr_types,
4880         [ARG_PTR_TO_LONG]               = &int_ptr_types,
4881         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
4882         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
4883         [ARG_PTR_TO_STACK_OR_NULL]      = &stack_ptr_types,
4884         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
4885         [ARG_PTR_TO_TIMER]              = &timer_types,
4886 };
4887
4888 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4889                           enum bpf_arg_type arg_type,
4890                           const u32 *arg_btf_id)
4891 {
4892         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4893         enum bpf_reg_type expected, type = reg->type;
4894         const struct bpf_reg_types *compatible;
4895         int i, j;
4896
4897         compatible = compatible_reg_types[arg_type];
4898         if (!compatible) {
4899                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4900                 return -EFAULT;
4901         }
4902
4903         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4904                 expected = compatible->types[i];
4905                 if (expected == NOT_INIT)
4906                         break;
4907
4908                 if (type == expected)
4909                         goto found;
4910         }
4911
4912         verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4913         for (j = 0; j + 1 < i; j++)
4914                 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4915         verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4916         return -EACCES;
4917
4918 found:
4919         if (type == PTR_TO_BTF_ID) {
4920                 if (!arg_btf_id) {
4921                         if (!compatible->btf_id) {
4922                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4923                                 return -EFAULT;
4924                         }
4925                         arg_btf_id = compatible->btf_id;
4926                 }
4927
4928                 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4929                                           btf_vmlinux, *arg_btf_id)) {
4930                         verbose(env, "R%d is of type %s but %s is expected\n",
4931                                 regno, kernel_type_name(reg->btf, reg->btf_id),
4932                                 kernel_type_name(btf_vmlinux, *arg_btf_id));
4933                         return -EACCES;
4934                 }
4935
4936                 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4937                         verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4938                                 regno);
4939                         return -EACCES;
4940                 }
4941         }
4942
4943         return 0;
4944 }
4945
4946 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4947                           struct bpf_call_arg_meta *meta,
4948                           const struct bpf_func_proto *fn)
4949 {
4950         u32 regno = BPF_REG_1 + arg;
4951         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4952         enum bpf_arg_type arg_type = fn->arg_type[arg];
4953         enum bpf_reg_type type = reg->type;
4954         int err = 0;
4955
4956         if (arg_type == ARG_DONTCARE)
4957                 return 0;
4958
4959         err = check_reg_arg(env, regno, SRC_OP);
4960         if (err)
4961                 return err;
4962
4963         if (arg_type == ARG_ANYTHING) {
4964                 if (is_pointer_value(env, regno)) {
4965                         verbose(env, "R%d leaks addr into helper function\n",
4966                                 regno);
4967                         return -EACCES;
4968                 }
4969                 return 0;
4970         }
4971
4972         if (type_is_pkt_pointer(type) &&
4973             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4974                 verbose(env, "helper access to the packet is not allowed\n");
4975                 return -EACCES;
4976         }
4977
4978         if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4979             arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4980             arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4981                 err = resolve_map_arg_type(env, meta, &arg_type);
4982                 if (err)
4983                         return err;
4984         }
4985
4986         if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4987                 /* A NULL register has a SCALAR_VALUE type, so skip
4988                  * type checking.
4989                  */
4990                 goto skip_type_check;
4991
4992         err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4993         if (err)
4994                 return err;
4995
4996         if (type == PTR_TO_CTX) {
4997                 err = check_ctx_reg(env, reg, regno);
4998                 if (err < 0)
4999                         return err;
5000         }
5001
5002 skip_type_check:
5003         if (reg->ref_obj_id) {
5004                 if (meta->ref_obj_id) {
5005                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5006                                 regno, reg->ref_obj_id,
5007                                 meta->ref_obj_id);
5008                         return -EFAULT;
5009                 }
5010                 meta->ref_obj_id = reg->ref_obj_id;
5011         }
5012
5013         if (arg_type == ARG_CONST_MAP_PTR) {
5014                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5015                 if (meta->map_ptr) {
5016                         /* Use map_uid (which is unique id of inner map) to reject:
5017                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5018                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5019                          * if (inner_map1 && inner_map2) {
5020                          *     timer = bpf_map_lookup_elem(inner_map1);
5021                          *     if (timer)
5022                          *         // mismatch would have been allowed
5023                          *         bpf_timer_init(timer, inner_map2);
5024                          * }
5025                          *
5026                          * Comparing map_ptr is enough to distinguish normal and outer maps.
5027                          */
5028                         if (meta->map_ptr != reg->map_ptr ||
5029                             meta->map_uid != reg->map_uid) {
5030                                 verbose(env,
5031                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5032                                         meta->map_uid, reg->map_uid);
5033                                 return -EINVAL;
5034                         }
5035                 }
5036                 meta->map_ptr = reg->map_ptr;
5037                 meta->map_uid = reg->map_uid;
5038         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5039                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
5040                  * check that [key, key + map->key_size) are within
5041                  * stack limits and initialized
5042                  */
5043                 if (!meta->map_ptr) {
5044                         /* in function declaration map_ptr must come before
5045                          * map_key, so that it's verified and known before
5046                          * we have to check map_key here. Otherwise it means
5047                          * that kernel subsystem misconfigured verifier
5048                          */
5049                         verbose(env, "invalid map_ptr to access map->key\n");
5050                         return -EACCES;
5051                 }
5052                 err = check_helper_mem_access(env, regno,
5053                                               meta->map_ptr->key_size, false,
5054                                               NULL);
5055         } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5056                    (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
5057                     !register_is_null(reg)) ||
5058                    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5059                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
5060                  * check [value, value + map->value_size) validity
5061                  */
5062                 if (!meta->map_ptr) {
5063                         /* kernel subsystem misconfigured verifier */
5064                         verbose(env, "invalid map_ptr to access map->value\n");
5065                         return -EACCES;
5066                 }
5067                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5068                 err = check_helper_mem_access(env, regno,
5069                                               meta->map_ptr->value_size, false,
5070                                               meta);
5071         } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5072                 if (!reg->btf_id) {
5073                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5074                         return -EACCES;
5075                 }
5076                 meta->ret_btf = reg->btf;
5077                 meta->ret_btf_id = reg->btf_id;
5078         } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5079                 if (meta->func_id == BPF_FUNC_spin_lock) {
5080                         if (process_spin_lock(env, regno, true))
5081                                 return -EACCES;
5082                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
5083                         if (process_spin_lock(env, regno, false))
5084                                 return -EACCES;
5085                 } else {
5086                         verbose(env, "verifier internal error\n");
5087                         return -EFAULT;
5088                 }
5089         } else if (arg_type == ARG_PTR_TO_TIMER) {
5090                 if (process_timer_func(env, regno, meta))
5091                         return -EACCES;
5092         } else if (arg_type == ARG_PTR_TO_FUNC) {
5093                 meta->subprogno = reg->subprogno;
5094         } else if (arg_type_is_mem_ptr(arg_type)) {
5095                 /* The access to this pointer is only checked when we hit the
5096                  * next is_mem_size argument below.
5097                  */
5098                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5099         } else if (arg_type_is_mem_size(arg_type)) {
5100                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5101
5102                 /* This is used to refine r0 return value bounds for helpers
5103                  * that enforce this value as an upper bound on return values.
5104                  * See do_refine_retval_range() for helpers that can refine
5105                  * the return value. C type of helper is u32 so we pull register
5106                  * bound from umax_value however, if negative verifier errors
5107                  * out. Only upper bounds can be learned because retval is an
5108                  * int type and negative retvals are allowed.
5109                  */
5110                 meta->msize_max_value = reg->umax_value;
5111
5112                 /* The register is SCALAR_VALUE; the access check
5113                  * happens using its boundaries.
5114                  */
5115                 if (!tnum_is_const(reg->var_off))
5116                         /* For unprivileged variable accesses, disable raw
5117                          * mode so that the program is required to
5118                          * initialize all the memory that the helper could
5119                          * just partially fill up.
5120                          */
5121                         meta = NULL;
5122
5123                 if (reg->smin_value < 0) {
5124                         verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5125                                 regno);
5126                         return -EACCES;
5127                 }
5128
5129                 if (reg->umin_value == 0) {
5130                         err = check_helper_mem_access(env, regno - 1, 0,
5131                                                       zero_size_allowed,
5132                                                       meta);
5133                         if (err)
5134                                 return err;
5135                 }
5136
5137                 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5138                         verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5139                                 regno);
5140                         return -EACCES;
5141                 }
5142                 err = check_helper_mem_access(env, regno - 1,
5143                                               reg->umax_value,
5144                                               zero_size_allowed, meta);
5145                 if (!err)
5146                         err = mark_chain_precision(env, regno);
5147         } else if (arg_type_is_alloc_size(arg_type)) {
5148                 if (!tnum_is_const(reg->var_off)) {
5149                         verbose(env, "R%d is not a known constant'\n",
5150                                 regno);
5151                         return -EACCES;
5152                 }
5153                 meta->mem_size = reg->var_off.value;
5154         } else if (arg_type_is_int_ptr(arg_type)) {
5155                 int size = int_ptr_type_to_size(arg_type);
5156
5157                 err = check_helper_mem_access(env, regno, size, false, meta);
5158                 if (err)
5159                         return err;
5160                 err = check_ptr_alignment(env, reg, 0, size, true);
5161         } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5162                 struct bpf_map *map = reg->map_ptr;
5163                 int map_off;
5164                 u64 map_addr;
5165                 char *str_ptr;
5166
5167                 if (!bpf_map_is_rdonly(map)) {
5168                         verbose(env, "R%d does not point to a readonly map'\n", regno);
5169                         return -EACCES;
5170                 }
5171
5172                 if (!tnum_is_const(reg->var_off)) {
5173                         verbose(env, "R%d is not a constant address'\n", regno);
5174                         return -EACCES;
5175                 }
5176
5177                 if (!map->ops->map_direct_value_addr) {
5178                         verbose(env, "no direct value access support for this map type\n");
5179                         return -EACCES;
5180                 }
5181
5182                 err = check_map_access(env, regno, reg->off,
5183                                        map->value_size - reg->off, false);
5184                 if (err)
5185                         return err;
5186
5187                 map_off = reg->off + reg->var_off.value;
5188                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5189                 if (err) {
5190                         verbose(env, "direct value access on string failed\n");
5191                         return err;
5192                 }
5193
5194                 str_ptr = (char *)(long)(map_addr);
5195                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5196                         verbose(env, "string is not zero-terminated\n");
5197                         return -EINVAL;
5198                 }
5199         }
5200
5201         return err;
5202 }
5203
5204 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5205 {
5206         enum bpf_attach_type eatype = env->prog->expected_attach_type;
5207         enum bpf_prog_type type = resolve_prog_type(env->prog);
5208
5209         if (func_id != BPF_FUNC_map_update_elem)
5210                 return false;
5211
5212         /* It's not possible to get access to a locked struct sock in these
5213          * contexts, so updating is safe.
5214          */
5215         switch (type) {
5216         case BPF_PROG_TYPE_TRACING:
5217                 if (eatype == BPF_TRACE_ITER)
5218                         return true;
5219                 break;
5220         case BPF_PROG_TYPE_SOCKET_FILTER:
5221         case BPF_PROG_TYPE_SCHED_CLS:
5222         case BPF_PROG_TYPE_SCHED_ACT:
5223         case BPF_PROG_TYPE_XDP:
5224         case BPF_PROG_TYPE_SK_REUSEPORT:
5225         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5226         case BPF_PROG_TYPE_SK_LOOKUP:
5227                 return true;
5228         default:
5229                 break;
5230         }
5231
5232         verbose(env, "cannot update sockmap in this context\n");
5233         return false;
5234 }
5235
5236 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5237 {
5238         return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5239 }
5240
5241 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5242                                         struct bpf_map *map, int func_id)
5243 {
5244         if (!map)
5245                 return 0;
5246
5247         /* We need a two way check, first is from map perspective ... */
5248         switch (map->map_type) {
5249         case BPF_MAP_TYPE_PROG_ARRAY:
5250                 if (func_id != BPF_FUNC_tail_call)
5251                         goto error;
5252                 break;
5253         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5254                 if (func_id != BPF_FUNC_perf_event_read &&
5255                     func_id != BPF_FUNC_perf_event_output &&
5256                     func_id != BPF_FUNC_skb_output &&
5257                     func_id != BPF_FUNC_perf_event_read_value &&
5258                     func_id != BPF_FUNC_xdp_output)
5259                         goto error;
5260                 break;
5261         case BPF_MAP_TYPE_RINGBUF:
5262                 if (func_id != BPF_FUNC_ringbuf_output &&
5263                     func_id != BPF_FUNC_ringbuf_reserve &&
5264                     func_id != BPF_FUNC_ringbuf_submit &&
5265                     func_id != BPF_FUNC_ringbuf_discard &&
5266                     func_id != BPF_FUNC_ringbuf_query)
5267                         goto error;
5268                 break;
5269         case BPF_MAP_TYPE_STACK_TRACE:
5270                 if (func_id != BPF_FUNC_get_stackid)
5271                         goto error;
5272                 break;
5273         case BPF_MAP_TYPE_CGROUP_ARRAY:
5274                 if (func_id != BPF_FUNC_skb_under_cgroup &&
5275                     func_id != BPF_FUNC_current_task_under_cgroup)
5276                         goto error;
5277                 break;
5278         case BPF_MAP_TYPE_CGROUP_STORAGE:
5279         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5280                 if (func_id != BPF_FUNC_get_local_storage)
5281                         goto error;
5282                 break;
5283         case BPF_MAP_TYPE_DEVMAP:
5284         case BPF_MAP_TYPE_DEVMAP_HASH:
5285                 if (func_id != BPF_FUNC_redirect_map &&
5286                     func_id != BPF_FUNC_map_lookup_elem)
5287                         goto error;
5288                 break;
5289         /* Restrict bpf side of cpumap and xskmap, open when use-cases
5290          * appear.
5291          */
5292         case BPF_MAP_TYPE_CPUMAP:
5293                 if (func_id != BPF_FUNC_redirect_map)
5294                         goto error;
5295                 break;
5296         case BPF_MAP_TYPE_XSKMAP:
5297                 if (func_id != BPF_FUNC_redirect_map &&
5298                     func_id != BPF_FUNC_map_lookup_elem)
5299                         goto error;
5300                 break;
5301         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5302         case BPF_MAP_TYPE_HASH_OF_MAPS:
5303                 if (func_id != BPF_FUNC_map_lookup_elem)
5304                         goto error;
5305                 break;
5306         case BPF_MAP_TYPE_SOCKMAP:
5307                 if (func_id != BPF_FUNC_sk_redirect_map &&
5308                     func_id != BPF_FUNC_sock_map_update &&
5309                     func_id != BPF_FUNC_map_delete_elem &&
5310                     func_id != BPF_FUNC_msg_redirect_map &&
5311                     func_id != BPF_FUNC_sk_select_reuseport &&
5312                     func_id != BPF_FUNC_map_lookup_elem &&
5313                     !may_update_sockmap(env, func_id))
5314                         goto error;
5315                 break;
5316         case BPF_MAP_TYPE_SOCKHASH:
5317                 if (func_id != BPF_FUNC_sk_redirect_hash &&
5318                     func_id != BPF_FUNC_sock_hash_update &&
5319                     func_id != BPF_FUNC_map_delete_elem &&
5320                     func_id != BPF_FUNC_msg_redirect_hash &&
5321                     func_id != BPF_FUNC_sk_select_reuseport &&
5322                     func_id != BPF_FUNC_map_lookup_elem &&
5323                     !may_update_sockmap(env, func_id))
5324                         goto error;
5325                 break;
5326         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5327                 if (func_id != BPF_FUNC_sk_select_reuseport)
5328                         goto error;
5329                 break;
5330         case BPF_MAP_TYPE_QUEUE:
5331         case BPF_MAP_TYPE_STACK:
5332                 if (func_id != BPF_FUNC_map_peek_elem &&
5333                     func_id != BPF_FUNC_map_pop_elem &&
5334                     func_id != BPF_FUNC_map_push_elem)
5335                         goto error;
5336                 break;
5337         case BPF_MAP_TYPE_SK_STORAGE:
5338                 if (func_id != BPF_FUNC_sk_storage_get &&
5339                     func_id != BPF_FUNC_sk_storage_delete)
5340                         goto error;
5341                 break;
5342         case BPF_MAP_TYPE_INODE_STORAGE:
5343                 if (func_id != BPF_FUNC_inode_storage_get &&
5344                     func_id != BPF_FUNC_inode_storage_delete)
5345                         goto error;
5346                 break;
5347         case BPF_MAP_TYPE_TASK_STORAGE:
5348                 if (func_id != BPF_FUNC_task_storage_get &&
5349                     func_id != BPF_FUNC_task_storage_delete)
5350                         goto error;
5351                 break;
5352         default:
5353                 break;
5354         }
5355
5356         /* ... and second from the function itself. */
5357         switch (func_id) {
5358         case BPF_FUNC_tail_call:
5359                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5360                         goto error;
5361                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5362                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5363                         return -EINVAL;
5364                 }
5365                 break;
5366         case BPF_FUNC_perf_event_read:
5367         case BPF_FUNC_perf_event_output:
5368         case BPF_FUNC_perf_event_read_value:
5369         case BPF_FUNC_skb_output:
5370         case BPF_FUNC_xdp_output:
5371                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5372                         goto error;
5373                 break;
5374         case BPF_FUNC_get_stackid:
5375                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5376                         goto error;
5377                 break;
5378         case BPF_FUNC_current_task_under_cgroup:
5379         case BPF_FUNC_skb_under_cgroup:
5380                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5381                         goto error;
5382                 break;
5383         case BPF_FUNC_redirect_map:
5384                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5385                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5386                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
5387                     map->map_type != BPF_MAP_TYPE_XSKMAP)
5388                         goto error;
5389                 break;
5390         case BPF_FUNC_sk_redirect_map:
5391         case BPF_FUNC_msg_redirect_map:
5392         case BPF_FUNC_sock_map_update:
5393                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5394                         goto error;
5395                 break;
5396         case BPF_FUNC_sk_redirect_hash:
5397         case BPF_FUNC_msg_redirect_hash:
5398         case BPF_FUNC_sock_hash_update:
5399                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5400                         goto error;
5401                 break;
5402         case BPF_FUNC_get_local_storage:
5403                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5404                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5405                         goto error;
5406                 break;
5407         case BPF_FUNC_sk_select_reuseport:
5408                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5409                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5410                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
5411                         goto error;
5412                 break;
5413         case BPF_FUNC_map_peek_elem:
5414         case BPF_FUNC_map_pop_elem:
5415         case BPF_FUNC_map_push_elem:
5416                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5417                     map->map_type != BPF_MAP_TYPE_STACK)
5418                         goto error;
5419                 break;
5420         case BPF_FUNC_sk_storage_get:
5421         case BPF_FUNC_sk_storage_delete:
5422                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5423                         goto error;
5424                 break;
5425         case BPF_FUNC_inode_storage_get:
5426         case BPF_FUNC_inode_storage_delete:
5427                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5428                         goto error;
5429                 break;
5430         case BPF_FUNC_task_storage_get:
5431         case BPF_FUNC_task_storage_delete:
5432                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5433                         goto error;
5434                 break;
5435         default:
5436                 break;
5437         }
5438
5439         return 0;
5440 error:
5441         verbose(env, "cannot pass map_type %d into func %s#%d\n",
5442                 map->map_type, func_id_name(func_id), func_id);
5443         return -EINVAL;
5444 }
5445
5446 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5447 {
5448         int count = 0;
5449
5450         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5451                 count++;
5452         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5453                 count++;
5454         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5455                 count++;
5456         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5457                 count++;
5458         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5459                 count++;
5460
5461         /* We only support one arg being in raw mode at the moment,
5462          * which is sufficient for the helper functions we have
5463          * right now.
5464          */
5465         return count <= 1;
5466 }
5467
5468 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5469                                     enum bpf_arg_type arg_next)
5470 {
5471         return (arg_type_is_mem_ptr(arg_curr) &&
5472                 !arg_type_is_mem_size(arg_next)) ||
5473                (!arg_type_is_mem_ptr(arg_curr) &&
5474                 arg_type_is_mem_size(arg_next));
5475 }
5476
5477 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5478 {
5479         /* bpf_xxx(..., buf, len) call will access 'len'
5480          * bytes from memory 'buf'. Both arg types need
5481          * to be paired, so make sure there's no buggy
5482          * helper function specification.
5483          */
5484         if (arg_type_is_mem_size(fn->arg1_type) ||
5485             arg_type_is_mem_ptr(fn->arg5_type)  ||
5486             check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5487             check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5488             check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5489             check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5490                 return false;
5491
5492         return true;
5493 }
5494
5495 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5496 {
5497         int count = 0;
5498
5499         if (arg_type_may_be_refcounted(fn->arg1_type))
5500                 count++;
5501         if (arg_type_may_be_refcounted(fn->arg2_type))
5502                 count++;
5503         if (arg_type_may_be_refcounted(fn->arg3_type))
5504                 count++;
5505         if (arg_type_may_be_refcounted(fn->arg4_type))
5506                 count++;
5507         if (arg_type_may_be_refcounted(fn->arg5_type))
5508                 count++;
5509
5510         /* A reference acquiring function cannot acquire
5511          * another refcounted ptr.
5512          */
5513         if (may_be_acquire_function(func_id) && count)
5514                 return false;
5515
5516         /* We only support one arg being unreferenced at the moment,
5517          * which is sufficient for the helper functions we have right now.
5518          */
5519         return count <= 1;
5520 }
5521
5522 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5523 {
5524         int i;
5525
5526         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5527                 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5528                         return false;
5529
5530                 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5531                         return false;
5532         }
5533
5534         return true;
5535 }
5536
5537 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5538 {
5539         return check_raw_mode_ok(fn) &&
5540                check_arg_pair_ok(fn) &&
5541                check_btf_id_ok(fn) &&
5542                check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5543 }
5544
5545 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5546  * are now invalid, so turn them into unknown SCALAR_VALUE.
5547  */
5548 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5549                                      struct bpf_func_state *state)
5550 {
5551         struct bpf_reg_state *regs = state->regs, *reg;
5552         int i;
5553
5554         for (i = 0; i < MAX_BPF_REG; i++)
5555                 if (reg_is_pkt_pointer_any(&regs[i]))
5556                         mark_reg_unknown(env, regs, i);
5557
5558         bpf_for_each_spilled_reg(i, state, reg) {
5559                 if (!reg)
5560                         continue;
5561                 if (reg_is_pkt_pointer_any(reg))
5562                         __mark_reg_unknown(env, reg);
5563         }
5564 }
5565
5566 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5567 {
5568         struct bpf_verifier_state *vstate = env->cur_state;
5569         int i;
5570
5571         for (i = 0; i <= vstate->curframe; i++)
5572                 __clear_all_pkt_pointers(env, vstate->frame[i]);
5573 }
5574
5575 enum {
5576         AT_PKT_END = -1,
5577         BEYOND_PKT_END = -2,
5578 };
5579
5580 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5581 {
5582         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5583         struct bpf_reg_state *reg = &state->regs[regn];
5584
5585         if (reg->type != PTR_TO_PACKET)
5586                 /* PTR_TO_PACKET_META is not supported yet */
5587                 return;
5588
5589         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5590          * How far beyond pkt_end it goes is unknown.
5591          * if (!range_open) it's the case of pkt >= pkt_end
5592          * if (range_open) it's the case of pkt > pkt_end
5593          * hence this pointer is at least 1 byte bigger than pkt_end
5594          */
5595         if (range_open)
5596                 reg->range = BEYOND_PKT_END;
5597         else
5598                 reg->range = AT_PKT_END;
5599 }
5600
5601 static void release_reg_references(struct bpf_verifier_env *env,
5602                                    struct bpf_func_state *state,
5603                                    int ref_obj_id)
5604 {
5605         struct bpf_reg_state *regs = state->regs, *reg;
5606         int i;
5607
5608         for (i = 0; i < MAX_BPF_REG; i++)
5609                 if (regs[i].ref_obj_id == ref_obj_id)
5610                         mark_reg_unknown(env, regs, i);
5611
5612         bpf_for_each_spilled_reg(i, state, reg) {
5613                 if (!reg)
5614                         continue;
5615                 if (reg->ref_obj_id == ref_obj_id)
5616                         __mark_reg_unknown(env, reg);
5617         }
5618 }
5619
5620 /* The pointer with the specified id has released its reference to kernel
5621  * resources. Identify all copies of the same pointer and clear the reference.
5622  */
5623 static int release_reference(struct bpf_verifier_env *env,
5624                              int ref_obj_id)
5625 {
5626         struct bpf_verifier_state *vstate = env->cur_state;
5627         int err;
5628         int i;
5629
5630         err = release_reference_state(cur_func(env), ref_obj_id);
5631         if (err)
5632                 return err;
5633
5634         for (i = 0; i <= vstate->curframe; i++)
5635                 release_reg_references(env, vstate->frame[i], ref_obj_id);
5636
5637         return 0;
5638 }
5639
5640 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5641                                     struct bpf_reg_state *regs)
5642 {
5643         int i;
5644
5645         /* after the call registers r0 - r5 were scratched */
5646         for (i = 0; i < CALLER_SAVED_REGS; i++) {
5647                 mark_reg_not_init(env, regs, caller_saved[i]);
5648                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5649         }
5650 }
5651
5652 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5653                                    struct bpf_func_state *caller,
5654                                    struct bpf_func_state *callee,
5655                                    int insn_idx);
5656
5657 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5658                              int *insn_idx, int subprog,
5659                              set_callee_state_fn set_callee_state_cb)
5660 {
5661         struct bpf_verifier_state *state = env->cur_state;
5662         struct bpf_func_info_aux *func_info_aux;
5663         struct bpf_func_state *caller, *callee;
5664         int err;
5665         bool is_global = false;
5666
5667         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5668                 verbose(env, "the call stack of %d frames is too deep\n",
5669                         state->curframe + 2);
5670                 return -E2BIG;
5671         }
5672
5673         caller = state->frame[state->curframe];
5674         if (state->frame[state->curframe + 1]) {
5675                 verbose(env, "verifier bug. Frame %d already allocated\n",
5676                         state->curframe + 1);
5677                 return -EFAULT;
5678         }
5679
5680         func_info_aux = env->prog->aux->func_info_aux;
5681         if (func_info_aux)
5682                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5683         err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5684         if (err == -EFAULT)
5685                 return err;
5686         if (is_global) {
5687                 if (err) {
5688                         verbose(env, "Caller passes invalid args into func#%d\n",
5689                                 subprog);
5690                         return err;
5691                 } else {
5692                         if (env->log.level & BPF_LOG_LEVEL)
5693                                 verbose(env,
5694                                         "Func#%d is global and valid. Skipping.\n",
5695                                         subprog);
5696                         clear_caller_saved_regs(env, caller->regs);
5697
5698                         /* All global functions return a 64-bit SCALAR_VALUE */
5699                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
5700                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5701
5702                         /* continue with next insn after call */
5703                         return 0;
5704                 }
5705         }
5706
5707         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5708         if (!callee)
5709                 return -ENOMEM;
5710         state->frame[state->curframe + 1] = callee;
5711
5712         /* callee cannot access r0, r6 - r9 for reading and has to write
5713          * into its own stack before reading from it.
5714          * callee can read/write into caller's stack
5715          */
5716         init_func_state(env, callee,
5717                         /* remember the callsite, it will be used by bpf_exit */
5718                         *insn_idx /* callsite */,
5719                         state->curframe + 1 /* frameno within this callchain */,
5720                         subprog /* subprog number within this prog */);
5721
5722         /* Transfer references to the callee */
5723         err = copy_reference_state(callee, caller);
5724         if (err)
5725                 return err;
5726
5727         err = set_callee_state_cb(env, caller, callee, *insn_idx);
5728         if (err)
5729                 return err;
5730
5731         clear_caller_saved_regs(env, caller->regs);
5732
5733         /* only increment it after check_reg_arg() finished */
5734         state->curframe++;
5735
5736         /* and go analyze first insn of the callee */
5737         *insn_idx = env->subprog_info[subprog].start - 1;
5738
5739         if (env->log.level & BPF_LOG_LEVEL) {
5740                 verbose(env, "caller:\n");
5741                 print_verifier_state(env, caller);
5742                 verbose(env, "callee:\n");
5743                 print_verifier_state(env, callee);
5744         }
5745         return 0;
5746 }
5747
5748 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5749                                    struct bpf_func_state *caller,
5750                                    struct bpf_func_state *callee)
5751 {
5752         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5753          *      void *callback_ctx, u64 flags);
5754          * callback_fn(struct bpf_map *map, void *key, void *value,
5755          *      void *callback_ctx);
5756          */
5757         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5758
5759         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5760         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5761         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5762
5763         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5764         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5765         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5766
5767         /* pointer to stack or null */
5768         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5769
5770         /* unused */
5771         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5772         return 0;
5773 }
5774
5775 static int set_callee_state(struct bpf_verifier_env *env,
5776                             struct bpf_func_state *caller,
5777                             struct bpf_func_state *callee, int insn_idx)
5778 {
5779         int i;
5780
5781         /* copy r1 - r5 args that callee can access.  The copy includes parent
5782          * pointers, which connects us up to the liveness chain
5783          */
5784         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5785                 callee->regs[i] = caller->regs[i];
5786         return 0;
5787 }
5788
5789 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5790                            int *insn_idx)
5791 {
5792         int subprog, target_insn;
5793
5794         target_insn = *insn_idx + insn->imm + 1;
5795         subprog = find_subprog(env, target_insn);
5796         if (subprog < 0) {
5797                 verbose(env, "verifier bug. No program starts at insn %d\n",
5798                         target_insn);
5799                 return -EFAULT;
5800         }
5801
5802         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5803 }
5804
5805 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5806                                        struct bpf_func_state *caller,
5807                                        struct bpf_func_state *callee,
5808                                        int insn_idx)
5809 {
5810         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5811         struct bpf_map *map;
5812         int err;
5813
5814         if (bpf_map_ptr_poisoned(insn_aux)) {
5815                 verbose(env, "tail_call abusing map_ptr\n");
5816                 return -EINVAL;
5817         }
5818
5819         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5820         if (!map->ops->map_set_for_each_callback_args ||
5821             !map->ops->map_for_each_callback) {
5822                 verbose(env, "callback function not allowed for map\n");
5823                 return -ENOTSUPP;
5824         }
5825
5826         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5827         if (err)
5828                 return err;
5829
5830         callee->in_callback_fn = true;
5831         return 0;
5832 }
5833
5834 static int set_timer_callback_state(struct bpf_verifier_env *env,
5835                                     struct bpf_func_state *caller,
5836                                     struct bpf_func_state *callee,
5837                                     int insn_idx)
5838 {
5839         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
5840
5841         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
5842          * callback_fn(struct bpf_map *map, void *key, void *value);
5843          */
5844         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
5845         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
5846         callee->regs[BPF_REG_1].map_ptr = map_ptr;
5847
5848         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5849         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5850         callee->regs[BPF_REG_2].map_ptr = map_ptr;
5851
5852         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5853         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5854         callee->regs[BPF_REG_3].map_ptr = map_ptr;
5855
5856         /* unused */
5857         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
5858         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5859         return 0;
5860 }
5861
5862 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5863 {
5864         struct bpf_verifier_state *state = env->cur_state;
5865         struct bpf_func_state *caller, *callee;
5866         struct bpf_reg_state *r0;
5867         int err;
5868
5869         callee = state->frame[state->curframe];
5870         r0 = &callee->regs[BPF_REG_0];
5871         if (r0->type == PTR_TO_STACK) {
5872                 /* technically it's ok to return caller's stack pointer
5873                  * (or caller's caller's pointer) back to the caller,
5874                  * since these pointers are valid. Only current stack
5875                  * pointer will be invalid as soon as function exits,
5876                  * but let's be conservative
5877                  */
5878                 verbose(env, "cannot return stack pointer to the caller\n");
5879                 return -EINVAL;
5880         }
5881
5882         state->curframe--;
5883         caller = state->frame[state->curframe];
5884         if (callee->in_callback_fn) {
5885                 /* enforce R0 return value range [0, 1]. */
5886                 struct tnum range = tnum_range(0, 1);
5887
5888                 if (r0->type != SCALAR_VALUE) {
5889                         verbose(env, "R0 not a scalar value\n");
5890                         return -EACCES;
5891                 }
5892                 if (!tnum_in(range, r0->var_off)) {
5893                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5894                         return -EINVAL;
5895                 }
5896         } else {
5897                 /* return to the caller whatever r0 had in the callee */
5898                 caller->regs[BPF_REG_0] = *r0;
5899         }
5900
5901         /* Transfer references to the caller */
5902         err = copy_reference_state(caller, callee);
5903         if (err)
5904                 return err;
5905
5906         *insn_idx = callee->callsite + 1;
5907         if (env->log.level & BPF_LOG_LEVEL) {
5908                 verbose(env, "returning from callee:\n");
5909                 print_verifier_state(env, callee);
5910                 verbose(env, "to caller at %d:\n", *insn_idx);
5911                 print_verifier_state(env, caller);
5912         }
5913         /* clear everything in the callee */
5914         free_func_state(callee);
5915         state->frame[state->curframe + 1] = NULL;
5916         return 0;
5917 }
5918
5919 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5920                                    int func_id,
5921                                    struct bpf_call_arg_meta *meta)
5922 {
5923         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5924
5925         if (ret_type != RET_INTEGER ||
5926             (func_id != BPF_FUNC_get_stack &&
5927              func_id != BPF_FUNC_get_task_stack &&
5928              func_id != BPF_FUNC_probe_read_str &&
5929              func_id != BPF_FUNC_probe_read_kernel_str &&
5930              func_id != BPF_FUNC_probe_read_user_str))
5931                 return;
5932
5933         ret_reg->smax_value = meta->msize_max_value;
5934         ret_reg->s32_max_value = meta->msize_max_value;
5935         ret_reg->smin_value = -MAX_ERRNO;
5936         ret_reg->s32_min_value = -MAX_ERRNO;
5937         __reg_deduce_bounds(ret_reg);
5938         __reg_bound_offset(ret_reg);
5939         __update_reg_bounds(ret_reg);
5940 }
5941
5942 static int
5943 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5944                 int func_id, int insn_idx)
5945 {
5946         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5947         struct bpf_map *map = meta->map_ptr;
5948
5949         if (func_id != BPF_FUNC_tail_call &&
5950             func_id != BPF_FUNC_map_lookup_elem &&
5951             func_id != BPF_FUNC_map_update_elem &&
5952             func_id != BPF_FUNC_map_delete_elem &&
5953             func_id != BPF_FUNC_map_push_elem &&
5954             func_id != BPF_FUNC_map_pop_elem &&
5955             func_id != BPF_FUNC_map_peek_elem &&
5956             func_id != BPF_FUNC_for_each_map_elem &&
5957             func_id != BPF_FUNC_redirect_map)
5958                 return 0;
5959
5960         if (map == NULL) {
5961                 verbose(env, "kernel subsystem misconfigured verifier\n");
5962                 return -EINVAL;
5963         }
5964
5965         /* In case of read-only, some additional restrictions
5966          * need to be applied in order to prevent altering the
5967          * state of the map from program side.
5968          */
5969         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5970             (func_id == BPF_FUNC_map_delete_elem ||
5971              func_id == BPF_FUNC_map_update_elem ||
5972              func_id == BPF_FUNC_map_push_elem ||
5973              func_id == BPF_FUNC_map_pop_elem)) {
5974                 verbose(env, "write into map forbidden\n");
5975                 return -EACCES;
5976         }
5977
5978         if (!BPF_MAP_PTR(aux->map_ptr_state))
5979                 bpf_map_ptr_store(aux, meta->map_ptr,
5980                                   !meta->map_ptr->bypass_spec_v1);
5981         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5982                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5983                                   !meta->map_ptr->bypass_spec_v1);
5984         return 0;
5985 }
5986
5987 static int
5988 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5989                 int func_id, int insn_idx)
5990 {
5991         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5992         struct bpf_reg_state *regs = cur_regs(env), *reg;
5993         struct bpf_map *map = meta->map_ptr;
5994         struct tnum range;
5995         u64 val;
5996         int err;
5997
5998         if (func_id != BPF_FUNC_tail_call)
5999                 return 0;
6000         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6001                 verbose(env, "kernel subsystem misconfigured verifier\n");
6002                 return -EINVAL;
6003         }
6004
6005         range = tnum_range(0, map->max_entries - 1);
6006         reg = &regs[BPF_REG_3];
6007
6008         if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6009                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6010                 return 0;
6011         }
6012
6013         err = mark_chain_precision(env, BPF_REG_3);
6014         if (err)
6015                 return err;
6016
6017         val = reg->var_off.value;
6018         if (bpf_map_key_unseen(aux))
6019                 bpf_map_key_store(aux, val);
6020         else if (!bpf_map_key_poisoned(aux) &&
6021                   bpf_map_key_immediate(aux) != val)
6022                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6023         return 0;
6024 }
6025
6026 static int check_reference_leak(struct bpf_verifier_env *env)
6027 {
6028         struct bpf_func_state *state = cur_func(env);
6029         int i;
6030
6031         for (i = 0; i < state->acquired_refs; i++) {
6032                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6033                         state->refs[i].id, state->refs[i].insn_idx);
6034         }
6035         return state->acquired_refs ? -EINVAL : 0;
6036 }
6037
6038 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6039                                    struct bpf_reg_state *regs)
6040 {
6041         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6042         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6043         struct bpf_map *fmt_map = fmt_reg->map_ptr;
6044         int err, fmt_map_off, num_args;
6045         u64 fmt_addr;
6046         char *fmt;
6047
6048         /* data must be an array of u64 */
6049         if (data_len_reg->var_off.value % 8)
6050                 return -EINVAL;
6051         num_args = data_len_reg->var_off.value / 8;
6052
6053         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6054          * and map_direct_value_addr is set.
6055          */
6056         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6057         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6058                                                   fmt_map_off);
6059         if (err) {
6060                 verbose(env, "verifier bug\n");
6061                 return -EFAULT;
6062         }
6063         fmt = (char *)(long)fmt_addr + fmt_map_off;
6064
6065         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6066          * can focus on validating the format specifiers.
6067          */
6068         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6069         if (err < 0)
6070                 verbose(env, "Invalid format string\n");
6071
6072         return err;
6073 }
6074
6075 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6076                              int *insn_idx_p)
6077 {
6078         const struct bpf_func_proto *fn = NULL;
6079         struct bpf_reg_state *regs;
6080         struct bpf_call_arg_meta meta;
6081         int insn_idx = *insn_idx_p;
6082         bool changes_data;
6083         int i, err, func_id;
6084
6085         /* find function prototype */
6086         func_id = insn->imm;
6087         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6088                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6089                         func_id);
6090                 return -EINVAL;
6091         }
6092
6093         if (env->ops->get_func_proto)
6094                 fn = env->ops->get_func_proto(func_id, env->prog);
6095         if (!fn) {
6096                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6097                         func_id);
6098                 return -EINVAL;
6099         }
6100
6101         /* eBPF programs must be GPL compatible to use GPL-ed functions */
6102         if (!env->prog->gpl_compatible && fn->gpl_only) {
6103                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6104                 return -EINVAL;
6105         }
6106
6107         if (fn->allowed && !fn->allowed(env->prog)) {
6108                 verbose(env, "helper call is not allowed in probe\n");
6109                 return -EINVAL;
6110         }
6111
6112         /* With LD_ABS/IND some JITs save/restore skb from r1. */
6113         changes_data = bpf_helper_changes_pkt_data(fn->func);
6114         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6115                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6116                         func_id_name(func_id), func_id);
6117                 return -EINVAL;
6118         }
6119
6120         memset(&meta, 0, sizeof(meta));
6121         meta.pkt_access = fn->pkt_access;
6122
6123         err = check_func_proto(fn, func_id);
6124         if (err) {
6125                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6126                         func_id_name(func_id), func_id);
6127                 return err;
6128         }
6129
6130         meta.func_id = func_id;
6131         /* check args */
6132         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6133                 err = check_func_arg(env, i, &meta, fn);
6134                 if (err)
6135                         return err;
6136         }
6137
6138         err = record_func_map(env, &meta, func_id, insn_idx);
6139         if (err)
6140                 return err;
6141
6142         err = record_func_key(env, &meta, func_id, insn_idx);
6143         if (err)
6144                 return err;
6145
6146         /* Mark slots with STACK_MISC in case of raw mode, stack offset
6147          * is inferred from register state.
6148          */
6149         for (i = 0; i < meta.access_size; i++) {
6150                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6151                                        BPF_WRITE, -1, false);
6152                 if (err)
6153                         return err;
6154         }
6155
6156         if (func_id == BPF_FUNC_tail_call) {
6157                 err = check_reference_leak(env);
6158                 if (err) {
6159                         verbose(env, "tail_call would lead to reference leak\n");
6160                         return err;
6161                 }
6162         } else if (is_release_function(func_id)) {
6163                 err = release_reference(env, meta.ref_obj_id);
6164                 if (err) {
6165                         verbose(env, "func %s#%d reference has not been acquired before\n",
6166                                 func_id_name(func_id), func_id);
6167                         return err;
6168                 }
6169         }
6170
6171         regs = cur_regs(env);
6172
6173         /* check that flags argument in get_local_storage(map, flags) is 0,
6174          * this is required because get_local_storage() can't return an error.
6175          */
6176         if (func_id == BPF_FUNC_get_local_storage &&
6177             !register_is_null(&regs[BPF_REG_2])) {
6178                 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6179                 return -EINVAL;
6180         }
6181
6182         if (func_id == BPF_FUNC_for_each_map_elem) {
6183                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6184                                         set_map_elem_callback_state);
6185                 if (err < 0)
6186                         return -EINVAL;
6187         }
6188
6189         if (func_id == BPF_FUNC_timer_set_callback) {
6190                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6191                                         set_timer_callback_state);
6192                 if (err < 0)
6193                         return -EINVAL;
6194         }
6195
6196         if (func_id == BPF_FUNC_snprintf) {
6197                 err = check_bpf_snprintf_call(env, regs);
6198                 if (err < 0)
6199                         return err;
6200         }
6201
6202         /* reset caller saved regs */
6203         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6204                 mark_reg_not_init(env, regs, caller_saved[i]);
6205                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6206         }
6207
6208         /* helper call returns 64-bit value. */
6209         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6210
6211         /* update return register (already marked as written above) */
6212         if (fn->ret_type == RET_INTEGER) {
6213                 /* sets type to SCALAR_VALUE */
6214                 mark_reg_unknown(env, regs, BPF_REG_0);
6215         } else if (fn->ret_type == RET_VOID) {
6216                 regs[BPF_REG_0].type = NOT_INIT;
6217         } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6218                    fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6219                 /* There is no offset yet applied, variable or fixed */
6220                 mark_reg_known_zero(env, regs, BPF_REG_0);
6221                 /* remember map_ptr, so that check_map_access()
6222                  * can check 'value_size' boundary of memory access
6223                  * to map element returned from bpf_map_lookup_elem()
6224                  */
6225                 if (meta.map_ptr == NULL) {
6226                         verbose(env,
6227                                 "kernel subsystem misconfigured verifier\n");
6228                         return -EINVAL;
6229                 }
6230                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
6231                 regs[BPF_REG_0].map_uid = meta.map_uid;
6232                 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6233                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
6234                         if (map_value_has_spin_lock(meta.map_ptr))
6235                                 regs[BPF_REG_0].id = ++env->id_gen;
6236                 } else {
6237                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
6238                 }
6239         } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6240                 mark_reg_known_zero(env, regs, BPF_REG_0);
6241                 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
6242         } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6243                 mark_reg_known_zero(env, regs, BPF_REG_0);
6244                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
6245         } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6246                 mark_reg_known_zero(env, regs, BPF_REG_0);
6247                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
6248         } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6249                 mark_reg_known_zero(env, regs, BPF_REG_0);
6250                 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
6251                 regs[BPF_REG_0].mem_size = meta.mem_size;
6252         } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6253                    fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
6254                 const struct btf_type *t;
6255
6256                 mark_reg_known_zero(env, regs, BPF_REG_0);
6257                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6258                 if (!btf_type_is_struct(t)) {
6259                         u32 tsize;
6260                         const struct btf_type *ret;
6261                         const char *tname;
6262
6263                         /* resolve the type size of ksym. */
6264                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6265                         if (IS_ERR(ret)) {
6266                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6267                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6268                                         tname, PTR_ERR(ret));
6269                                 return -EINVAL;
6270                         }
6271                         regs[BPF_REG_0].type =
6272                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6273                                 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
6274                         regs[BPF_REG_0].mem_size = tsize;
6275                 } else {
6276                         regs[BPF_REG_0].type =
6277                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6278                                 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
6279                         regs[BPF_REG_0].btf = meta.ret_btf;
6280                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6281                 }
6282         } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6283                    fn->ret_type == RET_PTR_TO_BTF_ID) {
6284                 int ret_btf_id;
6285
6286                 mark_reg_known_zero(env, regs, BPF_REG_0);
6287                 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6288                                                      PTR_TO_BTF_ID :
6289                                                      PTR_TO_BTF_ID_OR_NULL;
6290                 ret_btf_id = *fn->ret_btf_id;
6291                 if (ret_btf_id == 0) {
6292                         verbose(env, "invalid return type %d of func %s#%d\n",
6293                                 fn->ret_type, func_id_name(func_id), func_id);
6294                         return -EINVAL;
6295                 }
6296                 /* current BPF helper definitions are only coming from
6297                  * built-in code with type IDs from  vmlinux BTF
6298                  */
6299                 regs[BPF_REG_0].btf = btf_vmlinux;
6300                 regs[BPF_REG_0].btf_id = ret_btf_id;
6301         } else {
6302                 verbose(env, "unknown return type %d of func %s#%d\n",
6303                         fn->ret_type, func_id_name(func_id), func_id);
6304                 return -EINVAL;
6305         }
6306
6307         if (reg_type_may_be_null(regs[BPF_REG_0].type))
6308                 regs[BPF_REG_0].id = ++env->id_gen;
6309
6310         if (is_ptr_cast_function(func_id)) {
6311                 /* For release_reference() */
6312                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6313         } else if (is_acquire_function(func_id, meta.map_ptr)) {
6314                 int id = acquire_reference_state(env, insn_idx);
6315
6316                 if (id < 0)
6317                         return id;
6318                 /* For mark_ptr_or_null_reg() */
6319                 regs[BPF_REG_0].id = id;
6320                 /* For release_reference() */
6321                 regs[BPF_REG_0].ref_obj_id = id;
6322         }
6323
6324         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6325
6326         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6327         if (err)
6328                 return err;
6329
6330         if ((func_id == BPF_FUNC_get_stack ||
6331              func_id == BPF_FUNC_get_task_stack) &&
6332             !env->prog->has_callchain_buf) {
6333                 const char *err_str;
6334
6335 #ifdef CONFIG_PERF_EVENTS
6336                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6337                 err_str = "cannot get callchain buffer for func %s#%d\n";
6338 #else
6339                 err = -ENOTSUPP;
6340                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6341 #endif
6342                 if (err) {
6343                         verbose(env, err_str, func_id_name(func_id), func_id);
6344                         return err;
6345                 }
6346
6347                 env->prog->has_callchain_buf = true;
6348         }
6349
6350         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6351                 env->prog->call_get_stack = true;
6352
6353         if (changes_data)
6354                 clear_all_pkt_pointers(env);
6355         return 0;
6356 }
6357
6358 /* mark_btf_func_reg_size() is used when the reg size is determined by
6359  * the BTF func_proto's return value size and argument.
6360  */
6361 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6362                                    size_t reg_size)
6363 {
6364         struct bpf_reg_state *reg = &cur_regs(env)[regno];
6365
6366         if (regno == BPF_REG_0) {
6367                 /* Function return value */
6368                 reg->live |= REG_LIVE_WRITTEN;
6369                 reg->subreg_def = reg_size == sizeof(u64) ?
6370                         DEF_NOT_SUBREG : env->insn_idx + 1;
6371         } else {
6372                 /* Function argument */
6373                 if (reg_size == sizeof(u64)) {
6374                         mark_insn_zext(env, reg);
6375                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6376                 } else {
6377                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6378                 }
6379         }
6380 }
6381
6382 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6383 {
6384         const struct btf_type *t, *func, *func_proto, *ptr_type;
6385         struct bpf_reg_state *regs = cur_regs(env);
6386         const char *func_name, *ptr_type_name;
6387         u32 i, nargs, func_id, ptr_type_id;
6388         const struct btf_param *args;
6389         int err;
6390
6391         func_id = insn->imm;
6392         func = btf_type_by_id(btf_vmlinux, func_id);
6393         func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6394         func_proto = btf_type_by_id(btf_vmlinux, func->type);
6395
6396         if (!env->ops->check_kfunc_call ||
6397             !env->ops->check_kfunc_call(func_id)) {
6398                 verbose(env, "calling kernel function %s is not allowed\n",
6399                         func_name);
6400                 return -EACCES;
6401         }
6402
6403         /* Check the arguments */
6404         err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6405         if (err)
6406                 return err;
6407
6408         for (i = 0; i < CALLER_SAVED_REGS; i++)
6409                 mark_reg_not_init(env, regs, caller_saved[i]);
6410
6411         /* Check return type */
6412         t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6413         if (btf_type_is_scalar(t)) {
6414                 mark_reg_unknown(env, regs, BPF_REG_0);
6415                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6416         } else if (btf_type_is_ptr(t)) {
6417                 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6418                                                    &ptr_type_id);
6419                 if (!btf_type_is_struct(ptr_type)) {
6420                         ptr_type_name = btf_name_by_offset(btf_vmlinux,
6421                                                            ptr_type->name_off);
6422                         verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6423                                 func_name, btf_type_str(ptr_type),
6424                                 ptr_type_name);
6425                         return -EINVAL;
6426                 }
6427                 mark_reg_known_zero(env, regs, BPF_REG_0);
6428                 regs[BPF_REG_0].btf = btf_vmlinux;
6429                 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6430                 regs[BPF_REG_0].btf_id = ptr_type_id;
6431                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6432         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6433
6434         nargs = btf_type_vlen(func_proto);
6435         args = (const struct btf_param *)(func_proto + 1);
6436         for (i = 0; i < nargs; i++) {
6437                 u32 regno = i + 1;
6438
6439                 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6440                 if (btf_type_is_ptr(t))
6441                         mark_btf_func_reg_size(env, regno, sizeof(void *));
6442                 else
6443                         /* scalar. ensured by btf_check_kfunc_arg_match() */
6444                         mark_btf_func_reg_size(env, regno, t->size);
6445         }
6446
6447         return 0;
6448 }
6449
6450 static bool signed_add_overflows(s64 a, s64 b)
6451 {
6452         /* Do the add in u64, where overflow is well-defined */
6453         s64 res = (s64)((u64)a + (u64)b);
6454
6455         if (b < 0)
6456                 return res > a;
6457         return res < a;
6458 }
6459
6460 static bool signed_add32_overflows(s32 a, s32 b)
6461 {
6462         /* Do the add in u32, where overflow is well-defined */
6463         s32 res = (s32)((u32)a + (u32)b);
6464
6465         if (b < 0)
6466                 return res > a;
6467         return res < a;
6468 }
6469
6470 static bool signed_sub_overflows(s64 a, s64 b)
6471 {
6472         /* Do the sub in u64, where overflow is well-defined */
6473         s64 res = (s64)((u64)a - (u64)b);
6474
6475         if (b < 0)
6476                 return res < a;
6477         return res > a;
6478 }
6479
6480 static bool signed_sub32_overflows(s32 a, s32 b)
6481 {
6482         /* Do the sub in u32, where overflow is well-defined */
6483         s32 res = (s32)((u32)a - (u32)b);
6484
6485         if (b < 0)
6486                 return res < a;
6487         return res > a;
6488 }
6489
6490 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6491                                   const struct bpf_reg_state *reg,
6492                                   enum bpf_reg_type type)
6493 {
6494         bool known = tnum_is_const(reg->var_off);
6495         s64 val = reg->var_off.value;
6496         s64 smin = reg->smin_value;
6497
6498         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6499                 verbose(env, "math between %s pointer and %lld is not allowed\n",
6500                         reg_type_str[type], val);
6501                 return false;
6502         }
6503
6504         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6505                 verbose(env, "%s pointer offset %d is not allowed\n",
6506                         reg_type_str[type], reg->off);
6507                 return false;
6508         }
6509
6510         if (smin == S64_MIN) {
6511                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6512                         reg_type_str[type]);
6513                 return false;
6514         }
6515
6516         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6517                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6518                         smin, reg_type_str[type]);
6519                 return false;
6520         }
6521
6522         return true;
6523 }
6524
6525 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6526 {
6527         return &env->insn_aux_data[env->insn_idx];
6528 }
6529
6530 enum {
6531         REASON_BOUNDS   = -1,
6532         REASON_TYPE     = -2,
6533         REASON_PATHS    = -3,
6534         REASON_LIMIT    = -4,
6535         REASON_STACK    = -5,
6536 };
6537
6538 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6539                               u32 *alu_limit, bool mask_to_left)
6540 {
6541         u32 max = 0, ptr_limit = 0;
6542
6543         switch (ptr_reg->type) {
6544         case PTR_TO_STACK:
6545                 /* Offset 0 is out-of-bounds, but acceptable start for the
6546                  * left direction, see BPF_REG_FP. Also, unknown scalar
6547                  * offset where we would need to deal with min/max bounds is
6548                  * currently prohibited for unprivileged.
6549                  */
6550                 max = MAX_BPF_STACK + mask_to_left;
6551                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6552                 break;
6553         case PTR_TO_MAP_VALUE:
6554                 max = ptr_reg->map_ptr->value_size;
6555                 ptr_limit = (mask_to_left ?
6556                              ptr_reg->smin_value :
6557                              ptr_reg->umax_value) + ptr_reg->off;
6558                 break;
6559         default:
6560                 return REASON_TYPE;
6561         }
6562
6563         if (ptr_limit >= max)
6564                 return REASON_LIMIT;
6565         *alu_limit = ptr_limit;
6566         return 0;
6567 }
6568
6569 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6570                                     const struct bpf_insn *insn)
6571 {
6572         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6573 }
6574
6575 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6576                                        u32 alu_state, u32 alu_limit)
6577 {
6578         /* If we arrived here from different branches with different
6579          * state or limits to sanitize, then this won't work.
6580          */
6581         if (aux->alu_state &&
6582             (aux->alu_state != alu_state ||
6583              aux->alu_limit != alu_limit))
6584                 return REASON_PATHS;
6585
6586         /* Corresponding fixup done in do_misc_fixups(). */
6587         aux->alu_state = alu_state;
6588         aux->alu_limit = alu_limit;
6589         return 0;
6590 }
6591
6592 static int sanitize_val_alu(struct bpf_verifier_env *env,
6593                             struct bpf_insn *insn)
6594 {
6595         struct bpf_insn_aux_data *aux = cur_aux(env);
6596
6597         if (can_skip_alu_sanitation(env, insn))
6598                 return 0;
6599
6600         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6601 }
6602
6603 static bool sanitize_needed(u8 opcode)
6604 {
6605         return opcode == BPF_ADD || opcode == BPF_SUB;
6606 }
6607
6608 struct bpf_sanitize_info {
6609         struct bpf_insn_aux_data aux;
6610         bool mask_to_left;
6611 };
6612
6613 static struct bpf_verifier_state *
6614 sanitize_speculative_path(struct bpf_verifier_env *env,
6615                           const struct bpf_insn *insn,
6616                           u32 next_idx, u32 curr_idx)
6617 {
6618         struct bpf_verifier_state *branch;
6619         struct bpf_reg_state *regs;
6620
6621         branch = push_stack(env, next_idx, curr_idx, true);
6622         if (branch && insn) {
6623                 regs = branch->frame[branch->curframe]->regs;
6624                 if (BPF_SRC(insn->code) == BPF_K) {
6625                         mark_reg_unknown(env, regs, insn->dst_reg);
6626                 } else if (BPF_SRC(insn->code) == BPF_X) {
6627                         mark_reg_unknown(env, regs, insn->dst_reg);
6628                         mark_reg_unknown(env, regs, insn->src_reg);
6629                 }
6630         }
6631         return branch;
6632 }
6633
6634 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6635                             struct bpf_insn *insn,
6636                             const struct bpf_reg_state *ptr_reg,
6637                             const struct bpf_reg_state *off_reg,
6638                             struct bpf_reg_state *dst_reg,
6639                             struct bpf_sanitize_info *info,
6640                             const bool commit_window)
6641 {
6642         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6643         struct bpf_verifier_state *vstate = env->cur_state;
6644         bool off_is_imm = tnum_is_const(off_reg->var_off);
6645         bool off_is_neg = off_reg->smin_value < 0;
6646         bool ptr_is_dst_reg = ptr_reg == dst_reg;
6647         u8 opcode = BPF_OP(insn->code);
6648         u32 alu_state, alu_limit;
6649         struct bpf_reg_state tmp;
6650         bool ret;
6651         int err;
6652
6653         if (can_skip_alu_sanitation(env, insn))
6654                 return 0;
6655
6656         /* We already marked aux for masking from non-speculative
6657          * paths, thus we got here in the first place. We only care
6658          * to explore bad access from here.
6659          */
6660         if (vstate->speculative)
6661                 goto do_sim;
6662
6663         if (!commit_window) {
6664                 if (!tnum_is_const(off_reg->var_off) &&
6665                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6666                         return REASON_BOUNDS;
6667
6668                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6669                                      (opcode == BPF_SUB && !off_is_neg);
6670         }
6671
6672         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6673         if (err < 0)
6674                 return err;
6675
6676         if (commit_window) {
6677                 /* In commit phase we narrow the masking window based on
6678                  * the observed pointer move after the simulated operation.
6679                  */
6680                 alu_state = info->aux.alu_state;
6681                 alu_limit = abs(info->aux.alu_limit - alu_limit);
6682         } else {
6683                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6684                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6685                 alu_state |= ptr_is_dst_reg ?
6686                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6687         }
6688
6689         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6690         if (err < 0)
6691                 return err;
6692 do_sim:
6693         /* If we're in commit phase, we're done here given we already
6694          * pushed the truncated dst_reg into the speculative verification
6695          * stack.
6696          *
6697          * Also, when register is a known constant, we rewrite register-based
6698          * operation to immediate-based, and thus do not need masking (and as
6699          * a consequence, do not need to simulate the zero-truncation either).
6700          */
6701         if (commit_window || off_is_imm)
6702                 return 0;
6703
6704         /* Simulate and find potential out-of-bounds access under
6705          * speculative execution from truncation as a result of
6706          * masking when off was not within expected range. If off
6707          * sits in dst, then we temporarily need to move ptr there
6708          * to simulate dst (== 0) +/-= ptr. Needed, for example,
6709          * for cases where we use K-based arithmetic in one direction
6710          * and truncated reg-based in the other in order to explore
6711          * bad access.
6712          */
6713         if (!ptr_is_dst_reg) {
6714                 tmp = *dst_reg;
6715                 *dst_reg = *ptr_reg;
6716         }
6717         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6718                                         env->insn_idx);
6719         if (!ptr_is_dst_reg && ret)
6720                 *dst_reg = tmp;
6721         return !ret ? REASON_STACK : 0;
6722 }
6723
6724 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6725 {
6726         struct bpf_verifier_state *vstate = env->cur_state;
6727
6728         /* If we simulate paths under speculation, we don't update the
6729          * insn as 'seen' such that when we verify unreachable paths in
6730          * the non-speculative domain, sanitize_dead_code() can still
6731          * rewrite/sanitize them.
6732          */
6733         if (!vstate->speculative)
6734                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6735 }
6736
6737 static int sanitize_err(struct bpf_verifier_env *env,
6738                         const struct bpf_insn *insn, int reason,
6739                         const struct bpf_reg_state *off_reg,
6740                         const struct bpf_reg_state *dst_reg)
6741 {
6742         static const char *err = "pointer arithmetic with it prohibited for !root";
6743         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6744         u32 dst = insn->dst_reg, src = insn->src_reg;
6745
6746         switch (reason) {
6747         case REASON_BOUNDS:
6748                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6749                         off_reg == dst_reg ? dst : src, err);
6750                 break;
6751         case REASON_TYPE:
6752                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6753                         off_reg == dst_reg ? src : dst, err);
6754                 break;
6755         case REASON_PATHS:
6756                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6757                         dst, op, err);
6758                 break;
6759         case REASON_LIMIT:
6760                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6761                         dst, op, err);
6762                 break;
6763         case REASON_STACK:
6764                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6765                         dst, err);
6766                 break;
6767         default:
6768                 verbose(env, "verifier internal error: unknown reason (%d)\n",
6769                         reason);
6770                 break;
6771         }
6772
6773         return -EACCES;
6774 }
6775
6776 /* check that stack access falls within stack limits and that 'reg' doesn't
6777  * have a variable offset.
6778  *
6779  * Variable offset is prohibited for unprivileged mode for simplicity since it
6780  * requires corresponding support in Spectre masking for stack ALU.  See also
6781  * retrieve_ptr_limit().
6782  *
6783  *
6784  * 'off' includes 'reg->off'.
6785  */
6786 static int check_stack_access_for_ptr_arithmetic(
6787                                 struct bpf_verifier_env *env,
6788                                 int regno,
6789                                 const struct bpf_reg_state *reg,
6790                                 int off)
6791 {
6792         if (!tnum_is_const(reg->var_off)) {
6793                 char tn_buf[48];
6794
6795                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6796                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6797                         regno, tn_buf, off);
6798                 return -EACCES;
6799         }
6800
6801         if (off >= 0 || off < -MAX_BPF_STACK) {
6802                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6803                         "prohibited for !root; off=%d\n", regno, off);
6804                 return -EACCES;
6805         }
6806
6807         return 0;
6808 }
6809
6810 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6811                                  const struct bpf_insn *insn,
6812                                  const struct bpf_reg_state *dst_reg)
6813 {
6814         u32 dst = insn->dst_reg;
6815
6816         /* For unprivileged we require that resulting offset must be in bounds
6817          * in order to be able to sanitize access later on.
6818          */
6819         if (env->bypass_spec_v1)
6820                 return 0;
6821
6822         switch (dst_reg->type) {
6823         case PTR_TO_STACK:
6824                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6825                                         dst_reg->off + dst_reg->var_off.value))
6826                         return -EACCES;
6827                 break;
6828         case PTR_TO_MAP_VALUE:
6829                 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6830                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6831                                 "prohibited for !root\n", dst);
6832                         return -EACCES;
6833                 }
6834                 break;
6835         default:
6836                 break;
6837         }
6838
6839         return 0;
6840 }
6841
6842 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6843  * Caller should also handle BPF_MOV case separately.
6844  * If we return -EACCES, caller may want to try again treating pointer as a
6845  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6846  */
6847 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6848                                    struct bpf_insn *insn,
6849                                    const struct bpf_reg_state *ptr_reg,
6850                                    const struct bpf_reg_state *off_reg)
6851 {
6852         struct bpf_verifier_state *vstate = env->cur_state;
6853         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6854         struct bpf_reg_state *regs = state->regs, *dst_reg;
6855         bool known = tnum_is_const(off_reg->var_off);
6856         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6857             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6858         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6859             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6860         struct bpf_sanitize_info info = {};
6861         u8 opcode = BPF_OP(insn->code);
6862         u32 dst = insn->dst_reg;
6863         int ret;
6864
6865         dst_reg = &regs[dst];
6866
6867         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6868             smin_val > smax_val || umin_val > umax_val) {
6869                 /* Taint dst register if offset had invalid bounds derived from
6870                  * e.g. dead branches.
6871                  */
6872                 __mark_reg_unknown(env, dst_reg);
6873                 return 0;
6874         }
6875
6876         if (BPF_CLASS(insn->code) != BPF_ALU64) {
6877                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6878                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6879                         __mark_reg_unknown(env, dst_reg);
6880                         return 0;
6881                 }
6882
6883                 verbose(env,
6884                         "R%d 32-bit pointer arithmetic prohibited\n",
6885                         dst);
6886                 return -EACCES;
6887         }
6888
6889         switch (ptr_reg->type) {
6890         case PTR_TO_MAP_VALUE_OR_NULL:
6891                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6892                         dst, reg_type_str[ptr_reg->type]);
6893                 return -EACCES;
6894         case CONST_PTR_TO_MAP:
6895                 /* smin_val represents the known value */
6896                 if (known && smin_val == 0 && opcode == BPF_ADD)
6897                         break;
6898                 fallthrough;
6899         case PTR_TO_PACKET_END:
6900         case PTR_TO_SOCKET:
6901         case PTR_TO_SOCKET_OR_NULL:
6902         case PTR_TO_SOCK_COMMON:
6903         case PTR_TO_SOCK_COMMON_OR_NULL:
6904         case PTR_TO_TCP_SOCK:
6905         case PTR_TO_TCP_SOCK_OR_NULL:
6906         case PTR_TO_XDP_SOCK:
6907                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6908                         dst, reg_type_str[ptr_reg->type]);
6909                 return -EACCES;
6910         default:
6911                 break;
6912         }
6913
6914         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6915          * The id may be overwritten later if we create a new variable offset.
6916          */
6917         dst_reg->type = ptr_reg->type;
6918         dst_reg->id = ptr_reg->id;
6919
6920         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6921             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6922                 return -EINVAL;
6923
6924         /* pointer types do not carry 32-bit bounds at the moment. */
6925         __mark_reg32_unbounded(dst_reg);
6926
6927         if (sanitize_needed(opcode)) {
6928                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6929                                        &info, false);
6930                 if (ret < 0)
6931                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
6932         }
6933
6934         switch (opcode) {
6935         case BPF_ADD:
6936                 /* We can take a fixed offset as long as it doesn't overflow
6937                  * the s32 'off' field
6938                  */
6939                 if (known && (ptr_reg->off + smin_val ==
6940                               (s64)(s32)(ptr_reg->off + smin_val))) {
6941                         /* pointer += K.  Accumulate it into fixed offset */
6942                         dst_reg->smin_value = smin_ptr;
6943                         dst_reg->smax_value = smax_ptr;
6944                         dst_reg->umin_value = umin_ptr;
6945                         dst_reg->umax_value = umax_ptr;
6946                         dst_reg->var_off = ptr_reg->var_off;
6947                         dst_reg->off = ptr_reg->off + smin_val;
6948                         dst_reg->raw = ptr_reg->raw;
6949                         break;
6950                 }
6951                 /* A new variable offset is created.  Note that off_reg->off
6952                  * == 0, since it's a scalar.
6953                  * dst_reg gets the pointer type and since some positive
6954                  * integer value was added to the pointer, give it a new 'id'
6955                  * if it's a PTR_TO_PACKET.
6956                  * this creates a new 'base' pointer, off_reg (variable) gets
6957                  * added into the variable offset, and we copy the fixed offset
6958                  * from ptr_reg.
6959                  */
6960                 if (signed_add_overflows(smin_ptr, smin_val) ||
6961                     signed_add_overflows(smax_ptr, smax_val)) {
6962                         dst_reg->smin_value = S64_MIN;
6963                         dst_reg->smax_value = S64_MAX;
6964                 } else {
6965                         dst_reg->smin_value = smin_ptr + smin_val;
6966                         dst_reg->smax_value = smax_ptr + smax_val;
6967                 }
6968                 if (umin_ptr + umin_val < umin_ptr ||
6969                     umax_ptr + umax_val < umax_ptr) {
6970                         dst_reg->umin_value = 0;
6971                         dst_reg->umax_value = U64_MAX;
6972                 } else {
6973                         dst_reg->umin_value = umin_ptr + umin_val;
6974                         dst_reg->umax_value = umax_ptr + umax_val;
6975                 }
6976                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6977                 dst_reg->off = ptr_reg->off;
6978                 dst_reg->raw = ptr_reg->raw;
6979                 if (reg_is_pkt_pointer(ptr_reg)) {
6980                         dst_reg->id = ++env->id_gen;
6981                         /* something was added to pkt_ptr, set range to zero */
6982                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6983                 }
6984                 break;
6985         case BPF_SUB:
6986                 if (dst_reg == off_reg) {
6987                         /* scalar -= pointer.  Creates an unknown scalar */
6988                         verbose(env, "R%d tried to subtract pointer from scalar\n",
6989                                 dst);
6990                         return -EACCES;
6991                 }
6992                 /* We don't allow subtraction from FP, because (according to
6993                  * test_verifier.c test "invalid fp arithmetic", JITs might not
6994                  * be able to deal with it.
6995                  */
6996                 if (ptr_reg->type == PTR_TO_STACK) {
6997                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
6998                                 dst);
6999                         return -EACCES;
7000                 }
7001                 if (known && (ptr_reg->off - smin_val ==
7002                               (s64)(s32)(ptr_reg->off - smin_val))) {
7003                         /* pointer -= K.  Subtract it from fixed offset */
7004                         dst_reg->smin_value = smin_ptr;
7005                         dst_reg->smax_value = smax_ptr;
7006                         dst_reg->umin_value = umin_ptr;
7007                         dst_reg->umax_value = umax_ptr;
7008                         dst_reg->var_off = ptr_reg->var_off;
7009                         dst_reg->id = ptr_reg->id;
7010                         dst_reg->off = ptr_reg->off - smin_val;
7011                         dst_reg->raw = ptr_reg->raw;
7012                         break;
7013                 }
7014                 /* A new variable offset is created.  If the subtrahend is known
7015                  * nonnegative, then any reg->range we had before is still good.
7016                  */
7017                 if (signed_sub_overflows(smin_ptr, smax_val) ||
7018                     signed_sub_overflows(smax_ptr, smin_val)) {
7019                         /* Overflow possible, we know nothing */
7020                         dst_reg->smin_value = S64_MIN;
7021                         dst_reg->smax_value = S64_MAX;
7022                 } else {
7023                         dst_reg->smin_value = smin_ptr - smax_val;
7024                         dst_reg->smax_value = smax_ptr - smin_val;
7025                 }
7026                 if (umin_ptr < umax_val) {
7027                         /* Overflow possible, we know nothing */
7028                         dst_reg->umin_value = 0;
7029                         dst_reg->umax_value = U64_MAX;
7030                 } else {
7031                         /* Cannot overflow (as long as bounds are consistent) */
7032                         dst_reg->umin_value = umin_ptr - umax_val;
7033                         dst_reg->umax_value = umax_ptr - umin_val;
7034                 }
7035                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7036                 dst_reg->off = ptr_reg->off;
7037                 dst_reg->raw = ptr_reg->raw;
7038                 if (reg_is_pkt_pointer(ptr_reg)) {
7039                         dst_reg->id = ++env->id_gen;
7040                         /* something was added to pkt_ptr, set range to zero */
7041                         if (smin_val < 0)
7042                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7043                 }
7044                 break;
7045         case BPF_AND:
7046         case BPF_OR:
7047         case BPF_XOR:
7048                 /* bitwise ops on pointers are troublesome, prohibit. */
7049                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7050                         dst, bpf_alu_string[opcode >> 4]);
7051                 return -EACCES;
7052         default:
7053                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
7054                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7055                         dst, bpf_alu_string[opcode >> 4]);
7056                 return -EACCES;
7057         }
7058
7059         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7060                 return -EINVAL;
7061
7062         __update_reg_bounds(dst_reg);
7063         __reg_deduce_bounds(dst_reg);
7064         __reg_bound_offset(dst_reg);
7065
7066         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7067                 return -EACCES;
7068         if (sanitize_needed(opcode)) {
7069                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7070                                        &info, true);
7071                 if (ret < 0)
7072                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
7073         }
7074
7075         return 0;
7076 }
7077
7078 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7079                                  struct bpf_reg_state *src_reg)
7080 {
7081         s32 smin_val = src_reg->s32_min_value;
7082         s32 smax_val = src_reg->s32_max_value;
7083         u32 umin_val = src_reg->u32_min_value;
7084         u32 umax_val = src_reg->u32_max_value;
7085
7086         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7087             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7088                 dst_reg->s32_min_value = S32_MIN;
7089                 dst_reg->s32_max_value = S32_MAX;
7090         } else {
7091                 dst_reg->s32_min_value += smin_val;
7092                 dst_reg->s32_max_value += smax_val;
7093         }
7094         if (dst_reg->u32_min_value + umin_val < umin_val ||
7095             dst_reg->u32_max_value + umax_val < umax_val) {
7096                 dst_reg->u32_min_value = 0;
7097                 dst_reg->u32_max_value = U32_MAX;
7098         } else {
7099                 dst_reg->u32_min_value += umin_val;
7100                 dst_reg->u32_max_value += umax_val;
7101         }
7102 }
7103
7104 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7105                                struct bpf_reg_state *src_reg)
7106 {
7107         s64 smin_val = src_reg->smin_value;
7108         s64 smax_val = src_reg->smax_value;
7109         u64 umin_val = src_reg->umin_value;
7110         u64 umax_val = src_reg->umax_value;
7111
7112         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7113             signed_add_overflows(dst_reg->smax_value, smax_val)) {
7114                 dst_reg->smin_value = S64_MIN;
7115                 dst_reg->smax_value = S64_MAX;
7116         } else {
7117                 dst_reg->smin_value += smin_val;
7118                 dst_reg->smax_value += smax_val;
7119         }
7120         if (dst_reg->umin_value + umin_val < umin_val ||
7121             dst_reg->umax_value + umax_val < umax_val) {
7122                 dst_reg->umin_value = 0;
7123                 dst_reg->umax_value = U64_MAX;
7124         } else {
7125                 dst_reg->umin_value += umin_val;
7126                 dst_reg->umax_value += umax_val;
7127         }
7128 }
7129
7130 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7131                                  struct bpf_reg_state *src_reg)
7132 {
7133         s32 smin_val = src_reg->s32_min_value;
7134         s32 smax_val = src_reg->s32_max_value;
7135         u32 umin_val = src_reg->u32_min_value;
7136         u32 umax_val = src_reg->u32_max_value;
7137
7138         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7139             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7140                 /* Overflow possible, we know nothing */
7141                 dst_reg->s32_min_value = S32_MIN;
7142                 dst_reg->s32_max_value = S32_MAX;
7143         } else {
7144                 dst_reg->s32_min_value -= smax_val;
7145                 dst_reg->s32_max_value -= smin_val;
7146         }
7147         if (dst_reg->u32_min_value < umax_val) {
7148                 /* Overflow possible, we know nothing */
7149                 dst_reg->u32_min_value = 0;
7150                 dst_reg->u32_max_value = U32_MAX;
7151         } else {
7152                 /* Cannot overflow (as long as bounds are consistent) */
7153                 dst_reg->u32_min_value -= umax_val;
7154                 dst_reg->u32_max_value -= umin_val;
7155         }
7156 }
7157
7158 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7159                                struct bpf_reg_state *src_reg)
7160 {
7161         s64 smin_val = src_reg->smin_value;
7162         s64 smax_val = src_reg->smax_value;
7163         u64 umin_val = src_reg->umin_value;
7164         u64 umax_val = src_reg->umax_value;
7165
7166         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7167             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7168                 /* Overflow possible, we know nothing */
7169                 dst_reg->smin_value = S64_MIN;
7170                 dst_reg->smax_value = S64_MAX;
7171         } else {
7172                 dst_reg->smin_value -= smax_val;
7173                 dst_reg->smax_value -= smin_val;
7174         }
7175         if (dst_reg->umin_value < umax_val) {
7176                 /* Overflow possible, we know nothing */
7177                 dst_reg->umin_value = 0;
7178                 dst_reg->umax_value = U64_MAX;
7179         } else {
7180                 /* Cannot overflow (as long as bounds are consistent) */
7181                 dst_reg->umin_value -= umax_val;
7182                 dst_reg->umax_value -= umin_val;
7183         }
7184 }
7185
7186 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7187                                  struct bpf_reg_state *src_reg)
7188 {
7189         s32 smin_val = src_reg->s32_min_value;
7190         u32 umin_val = src_reg->u32_min_value;
7191         u32 umax_val = src_reg->u32_max_value;
7192
7193         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7194                 /* Ain't nobody got time to multiply that sign */
7195                 __mark_reg32_unbounded(dst_reg);
7196                 return;
7197         }
7198         /* Both values are positive, so we can work with unsigned and
7199          * copy the result to signed (unless it exceeds S32_MAX).
7200          */
7201         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7202                 /* Potential overflow, we know nothing */
7203                 __mark_reg32_unbounded(dst_reg);
7204                 return;
7205         }
7206         dst_reg->u32_min_value *= umin_val;
7207         dst_reg->u32_max_value *= umax_val;
7208         if (dst_reg->u32_max_value > S32_MAX) {
7209                 /* Overflow possible, we know nothing */
7210                 dst_reg->s32_min_value = S32_MIN;
7211                 dst_reg->s32_max_value = S32_MAX;
7212         } else {
7213                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7214                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7215         }
7216 }
7217
7218 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7219                                struct bpf_reg_state *src_reg)
7220 {
7221         s64 smin_val = src_reg->smin_value;
7222         u64 umin_val = src_reg->umin_value;
7223         u64 umax_val = src_reg->umax_value;
7224
7225         if (smin_val < 0 || dst_reg->smin_value < 0) {
7226                 /* Ain't nobody got time to multiply that sign */
7227                 __mark_reg64_unbounded(dst_reg);
7228                 return;
7229         }
7230         /* Both values are positive, so we can work with unsigned and
7231          * copy the result to signed (unless it exceeds S64_MAX).
7232          */
7233         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7234                 /* Potential overflow, we know nothing */
7235                 __mark_reg64_unbounded(dst_reg);
7236                 return;
7237         }
7238         dst_reg->umin_value *= umin_val;
7239         dst_reg->umax_value *= umax_val;
7240         if (dst_reg->umax_value > S64_MAX) {
7241                 /* Overflow possible, we know nothing */
7242                 dst_reg->smin_value = S64_MIN;
7243                 dst_reg->smax_value = S64_MAX;
7244         } else {
7245                 dst_reg->smin_value = dst_reg->umin_value;
7246                 dst_reg->smax_value = dst_reg->umax_value;
7247         }
7248 }
7249
7250 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7251                                  struct bpf_reg_state *src_reg)
7252 {
7253         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7254         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7255         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7256         s32 smin_val = src_reg->s32_min_value;
7257         u32 umax_val = src_reg->u32_max_value;
7258
7259         if (src_known && dst_known) {
7260                 __mark_reg32_known(dst_reg, var32_off.value);
7261                 return;
7262         }
7263
7264         /* We get our minimum from the var_off, since that's inherently
7265          * bitwise.  Our maximum is the minimum of the operands' maxima.
7266          */
7267         dst_reg->u32_min_value = var32_off.value;
7268         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7269         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7270                 /* Lose signed bounds when ANDing negative numbers,
7271                  * ain't nobody got time for that.
7272                  */
7273                 dst_reg->s32_min_value = S32_MIN;
7274                 dst_reg->s32_max_value = S32_MAX;
7275         } else {
7276                 /* ANDing two positives gives a positive, so safe to
7277                  * cast result into s64.
7278                  */
7279                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7280                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7281         }
7282 }
7283
7284 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7285                                struct bpf_reg_state *src_reg)
7286 {
7287         bool src_known = tnum_is_const(src_reg->var_off);
7288         bool dst_known = tnum_is_const(dst_reg->var_off);
7289         s64 smin_val = src_reg->smin_value;
7290         u64 umax_val = src_reg->umax_value;
7291
7292         if (src_known && dst_known) {
7293                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7294                 return;
7295         }
7296
7297         /* We get our minimum from the var_off, since that's inherently
7298          * bitwise.  Our maximum is the minimum of the operands' maxima.
7299          */
7300         dst_reg->umin_value = dst_reg->var_off.value;
7301         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7302         if (dst_reg->smin_value < 0 || smin_val < 0) {
7303                 /* Lose signed bounds when ANDing negative numbers,
7304                  * ain't nobody got time for that.
7305                  */
7306                 dst_reg->smin_value = S64_MIN;
7307                 dst_reg->smax_value = S64_MAX;
7308         } else {
7309                 /* ANDing two positives gives a positive, so safe to
7310                  * cast result into s64.
7311                  */
7312                 dst_reg->smin_value = dst_reg->umin_value;
7313                 dst_reg->smax_value = dst_reg->umax_value;
7314         }
7315         /* We may learn something more from the var_off */
7316         __update_reg_bounds(dst_reg);
7317 }
7318
7319 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7320                                 struct bpf_reg_state *src_reg)
7321 {
7322         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7323         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7324         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7325         s32 smin_val = src_reg->s32_min_value;
7326         u32 umin_val = src_reg->u32_min_value;
7327
7328         if (src_known && dst_known) {
7329                 __mark_reg32_known(dst_reg, var32_off.value);
7330                 return;
7331         }
7332
7333         /* We get our maximum from the var_off, and our minimum is the
7334          * maximum of the operands' minima
7335          */
7336         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7337         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7338         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7339                 /* Lose signed bounds when ORing negative numbers,
7340                  * ain't nobody got time for that.
7341                  */
7342                 dst_reg->s32_min_value = S32_MIN;
7343                 dst_reg->s32_max_value = S32_MAX;
7344         } else {
7345                 /* ORing two positives gives a positive, so safe to
7346                  * cast result into s64.
7347                  */
7348                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7349                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7350         }
7351 }
7352
7353 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7354                               struct bpf_reg_state *src_reg)
7355 {
7356         bool src_known = tnum_is_const(src_reg->var_off);
7357         bool dst_known = tnum_is_const(dst_reg->var_off);
7358         s64 smin_val = src_reg->smin_value;
7359         u64 umin_val = src_reg->umin_value;
7360
7361         if (src_known && dst_known) {
7362                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7363                 return;
7364         }
7365
7366         /* We get our maximum from the var_off, and our minimum is the
7367          * maximum of the operands' minima
7368          */
7369         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7370         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7371         if (dst_reg->smin_value < 0 || smin_val < 0) {
7372                 /* Lose signed bounds when ORing negative numbers,
7373                  * ain't nobody got time for that.
7374                  */
7375                 dst_reg->smin_value = S64_MIN;
7376                 dst_reg->smax_value = S64_MAX;
7377         } else {
7378                 /* ORing two positives gives a positive, so safe to
7379                  * cast result into s64.
7380                  */
7381                 dst_reg->smin_value = dst_reg->umin_value;
7382                 dst_reg->smax_value = dst_reg->umax_value;
7383         }
7384         /* We may learn something more from the var_off */
7385         __update_reg_bounds(dst_reg);
7386 }
7387
7388 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7389                                  struct bpf_reg_state *src_reg)
7390 {
7391         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7392         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7393         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7394         s32 smin_val = src_reg->s32_min_value;
7395
7396         if (src_known && dst_known) {
7397                 __mark_reg32_known(dst_reg, var32_off.value);
7398                 return;
7399         }
7400
7401         /* We get both minimum and maximum from the var32_off. */
7402         dst_reg->u32_min_value = var32_off.value;
7403         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7404
7405         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7406                 /* XORing two positive sign numbers gives a positive,
7407                  * so safe to cast u32 result into s32.
7408                  */
7409                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7410                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7411         } else {
7412                 dst_reg->s32_min_value = S32_MIN;
7413                 dst_reg->s32_max_value = S32_MAX;
7414         }
7415 }
7416
7417 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7418                                struct bpf_reg_state *src_reg)
7419 {
7420         bool src_known = tnum_is_const(src_reg->var_off);
7421         bool dst_known = tnum_is_const(dst_reg->var_off);
7422         s64 smin_val = src_reg->smin_value;
7423
7424         if (src_known && dst_known) {
7425                 /* dst_reg->var_off.value has been updated earlier */
7426                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7427                 return;
7428         }
7429
7430         /* We get both minimum and maximum from the var_off. */
7431         dst_reg->umin_value = dst_reg->var_off.value;
7432         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7433
7434         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7435                 /* XORing two positive sign numbers gives a positive,
7436                  * so safe to cast u64 result into s64.
7437                  */
7438                 dst_reg->smin_value = dst_reg->umin_value;
7439                 dst_reg->smax_value = dst_reg->umax_value;
7440         } else {
7441                 dst_reg->smin_value = S64_MIN;
7442                 dst_reg->smax_value = S64_MAX;
7443         }
7444
7445         __update_reg_bounds(dst_reg);
7446 }
7447
7448 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7449                                    u64 umin_val, u64 umax_val)
7450 {
7451         /* We lose all sign bit information (except what we can pick
7452          * up from var_off)
7453          */
7454         dst_reg->s32_min_value = S32_MIN;
7455         dst_reg->s32_max_value = S32_MAX;
7456         /* If we might shift our top bit out, then we know nothing */
7457         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7458                 dst_reg->u32_min_value = 0;
7459                 dst_reg->u32_max_value = U32_MAX;
7460         } else {
7461                 dst_reg->u32_min_value <<= umin_val;
7462                 dst_reg->u32_max_value <<= umax_val;
7463         }
7464 }
7465
7466 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7467                                  struct bpf_reg_state *src_reg)
7468 {
7469         u32 umax_val = src_reg->u32_max_value;
7470         u32 umin_val = src_reg->u32_min_value;
7471         /* u32 alu operation will zext upper bits */
7472         struct tnum subreg = tnum_subreg(dst_reg->var_off);
7473
7474         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7475         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7476         /* Not required but being careful mark reg64 bounds as unknown so
7477          * that we are forced to pick them up from tnum and zext later and
7478          * if some path skips this step we are still safe.
7479          */
7480         __mark_reg64_unbounded(dst_reg);
7481         __update_reg32_bounds(dst_reg);
7482 }
7483
7484 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7485                                    u64 umin_val, u64 umax_val)
7486 {
7487         /* Special case <<32 because it is a common compiler pattern to sign
7488          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7489          * positive we know this shift will also be positive so we can track
7490          * bounds correctly. Otherwise we lose all sign bit information except
7491          * what we can pick up from var_off. Perhaps we can generalize this
7492          * later to shifts of any length.
7493          */
7494         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7495                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7496         else
7497                 dst_reg->smax_value = S64_MAX;
7498
7499         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7500                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7501         else
7502                 dst_reg->smin_value = S64_MIN;
7503
7504         /* If we might shift our top bit out, then we know nothing */
7505         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7506                 dst_reg->umin_value = 0;
7507                 dst_reg->umax_value = U64_MAX;
7508         } else {
7509                 dst_reg->umin_value <<= umin_val;
7510                 dst_reg->umax_value <<= umax_val;
7511         }
7512 }
7513
7514 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7515                                struct bpf_reg_state *src_reg)
7516 {
7517         u64 umax_val = src_reg->umax_value;
7518         u64 umin_val = src_reg->umin_value;
7519
7520         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7521         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7522         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7523
7524         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7525         /* We may learn something more from the var_off */
7526         __update_reg_bounds(dst_reg);
7527 }
7528
7529 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7530                                  struct bpf_reg_state *src_reg)
7531 {
7532         struct tnum subreg = tnum_subreg(dst_reg->var_off);
7533         u32 umax_val = src_reg->u32_max_value;
7534         u32 umin_val = src_reg->u32_min_value;
7535
7536         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7537          * be negative, then either:
7538          * 1) src_reg might be zero, so the sign bit of the result is
7539          *    unknown, so we lose our signed bounds
7540          * 2) it's known negative, thus the unsigned bounds capture the
7541          *    signed bounds
7542          * 3) the signed bounds cross zero, so they tell us nothing
7543          *    about the result
7544          * If the value in dst_reg is known nonnegative, then again the
7545          * unsigned bounds capture the signed bounds.
7546          * Thus, in all cases it suffices to blow away our signed bounds
7547          * and rely on inferring new ones from the unsigned bounds and
7548          * var_off of the result.
7549          */
7550         dst_reg->s32_min_value = S32_MIN;
7551         dst_reg->s32_max_value = S32_MAX;
7552
7553         dst_reg->var_off = tnum_rshift(subreg, umin_val);
7554         dst_reg->u32_min_value >>= umax_val;
7555         dst_reg->u32_max_value >>= umin_val;
7556
7557         __mark_reg64_unbounded(dst_reg);
7558         __update_reg32_bounds(dst_reg);
7559 }
7560
7561 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7562                                struct bpf_reg_state *src_reg)
7563 {
7564         u64 umax_val = src_reg->umax_value;
7565         u64 umin_val = src_reg->umin_value;
7566
7567         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7568          * be negative, then either:
7569          * 1) src_reg might be zero, so the sign bit of the result is
7570          *    unknown, so we lose our signed bounds
7571          * 2) it's known negative, thus the unsigned bounds capture the
7572          *    signed bounds
7573          * 3) the signed bounds cross zero, so they tell us nothing
7574          *    about the result
7575          * If the value in dst_reg is known nonnegative, then again the
7576          * unsigned bounds capture the signed bounds.
7577          * Thus, in all cases it suffices to blow away our signed bounds
7578          * and rely on inferring new ones from the unsigned bounds and
7579          * var_off of the result.
7580          */
7581         dst_reg->smin_value = S64_MIN;
7582         dst_reg->smax_value = S64_MAX;
7583         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7584         dst_reg->umin_value >>= umax_val;
7585         dst_reg->umax_value >>= umin_val;
7586
7587         /* Its not easy to operate on alu32 bounds here because it depends
7588          * on bits being shifted in. Take easy way out and mark unbounded
7589          * so we can recalculate later from tnum.
7590          */
7591         __mark_reg32_unbounded(dst_reg);
7592         __update_reg_bounds(dst_reg);
7593 }
7594
7595 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7596                                   struct bpf_reg_state *src_reg)
7597 {
7598         u64 umin_val = src_reg->u32_min_value;
7599
7600         /* Upon reaching here, src_known is true and
7601          * umax_val is equal to umin_val.
7602          */
7603         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7604         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7605
7606         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7607
7608         /* blow away the dst_reg umin_value/umax_value and rely on
7609          * dst_reg var_off to refine the result.
7610          */
7611         dst_reg->u32_min_value = 0;
7612         dst_reg->u32_max_value = U32_MAX;
7613
7614         __mark_reg64_unbounded(dst_reg);
7615         __update_reg32_bounds(dst_reg);
7616 }
7617
7618 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7619                                 struct bpf_reg_state *src_reg)
7620 {
7621         u64 umin_val = src_reg->umin_value;
7622
7623         /* Upon reaching here, src_known is true and umax_val is equal
7624          * to umin_val.
7625          */
7626         dst_reg->smin_value >>= umin_val;
7627         dst_reg->smax_value >>= umin_val;
7628
7629         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7630
7631         /* blow away the dst_reg umin_value/umax_value and rely on
7632          * dst_reg var_off to refine the result.
7633          */
7634         dst_reg->umin_value = 0;
7635         dst_reg->umax_value = U64_MAX;
7636
7637         /* Its not easy to operate on alu32 bounds here because it depends
7638          * on bits being shifted in from upper 32-bits. Take easy way out
7639          * and mark unbounded so we can recalculate later from tnum.
7640          */
7641         __mark_reg32_unbounded(dst_reg);
7642         __update_reg_bounds(dst_reg);
7643 }
7644
7645 /* WARNING: This function does calculations on 64-bit values, but the actual
7646  * execution may occur on 32-bit values. Therefore, things like bitshifts
7647  * need extra checks in the 32-bit case.
7648  */
7649 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7650                                       struct bpf_insn *insn,
7651                                       struct bpf_reg_state *dst_reg,
7652                                       struct bpf_reg_state src_reg)
7653 {
7654         struct bpf_reg_state *regs = cur_regs(env);
7655         u8 opcode = BPF_OP(insn->code);
7656         bool src_known;
7657         s64 smin_val, smax_val;
7658         u64 umin_val, umax_val;
7659         s32 s32_min_val, s32_max_val;
7660         u32 u32_min_val, u32_max_val;
7661         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7662         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7663         int ret;
7664
7665         smin_val = src_reg.smin_value;
7666         smax_val = src_reg.smax_value;
7667         umin_val = src_reg.umin_value;
7668         umax_val = src_reg.umax_value;
7669
7670         s32_min_val = src_reg.s32_min_value;
7671         s32_max_val = src_reg.s32_max_value;
7672         u32_min_val = src_reg.u32_min_value;
7673         u32_max_val = src_reg.u32_max_value;
7674
7675         if (alu32) {
7676                 src_known = tnum_subreg_is_const(src_reg.var_off);
7677                 if ((src_known &&
7678                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7679                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7680                         /* Taint dst register if offset had invalid bounds
7681                          * derived from e.g. dead branches.
7682                          */
7683                         __mark_reg_unknown(env, dst_reg);
7684                         return 0;
7685                 }
7686         } else {
7687                 src_known = tnum_is_const(src_reg.var_off);
7688                 if ((src_known &&
7689                      (smin_val != smax_val || umin_val != umax_val)) ||
7690                     smin_val > smax_val || umin_val > umax_val) {
7691                         /* Taint dst register if offset had invalid bounds
7692                          * derived from e.g. dead branches.
7693                          */
7694                         __mark_reg_unknown(env, dst_reg);
7695                         return 0;
7696                 }
7697         }
7698
7699         if (!src_known &&
7700             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7701                 __mark_reg_unknown(env, dst_reg);
7702                 return 0;
7703         }
7704
7705         if (sanitize_needed(opcode)) {
7706                 ret = sanitize_val_alu(env, insn);
7707                 if (ret < 0)
7708                         return sanitize_err(env, insn, ret, NULL, NULL);
7709         }
7710
7711         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7712          * There are two classes of instructions: The first class we track both
7713          * alu32 and alu64 sign/unsigned bounds independently this provides the
7714          * greatest amount of precision when alu operations are mixed with jmp32
7715          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7716          * and BPF_OR. This is possible because these ops have fairly easy to
7717          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7718          * See alu32 verifier tests for examples. The second class of
7719          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7720          * with regards to tracking sign/unsigned bounds because the bits may
7721          * cross subreg boundaries in the alu64 case. When this happens we mark
7722          * the reg unbounded in the subreg bound space and use the resulting
7723          * tnum to calculate an approximation of the sign/unsigned bounds.
7724          */
7725         switch (opcode) {
7726         case BPF_ADD:
7727                 scalar32_min_max_add(dst_reg, &src_reg);
7728                 scalar_min_max_add(dst_reg, &src_reg);
7729                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7730                 break;
7731         case BPF_SUB:
7732                 scalar32_min_max_sub(dst_reg, &src_reg);
7733                 scalar_min_max_sub(dst_reg, &src_reg);
7734                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7735                 break;
7736         case BPF_MUL:
7737                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7738                 scalar32_min_max_mul(dst_reg, &src_reg);
7739                 scalar_min_max_mul(dst_reg, &src_reg);
7740                 break;
7741         case BPF_AND:
7742                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7743                 scalar32_min_max_and(dst_reg, &src_reg);
7744                 scalar_min_max_and(dst_reg, &src_reg);
7745                 break;
7746         case BPF_OR:
7747                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7748                 scalar32_min_max_or(dst_reg, &src_reg);
7749                 scalar_min_max_or(dst_reg, &src_reg);
7750                 break;
7751         case BPF_XOR:
7752                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7753                 scalar32_min_max_xor(dst_reg, &src_reg);
7754                 scalar_min_max_xor(dst_reg, &src_reg);
7755                 break;
7756         case BPF_LSH:
7757                 if (umax_val >= insn_bitness) {
7758                         /* Shifts greater than 31 or 63 are undefined.
7759                          * This includes shifts by a negative number.
7760                          */
7761                         mark_reg_unknown(env, regs, insn->dst_reg);
7762                         break;
7763                 }
7764                 if (alu32)
7765                         scalar32_min_max_lsh(dst_reg, &src_reg);
7766                 else
7767                         scalar_min_max_lsh(dst_reg, &src_reg);
7768                 break;
7769         case BPF_RSH:
7770                 if (umax_val >= insn_bitness) {
7771                         /* Shifts greater than 31 or 63 are undefined.
7772                          * This includes shifts by a negative number.
7773                          */
7774                         mark_reg_unknown(env, regs, insn->dst_reg);
7775                         break;
7776                 }
7777                 if (alu32)
7778                         scalar32_min_max_rsh(dst_reg, &src_reg);
7779                 else
7780                         scalar_min_max_rsh(dst_reg, &src_reg);
7781                 break;
7782         case BPF_ARSH:
7783                 if (umax_val >= insn_bitness) {
7784                         /* Shifts greater than 31 or 63 are undefined.
7785                          * This includes shifts by a negative number.
7786                          */
7787                         mark_reg_unknown(env, regs, insn->dst_reg);
7788                         break;
7789                 }
7790                 if (alu32)
7791                         scalar32_min_max_arsh(dst_reg, &src_reg);
7792                 else
7793                         scalar_min_max_arsh(dst_reg, &src_reg);
7794                 break;
7795         default:
7796                 mark_reg_unknown(env, regs, insn->dst_reg);
7797                 break;
7798         }
7799
7800         /* ALU32 ops are zero extended into 64bit register */
7801         if (alu32)
7802                 zext_32_to_64(dst_reg);
7803
7804         __update_reg_bounds(dst_reg);
7805         __reg_deduce_bounds(dst_reg);
7806         __reg_bound_offset(dst_reg);
7807         return 0;
7808 }
7809
7810 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7811  * and var_off.
7812  */
7813 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7814                                    struct bpf_insn *insn)
7815 {
7816         struct bpf_verifier_state *vstate = env->cur_state;
7817         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7818         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7819         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7820         u8 opcode = BPF_OP(insn->code);
7821         int err;
7822
7823         dst_reg = &regs[insn->dst_reg];
7824         src_reg = NULL;
7825         if (dst_reg->type != SCALAR_VALUE)
7826                 ptr_reg = dst_reg;
7827         else
7828                 /* Make sure ID is cleared otherwise dst_reg min/max could be
7829                  * incorrectly propagated into other registers by find_equal_scalars()
7830                  */
7831                 dst_reg->id = 0;
7832         if (BPF_SRC(insn->code) == BPF_X) {
7833                 src_reg = &regs[insn->src_reg];
7834                 if (src_reg->type != SCALAR_VALUE) {
7835                         if (dst_reg->type != SCALAR_VALUE) {
7836                                 /* Combining two pointers by any ALU op yields
7837                                  * an arbitrary scalar. Disallow all math except
7838                                  * pointer subtraction
7839                                  */
7840                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7841                                         mark_reg_unknown(env, regs, insn->dst_reg);
7842                                         return 0;
7843                                 }
7844                                 verbose(env, "R%d pointer %s pointer prohibited\n",
7845                                         insn->dst_reg,
7846                                         bpf_alu_string[opcode >> 4]);
7847                                 return -EACCES;
7848                         } else {
7849                                 /* scalar += pointer
7850                                  * This is legal, but we have to reverse our
7851                                  * src/dest handling in computing the range
7852                                  */
7853                                 err = mark_chain_precision(env, insn->dst_reg);
7854                                 if (err)
7855                                         return err;
7856                                 return adjust_ptr_min_max_vals(env, insn,
7857                                                                src_reg, dst_reg);
7858                         }
7859                 } else if (ptr_reg) {
7860                         /* pointer += scalar */
7861                         err = mark_chain_precision(env, insn->src_reg);
7862                         if (err)
7863                                 return err;
7864                         return adjust_ptr_min_max_vals(env, insn,
7865                                                        dst_reg, src_reg);
7866                 }
7867         } else {
7868                 /* Pretend the src is a reg with a known value, since we only
7869                  * need to be able to read from this state.
7870                  */
7871                 off_reg.type = SCALAR_VALUE;
7872                 __mark_reg_known(&off_reg, insn->imm);
7873                 src_reg = &off_reg;
7874                 if (ptr_reg) /* pointer += K */
7875                         return adjust_ptr_min_max_vals(env, insn,
7876                                                        ptr_reg, src_reg);
7877         }
7878
7879         /* Got here implies adding two SCALAR_VALUEs */
7880         if (WARN_ON_ONCE(ptr_reg)) {
7881                 print_verifier_state(env, state);
7882                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7883                 return -EINVAL;
7884         }
7885         if (WARN_ON(!src_reg)) {
7886                 print_verifier_state(env, state);
7887                 verbose(env, "verifier internal error: no src_reg\n");
7888                 return -EINVAL;
7889         }
7890         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7891 }
7892
7893 /* check validity of 32-bit and 64-bit arithmetic operations */
7894 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7895 {
7896         struct bpf_reg_state *regs = cur_regs(env);
7897         u8 opcode = BPF_OP(insn->code);
7898         int err;
7899
7900         if (opcode == BPF_END || opcode == BPF_NEG) {
7901                 if (opcode == BPF_NEG) {
7902                         if (BPF_SRC(insn->code) != 0 ||
7903                             insn->src_reg != BPF_REG_0 ||
7904                             insn->off != 0 || insn->imm != 0) {
7905                                 verbose(env, "BPF_NEG uses reserved fields\n");
7906                                 return -EINVAL;
7907                         }
7908                 } else {
7909                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7910                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7911                             BPF_CLASS(insn->code) == BPF_ALU64) {
7912                                 verbose(env, "BPF_END uses reserved fields\n");
7913                                 return -EINVAL;
7914                         }
7915                 }
7916
7917                 /* check src operand */
7918                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7919                 if (err)
7920                         return err;
7921
7922                 if (is_pointer_value(env, insn->dst_reg)) {
7923                         verbose(env, "R%d pointer arithmetic prohibited\n",
7924                                 insn->dst_reg);
7925                         return -EACCES;
7926                 }
7927
7928                 /* check dest operand */
7929                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7930                 if (err)
7931                         return err;
7932
7933         } else if (opcode == BPF_MOV) {
7934
7935                 if (BPF_SRC(insn->code) == BPF_X) {
7936                         if (insn->imm != 0 || insn->off != 0) {
7937                                 verbose(env, "BPF_MOV uses reserved fields\n");
7938                                 return -EINVAL;
7939                         }
7940
7941                         /* check src operand */
7942                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
7943                         if (err)
7944                                 return err;
7945                 } else {
7946                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7947                                 verbose(env, "BPF_MOV uses reserved fields\n");
7948                                 return -EINVAL;
7949                         }
7950                 }
7951
7952                 /* check dest operand, mark as required later */
7953                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7954                 if (err)
7955                         return err;
7956
7957                 if (BPF_SRC(insn->code) == BPF_X) {
7958                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
7959                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7960
7961                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
7962                                 /* case: R1 = R2
7963                                  * copy register state to dest reg
7964                                  */
7965                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7966                                         /* Assign src and dst registers the same ID
7967                                          * that will be used by find_equal_scalars()
7968                                          * to propagate min/max range.
7969                                          */
7970                                         src_reg->id = ++env->id_gen;
7971                                 *dst_reg = *src_reg;
7972                                 dst_reg->live |= REG_LIVE_WRITTEN;
7973                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
7974                         } else {
7975                                 /* R1 = (u32) R2 */
7976                                 if (is_pointer_value(env, insn->src_reg)) {
7977                                         verbose(env,
7978                                                 "R%d partial copy of pointer\n",
7979                                                 insn->src_reg);
7980                                         return -EACCES;
7981                                 } else if (src_reg->type == SCALAR_VALUE) {
7982                                         *dst_reg = *src_reg;
7983                                         /* Make sure ID is cleared otherwise
7984                                          * dst_reg min/max could be incorrectly
7985                                          * propagated into src_reg by find_equal_scalars()
7986                                          */
7987                                         dst_reg->id = 0;
7988                                         dst_reg->live |= REG_LIVE_WRITTEN;
7989                                         dst_reg->subreg_def = env->insn_idx + 1;
7990                                 } else {
7991                                         mark_reg_unknown(env, regs,
7992                                                          insn->dst_reg);
7993                                 }
7994                                 zext_32_to_64(dst_reg);
7995                         }
7996                 } else {
7997                         /* case: R = imm
7998                          * remember the value we stored into this reg
7999                          */
8000                         /* clear any state __mark_reg_known doesn't set */
8001                         mark_reg_unknown(env, regs, insn->dst_reg);
8002                         regs[insn->dst_reg].type = SCALAR_VALUE;
8003                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
8004                                 __mark_reg_known(regs + insn->dst_reg,
8005                                                  insn->imm);
8006                         } else {
8007                                 __mark_reg_known(regs + insn->dst_reg,
8008                                                  (u32)insn->imm);
8009                         }
8010                 }
8011
8012         } else if (opcode > BPF_END) {
8013                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8014                 return -EINVAL;
8015
8016         } else {        /* all other ALU ops: and, sub, xor, add, ... */
8017
8018                 if (BPF_SRC(insn->code) == BPF_X) {
8019                         if (insn->imm != 0 || insn->off != 0) {
8020                                 verbose(env, "BPF_ALU uses reserved fields\n");
8021                                 return -EINVAL;
8022                         }
8023                         /* check src1 operand */
8024                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
8025                         if (err)
8026                                 return err;
8027                 } else {
8028                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8029                                 verbose(env, "BPF_ALU uses reserved fields\n");
8030                                 return -EINVAL;
8031                         }
8032                 }
8033
8034                 /* check src2 operand */
8035                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8036                 if (err)
8037                         return err;
8038
8039                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8040                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8041                         verbose(env, "div by zero\n");
8042                         return -EINVAL;
8043                 }
8044
8045                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8046                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8047                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8048
8049                         if (insn->imm < 0 || insn->imm >= size) {
8050                                 verbose(env, "invalid shift %d\n", insn->imm);
8051                                 return -EINVAL;
8052                         }
8053                 }
8054
8055                 /* check dest operand */
8056                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8057                 if (err)
8058                         return err;
8059
8060                 return adjust_reg_min_max_vals(env, insn);
8061         }
8062
8063         return 0;
8064 }
8065
8066 static void __find_good_pkt_pointers(struct bpf_func_state *state,
8067                                      struct bpf_reg_state *dst_reg,
8068                                      enum bpf_reg_type type, int new_range)
8069 {
8070         struct bpf_reg_state *reg;
8071         int i;
8072
8073         for (i = 0; i < MAX_BPF_REG; i++) {
8074                 reg = &state->regs[i];
8075                 if (reg->type == type && reg->id == dst_reg->id)
8076                         /* keep the maximum range already checked */
8077                         reg->range = max(reg->range, new_range);
8078         }
8079
8080         bpf_for_each_spilled_reg(i, state, reg) {
8081                 if (!reg)
8082                         continue;
8083                 if (reg->type == type && reg->id == dst_reg->id)
8084                         reg->range = max(reg->range, new_range);
8085         }
8086 }
8087
8088 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8089                                    struct bpf_reg_state *dst_reg,
8090                                    enum bpf_reg_type type,
8091                                    bool range_right_open)
8092 {
8093         int new_range, i;
8094
8095         if (dst_reg->off < 0 ||
8096             (dst_reg->off == 0 && range_right_open))
8097                 /* This doesn't give us any range */
8098                 return;
8099
8100         if (dst_reg->umax_value > MAX_PACKET_OFF ||
8101             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8102                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
8103                  * than pkt_end, but that's because it's also less than pkt.
8104                  */
8105                 return;
8106
8107         new_range = dst_reg->off;
8108         if (range_right_open)
8109                 new_range--;
8110
8111         /* Examples for register markings:
8112          *
8113          * pkt_data in dst register:
8114          *
8115          *   r2 = r3;
8116          *   r2 += 8;
8117          *   if (r2 > pkt_end) goto <handle exception>
8118          *   <access okay>
8119          *
8120          *   r2 = r3;
8121          *   r2 += 8;
8122          *   if (r2 < pkt_end) goto <access okay>
8123          *   <handle exception>
8124          *
8125          *   Where:
8126          *     r2 == dst_reg, pkt_end == src_reg
8127          *     r2=pkt(id=n,off=8,r=0)
8128          *     r3=pkt(id=n,off=0,r=0)
8129          *
8130          * pkt_data in src register:
8131          *
8132          *   r2 = r3;
8133          *   r2 += 8;
8134          *   if (pkt_end >= r2) goto <access okay>
8135          *   <handle exception>
8136          *
8137          *   r2 = r3;
8138          *   r2 += 8;
8139          *   if (pkt_end <= r2) goto <handle exception>
8140          *   <access okay>
8141          *
8142          *   Where:
8143          *     pkt_end == dst_reg, r2 == src_reg
8144          *     r2=pkt(id=n,off=8,r=0)
8145          *     r3=pkt(id=n,off=0,r=0)
8146          *
8147          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8148          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8149          * and [r3, r3 + 8-1) respectively is safe to access depending on
8150          * the check.
8151          */
8152
8153         /* If our ids match, then we must have the same max_value.  And we
8154          * don't care about the other reg's fixed offset, since if it's too big
8155          * the range won't allow anything.
8156          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8157          */
8158         for (i = 0; i <= vstate->curframe; i++)
8159                 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8160                                          new_range);
8161 }
8162
8163 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8164 {
8165         struct tnum subreg = tnum_subreg(reg->var_off);
8166         s32 sval = (s32)val;
8167
8168         switch (opcode) {
8169         case BPF_JEQ:
8170                 if (tnum_is_const(subreg))
8171                         return !!tnum_equals_const(subreg, val);
8172                 break;
8173         case BPF_JNE:
8174                 if (tnum_is_const(subreg))
8175                         return !tnum_equals_const(subreg, val);
8176                 break;
8177         case BPF_JSET:
8178                 if ((~subreg.mask & subreg.value) & val)
8179                         return 1;
8180                 if (!((subreg.mask | subreg.value) & val))
8181                         return 0;
8182                 break;
8183         case BPF_JGT:
8184                 if (reg->u32_min_value > val)
8185                         return 1;
8186                 else if (reg->u32_max_value <= val)
8187                         return 0;
8188                 break;
8189         case BPF_JSGT:
8190                 if (reg->s32_min_value > sval)
8191                         return 1;
8192                 else if (reg->s32_max_value <= sval)
8193                         return 0;
8194                 break;
8195         case BPF_JLT:
8196                 if (reg->u32_max_value < val)
8197                         return 1;
8198                 else if (reg->u32_min_value >= val)
8199                         return 0;
8200                 break;
8201         case BPF_JSLT:
8202                 if (reg->s32_max_value < sval)
8203                         return 1;
8204                 else if (reg->s32_min_value >= sval)
8205                         return 0;
8206                 break;
8207         case BPF_JGE:
8208                 if (reg->u32_min_value >= val)
8209                         return 1;
8210                 else if (reg->u32_max_value < val)
8211                         return 0;
8212                 break;
8213         case BPF_JSGE:
8214                 if (reg->s32_min_value >= sval)
8215                         return 1;
8216                 else if (reg->s32_max_value < sval)
8217                         return 0;
8218                 break;
8219         case BPF_JLE:
8220                 if (reg->u32_max_value <= val)
8221                         return 1;
8222                 else if (reg->u32_min_value > val)
8223                         return 0;
8224                 break;
8225         case BPF_JSLE:
8226                 if (reg->s32_max_value <= sval)
8227                         return 1;
8228                 else if (reg->s32_min_value > sval)
8229                         return 0;
8230                 break;
8231         }
8232
8233         return -1;
8234 }
8235
8236
8237 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8238 {
8239         s64 sval = (s64)val;
8240
8241         switch (opcode) {
8242         case BPF_JEQ:
8243                 if (tnum_is_const(reg->var_off))
8244                         return !!tnum_equals_const(reg->var_off, val);
8245                 break;
8246         case BPF_JNE:
8247                 if (tnum_is_const(reg->var_off))
8248                         return !tnum_equals_const(reg->var_off, val);
8249                 break;
8250         case BPF_JSET:
8251                 if ((~reg->var_off.mask & reg->var_off.value) & val)
8252                         return 1;
8253                 if (!((reg->var_off.mask | reg->var_off.value) & val))
8254                         return 0;
8255                 break;
8256         case BPF_JGT:
8257                 if (reg->umin_value > val)
8258                         return 1;
8259                 else if (reg->umax_value <= val)
8260                         return 0;
8261                 break;
8262         case BPF_JSGT:
8263                 if (reg->smin_value > sval)
8264                         return 1;
8265                 else if (reg->smax_value <= sval)
8266                         return 0;
8267                 break;
8268         case BPF_JLT:
8269                 if (reg->umax_value < val)
8270                         return 1;
8271                 else if (reg->umin_value >= val)
8272                         return 0;
8273                 break;
8274         case BPF_JSLT:
8275                 if (reg->smax_value < sval)
8276                         return 1;
8277                 else if (reg->smin_value >= sval)
8278                         return 0;
8279                 break;
8280         case BPF_JGE:
8281                 if (reg->umin_value >= val)
8282                         return 1;
8283                 else if (reg->umax_value < val)
8284                         return 0;
8285                 break;
8286         case BPF_JSGE:
8287                 if (reg->smin_value >= sval)
8288                         return 1;
8289                 else if (reg->smax_value < sval)
8290                         return 0;
8291                 break;
8292         case BPF_JLE:
8293                 if (reg->umax_value <= val)
8294                         return 1;
8295                 else if (reg->umin_value > val)
8296                         return 0;
8297                 break;
8298         case BPF_JSLE:
8299                 if (reg->smax_value <= sval)
8300                         return 1;
8301                 else if (reg->smin_value > sval)
8302                         return 0;
8303                 break;
8304         }
8305
8306         return -1;
8307 }
8308
8309 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8310  * and return:
8311  *  1 - branch will be taken and "goto target" will be executed
8312  *  0 - branch will not be taken and fall-through to next insn
8313  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8314  *      range [0,10]
8315  */
8316 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8317                            bool is_jmp32)
8318 {
8319         if (__is_pointer_value(false, reg)) {
8320                 if (!reg_type_not_null(reg->type))
8321                         return -1;
8322
8323                 /* If pointer is valid tests against zero will fail so we can
8324                  * use this to direct branch taken.
8325                  */
8326                 if (val != 0)
8327                         return -1;
8328
8329                 switch (opcode) {
8330                 case BPF_JEQ:
8331                         return 0;
8332                 case BPF_JNE:
8333                         return 1;
8334                 default:
8335                         return -1;
8336                 }
8337         }
8338
8339         if (is_jmp32)
8340                 return is_branch32_taken(reg, val, opcode);
8341         return is_branch64_taken(reg, val, opcode);
8342 }
8343
8344 static int flip_opcode(u32 opcode)
8345 {
8346         /* How can we transform "a <op> b" into "b <op> a"? */
8347         static const u8 opcode_flip[16] = {
8348                 /* these stay the same */
8349                 [BPF_JEQ  >> 4] = BPF_JEQ,
8350                 [BPF_JNE  >> 4] = BPF_JNE,
8351                 [BPF_JSET >> 4] = BPF_JSET,
8352                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8353                 [BPF_JGE  >> 4] = BPF_JLE,
8354                 [BPF_JGT  >> 4] = BPF_JLT,
8355                 [BPF_JLE  >> 4] = BPF_JGE,
8356                 [BPF_JLT  >> 4] = BPF_JGT,
8357                 [BPF_JSGE >> 4] = BPF_JSLE,
8358                 [BPF_JSGT >> 4] = BPF_JSLT,
8359                 [BPF_JSLE >> 4] = BPF_JSGE,
8360                 [BPF_JSLT >> 4] = BPF_JSGT
8361         };
8362         return opcode_flip[opcode >> 4];
8363 }
8364
8365 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8366                                    struct bpf_reg_state *src_reg,
8367                                    u8 opcode)
8368 {
8369         struct bpf_reg_state *pkt;
8370
8371         if (src_reg->type == PTR_TO_PACKET_END) {
8372                 pkt = dst_reg;
8373         } else if (dst_reg->type == PTR_TO_PACKET_END) {
8374                 pkt = src_reg;
8375                 opcode = flip_opcode(opcode);
8376         } else {
8377                 return -1;
8378         }
8379
8380         if (pkt->range >= 0)
8381                 return -1;
8382
8383         switch (opcode) {
8384         case BPF_JLE:
8385                 /* pkt <= pkt_end */
8386                 fallthrough;
8387         case BPF_JGT:
8388                 /* pkt > pkt_end */
8389                 if (pkt->range == BEYOND_PKT_END)
8390                         /* pkt has at last one extra byte beyond pkt_end */
8391                         return opcode == BPF_JGT;
8392                 break;
8393         case BPF_JLT:
8394                 /* pkt < pkt_end */
8395                 fallthrough;
8396         case BPF_JGE:
8397                 /* pkt >= pkt_end */
8398                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8399                         return opcode == BPF_JGE;
8400                 break;
8401         }
8402         return -1;
8403 }
8404
8405 /* Adjusts the register min/max values in the case that the dst_reg is the
8406  * variable register that we are working on, and src_reg is a constant or we're
8407  * simply doing a BPF_K check.
8408  * In JEQ/JNE cases we also adjust the var_off values.
8409  */
8410 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8411                             struct bpf_reg_state *false_reg,
8412                             u64 val, u32 val32,
8413                             u8 opcode, bool is_jmp32)
8414 {
8415         struct tnum false_32off = tnum_subreg(false_reg->var_off);
8416         struct tnum false_64off = false_reg->var_off;
8417         struct tnum true_32off = tnum_subreg(true_reg->var_off);
8418         struct tnum true_64off = true_reg->var_off;
8419         s64 sval = (s64)val;
8420         s32 sval32 = (s32)val32;
8421
8422         /* If the dst_reg is a pointer, we can't learn anything about its
8423          * variable offset from the compare (unless src_reg were a pointer into
8424          * the same object, but we don't bother with that.
8425          * Since false_reg and true_reg have the same type by construction, we
8426          * only need to check one of them for pointerness.
8427          */
8428         if (__is_pointer_value(false, false_reg))
8429                 return;
8430
8431         switch (opcode) {
8432         case BPF_JEQ:
8433         case BPF_JNE:
8434         {
8435                 struct bpf_reg_state *reg =
8436                         opcode == BPF_JEQ ? true_reg : false_reg;
8437
8438                 /* JEQ/JNE comparison doesn't change the register equivalence.
8439                  * r1 = r2;
8440                  * if (r1 == 42) goto label;
8441                  * ...
8442                  * label: // here both r1 and r2 are known to be 42.
8443                  *
8444                  * Hence when marking register as known preserve it's ID.
8445                  */
8446                 if (is_jmp32)
8447                         __mark_reg32_known(reg, val32);
8448                 else
8449                         ___mark_reg_known(reg, val);
8450                 break;
8451         }
8452         case BPF_JSET:
8453                 if (is_jmp32) {
8454                         false_32off = tnum_and(false_32off, tnum_const(~val32));
8455                         if (is_power_of_2(val32))
8456                                 true_32off = tnum_or(true_32off,
8457                                                      tnum_const(val32));
8458                 } else {
8459                         false_64off = tnum_and(false_64off, tnum_const(~val));
8460                         if (is_power_of_2(val))
8461                                 true_64off = tnum_or(true_64off,
8462                                                      tnum_const(val));
8463                 }
8464                 break;
8465         case BPF_JGE:
8466         case BPF_JGT:
8467         {
8468                 if (is_jmp32) {
8469                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8470                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8471
8472                         false_reg->u32_max_value = min(false_reg->u32_max_value,
8473                                                        false_umax);
8474                         true_reg->u32_min_value = max(true_reg->u32_min_value,
8475                                                       true_umin);
8476                 } else {
8477                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8478                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8479
8480                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
8481                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
8482                 }
8483                 break;
8484         }
8485         case BPF_JSGE:
8486         case BPF_JSGT:
8487         {
8488                 if (is_jmp32) {
8489                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8490                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8491
8492                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8493                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8494                 } else {
8495                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8496                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8497
8498                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
8499                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
8500                 }
8501                 break;
8502         }
8503         case BPF_JLE:
8504         case BPF_JLT:
8505         {
8506                 if (is_jmp32) {
8507                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8508                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8509
8510                         false_reg->u32_min_value = max(false_reg->u32_min_value,
8511                                                        false_umin);
8512                         true_reg->u32_max_value = min(true_reg->u32_max_value,
8513                                                       true_umax);
8514                 } else {
8515                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8516                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8517
8518                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
8519                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
8520                 }
8521                 break;
8522         }
8523         case BPF_JSLE:
8524         case BPF_JSLT:
8525         {
8526                 if (is_jmp32) {
8527                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8528                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8529
8530                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8531                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8532                 } else {
8533                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8534                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8535
8536                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
8537                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
8538                 }
8539                 break;
8540         }
8541         default:
8542                 return;
8543         }
8544
8545         if (is_jmp32) {
8546                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8547                                              tnum_subreg(false_32off));
8548                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8549                                             tnum_subreg(true_32off));
8550                 __reg_combine_32_into_64(false_reg);
8551                 __reg_combine_32_into_64(true_reg);
8552         } else {
8553                 false_reg->var_off = false_64off;
8554                 true_reg->var_off = true_64off;
8555                 __reg_combine_64_into_32(false_reg);
8556                 __reg_combine_64_into_32(true_reg);
8557         }
8558 }
8559
8560 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8561  * the variable reg.
8562  */
8563 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8564                                 struct bpf_reg_state *false_reg,
8565                                 u64 val, u32 val32,
8566                                 u8 opcode, bool is_jmp32)
8567 {
8568         opcode = flip_opcode(opcode);
8569         /* This uses zero as "not present in table"; luckily the zero opcode,
8570          * BPF_JA, can't get here.
8571          */
8572         if (opcode)
8573                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8574 }
8575
8576 /* Regs are known to be equal, so intersect their min/max/var_off */
8577 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8578                                   struct bpf_reg_state *dst_reg)
8579 {
8580         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8581                                                         dst_reg->umin_value);
8582         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8583                                                         dst_reg->umax_value);
8584         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8585                                                         dst_reg->smin_value);
8586         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8587                                                         dst_reg->smax_value);
8588         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8589                                                              dst_reg->var_off);
8590         /* We might have learned new bounds from the var_off. */
8591         __update_reg_bounds(src_reg);
8592         __update_reg_bounds(dst_reg);
8593         /* We might have learned something about the sign bit. */
8594         __reg_deduce_bounds(src_reg);
8595         __reg_deduce_bounds(dst_reg);
8596         /* We might have learned some bits from the bounds. */
8597         __reg_bound_offset(src_reg);
8598         __reg_bound_offset(dst_reg);
8599         /* Intersecting with the old var_off might have improved our bounds
8600          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8601          * then new var_off is (0; 0x7f...fc) which improves our umax.
8602          */
8603         __update_reg_bounds(src_reg);
8604         __update_reg_bounds(dst_reg);
8605 }
8606
8607 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8608                                 struct bpf_reg_state *true_dst,
8609                                 struct bpf_reg_state *false_src,
8610                                 struct bpf_reg_state *false_dst,
8611                                 u8 opcode)
8612 {
8613         switch (opcode) {
8614         case BPF_JEQ:
8615                 __reg_combine_min_max(true_src, true_dst);
8616                 break;
8617         case BPF_JNE:
8618                 __reg_combine_min_max(false_src, false_dst);
8619                 break;
8620         }
8621 }
8622
8623 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8624                                  struct bpf_reg_state *reg, u32 id,
8625                                  bool is_null)
8626 {
8627         if (reg_type_may_be_null(reg->type) && reg->id == id &&
8628             !WARN_ON_ONCE(!reg->id)) {
8629                 /* Old offset (both fixed and variable parts) should
8630                  * have been known-zero, because we don't allow pointer
8631                  * arithmetic on pointers that might be NULL.
8632                  */
8633                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8634                                  !tnum_equals_const(reg->var_off, 0) ||
8635                                  reg->off)) {
8636                         __mark_reg_known_zero(reg);
8637                         reg->off = 0;
8638                 }
8639                 if (is_null) {
8640                         reg->type = SCALAR_VALUE;
8641                         /* We don't need id and ref_obj_id from this point
8642                          * onwards anymore, thus we should better reset it,
8643                          * so that state pruning has chances to take effect.
8644                          */
8645                         reg->id = 0;
8646                         reg->ref_obj_id = 0;
8647
8648                         return;
8649                 }
8650
8651                 mark_ptr_not_null_reg(reg);
8652
8653                 if (!reg_may_point_to_spin_lock(reg)) {
8654                         /* For not-NULL ptr, reg->ref_obj_id will be reset
8655                          * in release_reg_references().
8656                          *
8657                          * reg->id is still used by spin_lock ptr. Other
8658                          * than spin_lock ptr type, reg->id can be reset.
8659                          */
8660                         reg->id = 0;
8661                 }
8662         }
8663 }
8664
8665 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8666                                     bool is_null)
8667 {
8668         struct bpf_reg_state *reg;
8669         int i;
8670
8671         for (i = 0; i < MAX_BPF_REG; i++)
8672                 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8673
8674         bpf_for_each_spilled_reg(i, state, reg) {
8675                 if (!reg)
8676                         continue;
8677                 mark_ptr_or_null_reg(state, reg, id, is_null);
8678         }
8679 }
8680
8681 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8682  * be folded together at some point.
8683  */
8684 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8685                                   bool is_null)
8686 {
8687         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8688         struct bpf_reg_state *regs = state->regs;
8689         u32 ref_obj_id = regs[regno].ref_obj_id;
8690         u32 id = regs[regno].id;
8691         int i;
8692
8693         if (ref_obj_id && ref_obj_id == id && is_null)
8694                 /* regs[regno] is in the " == NULL" branch.
8695                  * No one could have freed the reference state before
8696                  * doing the NULL check.
8697                  */
8698                 WARN_ON_ONCE(release_reference_state(state, id));
8699
8700         for (i = 0; i <= vstate->curframe; i++)
8701                 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
8702 }
8703
8704 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8705                                    struct bpf_reg_state *dst_reg,
8706                                    struct bpf_reg_state *src_reg,
8707                                    struct bpf_verifier_state *this_branch,
8708                                    struct bpf_verifier_state *other_branch)
8709 {
8710         if (BPF_SRC(insn->code) != BPF_X)
8711                 return false;
8712
8713         /* Pointers are always 64-bit. */
8714         if (BPF_CLASS(insn->code) == BPF_JMP32)
8715                 return false;
8716
8717         switch (BPF_OP(insn->code)) {
8718         case BPF_JGT:
8719                 if ((dst_reg->type == PTR_TO_PACKET &&
8720                      src_reg->type == PTR_TO_PACKET_END) ||
8721                     (dst_reg->type == PTR_TO_PACKET_META &&
8722                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8723                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8724                         find_good_pkt_pointers(this_branch, dst_reg,
8725                                                dst_reg->type, false);
8726                         mark_pkt_end(other_branch, insn->dst_reg, true);
8727                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8728                             src_reg->type == PTR_TO_PACKET) ||
8729                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8730                             src_reg->type == PTR_TO_PACKET_META)) {
8731                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8732                         find_good_pkt_pointers(other_branch, src_reg,
8733                                                src_reg->type, true);
8734                         mark_pkt_end(this_branch, insn->src_reg, false);
8735                 } else {
8736                         return false;
8737                 }
8738                 break;
8739         case BPF_JLT:
8740                 if ((dst_reg->type == PTR_TO_PACKET &&
8741                      src_reg->type == PTR_TO_PACKET_END) ||
8742                     (dst_reg->type == PTR_TO_PACKET_META &&
8743                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8744                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8745                         find_good_pkt_pointers(other_branch, dst_reg,
8746                                                dst_reg->type, true);
8747                         mark_pkt_end(this_branch, insn->dst_reg, false);
8748                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8749                             src_reg->type == PTR_TO_PACKET) ||
8750                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8751                             src_reg->type == PTR_TO_PACKET_META)) {
8752                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8753                         find_good_pkt_pointers(this_branch, src_reg,
8754                                                src_reg->type, false);
8755                         mark_pkt_end(other_branch, insn->src_reg, true);
8756                 } else {
8757                         return false;
8758                 }
8759                 break;
8760         case BPF_JGE:
8761                 if ((dst_reg->type == PTR_TO_PACKET &&
8762                      src_reg->type == PTR_TO_PACKET_END) ||
8763                     (dst_reg->type == PTR_TO_PACKET_META &&
8764                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8765                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8766                         find_good_pkt_pointers(this_branch, dst_reg,
8767                                                dst_reg->type, true);
8768                         mark_pkt_end(other_branch, insn->dst_reg, false);
8769                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8770                             src_reg->type == PTR_TO_PACKET) ||
8771                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8772                             src_reg->type == PTR_TO_PACKET_META)) {
8773                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8774                         find_good_pkt_pointers(other_branch, src_reg,
8775                                                src_reg->type, false);
8776                         mark_pkt_end(this_branch, insn->src_reg, true);
8777                 } else {
8778                         return false;
8779                 }
8780                 break;
8781         case BPF_JLE:
8782                 if ((dst_reg->type == PTR_TO_PACKET &&
8783                      src_reg->type == PTR_TO_PACKET_END) ||
8784                     (dst_reg->type == PTR_TO_PACKET_META &&
8785                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8786                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8787                         find_good_pkt_pointers(other_branch, dst_reg,
8788                                                dst_reg->type, false);
8789                         mark_pkt_end(this_branch, insn->dst_reg, true);
8790                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8791                             src_reg->type == PTR_TO_PACKET) ||
8792                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8793                             src_reg->type == PTR_TO_PACKET_META)) {
8794                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8795                         find_good_pkt_pointers(this_branch, src_reg,
8796                                                src_reg->type, true);
8797                         mark_pkt_end(other_branch, insn->src_reg, false);
8798                 } else {
8799                         return false;
8800                 }
8801                 break;
8802         default:
8803                 return false;
8804         }
8805
8806         return true;
8807 }
8808
8809 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8810                                struct bpf_reg_state *known_reg)
8811 {
8812         struct bpf_func_state *state;
8813         struct bpf_reg_state *reg;
8814         int i, j;
8815
8816         for (i = 0; i <= vstate->curframe; i++) {
8817                 state = vstate->frame[i];
8818                 for (j = 0; j < MAX_BPF_REG; j++) {
8819                         reg = &state->regs[j];
8820                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8821                                 *reg = *known_reg;
8822                 }
8823
8824                 bpf_for_each_spilled_reg(j, state, reg) {
8825                         if (!reg)
8826                                 continue;
8827                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8828                                 *reg = *known_reg;
8829                 }
8830         }
8831 }
8832
8833 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8834                              struct bpf_insn *insn, int *insn_idx)
8835 {
8836         struct bpf_verifier_state *this_branch = env->cur_state;
8837         struct bpf_verifier_state *other_branch;
8838         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8839         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8840         u8 opcode = BPF_OP(insn->code);
8841         bool is_jmp32;
8842         int pred = -1;
8843         int err;
8844
8845         /* Only conditional jumps are expected to reach here. */
8846         if (opcode == BPF_JA || opcode > BPF_JSLE) {
8847                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8848                 return -EINVAL;
8849         }
8850
8851         if (BPF_SRC(insn->code) == BPF_X) {
8852                 if (insn->imm != 0) {
8853                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8854                         return -EINVAL;
8855                 }
8856
8857                 /* check src1 operand */
8858                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8859                 if (err)
8860                         return err;
8861
8862                 if (is_pointer_value(env, insn->src_reg)) {
8863                         verbose(env, "R%d pointer comparison prohibited\n",
8864                                 insn->src_reg);
8865                         return -EACCES;
8866                 }
8867                 src_reg = &regs[insn->src_reg];
8868         } else {
8869                 if (insn->src_reg != BPF_REG_0) {
8870                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8871                         return -EINVAL;
8872                 }
8873         }
8874
8875         /* check src2 operand */
8876         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8877         if (err)
8878                 return err;
8879
8880         dst_reg = &regs[insn->dst_reg];
8881         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8882
8883         if (BPF_SRC(insn->code) == BPF_K) {
8884                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8885         } else if (src_reg->type == SCALAR_VALUE &&
8886                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8887                 pred = is_branch_taken(dst_reg,
8888                                        tnum_subreg(src_reg->var_off).value,
8889                                        opcode,
8890                                        is_jmp32);
8891         } else if (src_reg->type == SCALAR_VALUE &&
8892                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8893                 pred = is_branch_taken(dst_reg,
8894                                        src_reg->var_off.value,
8895                                        opcode,
8896                                        is_jmp32);
8897         } else if (reg_is_pkt_pointer_any(dst_reg) &&
8898                    reg_is_pkt_pointer_any(src_reg) &&
8899                    !is_jmp32) {
8900                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8901         }
8902
8903         if (pred >= 0) {
8904                 /* If we get here with a dst_reg pointer type it is because
8905                  * above is_branch_taken() special cased the 0 comparison.
8906                  */
8907                 if (!__is_pointer_value(false, dst_reg))
8908                         err = mark_chain_precision(env, insn->dst_reg);
8909                 if (BPF_SRC(insn->code) == BPF_X && !err &&
8910                     !__is_pointer_value(false, src_reg))
8911                         err = mark_chain_precision(env, insn->src_reg);
8912                 if (err)
8913                         return err;
8914         }
8915
8916         if (pred == 1) {
8917                 /* Only follow the goto, ignore fall-through. If needed, push
8918                  * the fall-through branch for simulation under speculative
8919                  * execution.
8920                  */
8921                 if (!env->bypass_spec_v1 &&
8922                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
8923                                                *insn_idx))
8924                         return -EFAULT;
8925                 *insn_idx += insn->off;
8926                 return 0;
8927         } else if (pred == 0) {
8928                 /* Only follow the fall-through branch, since that's where the
8929                  * program will go. If needed, push the goto branch for
8930                  * simulation under speculative execution.
8931                  */
8932                 if (!env->bypass_spec_v1 &&
8933                     !sanitize_speculative_path(env, insn,
8934                                                *insn_idx + insn->off + 1,
8935                                                *insn_idx))
8936                         return -EFAULT;
8937                 return 0;
8938         }
8939
8940         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8941                                   false);
8942         if (!other_branch)
8943                 return -EFAULT;
8944         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8945
8946         /* detect if we are comparing against a constant value so we can adjust
8947          * our min/max values for our dst register.
8948          * this is only legit if both are scalars (or pointers to the same
8949          * object, I suppose, but we don't support that right now), because
8950          * otherwise the different base pointers mean the offsets aren't
8951          * comparable.
8952          */
8953         if (BPF_SRC(insn->code) == BPF_X) {
8954                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8955
8956                 if (dst_reg->type == SCALAR_VALUE &&
8957                     src_reg->type == SCALAR_VALUE) {
8958                         if (tnum_is_const(src_reg->var_off) ||
8959                             (is_jmp32 &&
8960                              tnum_is_const(tnum_subreg(src_reg->var_off))))
8961                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8962                                                 dst_reg,
8963                                                 src_reg->var_off.value,
8964                                                 tnum_subreg(src_reg->var_off).value,
8965                                                 opcode, is_jmp32);
8966                         else if (tnum_is_const(dst_reg->var_off) ||
8967                                  (is_jmp32 &&
8968                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
8969                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8970                                                     src_reg,
8971                                                     dst_reg->var_off.value,
8972                                                     tnum_subreg(dst_reg->var_off).value,
8973                                                     opcode, is_jmp32);
8974                         else if (!is_jmp32 &&
8975                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
8976                                 /* Comparing for equality, we can combine knowledge */
8977                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8978                                                     &other_branch_regs[insn->dst_reg],
8979                                                     src_reg, dst_reg, opcode);
8980                         if (src_reg->id &&
8981                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8982                                 find_equal_scalars(this_branch, src_reg);
8983                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8984                         }
8985
8986                 }
8987         } else if (dst_reg->type == SCALAR_VALUE) {
8988                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8989                                         dst_reg, insn->imm, (u32)insn->imm,
8990                                         opcode, is_jmp32);
8991         }
8992
8993         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8994             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8995                 find_equal_scalars(this_branch, dst_reg);
8996                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8997         }
8998
8999         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9000          * NOTE: these optimizations below are related with pointer comparison
9001          *       which will never be JMP32.
9002          */
9003         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9004             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9005             reg_type_may_be_null(dst_reg->type)) {
9006                 /* Mark all identical registers in each branch as either
9007                  * safe or unknown depending R == 0 or R != 0 conditional.
9008                  */
9009                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9010                                       opcode == BPF_JNE);
9011                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9012                                       opcode == BPF_JEQ);
9013         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9014                                            this_branch, other_branch) &&
9015                    is_pointer_value(env, insn->dst_reg)) {
9016                 verbose(env, "R%d pointer comparison prohibited\n",
9017                         insn->dst_reg);
9018                 return -EACCES;
9019         }
9020         if (env->log.level & BPF_LOG_LEVEL)
9021                 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9022         return 0;
9023 }
9024
9025 /* verify BPF_LD_IMM64 instruction */
9026 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9027 {
9028         struct bpf_insn_aux_data *aux = cur_aux(env);
9029         struct bpf_reg_state *regs = cur_regs(env);
9030         struct bpf_reg_state *dst_reg;
9031         struct bpf_map *map;
9032         int err;
9033
9034         if (BPF_SIZE(insn->code) != BPF_DW) {
9035                 verbose(env, "invalid BPF_LD_IMM insn\n");
9036                 return -EINVAL;
9037         }
9038         if (insn->off != 0) {
9039                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9040                 return -EINVAL;
9041         }
9042
9043         err = check_reg_arg(env, insn->dst_reg, DST_OP);
9044         if (err)
9045                 return err;
9046
9047         dst_reg = &regs[insn->dst_reg];
9048         if (insn->src_reg == 0) {
9049                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9050
9051                 dst_reg->type = SCALAR_VALUE;
9052                 __mark_reg_known(&regs[insn->dst_reg], imm);
9053                 return 0;
9054         }
9055
9056         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9057                 mark_reg_known_zero(env, regs, insn->dst_reg);
9058
9059                 dst_reg->type = aux->btf_var.reg_type;
9060                 switch (dst_reg->type) {
9061                 case PTR_TO_MEM:
9062                         dst_reg->mem_size = aux->btf_var.mem_size;
9063                         break;
9064                 case PTR_TO_BTF_ID:
9065                 case PTR_TO_PERCPU_BTF_ID:
9066                         dst_reg->btf = aux->btf_var.btf;
9067                         dst_reg->btf_id = aux->btf_var.btf_id;
9068                         break;
9069                 default:
9070                         verbose(env, "bpf verifier is misconfigured\n");
9071                         return -EFAULT;
9072                 }
9073                 return 0;
9074         }
9075
9076         if (insn->src_reg == BPF_PSEUDO_FUNC) {
9077                 struct bpf_prog_aux *aux = env->prog->aux;
9078                 u32 subprogno = insn[1].imm;
9079
9080                 if (!aux->func_info) {
9081                         verbose(env, "missing btf func_info\n");
9082                         return -EINVAL;
9083                 }
9084                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9085                         verbose(env, "callback function not static\n");
9086                         return -EINVAL;
9087                 }
9088
9089                 dst_reg->type = PTR_TO_FUNC;
9090                 dst_reg->subprogno = subprogno;
9091                 return 0;
9092         }
9093
9094         map = env->used_maps[aux->map_index];
9095         mark_reg_known_zero(env, regs, insn->dst_reg);
9096         dst_reg->map_ptr = map;
9097
9098         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9099             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9100                 dst_reg->type = PTR_TO_MAP_VALUE;
9101                 dst_reg->off = aux->map_off;
9102                 if (map_value_has_spin_lock(map))
9103                         dst_reg->id = ++env->id_gen;
9104         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9105                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9106                 dst_reg->type = CONST_PTR_TO_MAP;
9107         } else {
9108                 verbose(env, "bpf verifier is misconfigured\n");
9109                 return -EINVAL;
9110         }
9111
9112         return 0;
9113 }
9114
9115 static bool may_access_skb(enum bpf_prog_type type)
9116 {
9117         switch (type) {
9118         case BPF_PROG_TYPE_SOCKET_FILTER:
9119         case BPF_PROG_TYPE_SCHED_CLS:
9120         case BPF_PROG_TYPE_SCHED_ACT:
9121                 return true;
9122         default:
9123                 return false;
9124         }
9125 }
9126
9127 /* verify safety of LD_ABS|LD_IND instructions:
9128  * - they can only appear in the programs where ctx == skb
9129  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9130  *   preserve R6-R9, and store return value into R0
9131  *
9132  * Implicit input:
9133  *   ctx == skb == R6 == CTX
9134  *
9135  * Explicit input:
9136  *   SRC == any register
9137  *   IMM == 32-bit immediate
9138  *
9139  * Output:
9140  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9141  */
9142 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9143 {
9144         struct bpf_reg_state *regs = cur_regs(env);
9145         static const int ctx_reg = BPF_REG_6;
9146         u8 mode = BPF_MODE(insn->code);
9147         int i, err;
9148
9149         if (!may_access_skb(resolve_prog_type(env->prog))) {
9150                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9151                 return -EINVAL;
9152         }
9153
9154         if (!env->ops->gen_ld_abs) {
9155                 verbose(env, "bpf verifier is misconfigured\n");
9156                 return -EINVAL;
9157         }
9158
9159         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9160             BPF_SIZE(insn->code) == BPF_DW ||
9161             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9162                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9163                 return -EINVAL;
9164         }
9165
9166         /* check whether implicit source operand (register R6) is readable */
9167         err = check_reg_arg(env, ctx_reg, SRC_OP);
9168         if (err)
9169                 return err;
9170
9171         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9172          * gen_ld_abs() may terminate the program at runtime, leading to
9173          * reference leak.
9174          */
9175         err = check_reference_leak(env);
9176         if (err) {
9177                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9178                 return err;
9179         }
9180
9181         if (env->cur_state->active_spin_lock) {
9182                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9183                 return -EINVAL;
9184         }
9185
9186         if (regs[ctx_reg].type != PTR_TO_CTX) {
9187                 verbose(env,
9188                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9189                 return -EINVAL;
9190         }
9191
9192         if (mode == BPF_IND) {
9193                 /* check explicit source operand */
9194                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9195                 if (err)
9196                         return err;
9197         }
9198
9199         err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9200         if (err < 0)
9201                 return err;
9202
9203         /* reset caller saved regs to unreadable */
9204         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9205                 mark_reg_not_init(env, regs, caller_saved[i]);
9206                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9207         }
9208
9209         /* mark destination R0 register as readable, since it contains
9210          * the value fetched from the packet.
9211          * Already marked as written above.
9212          */
9213         mark_reg_unknown(env, regs, BPF_REG_0);
9214         /* ld_abs load up to 32-bit skb data. */
9215         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9216         return 0;
9217 }
9218
9219 static int check_return_code(struct bpf_verifier_env *env)
9220 {
9221         struct tnum enforce_attach_type_range = tnum_unknown;
9222         const struct bpf_prog *prog = env->prog;
9223         struct bpf_reg_state *reg;
9224         struct tnum range = tnum_range(0, 1);
9225         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9226         int err;
9227         const bool is_subprog = env->cur_state->frame[0]->subprogno;
9228
9229         /* LSM and struct_ops func-ptr's return type could be "void" */
9230         if (!is_subprog &&
9231             (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9232              prog_type == BPF_PROG_TYPE_LSM) &&
9233             !prog->aux->attach_func_proto->type)
9234                 return 0;
9235
9236         /* eBPF calling convention is such that R0 is used
9237          * to return the value from eBPF program.
9238          * Make sure that it's readable at this time
9239          * of bpf_exit, which means that program wrote
9240          * something into it earlier
9241          */
9242         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9243         if (err)
9244                 return err;
9245
9246         if (is_pointer_value(env, BPF_REG_0)) {
9247                 verbose(env, "R0 leaks addr as return value\n");
9248                 return -EACCES;
9249         }
9250
9251         reg = cur_regs(env) + BPF_REG_0;
9252         if (is_subprog) {
9253                 if (reg->type != SCALAR_VALUE) {
9254                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9255                                 reg_type_str[reg->type]);
9256                         return -EINVAL;
9257                 }
9258                 return 0;
9259         }
9260
9261         switch (prog_type) {
9262         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9263                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9264                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9265                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9266                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9267                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9268                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9269                         range = tnum_range(1, 1);
9270                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9271                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9272                         range = tnum_range(0, 3);
9273                 break;
9274         case BPF_PROG_TYPE_CGROUP_SKB:
9275                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9276                         range = tnum_range(0, 3);
9277                         enforce_attach_type_range = tnum_range(2, 3);
9278                 }
9279                 break;
9280         case BPF_PROG_TYPE_CGROUP_SOCK:
9281         case BPF_PROG_TYPE_SOCK_OPS:
9282         case BPF_PROG_TYPE_CGROUP_DEVICE:
9283         case BPF_PROG_TYPE_CGROUP_SYSCTL:
9284         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9285                 break;
9286         case BPF_PROG_TYPE_RAW_TRACEPOINT:
9287                 if (!env->prog->aux->attach_btf_id)
9288                         return 0;
9289                 range = tnum_const(0);
9290                 break;
9291         case BPF_PROG_TYPE_TRACING:
9292                 switch (env->prog->expected_attach_type) {
9293                 case BPF_TRACE_FENTRY:
9294                 case BPF_TRACE_FEXIT:
9295                         range = tnum_const(0);
9296                         break;
9297                 case BPF_TRACE_RAW_TP:
9298                 case BPF_MODIFY_RETURN:
9299                         return 0;
9300                 case BPF_TRACE_ITER:
9301                         break;
9302                 default:
9303                         return -ENOTSUPP;
9304                 }
9305                 break;
9306         case BPF_PROG_TYPE_SK_LOOKUP:
9307                 range = tnum_range(SK_DROP, SK_PASS);
9308                 break;
9309         case BPF_PROG_TYPE_EXT:
9310                 /* freplace program can return anything as its return value
9311                  * depends on the to-be-replaced kernel func or bpf program.
9312                  */
9313         default:
9314                 return 0;
9315         }
9316
9317         if (reg->type != SCALAR_VALUE) {
9318                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9319                         reg_type_str[reg->type]);
9320                 return -EINVAL;
9321         }
9322
9323         if (!tnum_in(range, reg->var_off)) {
9324                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9325                 return -EINVAL;
9326         }
9327
9328         if (!tnum_is_unknown(enforce_attach_type_range) &&
9329             tnum_in(enforce_attach_type_range, reg->var_off))
9330                 env->prog->enforce_expected_attach_type = 1;
9331         return 0;
9332 }
9333
9334 /* non-recursive DFS pseudo code
9335  * 1  procedure DFS-iterative(G,v):
9336  * 2      label v as discovered
9337  * 3      let S be a stack
9338  * 4      S.push(v)
9339  * 5      while S is not empty
9340  * 6            t <- S.pop()
9341  * 7            if t is what we're looking for:
9342  * 8                return t
9343  * 9            for all edges e in G.adjacentEdges(t) do
9344  * 10               if edge e is already labelled
9345  * 11                   continue with the next edge
9346  * 12               w <- G.adjacentVertex(t,e)
9347  * 13               if vertex w is not discovered and not explored
9348  * 14                   label e as tree-edge
9349  * 15                   label w as discovered
9350  * 16                   S.push(w)
9351  * 17                   continue at 5
9352  * 18               else if vertex w is discovered
9353  * 19                   label e as back-edge
9354  * 20               else
9355  * 21                   // vertex w is explored
9356  * 22                   label e as forward- or cross-edge
9357  * 23           label t as explored
9358  * 24           S.pop()
9359  *
9360  * convention:
9361  * 0x10 - discovered
9362  * 0x11 - discovered and fall-through edge labelled
9363  * 0x12 - discovered and fall-through and branch edges labelled
9364  * 0x20 - explored
9365  */
9366
9367 enum {
9368         DISCOVERED = 0x10,
9369         EXPLORED = 0x20,
9370         FALLTHROUGH = 1,
9371         BRANCH = 2,
9372 };
9373
9374 static u32 state_htab_size(struct bpf_verifier_env *env)
9375 {
9376         return env->prog->len;
9377 }
9378
9379 static struct bpf_verifier_state_list **explored_state(
9380                                         struct bpf_verifier_env *env,
9381                                         int idx)
9382 {
9383         struct bpf_verifier_state *cur = env->cur_state;
9384         struct bpf_func_state *state = cur->frame[cur->curframe];
9385
9386         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9387 }
9388
9389 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9390 {
9391         env->insn_aux_data[idx].prune_point = true;
9392 }
9393
9394 enum {
9395         DONE_EXPLORING = 0,
9396         KEEP_EXPLORING = 1,
9397 };
9398
9399 /* t, w, e - match pseudo-code above:
9400  * t - index of current instruction
9401  * w - next instruction
9402  * e - edge
9403  */
9404 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9405                      bool loop_ok)
9406 {
9407         int *insn_stack = env->cfg.insn_stack;
9408         int *insn_state = env->cfg.insn_state;
9409
9410         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9411                 return DONE_EXPLORING;
9412
9413         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9414                 return DONE_EXPLORING;
9415
9416         if (w < 0 || w >= env->prog->len) {
9417                 verbose_linfo(env, t, "%d: ", t);
9418                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
9419                 return -EINVAL;
9420         }
9421
9422         if (e == BRANCH)
9423                 /* mark branch target for state pruning */
9424                 init_explored_state(env, w);
9425
9426         if (insn_state[w] == 0) {
9427                 /* tree-edge */
9428                 insn_state[t] = DISCOVERED | e;
9429                 insn_state[w] = DISCOVERED;
9430                 if (env->cfg.cur_stack >= env->prog->len)
9431                         return -E2BIG;
9432                 insn_stack[env->cfg.cur_stack++] = w;
9433                 return KEEP_EXPLORING;
9434         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9435                 if (loop_ok && env->bpf_capable)
9436                         return DONE_EXPLORING;
9437                 verbose_linfo(env, t, "%d: ", t);
9438                 verbose_linfo(env, w, "%d: ", w);
9439                 verbose(env, "back-edge from insn %d to %d\n", t, w);
9440                 return -EINVAL;
9441         } else if (insn_state[w] == EXPLORED) {
9442                 /* forward- or cross-edge */
9443                 insn_state[t] = DISCOVERED | e;
9444         } else {
9445                 verbose(env, "insn state internal bug\n");
9446                 return -EFAULT;
9447         }
9448         return DONE_EXPLORING;
9449 }
9450
9451 static int visit_func_call_insn(int t, int insn_cnt,
9452                                 struct bpf_insn *insns,
9453                                 struct bpf_verifier_env *env,
9454                                 bool visit_callee)
9455 {
9456         int ret;
9457
9458         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9459         if (ret)
9460                 return ret;
9461
9462         if (t + 1 < insn_cnt)
9463                 init_explored_state(env, t + 1);
9464         if (visit_callee) {
9465                 init_explored_state(env, t);
9466                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
9467                                 env, false);
9468         }
9469         return ret;
9470 }
9471
9472 /* Visits the instruction at index t and returns one of the following:
9473  *  < 0 - an error occurred
9474  *  DONE_EXPLORING - the instruction was fully explored
9475  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9476  */
9477 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9478 {
9479         struct bpf_insn *insns = env->prog->insnsi;
9480         int ret;
9481
9482         if (bpf_pseudo_func(insns + t))
9483                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9484
9485         /* All non-branch instructions have a single fall-through edge. */
9486         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9487             BPF_CLASS(insns[t].code) != BPF_JMP32)
9488                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9489
9490         switch (BPF_OP(insns[t].code)) {
9491         case BPF_EXIT:
9492                 return DONE_EXPLORING;
9493
9494         case BPF_CALL:
9495                 return visit_func_call_insn(t, insn_cnt, insns, env,
9496                                             insns[t].src_reg == BPF_PSEUDO_CALL);
9497
9498         case BPF_JA:
9499                 if (BPF_SRC(insns[t].code) != BPF_K)
9500                         return -EINVAL;
9501
9502                 /* unconditional jump with single edge */
9503                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9504                                 true);
9505                 if (ret)
9506                         return ret;
9507
9508                 /* unconditional jmp is not a good pruning point,
9509                  * but it's marked, since backtracking needs
9510                  * to record jmp history in is_state_visited().
9511                  */
9512                 init_explored_state(env, t + insns[t].off + 1);
9513                 /* tell verifier to check for equivalent states
9514                  * after every call and jump
9515                  */
9516                 if (t + 1 < insn_cnt)
9517                         init_explored_state(env, t + 1);
9518
9519                 return ret;
9520
9521         default:
9522                 /* conditional jump with two edges */
9523                 init_explored_state(env, t);
9524                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9525                 if (ret)
9526                         return ret;
9527
9528                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9529         }
9530 }
9531
9532 /* non-recursive depth-first-search to detect loops in BPF program
9533  * loop == back-edge in directed graph
9534  */
9535 static int check_cfg(struct bpf_verifier_env *env)
9536 {
9537         int insn_cnt = env->prog->len;
9538         int *insn_stack, *insn_state;
9539         int ret = 0;
9540         int i;
9541
9542         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9543         if (!insn_state)
9544                 return -ENOMEM;
9545
9546         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9547         if (!insn_stack) {
9548                 kvfree(insn_state);
9549                 return -ENOMEM;
9550         }
9551
9552         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9553         insn_stack[0] = 0; /* 0 is the first instruction */
9554         env->cfg.cur_stack = 1;
9555
9556         while (env->cfg.cur_stack > 0) {
9557                 int t = insn_stack[env->cfg.cur_stack - 1];
9558
9559                 ret = visit_insn(t, insn_cnt, env);
9560                 switch (ret) {
9561                 case DONE_EXPLORING:
9562                         insn_state[t] = EXPLORED;
9563                         env->cfg.cur_stack--;
9564                         break;
9565                 case KEEP_EXPLORING:
9566                         break;
9567                 default:
9568                         if (ret > 0) {
9569                                 verbose(env, "visit_insn internal bug\n");
9570                                 ret = -EFAULT;
9571                         }
9572                         goto err_free;
9573                 }
9574         }
9575
9576         if (env->cfg.cur_stack < 0) {
9577                 verbose(env, "pop stack internal bug\n");
9578                 ret = -EFAULT;
9579                 goto err_free;
9580         }
9581
9582         for (i = 0; i < insn_cnt; i++) {
9583                 if (insn_state[i] != EXPLORED) {
9584                         verbose(env, "unreachable insn %d\n", i);
9585                         ret = -EINVAL;
9586                         goto err_free;
9587                 }
9588         }
9589         ret = 0; /* cfg looks good */
9590
9591 err_free:
9592         kvfree(insn_state);
9593         kvfree(insn_stack);
9594         env->cfg.insn_state = env->cfg.insn_stack = NULL;
9595         return ret;
9596 }
9597
9598 static int check_abnormal_return(struct bpf_verifier_env *env)
9599 {
9600         int i;
9601
9602         for (i = 1; i < env->subprog_cnt; i++) {
9603                 if (env->subprog_info[i].has_ld_abs) {
9604                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9605                         return -EINVAL;
9606                 }
9607                 if (env->subprog_info[i].has_tail_call) {
9608                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9609                         return -EINVAL;
9610                 }
9611         }
9612         return 0;
9613 }
9614
9615 /* The minimum supported BTF func info size */
9616 #define MIN_BPF_FUNCINFO_SIZE   8
9617 #define MAX_FUNCINFO_REC_SIZE   252
9618
9619 static int check_btf_func(struct bpf_verifier_env *env,
9620                           const union bpf_attr *attr,
9621                           bpfptr_t uattr)
9622 {
9623         const struct btf_type *type, *func_proto, *ret_type;
9624         u32 i, nfuncs, urec_size, min_size;
9625         u32 krec_size = sizeof(struct bpf_func_info);
9626         struct bpf_func_info *krecord;
9627         struct bpf_func_info_aux *info_aux = NULL;
9628         struct bpf_prog *prog;
9629         const struct btf *btf;
9630         bpfptr_t urecord;
9631         u32 prev_offset = 0;
9632         bool scalar_return;
9633         int ret = -ENOMEM;
9634
9635         nfuncs = attr->func_info_cnt;
9636         if (!nfuncs) {
9637                 if (check_abnormal_return(env))
9638                         return -EINVAL;
9639                 return 0;
9640         }
9641
9642         if (nfuncs != env->subprog_cnt) {
9643                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9644                 return -EINVAL;
9645         }
9646
9647         urec_size = attr->func_info_rec_size;
9648         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9649             urec_size > MAX_FUNCINFO_REC_SIZE ||
9650             urec_size % sizeof(u32)) {
9651                 verbose(env, "invalid func info rec size %u\n", urec_size);
9652                 return -EINVAL;
9653         }
9654
9655         prog = env->prog;
9656         btf = prog->aux->btf;
9657
9658         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
9659         min_size = min_t(u32, krec_size, urec_size);
9660
9661         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9662         if (!krecord)
9663                 return -ENOMEM;
9664         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9665         if (!info_aux)
9666                 goto err_free;
9667
9668         for (i = 0; i < nfuncs; i++) {
9669                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9670                 if (ret) {
9671                         if (ret == -E2BIG) {
9672                                 verbose(env, "nonzero tailing record in func info");
9673                                 /* set the size kernel expects so loader can zero
9674                                  * out the rest of the record.
9675                                  */
9676                                 if (copy_to_bpfptr_offset(uattr,
9677                                                           offsetof(union bpf_attr, func_info_rec_size),
9678                                                           &min_size, sizeof(min_size)))
9679                                         ret = -EFAULT;
9680                         }
9681                         goto err_free;
9682                 }
9683
9684                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
9685                         ret = -EFAULT;
9686                         goto err_free;
9687                 }
9688
9689                 /* check insn_off */
9690                 ret = -EINVAL;
9691                 if (i == 0) {
9692                         if (krecord[i].insn_off) {
9693                                 verbose(env,
9694                                         "nonzero insn_off %u for the first func info record",
9695                                         krecord[i].insn_off);
9696                                 goto err_free;
9697                         }
9698                 } else if (krecord[i].insn_off <= prev_offset) {
9699                         verbose(env,
9700                                 "same or smaller insn offset (%u) than previous func info record (%u)",
9701                                 krecord[i].insn_off, prev_offset);
9702                         goto err_free;
9703                 }
9704
9705                 if (env->subprog_info[i].start != krecord[i].insn_off) {
9706                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9707                         goto err_free;
9708                 }
9709
9710                 /* check type_id */
9711                 type = btf_type_by_id(btf, krecord[i].type_id);
9712                 if (!type || !btf_type_is_func(type)) {
9713                         verbose(env, "invalid type id %d in func info",
9714                                 krecord[i].type_id);
9715                         goto err_free;
9716                 }
9717                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9718
9719                 func_proto = btf_type_by_id(btf, type->type);
9720                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9721                         /* btf_func_check() already verified it during BTF load */
9722                         goto err_free;
9723                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9724                 scalar_return =
9725                         btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9726                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9727                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9728                         goto err_free;
9729                 }
9730                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9731                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9732                         goto err_free;
9733                 }
9734
9735                 prev_offset = krecord[i].insn_off;
9736                 bpfptr_add(&urecord, urec_size);
9737         }
9738
9739         prog->aux->func_info = krecord;
9740         prog->aux->func_info_cnt = nfuncs;
9741         prog->aux->func_info_aux = info_aux;
9742         return 0;
9743
9744 err_free:
9745         kvfree(krecord);
9746         kfree(info_aux);
9747         return ret;
9748 }
9749
9750 static void adjust_btf_func(struct bpf_verifier_env *env)
9751 {
9752         struct bpf_prog_aux *aux = env->prog->aux;
9753         int i;
9754
9755         if (!aux->func_info)
9756                 return;
9757
9758         for (i = 0; i < env->subprog_cnt; i++)
9759                 aux->func_info[i].insn_off = env->subprog_info[i].start;
9760 }
9761
9762 #define MIN_BPF_LINEINFO_SIZE   (offsetof(struct bpf_line_info, line_col) + \
9763                 sizeof(((struct bpf_line_info *)(0))->line_col))
9764 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
9765
9766 static int check_btf_line(struct bpf_verifier_env *env,
9767                           const union bpf_attr *attr,
9768                           bpfptr_t uattr)
9769 {
9770         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9771         struct bpf_subprog_info *sub;
9772         struct bpf_line_info *linfo;
9773         struct bpf_prog *prog;
9774         const struct btf *btf;
9775         bpfptr_t ulinfo;
9776         int err;
9777
9778         nr_linfo = attr->line_info_cnt;
9779         if (!nr_linfo)
9780                 return 0;
9781
9782         rec_size = attr->line_info_rec_size;
9783         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9784             rec_size > MAX_LINEINFO_REC_SIZE ||
9785             rec_size & (sizeof(u32) - 1))
9786                 return -EINVAL;
9787
9788         /* Need to zero it in case the userspace may
9789          * pass in a smaller bpf_line_info object.
9790          */
9791         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9792                          GFP_KERNEL | __GFP_NOWARN);
9793         if (!linfo)
9794                 return -ENOMEM;
9795
9796         prog = env->prog;
9797         btf = prog->aux->btf;
9798
9799         s = 0;
9800         sub = env->subprog_info;
9801         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
9802         expected_size = sizeof(struct bpf_line_info);
9803         ncopy = min_t(u32, expected_size, rec_size);
9804         for (i = 0; i < nr_linfo; i++) {
9805                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9806                 if (err) {
9807                         if (err == -E2BIG) {
9808                                 verbose(env, "nonzero tailing record in line_info");
9809                                 if (copy_to_bpfptr_offset(uattr,
9810                                                           offsetof(union bpf_attr, line_info_rec_size),
9811                                                           &expected_size, sizeof(expected_size)))
9812                                         err = -EFAULT;
9813                         }
9814                         goto err_free;
9815                 }
9816
9817                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
9818                         err = -EFAULT;
9819                         goto err_free;
9820                 }
9821
9822                 /*
9823                  * Check insn_off to ensure
9824                  * 1) strictly increasing AND
9825                  * 2) bounded by prog->len
9826                  *
9827                  * The linfo[0].insn_off == 0 check logically falls into
9828                  * the later "missing bpf_line_info for func..." case
9829                  * because the first linfo[0].insn_off must be the
9830                  * first sub also and the first sub must have
9831                  * subprog_info[0].start == 0.
9832                  */
9833                 if ((i && linfo[i].insn_off <= prev_offset) ||
9834                     linfo[i].insn_off >= prog->len) {
9835                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9836                                 i, linfo[i].insn_off, prev_offset,
9837                                 prog->len);
9838                         err = -EINVAL;
9839                         goto err_free;
9840                 }
9841
9842                 if (!prog->insnsi[linfo[i].insn_off].code) {
9843                         verbose(env,
9844                                 "Invalid insn code at line_info[%u].insn_off\n",
9845                                 i);
9846                         err = -EINVAL;
9847                         goto err_free;
9848                 }
9849
9850                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9851                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9852                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9853                         err = -EINVAL;
9854                         goto err_free;
9855                 }
9856
9857                 if (s != env->subprog_cnt) {
9858                         if (linfo[i].insn_off == sub[s].start) {
9859                                 sub[s].linfo_idx = i;
9860                                 s++;
9861                         } else if (sub[s].start < linfo[i].insn_off) {
9862                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
9863                                 err = -EINVAL;
9864                                 goto err_free;
9865                         }
9866                 }
9867
9868                 prev_offset = linfo[i].insn_off;
9869                 bpfptr_add(&ulinfo, rec_size);
9870         }
9871
9872         if (s != env->subprog_cnt) {
9873                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9874                         env->subprog_cnt - s, s);
9875                 err = -EINVAL;
9876                 goto err_free;
9877         }
9878
9879         prog->aux->linfo = linfo;
9880         prog->aux->nr_linfo = nr_linfo;
9881
9882         return 0;
9883
9884 err_free:
9885         kvfree(linfo);
9886         return err;
9887 }
9888
9889 static int check_btf_info(struct bpf_verifier_env *env,
9890                           const union bpf_attr *attr,
9891                           bpfptr_t uattr)
9892 {
9893         struct btf *btf;
9894         int err;
9895
9896         if (!attr->func_info_cnt && !attr->line_info_cnt) {
9897                 if (check_abnormal_return(env))
9898                         return -EINVAL;
9899                 return 0;
9900         }
9901
9902         btf = btf_get_by_fd(attr->prog_btf_fd);
9903         if (IS_ERR(btf))
9904                 return PTR_ERR(btf);
9905         if (btf_is_kernel(btf)) {
9906                 btf_put(btf);
9907                 return -EACCES;
9908         }
9909         env->prog->aux->btf = btf;
9910
9911         err = check_btf_func(env, attr, uattr);
9912         if (err)
9913                 return err;
9914
9915         err = check_btf_line(env, attr, uattr);
9916         if (err)
9917                 return err;
9918
9919         return 0;
9920 }
9921
9922 /* check %cur's range satisfies %old's */
9923 static bool range_within(struct bpf_reg_state *old,
9924                          struct bpf_reg_state *cur)
9925 {
9926         return old->umin_value <= cur->umin_value &&
9927                old->umax_value >= cur->umax_value &&
9928                old->smin_value <= cur->smin_value &&
9929                old->smax_value >= cur->smax_value &&
9930                old->u32_min_value <= cur->u32_min_value &&
9931                old->u32_max_value >= cur->u32_max_value &&
9932                old->s32_min_value <= cur->s32_min_value &&
9933                old->s32_max_value >= cur->s32_max_value;
9934 }
9935
9936 /* If in the old state two registers had the same id, then they need to have
9937  * the same id in the new state as well.  But that id could be different from
9938  * the old state, so we need to track the mapping from old to new ids.
9939  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9940  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9941  * regs with a different old id could still have new id 9, we don't care about
9942  * that.
9943  * So we look through our idmap to see if this old id has been seen before.  If
9944  * so, we require the new id to match; otherwise, we add the id pair to the map.
9945  */
9946 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
9947 {
9948         unsigned int i;
9949
9950         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
9951                 if (!idmap[i].old) {
9952                         /* Reached an empty slot; haven't seen this id before */
9953                         idmap[i].old = old_id;
9954                         idmap[i].cur = cur_id;
9955                         return true;
9956                 }
9957                 if (idmap[i].old == old_id)
9958                         return idmap[i].cur == cur_id;
9959         }
9960         /* We ran out of idmap slots, which should be impossible */
9961         WARN_ON_ONCE(1);
9962         return false;
9963 }
9964
9965 static void clean_func_state(struct bpf_verifier_env *env,
9966                              struct bpf_func_state *st)
9967 {
9968         enum bpf_reg_liveness live;
9969         int i, j;
9970
9971         for (i = 0; i < BPF_REG_FP; i++) {
9972                 live = st->regs[i].live;
9973                 /* liveness must not touch this register anymore */
9974                 st->regs[i].live |= REG_LIVE_DONE;
9975                 if (!(live & REG_LIVE_READ))
9976                         /* since the register is unused, clear its state
9977                          * to make further comparison simpler
9978                          */
9979                         __mark_reg_not_init(env, &st->regs[i]);
9980         }
9981
9982         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9983                 live = st->stack[i].spilled_ptr.live;
9984                 /* liveness must not touch this stack slot anymore */
9985                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9986                 if (!(live & REG_LIVE_READ)) {
9987                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9988                         for (j = 0; j < BPF_REG_SIZE; j++)
9989                                 st->stack[i].slot_type[j] = STACK_INVALID;
9990                 }
9991         }
9992 }
9993
9994 static void clean_verifier_state(struct bpf_verifier_env *env,
9995                                  struct bpf_verifier_state *st)
9996 {
9997         int i;
9998
9999         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10000                 /* all regs in this state in all frames were already marked */
10001                 return;
10002
10003         for (i = 0; i <= st->curframe; i++)
10004                 clean_func_state(env, st->frame[i]);
10005 }
10006
10007 /* the parentage chains form a tree.
10008  * the verifier states are added to state lists at given insn and
10009  * pushed into state stack for future exploration.
10010  * when the verifier reaches bpf_exit insn some of the verifer states
10011  * stored in the state lists have their final liveness state already,
10012  * but a lot of states will get revised from liveness point of view when
10013  * the verifier explores other branches.
10014  * Example:
10015  * 1: r0 = 1
10016  * 2: if r1 == 100 goto pc+1
10017  * 3: r0 = 2
10018  * 4: exit
10019  * when the verifier reaches exit insn the register r0 in the state list of
10020  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10021  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10022  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10023  *
10024  * Since the verifier pushes the branch states as it sees them while exploring
10025  * the program the condition of walking the branch instruction for the second
10026  * time means that all states below this branch were already explored and
10027  * their final liveness marks are already propagated.
10028  * Hence when the verifier completes the search of state list in is_state_visited()
10029  * we can call this clean_live_states() function to mark all liveness states
10030  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10031  * will not be used.
10032  * This function also clears the registers and stack for states that !READ
10033  * to simplify state merging.
10034  *
10035  * Important note here that walking the same branch instruction in the callee
10036  * doesn't meant that the states are DONE. The verifier has to compare
10037  * the callsites
10038  */
10039 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10040                               struct bpf_verifier_state *cur)
10041 {
10042         struct bpf_verifier_state_list *sl;
10043         int i;
10044
10045         sl = *explored_state(env, insn);
10046         while (sl) {
10047                 if (sl->state.branches)
10048                         goto next;
10049                 if (sl->state.insn_idx != insn ||
10050                     sl->state.curframe != cur->curframe)
10051                         goto next;
10052                 for (i = 0; i <= cur->curframe; i++)
10053                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10054                                 goto next;
10055                 clean_verifier_state(env, &sl->state);
10056 next:
10057                 sl = sl->next;
10058         }
10059 }
10060
10061 /* Returns true if (rold safe implies rcur safe) */
10062 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
10063                     struct bpf_id_pair *idmap)
10064 {
10065         bool equal;
10066
10067         if (!(rold->live & REG_LIVE_READ))
10068                 /* explored state didn't use this */
10069                 return true;
10070
10071         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10072
10073         if (rold->type == PTR_TO_STACK)
10074                 /* two stack pointers are equal only if they're pointing to
10075                  * the same stack frame, since fp-8 in foo != fp-8 in bar
10076                  */
10077                 return equal && rold->frameno == rcur->frameno;
10078
10079         if (equal)
10080                 return true;
10081
10082         if (rold->type == NOT_INIT)
10083                 /* explored state can't have used this */
10084                 return true;
10085         if (rcur->type == NOT_INIT)
10086                 return false;
10087         switch (rold->type) {
10088         case SCALAR_VALUE:
10089                 if (rcur->type == SCALAR_VALUE) {
10090                         if (!rold->precise && !rcur->precise)
10091                                 return true;
10092                         /* new val must satisfy old val knowledge */
10093                         return range_within(rold, rcur) &&
10094                                tnum_in(rold->var_off, rcur->var_off);
10095                 } else {
10096                         /* We're trying to use a pointer in place of a scalar.
10097                          * Even if the scalar was unbounded, this could lead to
10098                          * pointer leaks because scalars are allowed to leak
10099                          * while pointers are not. We could make this safe in
10100                          * special cases if root is calling us, but it's
10101                          * probably not worth the hassle.
10102                          */
10103                         return false;
10104                 }
10105         case PTR_TO_MAP_KEY:
10106         case PTR_TO_MAP_VALUE:
10107                 /* If the new min/max/var_off satisfy the old ones and
10108                  * everything else matches, we are OK.
10109                  * 'id' is not compared, since it's only used for maps with
10110                  * bpf_spin_lock inside map element and in such cases if
10111                  * the rest of the prog is valid for one map element then
10112                  * it's valid for all map elements regardless of the key
10113                  * used in bpf_map_lookup()
10114                  */
10115                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10116                        range_within(rold, rcur) &&
10117                        tnum_in(rold->var_off, rcur->var_off);
10118         case PTR_TO_MAP_VALUE_OR_NULL:
10119                 /* a PTR_TO_MAP_VALUE could be safe to use as a
10120                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10121                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10122                  * checked, doing so could have affected others with the same
10123                  * id, and we can't check for that because we lost the id when
10124                  * we converted to a PTR_TO_MAP_VALUE.
10125                  */
10126                 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
10127                         return false;
10128                 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10129                         return false;
10130                 /* Check our ids match any regs they're supposed to */
10131                 return check_ids(rold->id, rcur->id, idmap);
10132         case PTR_TO_PACKET_META:
10133         case PTR_TO_PACKET:
10134                 if (rcur->type != rold->type)
10135                         return false;
10136                 /* We must have at least as much range as the old ptr
10137                  * did, so that any accesses which were safe before are
10138                  * still safe.  This is true even if old range < old off,
10139                  * since someone could have accessed through (ptr - k), or
10140                  * even done ptr -= k in a register, to get a safe access.
10141                  */
10142                 if (rold->range > rcur->range)
10143                         return false;
10144                 /* If the offsets don't match, we can't trust our alignment;
10145                  * nor can we be sure that we won't fall out of range.
10146                  */
10147                 if (rold->off != rcur->off)
10148                         return false;
10149                 /* id relations must be preserved */
10150                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10151                         return false;
10152                 /* new val must satisfy old val knowledge */
10153                 return range_within(rold, rcur) &&
10154                        tnum_in(rold->var_off, rcur->var_off);
10155         case PTR_TO_CTX:
10156         case CONST_PTR_TO_MAP:
10157         case PTR_TO_PACKET_END:
10158         case PTR_TO_FLOW_KEYS:
10159         case PTR_TO_SOCKET:
10160         case PTR_TO_SOCKET_OR_NULL:
10161         case PTR_TO_SOCK_COMMON:
10162         case PTR_TO_SOCK_COMMON_OR_NULL:
10163         case PTR_TO_TCP_SOCK:
10164         case PTR_TO_TCP_SOCK_OR_NULL:
10165         case PTR_TO_XDP_SOCK:
10166                 /* Only valid matches are exact, which memcmp() above
10167                  * would have accepted
10168                  */
10169         default:
10170                 /* Don't know what's going on, just say it's not safe */
10171                 return false;
10172         }
10173
10174         /* Shouldn't get here; if we do, say it's not safe */
10175         WARN_ON_ONCE(1);
10176         return false;
10177 }
10178
10179 static bool stacksafe(struct bpf_func_state *old,
10180                       struct bpf_func_state *cur,
10181                       struct bpf_id_pair *idmap)
10182 {
10183         int i, spi;
10184
10185         /* walk slots of the explored stack and ignore any additional
10186          * slots in the current stack, since explored(safe) state
10187          * didn't use them
10188          */
10189         for (i = 0; i < old->allocated_stack; i++) {
10190                 spi = i / BPF_REG_SIZE;
10191
10192                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10193                         i += BPF_REG_SIZE - 1;
10194                         /* explored state didn't use this */
10195                         continue;
10196                 }
10197
10198                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10199                         continue;
10200
10201                 /* explored stack has more populated slots than current stack
10202                  * and these slots were used
10203                  */
10204                 if (i >= cur->allocated_stack)
10205                         return false;
10206
10207                 /* if old state was safe with misc data in the stack
10208                  * it will be safe with zero-initialized stack.
10209                  * The opposite is not true
10210                  */
10211                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10212                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10213                         continue;
10214                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10215                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10216                         /* Ex: old explored (safe) state has STACK_SPILL in
10217                          * this stack slot, but current has STACK_MISC ->
10218                          * this verifier states are not equivalent,
10219                          * return false to continue verification of this path
10220                          */
10221                         return false;
10222                 if (i % BPF_REG_SIZE)
10223                         continue;
10224                 if (old->stack[spi].slot_type[0] != STACK_SPILL)
10225                         continue;
10226                 if (!regsafe(&old->stack[spi].spilled_ptr,
10227                              &cur->stack[spi].spilled_ptr,
10228                              idmap))
10229                         /* when explored and current stack slot are both storing
10230                          * spilled registers, check that stored pointers types
10231                          * are the same as well.
10232                          * Ex: explored safe path could have stored
10233                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10234                          * but current path has stored:
10235                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10236                          * such verifier states are not equivalent.
10237                          * return false to continue verification of this path
10238                          */
10239                         return false;
10240         }
10241         return true;
10242 }
10243
10244 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10245 {
10246         if (old->acquired_refs != cur->acquired_refs)
10247                 return false;
10248         return !memcmp(old->refs, cur->refs,
10249                        sizeof(*old->refs) * old->acquired_refs);
10250 }
10251
10252 /* compare two verifier states
10253  *
10254  * all states stored in state_list are known to be valid, since
10255  * verifier reached 'bpf_exit' instruction through them
10256  *
10257  * this function is called when verifier exploring different branches of
10258  * execution popped from the state stack. If it sees an old state that has
10259  * more strict register state and more strict stack state then this execution
10260  * branch doesn't need to be explored further, since verifier already
10261  * concluded that more strict state leads to valid finish.
10262  *
10263  * Therefore two states are equivalent if register state is more conservative
10264  * and explored stack state is more conservative than the current one.
10265  * Example:
10266  *       explored                   current
10267  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10268  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10269  *
10270  * In other words if current stack state (one being explored) has more
10271  * valid slots than old one that already passed validation, it means
10272  * the verifier can stop exploring and conclude that current state is valid too
10273  *
10274  * Similarly with registers. If explored state has register type as invalid
10275  * whereas register type in current state is meaningful, it means that
10276  * the current state will reach 'bpf_exit' instruction safely
10277  */
10278 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10279                               struct bpf_func_state *cur)
10280 {
10281         int i;
10282
10283         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10284         for (i = 0; i < MAX_BPF_REG; i++)
10285                 if (!regsafe(&old->regs[i], &cur->regs[i], env->idmap_scratch))
10286                         return false;
10287
10288         if (!stacksafe(old, cur, env->idmap_scratch))
10289                 return false;
10290
10291         if (!refsafe(old, cur))
10292                 return false;
10293
10294         return true;
10295 }
10296
10297 static bool states_equal(struct bpf_verifier_env *env,
10298                          struct bpf_verifier_state *old,
10299                          struct bpf_verifier_state *cur)
10300 {
10301         int i;
10302
10303         if (old->curframe != cur->curframe)
10304                 return false;
10305
10306         /* Verification state from speculative execution simulation
10307          * must never prune a non-speculative execution one.
10308          */
10309         if (old->speculative && !cur->speculative)
10310                 return false;
10311
10312         if (old->active_spin_lock != cur->active_spin_lock)
10313                 return false;
10314
10315         /* for states to be equal callsites have to be the same
10316          * and all frame states need to be equivalent
10317          */
10318         for (i = 0; i <= old->curframe; i++) {
10319                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10320                         return false;
10321                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10322                         return false;
10323         }
10324         return true;
10325 }
10326
10327 /* Return 0 if no propagation happened. Return negative error code if error
10328  * happened. Otherwise, return the propagated bit.
10329  */
10330 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10331                                   struct bpf_reg_state *reg,
10332                                   struct bpf_reg_state *parent_reg)
10333 {
10334         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10335         u8 flag = reg->live & REG_LIVE_READ;
10336         int err;
10337
10338         /* When comes here, read flags of PARENT_REG or REG could be any of
10339          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10340          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10341          */
10342         if (parent_flag == REG_LIVE_READ64 ||
10343             /* Or if there is no read flag from REG. */
10344             !flag ||
10345             /* Or if the read flag from REG is the same as PARENT_REG. */
10346             parent_flag == flag)
10347                 return 0;
10348
10349         err = mark_reg_read(env, reg, parent_reg, flag);
10350         if (err)
10351                 return err;
10352
10353         return flag;
10354 }
10355
10356 /* A write screens off any subsequent reads; but write marks come from the
10357  * straight-line code between a state and its parent.  When we arrive at an
10358  * equivalent state (jump target or such) we didn't arrive by the straight-line
10359  * code, so read marks in the state must propagate to the parent regardless
10360  * of the state's write marks. That's what 'parent == state->parent' comparison
10361  * in mark_reg_read() is for.
10362  */
10363 static int propagate_liveness(struct bpf_verifier_env *env,
10364                               const struct bpf_verifier_state *vstate,
10365                               struct bpf_verifier_state *vparent)
10366 {
10367         struct bpf_reg_state *state_reg, *parent_reg;
10368         struct bpf_func_state *state, *parent;
10369         int i, frame, err = 0;
10370
10371         if (vparent->curframe != vstate->curframe) {
10372                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10373                      vparent->curframe, vstate->curframe);
10374                 return -EFAULT;
10375         }
10376         /* Propagate read liveness of registers... */
10377         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10378         for (frame = 0; frame <= vstate->curframe; frame++) {
10379                 parent = vparent->frame[frame];
10380                 state = vstate->frame[frame];
10381                 parent_reg = parent->regs;
10382                 state_reg = state->regs;
10383                 /* We don't need to worry about FP liveness, it's read-only */
10384                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10385                         err = propagate_liveness_reg(env, &state_reg[i],
10386                                                      &parent_reg[i]);
10387                         if (err < 0)
10388                                 return err;
10389                         if (err == REG_LIVE_READ64)
10390                                 mark_insn_zext(env, &parent_reg[i]);
10391                 }
10392
10393                 /* Propagate stack slots. */
10394                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10395                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10396                         parent_reg = &parent->stack[i].spilled_ptr;
10397                         state_reg = &state->stack[i].spilled_ptr;
10398                         err = propagate_liveness_reg(env, state_reg,
10399                                                      parent_reg);
10400                         if (err < 0)
10401                                 return err;
10402                 }
10403         }
10404         return 0;
10405 }
10406
10407 /* find precise scalars in the previous equivalent state and
10408  * propagate them into the current state
10409  */
10410 static int propagate_precision(struct bpf_verifier_env *env,
10411                                const struct bpf_verifier_state *old)
10412 {
10413         struct bpf_reg_state *state_reg;
10414         struct bpf_func_state *state;
10415         int i, err = 0;
10416
10417         state = old->frame[old->curframe];
10418         state_reg = state->regs;
10419         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10420                 if (state_reg->type != SCALAR_VALUE ||
10421                     !state_reg->precise)
10422                         continue;
10423                 if (env->log.level & BPF_LOG_LEVEL2)
10424                         verbose(env, "propagating r%d\n", i);
10425                 err = mark_chain_precision(env, i);
10426                 if (err < 0)
10427                         return err;
10428         }
10429
10430         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10431                 if (state->stack[i].slot_type[0] != STACK_SPILL)
10432                         continue;
10433                 state_reg = &state->stack[i].spilled_ptr;
10434                 if (state_reg->type != SCALAR_VALUE ||
10435                     !state_reg->precise)
10436                         continue;
10437                 if (env->log.level & BPF_LOG_LEVEL2)
10438                         verbose(env, "propagating fp%d\n",
10439                                 (-i - 1) * BPF_REG_SIZE);
10440                 err = mark_chain_precision_stack(env, i);
10441                 if (err < 0)
10442                         return err;
10443         }
10444         return 0;
10445 }
10446
10447 static bool states_maybe_looping(struct bpf_verifier_state *old,
10448                                  struct bpf_verifier_state *cur)
10449 {
10450         struct bpf_func_state *fold, *fcur;
10451         int i, fr = cur->curframe;
10452
10453         if (old->curframe != fr)
10454                 return false;
10455
10456         fold = old->frame[fr];
10457         fcur = cur->frame[fr];
10458         for (i = 0; i < MAX_BPF_REG; i++)
10459                 if (memcmp(&fold->regs[i], &fcur->regs[i],
10460                            offsetof(struct bpf_reg_state, parent)))
10461                         return false;
10462         return true;
10463 }
10464
10465
10466 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10467 {
10468         struct bpf_verifier_state_list *new_sl;
10469         struct bpf_verifier_state_list *sl, **pprev;
10470         struct bpf_verifier_state *cur = env->cur_state, *new;
10471         int i, j, err, states_cnt = 0;
10472         bool add_new_state = env->test_state_freq ? true : false;
10473
10474         cur->last_insn_idx = env->prev_insn_idx;
10475         if (!env->insn_aux_data[insn_idx].prune_point)
10476                 /* this 'insn_idx' instruction wasn't marked, so we will not
10477                  * be doing state search here
10478                  */
10479                 return 0;
10480
10481         /* bpf progs typically have pruning point every 4 instructions
10482          * http://vger.kernel.org/bpfconf2019.html#session-1
10483          * Do not add new state for future pruning if the verifier hasn't seen
10484          * at least 2 jumps and at least 8 instructions.
10485          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10486          * In tests that amounts to up to 50% reduction into total verifier
10487          * memory consumption and 20% verifier time speedup.
10488          */
10489         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10490             env->insn_processed - env->prev_insn_processed >= 8)
10491                 add_new_state = true;
10492
10493         pprev = explored_state(env, insn_idx);
10494         sl = *pprev;
10495
10496         clean_live_states(env, insn_idx, cur);
10497
10498         while (sl) {
10499                 states_cnt++;
10500                 if (sl->state.insn_idx != insn_idx)
10501                         goto next;
10502                 if (sl->state.branches) {
10503                         if (states_maybe_looping(&sl->state, cur) &&
10504                             states_equal(env, &sl->state, cur)) {
10505                                 verbose_linfo(env, insn_idx, "; ");
10506                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10507                                 return -EINVAL;
10508                         }
10509                         /* if the verifier is processing a loop, avoid adding new state
10510                          * too often, since different loop iterations have distinct
10511                          * states and may not help future pruning.
10512                          * This threshold shouldn't be too low to make sure that
10513                          * a loop with large bound will be rejected quickly.
10514                          * The most abusive loop will be:
10515                          * r1 += 1
10516                          * if r1 < 1000000 goto pc-2
10517                          * 1M insn_procssed limit / 100 == 10k peak states.
10518                          * This threshold shouldn't be too high either, since states
10519                          * at the end of the loop are likely to be useful in pruning.
10520                          */
10521                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10522                             env->insn_processed - env->prev_insn_processed < 100)
10523                                 add_new_state = false;
10524                         goto miss;
10525                 }
10526                 if (states_equal(env, &sl->state, cur)) {
10527                         sl->hit_cnt++;
10528                         /* reached equivalent register/stack state,
10529                          * prune the search.
10530                          * Registers read by the continuation are read by us.
10531                          * If we have any write marks in env->cur_state, they
10532                          * will prevent corresponding reads in the continuation
10533                          * from reaching our parent (an explored_state).  Our
10534                          * own state will get the read marks recorded, but
10535                          * they'll be immediately forgotten as we're pruning
10536                          * this state and will pop a new one.
10537                          */
10538                         err = propagate_liveness(env, &sl->state, cur);
10539
10540                         /* if previous state reached the exit with precision and
10541                          * current state is equivalent to it (except precsion marks)
10542                          * the precision needs to be propagated back in
10543                          * the current state.
10544                          */
10545                         err = err ? : push_jmp_history(env, cur);
10546                         err = err ? : propagate_precision(env, &sl->state);
10547                         if (err)
10548                                 return err;
10549                         return 1;
10550                 }
10551 miss:
10552                 /* when new state is not going to be added do not increase miss count.
10553                  * Otherwise several loop iterations will remove the state
10554                  * recorded earlier. The goal of these heuristics is to have
10555                  * states from some iterations of the loop (some in the beginning
10556                  * and some at the end) to help pruning.
10557                  */
10558                 if (add_new_state)
10559                         sl->miss_cnt++;
10560                 /* heuristic to determine whether this state is beneficial
10561                  * to keep checking from state equivalence point of view.
10562                  * Higher numbers increase max_states_per_insn and verification time,
10563                  * but do not meaningfully decrease insn_processed.
10564                  */
10565                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10566                         /* the state is unlikely to be useful. Remove it to
10567                          * speed up verification
10568                          */
10569                         *pprev = sl->next;
10570                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10571                                 u32 br = sl->state.branches;
10572
10573                                 WARN_ONCE(br,
10574                                           "BUG live_done but branches_to_explore %d\n",
10575                                           br);
10576                                 free_verifier_state(&sl->state, false);
10577                                 kfree(sl);
10578                                 env->peak_states--;
10579                         } else {
10580                                 /* cannot free this state, since parentage chain may
10581                                  * walk it later. Add it for free_list instead to
10582                                  * be freed at the end of verification
10583                                  */
10584                                 sl->next = env->free_list;
10585                                 env->free_list = sl;
10586                         }
10587                         sl = *pprev;
10588                         continue;
10589                 }
10590 next:
10591                 pprev = &sl->next;
10592                 sl = *pprev;
10593         }
10594
10595         if (env->max_states_per_insn < states_cnt)
10596                 env->max_states_per_insn = states_cnt;
10597
10598         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10599                 return push_jmp_history(env, cur);
10600
10601         if (!add_new_state)
10602                 return push_jmp_history(env, cur);
10603
10604         /* There were no equivalent states, remember the current one.
10605          * Technically the current state is not proven to be safe yet,
10606          * but it will either reach outer most bpf_exit (which means it's safe)
10607          * or it will be rejected. When there are no loops the verifier won't be
10608          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
10609          * again on the way to bpf_exit.
10610          * When looping the sl->state.branches will be > 0 and this state
10611          * will not be considered for equivalence until branches == 0.
10612          */
10613         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10614         if (!new_sl)
10615                 return -ENOMEM;
10616         env->total_states++;
10617         env->peak_states++;
10618         env->prev_jmps_processed = env->jmps_processed;
10619         env->prev_insn_processed = env->insn_processed;
10620
10621         /* add new state to the head of linked list */
10622         new = &new_sl->state;
10623         err = copy_verifier_state(new, cur);
10624         if (err) {
10625                 free_verifier_state(new, false);
10626                 kfree(new_sl);
10627                 return err;
10628         }
10629         new->insn_idx = insn_idx;
10630         WARN_ONCE(new->branches != 1,
10631                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10632
10633         cur->parent = new;
10634         cur->first_insn_idx = insn_idx;
10635         clear_jmp_history(cur);
10636         new_sl->next = *explored_state(env, insn_idx);
10637         *explored_state(env, insn_idx) = new_sl;
10638         /* connect new state to parentage chain. Current frame needs all
10639          * registers connected. Only r6 - r9 of the callers are alive (pushed
10640          * to the stack implicitly by JITs) so in callers' frames connect just
10641          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10642          * the state of the call instruction (with WRITTEN set), and r0 comes
10643          * from callee with its full parentage chain, anyway.
10644          */
10645         /* clear write marks in current state: the writes we did are not writes
10646          * our child did, so they don't screen off its reads from us.
10647          * (There are no read marks in current state, because reads always mark
10648          * their parent and current state never has children yet.  Only
10649          * explored_states can get read marks.)
10650          */
10651         for (j = 0; j <= cur->curframe; j++) {
10652                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10653                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10654                 for (i = 0; i < BPF_REG_FP; i++)
10655                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10656         }
10657
10658         /* all stack frames are accessible from callee, clear them all */
10659         for (j = 0; j <= cur->curframe; j++) {
10660                 struct bpf_func_state *frame = cur->frame[j];
10661                 struct bpf_func_state *newframe = new->frame[j];
10662
10663                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10664                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10665                         frame->stack[i].spilled_ptr.parent =
10666                                                 &newframe->stack[i].spilled_ptr;
10667                 }
10668         }
10669         return 0;
10670 }
10671
10672 /* Return true if it's OK to have the same insn return a different type. */
10673 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10674 {
10675         switch (type) {
10676         case PTR_TO_CTX:
10677         case PTR_TO_SOCKET:
10678         case PTR_TO_SOCKET_OR_NULL:
10679         case PTR_TO_SOCK_COMMON:
10680         case PTR_TO_SOCK_COMMON_OR_NULL:
10681         case PTR_TO_TCP_SOCK:
10682         case PTR_TO_TCP_SOCK_OR_NULL:
10683         case PTR_TO_XDP_SOCK:
10684         case PTR_TO_BTF_ID:
10685         case PTR_TO_BTF_ID_OR_NULL:
10686                 return false;
10687         default:
10688                 return true;
10689         }
10690 }
10691
10692 /* If an instruction was previously used with particular pointer types, then we
10693  * need to be careful to avoid cases such as the below, where it may be ok
10694  * for one branch accessing the pointer, but not ok for the other branch:
10695  *
10696  * R1 = sock_ptr
10697  * goto X;
10698  * ...
10699  * R1 = some_other_valid_ptr;
10700  * goto X;
10701  * ...
10702  * R2 = *(u32 *)(R1 + 0);
10703  */
10704 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10705 {
10706         return src != prev && (!reg_type_mismatch_ok(src) ||
10707                                !reg_type_mismatch_ok(prev));
10708 }
10709
10710 static int do_check(struct bpf_verifier_env *env)
10711 {
10712         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10713         struct bpf_verifier_state *state = env->cur_state;
10714         struct bpf_insn *insns = env->prog->insnsi;
10715         struct bpf_reg_state *regs;
10716         int insn_cnt = env->prog->len;
10717         bool do_print_state = false;
10718         int prev_insn_idx = -1;
10719
10720         for (;;) {
10721                 struct bpf_insn *insn;
10722                 u8 class;
10723                 int err;
10724
10725                 env->prev_insn_idx = prev_insn_idx;
10726                 if (env->insn_idx >= insn_cnt) {
10727                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
10728                                 env->insn_idx, insn_cnt);
10729                         return -EFAULT;
10730                 }
10731
10732                 insn = &insns[env->insn_idx];
10733                 class = BPF_CLASS(insn->code);
10734
10735                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10736                         verbose(env,
10737                                 "BPF program is too large. Processed %d insn\n",
10738                                 env->insn_processed);
10739                         return -E2BIG;
10740                 }
10741
10742                 err = is_state_visited(env, env->insn_idx);
10743                 if (err < 0)
10744                         return err;
10745                 if (err == 1) {
10746                         /* found equivalent state, can prune the search */
10747                         if (env->log.level & BPF_LOG_LEVEL) {
10748                                 if (do_print_state)
10749                                         verbose(env, "\nfrom %d to %d%s: safe\n",
10750                                                 env->prev_insn_idx, env->insn_idx,
10751                                                 env->cur_state->speculative ?
10752                                                 " (speculative execution)" : "");
10753                                 else
10754                                         verbose(env, "%d: safe\n", env->insn_idx);
10755                         }
10756                         goto process_bpf_exit;
10757                 }
10758
10759                 if (signal_pending(current))
10760                         return -EAGAIN;
10761
10762                 if (need_resched())
10763                         cond_resched();
10764
10765                 if (env->log.level & BPF_LOG_LEVEL2 ||
10766                     (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10767                         if (env->log.level & BPF_LOG_LEVEL2)
10768                                 verbose(env, "%d:", env->insn_idx);
10769                         else
10770                                 verbose(env, "\nfrom %d to %d%s:",
10771                                         env->prev_insn_idx, env->insn_idx,
10772                                         env->cur_state->speculative ?
10773                                         " (speculative execution)" : "");
10774                         print_verifier_state(env, state->frame[state->curframe]);
10775                         do_print_state = false;
10776                 }
10777
10778                 if (env->log.level & BPF_LOG_LEVEL) {
10779                         const struct bpf_insn_cbs cbs = {
10780                                 .cb_call        = disasm_kfunc_name,
10781                                 .cb_print       = verbose,
10782                                 .private_data   = env,
10783                         };
10784
10785                         verbose_linfo(env, env->insn_idx, "; ");
10786                         verbose(env, "%d: ", env->insn_idx);
10787                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10788                 }
10789
10790                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10791                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10792                                                            env->prev_insn_idx);
10793                         if (err)
10794                                 return err;
10795                 }
10796
10797                 regs = cur_regs(env);
10798                 sanitize_mark_insn_seen(env);
10799                 prev_insn_idx = env->insn_idx;
10800
10801                 if (class == BPF_ALU || class == BPF_ALU64) {
10802                         err = check_alu_op(env, insn);
10803                         if (err)
10804                                 return err;
10805
10806                 } else if (class == BPF_LDX) {
10807                         enum bpf_reg_type *prev_src_type, src_reg_type;
10808
10809                         /* check for reserved fields is already done */
10810
10811                         /* check src operand */
10812                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10813                         if (err)
10814                                 return err;
10815
10816                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10817                         if (err)
10818                                 return err;
10819
10820                         src_reg_type = regs[insn->src_reg].type;
10821
10822                         /* check that memory (src_reg + off) is readable,
10823                          * the state of dst_reg will be updated by this func
10824                          */
10825                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
10826                                                insn->off, BPF_SIZE(insn->code),
10827                                                BPF_READ, insn->dst_reg, false);
10828                         if (err)
10829                                 return err;
10830
10831                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10832
10833                         if (*prev_src_type == NOT_INIT) {
10834                                 /* saw a valid insn
10835                                  * dst_reg = *(u32 *)(src_reg + off)
10836                                  * save type to validate intersecting paths
10837                                  */
10838                                 *prev_src_type = src_reg_type;
10839
10840                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10841                                 /* ABuser program is trying to use the same insn
10842                                  * dst_reg = *(u32*) (src_reg + off)
10843                                  * with different pointer types:
10844                                  * src_reg == ctx in one branch and
10845                                  * src_reg == stack|map in some other branch.
10846                                  * Reject it.
10847                                  */
10848                                 verbose(env, "same insn cannot be used with different pointers\n");
10849                                 return -EINVAL;
10850                         }
10851
10852                 } else if (class == BPF_STX) {
10853                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
10854
10855                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10856                                 err = check_atomic(env, env->insn_idx, insn);
10857                                 if (err)
10858                                         return err;
10859                                 env->insn_idx++;
10860                                 continue;
10861                         }
10862
10863                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10864                                 verbose(env, "BPF_STX uses reserved fields\n");
10865                                 return -EINVAL;
10866                         }
10867
10868                         /* check src1 operand */
10869                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10870                         if (err)
10871                                 return err;
10872                         /* check src2 operand */
10873                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10874                         if (err)
10875                                 return err;
10876
10877                         dst_reg_type = regs[insn->dst_reg].type;
10878
10879                         /* check that memory (dst_reg + off) is writeable */
10880                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10881                                                insn->off, BPF_SIZE(insn->code),
10882                                                BPF_WRITE, insn->src_reg, false);
10883                         if (err)
10884                                 return err;
10885
10886                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10887
10888                         if (*prev_dst_type == NOT_INIT) {
10889                                 *prev_dst_type = dst_reg_type;
10890                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10891                                 verbose(env, "same insn cannot be used with different pointers\n");
10892                                 return -EINVAL;
10893                         }
10894
10895                 } else if (class == BPF_ST) {
10896                         if (BPF_MODE(insn->code) != BPF_MEM ||
10897                             insn->src_reg != BPF_REG_0) {
10898                                 verbose(env, "BPF_ST uses reserved fields\n");
10899                                 return -EINVAL;
10900                         }
10901                         /* check src operand */
10902                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10903                         if (err)
10904                                 return err;
10905
10906                         if (is_ctx_reg(env, insn->dst_reg)) {
10907                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10908                                         insn->dst_reg,
10909                                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
10910                                 return -EACCES;
10911                         }
10912
10913                         /* check that memory (dst_reg + off) is writeable */
10914                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10915                                                insn->off, BPF_SIZE(insn->code),
10916                                                BPF_WRITE, -1, false);
10917                         if (err)
10918                                 return err;
10919
10920                 } else if (class == BPF_JMP || class == BPF_JMP32) {
10921                         u8 opcode = BPF_OP(insn->code);
10922
10923                         env->jmps_processed++;
10924                         if (opcode == BPF_CALL) {
10925                                 if (BPF_SRC(insn->code) != BPF_K ||
10926                                     insn->off != 0 ||
10927                                     (insn->src_reg != BPF_REG_0 &&
10928                                      insn->src_reg != BPF_PSEUDO_CALL &&
10929                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
10930                                     insn->dst_reg != BPF_REG_0 ||
10931                                     class == BPF_JMP32) {
10932                                         verbose(env, "BPF_CALL uses reserved fields\n");
10933                                         return -EINVAL;
10934                                 }
10935
10936                                 if (env->cur_state->active_spin_lock &&
10937                                     (insn->src_reg == BPF_PSEUDO_CALL ||
10938                                      insn->imm != BPF_FUNC_spin_unlock)) {
10939                                         verbose(env, "function calls are not allowed while holding a lock\n");
10940                                         return -EINVAL;
10941                                 }
10942                                 if (insn->src_reg == BPF_PSEUDO_CALL)
10943                                         err = check_func_call(env, insn, &env->insn_idx);
10944                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
10945                                         err = check_kfunc_call(env, insn);
10946                                 else
10947                                         err = check_helper_call(env, insn, &env->insn_idx);
10948                                 if (err)
10949                                         return err;
10950                         } else if (opcode == BPF_JA) {
10951                                 if (BPF_SRC(insn->code) != BPF_K ||
10952                                     insn->imm != 0 ||
10953                                     insn->src_reg != BPF_REG_0 ||
10954                                     insn->dst_reg != BPF_REG_0 ||
10955                                     class == BPF_JMP32) {
10956                                         verbose(env, "BPF_JA uses reserved fields\n");
10957                                         return -EINVAL;
10958                                 }
10959
10960                                 env->insn_idx += insn->off + 1;
10961                                 continue;
10962
10963                         } else if (opcode == BPF_EXIT) {
10964                                 if (BPF_SRC(insn->code) != BPF_K ||
10965                                     insn->imm != 0 ||
10966                                     insn->src_reg != BPF_REG_0 ||
10967                                     insn->dst_reg != BPF_REG_0 ||
10968                                     class == BPF_JMP32) {
10969                                         verbose(env, "BPF_EXIT uses reserved fields\n");
10970                                         return -EINVAL;
10971                                 }
10972
10973                                 if (env->cur_state->active_spin_lock) {
10974                                         verbose(env, "bpf_spin_unlock is missing\n");
10975                                         return -EINVAL;
10976                                 }
10977
10978                                 if (state->curframe) {
10979                                         /* exit from nested function */
10980                                         err = prepare_func_exit(env, &env->insn_idx);
10981                                         if (err)
10982                                                 return err;
10983                                         do_print_state = true;
10984                                         continue;
10985                                 }
10986
10987                                 err = check_reference_leak(env);
10988                                 if (err)
10989                                         return err;
10990
10991                                 err = check_return_code(env);
10992                                 if (err)
10993                                         return err;
10994 process_bpf_exit:
10995                                 update_branch_counts(env, env->cur_state);
10996                                 err = pop_stack(env, &prev_insn_idx,
10997                                                 &env->insn_idx, pop_log);
10998                                 if (err < 0) {
10999                                         if (err != -ENOENT)
11000                                                 return err;
11001                                         break;
11002                                 } else {
11003                                         do_print_state = true;
11004                                         continue;
11005                                 }
11006                         } else {
11007                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
11008                                 if (err)
11009                                         return err;
11010                         }
11011                 } else if (class == BPF_LD) {
11012                         u8 mode = BPF_MODE(insn->code);
11013
11014                         if (mode == BPF_ABS || mode == BPF_IND) {
11015                                 err = check_ld_abs(env, insn);
11016                                 if (err)
11017                                         return err;
11018
11019                         } else if (mode == BPF_IMM) {
11020                                 err = check_ld_imm(env, insn);
11021                                 if (err)
11022                                         return err;
11023
11024                                 env->insn_idx++;
11025                                 sanitize_mark_insn_seen(env);
11026                         } else {
11027                                 verbose(env, "invalid BPF_LD mode\n");
11028                                 return -EINVAL;
11029                         }
11030                 } else {
11031                         verbose(env, "unknown insn class %d\n", class);
11032                         return -EINVAL;
11033                 }
11034
11035                 env->insn_idx++;
11036         }
11037
11038         return 0;
11039 }
11040
11041 static int find_btf_percpu_datasec(struct btf *btf)
11042 {
11043         const struct btf_type *t;
11044         const char *tname;
11045         int i, n;
11046
11047         /*
11048          * Both vmlinux and module each have their own ".data..percpu"
11049          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11050          * types to look at only module's own BTF types.
11051          */
11052         n = btf_nr_types(btf);
11053         if (btf_is_module(btf))
11054                 i = btf_nr_types(btf_vmlinux);
11055         else
11056                 i = 1;
11057
11058         for(; i < n; i++) {
11059                 t = btf_type_by_id(btf, i);
11060                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11061                         continue;
11062
11063                 tname = btf_name_by_offset(btf, t->name_off);
11064                 if (!strcmp(tname, ".data..percpu"))
11065                         return i;
11066         }
11067
11068         return -ENOENT;
11069 }
11070
11071 /* replace pseudo btf_id with kernel symbol address */
11072 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11073                                struct bpf_insn *insn,
11074                                struct bpf_insn_aux_data *aux)
11075 {
11076         const struct btf_var_secinfo *vsi;
11077         const struct btf_type *datasec;
11078         struct btf_mod_pair *btf_mod;
11079         const struct btf_type *t;
11080         const char *sym_name;
11081         bool percpu = false;
11082         u32 type, id = insn->imm;
11083         struct btf *btf;
11084         s32 datasec_id;
11085         u64 addr;
11086         int i, btf_fd, err;
11087
11088         btf_fd = insn[1].imm;
11089         if (btf_fd) {
11090                 btf = btf_get_by_fd(btf_fd);
11091                 if (IS_ERR(btf)) {
11092                         verbose(env, "invalid module BTF object FD specified.\n");
11093                         return -EINVAL;
11094                 }
11095         } else {
11096                 if (!btf_vmlinux) {
11097                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11098                         return -EINVAL;
11099                 }
11100                 btf = btf_vmlinux;
11101                 btf_get(btf);
11102         }
11103
11104         t = btf_type_by_id(btf, id);
11105         if (!t) {
11106                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11107                 err = -ENOENT;
11108                 goto err_put;
11109         }
11110
11111         if (!btf_type_is_var(t)) {
11112                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11113                 err = -EINVAL;
11114                 goto err_put;
11115         }
11116
11117         sym_name = btf_name_by_offset(btf, t->name_off);
11118         addr = kallsyms_lookup_name(sym_name);
11119         if (!addr) {
11120                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11121                         sym_name);
11122                 err = -ENOENT;
11123                 goto err_put;
11124         }
11125
11126         datasec_id = find_btf_percpu_datasec(btf);
11127         if (datasec_id > 0) {
11128                 datasec = btf_type_by_id(btf, datasec_id);
11129                 for_each_vsi(i, datasec, vsi) {
11130                         if (vsi->type == id) {
11131                                 percpu = true;
11132                                 break;
11133                         }
11134                 }
11135         }
11136
11137         insn[0].imm = (u32)addr;
11138         insn[1].imm = addr >> 32;
11139
11140         type = t->type;
11141         t = btf_type_skip_modifiers(btf, type, NULL);
11142         if (percpu) {
11143                 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11144                 aux->btf_var.btf = btf;
11145                 aux->btf_var.btf_id = type;
11146         } else if (!btf_type_is_struct(t)) {
11147                 const struct btf_type *ret;
11148                 const char *tname;
11149                 u32 tsize;
11150
11151                 /* resolve the type size of ksym. */
11152                 ret = btf_resolve_size(btf, t, &tsize);
11153                 if (IS_ERR(ret)) {
11154                         tname = btf_name_by_offset(btf, t->name_off);
11155                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11156                                 tname, PTR_ERR(ret));
11157                         err = -EINVAL;
11158                         goto err_put;
11159                 }
11160                 aux->btf_var.reg_type = PTR_TO_MEM;
11161                 aux->btf_var.mem_size = tsize;
11162         } else {
11163                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
11164                 aux->btf_var.btf = btf;
11165                 aux->btf_var.btf_id = type;
11166         }
11167
11168         /* check whether we recorded this BTF (and maybe module) already */
11169         for (i = 0; i < env->used_btf_cnt; i++) {
11170                 if (env->used_btfs[i].btf == btf) {
11171                         btf_put(btf);
11172                         return 0;
11173                 }
11174         }
11175
11176         if (env->used_btf_cnt >= MAX_USED_BTFS) {
11177                 err = -E2BIG;
11178                 goto err_put;
11179         }
11180
11181         btf_mod = &env->used_btfs[env->used_btf_cnt];
11182         btf_mod->btf = btf;
11183         btf_mod->module = NULL;
11184
11185         /* if we reference variables from kernel module, bump its refcount */
11186         if (btf_is_module(btf)) {
11187                 btf_mod->module = btf_try_get_module(btf);
11188                 if (!btf_mod->module) {
11189                         err = -ENXIO;
11190                         goto err_put;
11191                 }
11192         }
11193
11194         env->used_btf_cnt++;
11195
11196         return 0;
11197 err_put:
11198         btf_put(btf);
11199         return err;
11200 }
11201
11202 static int check_map_prealloc(struct bpf_map *map)
11203 {
11204         return (map->map_type != BPF_MAP_TYPE_HASH &&
11205                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11206                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11207                 !(map->map_flags & BPF_F_NO_PREALLOC);
11208 }
11209
11210 static bool is_tracing_prog_type(enum bpf_prog_type type)
11211 {
11212         switch (type) {
11213         case BPF_PROG_TYPE_KPROBE:
11214         case BPF_PROG_TYPE_TRACEPOINT:
11215         case BPF_PROG_TYPE_PERF_EVENT:
11216         case BPF_PROG_TYPE_RAW_TRACEPOINT:
11217                 return true;
11218         default:
11219                 return false;
11220         }
11221 }
11222
11223 static bool is_preallocated_map(struct bpf_map *map)
11224 {
11225         if (!check_map_prealloc(map))
11226                 return false;
11227         if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11228                 return false;
11229         return true;
11230 }
11231
11232 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11233                                         struct bpf_map *map,
11234                                         struct bpf_prog *prog)
11235
11236 {
11237         enum bpf_prog_type prog_type = resolve_prog_type(prog);
11238         /*
11239          * Validate that trace type programs use preallocated hash maps.
11240          *
11241          * For programs attached to PERF events this is mandatory as the
11242          * perf NMI can hit any arbitrary code sequence.
11243          *
11244          * All other trace types using preallocated hash maps are unsafe as
11245          * well because tracepoint or kprobes can be inside locked regions
11246          * of the memory allocator or at a place where a recursion into the
11247          * memory allocator would see inconsistent state.
11248          *
11249          * On RT enabled kernels run-time allocation of all trace type
11250          * programs is strictly prohibited due to lock type constraints. On
11251          * !RT kernels it is allowed for backwards compatibility reasons for
11252          * now, but warnings are emitted so developers are made aware of
11253          * the unsafety and can fix their programs before this is enforced.
11254          */
11255         if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11256                 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11257                         verbose(env, "perf_event programs can only use preallocated hash map\n");
11258                         return -EINVAL;
11259                 }
11260                 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11261                         verbose(env, "trace type programs can only use preallocated hash map\n");
11262                         return -EINVAL;
11263                 }
11264                 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11265                 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11266         }
11267
11268         if (map_value_has_spin_lock(map)) {
11269                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11270                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11271                         return -EINVAL;
11272                 }
11273
11274                 if (is_tracing_prog_type(prog_type)) {
11275                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11276                         return -EINVAL;
11277                 }
11278
11279                 if (prog->aux->sleepable) {
11280                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11281                         return -EINVAL;
11282                 }
11283         }
11284
11285         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11286             !bpf_offload_prog_map_match(prog, map)) {
11287                 verbose(env, "offload device mismatch between prog and map\n");
11288                 return -EINVAL;
11289         }
11290
11291         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11292                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11293                 return -EINVAL;
11294         }
11295
11296         if (prog->aux->sleepable)
11297                 switch (map->map_type) {
11298                 case BPF_MAP_TYPE_HASH:
11299                 case BPF_MAP_TYPE_LRU_HASH:
11300                 case BPF_MAP_TYPE_ARRAY:
11301                 case BPF_MAP_TYPE_PERCPU_HASH:
11302                 case BPF_MAP_TYPE_PERCPU_ARRAY:
11303                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11304                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11305                 case BPF_MAP_TYPE_HASH_OF_MAPS:
11306                         if (!is_preallocated_map(map)) {
11307                                 verbose(env,
11308                                         "Sleepable programs can only use preallocated maps\n");
11309                                 return -EINVAL;
11310                         }
11311                         break;
11312                 case BPF_MAP_TYPE_RINGBUF:
11313                         break;
11314                 default:
11315                         verbose(env,
11316                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
11317                         return -EINVAL;
11318                 }
11319
11320         return 0;
11321 }
11322
11323 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11324 {
11325         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11326                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11327 }
11328
11329 /* find and rewrite pseudo imm in ld_imm64 instructions:
11330  *
11331  * 1. if it accesses map FD, replace it with actual map pointer.
11332  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11333  *
11334  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11335  */
11336 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11337 {
11338         struct bpf_insn *insn = env->prog->insnsi;
11339         int insn_cnt = env->prog->len;
11340         int i, j, err;
11341
11342         err = bpf_prog_calc_tag(env->prog);
11343         if (err)
11344                 return err;
11345
11346         for (i = 0; i < insn_cnt; i++, insn++) {
11347                 if (BPF_CLASS(insn->code) == BPF_LDX &&
11348                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11349                         verbose(env, "BPF_LDX uses reserved fields\n");
11350                         return -EINVAL;
11351                 }
11352
11353                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11354                         struct bpf_insn_aux_data *aux;
11355                         struct bpf_map *map;
11356                         struct fd f;
11357                         u64 addr;
11358                         u32 fd;
11359
11360                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
11361                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11362                             insn[1].off != 0) {
11363                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
11364                                 return -EINVAL;
11365                         }
11366
11367                         if (insn[0].src_reg == 0)
11368                                 /* valid generic load 64-bit imm */
11369                                 goto next_insn;
11370
11371                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11372                                 aux = &env->insn_aux_data[i];
11373                                 err = check_pseudo_btf_id(env, insn, aux);
11374                                 if (err)
11375                                         return err;
11376                                 goto next_insn;
11377                         }
11378
11379                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11380                                 aux = &env->insn_aux_data[i];
11381                                 aux->ptr_type = PTR_TO_FUNC;
11382                                 goto next_insn;
11383                         }
11384
11385                         /* In final convert_pseudo_ld_imm64() step, this is
11386                          * converted into regular 64-bit imm load insn.
11387                          */
11388                         switch (insn[0].src_reg) {
11389                         case BPF_PSEUDO_MAP_VALUE:
11390                         case BPF_PSEUDO_MAP_IDX_VALUE:
11391                                 break;
11392                         case BPF_PSEUDO_MAP_FD:
11393                         case BPF_PSEUDO_MAP_IDX:
11394                                 if (insn[1].imm == 0)
11395                                         break;
11396                                 fallthrough;
11397                         default:
11398                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11399                                 return -EINVAL;
11400                         }
11401
11402                         switch (insn[0].src_reg) {
11403                         case BPF_PSEUDO_MAP_IDX_VALUE:
11404                         case BPF_PSEUDO_MAP_IDX:
11405                                 if (bpfptr_is_null(env->fd_array)) {
11406                                         verbose(env, "fd_idx without fd_array is invalid\n");
11407                                         return -EPROTO;
11408                                 }
11409                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
11410                                                             insn[0].imm * sizeof(fd),
11411                                                             sizeof(fd)))
11412                                         return -EFAULT;
11413                                 break;
11414                         default:
11415                                 fd = insn[0].imm;
11416                                 break;
11417                         }
11418
11419                         f = fdget(fd);
11420                         map = __bpf_map_get(f);
11421                         if (IS_ERR(map)) {
11422                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
11423                                         insn[0].imm);
11424                                 return PTR_ERR(map);
11425                         }
11426
11427                         err = check_map_prog_compatibility(env, map, env->prog);
11428                         if (err) {
11429                                 fdput(f);
11430                                 return err;
11431                         }
11432
11433                         aux = &env->insn_aux_data[i];
11434                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11435                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11436                                 addr = (unsigned long)map;
11437                         } else {
11438                                 u32 off = insn[1].imm;
11439
11440                                 if (off >= BPF_MAX_VAR_OFF) {
11441                                         verbose(env, "direct value offset of %u is not allowed\n", off);
11442                                         fdput(f);
11443                                         return -EINVAL;
11444                                 }
11445
11446                                 if (!map->ops->map_direct_value_addr) {
11447                                         verbose(env, "no direct value access support for this map type\n");
11448                                         fdput(f);
11449                                         return -EINVAL;
11450                                 }
11451
11452                                 err = map->ops->map_direct_value_addr(map, &addr, off);
11453                                 if (err) {
11454                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11455                                                 map->value_size, off);
11456                                         fdput(f);
11457                                         return err;
11458                                 }
11459
11460                                 aux->map_off = off;
11461                                 addr += off;
11462                         }
11463
11464                         insn[0].imm = (u32)addr;
11465                         insn[1].imm = addr >> 32;
11466
11467                         /* check whether we recorded this map already */
11468                         for (j = 0; j < env->used_map_cnt; j++) {
11469                                 if (env->used_maps[j] == map) {
11470                                         aux->map_index = j;
11471                                         fdput(f);
11472                                         goto next_insn;
11473                                 }
11474                         }
11475
11476                         if (env->used_map_cnt >= MAX_USED_MAPS) {
11477                                 fdput(f);
11478                                 return -E2BIG;
11479                         }
11480
11481                         /* hold the map. If the program is rejected by verifier,
11482                          * the map will be released by release_maps() or it
11483                          * will be used by the valid program until it's unloaded
11484                          * and all maps are released in free_used_maps()
11485                          */
11486                         bpf_map_inc(map);
11487
11488                         aux->map_index = env->used_map_cnt;
11489                         env->used_maps[env->used_map_cnt++] = map;
11490
11491                         if (bpf_map_is_cgroup_storage(map) &&
11492                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
11493                                 verbose(env, "only one cgroup storage of each type is allowed\n");
11494                                 fdput(f);
11495                                 return -EBUSY;
11496                         }
11497
11498                         fdput(f);
11499 next_insn:
11500                         insn++;
11501                         i++;
11502                         continue;
11503                 }
11504
11505                 /* Basic sanity check before we invest more work here. */
11506                 if (!bpf_opcode_in_insntable(insn->code)) {
11507                         verbose(env, "unknown opcode %02x\n", insn->code);
11508                         return -EINVAL;
11509                 }
11510         }
11511
11512         /* now all pseudo BPF_LD_IMM64 instructions load valid
11513          * 'struct bpf_map *' into a register instead of user map_fd.
11514          * These pointers will be used later by verifier to validate map access.
11515          */
11516         return 0;
11517 }
11518
11519 /* drop refcnt of maps used by the rejected program */
11520 static void release_maps(struct bpf_verifier_env *env)
11521 {
11522         __bpf_free_used_maps(env->prog->aux, env->used_maps,
11523                              env->used_map_cnt);
11524 }
11525
11526 /* drop refcnt of maps used by the rejected program */
11527 static void release_btfs(struct bpf_verifier_env *env)
11528 {
11529         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11530                              env->used_btf_cnt);
11531 }
11532
11533 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11534 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11535 {
11536         struct bpf_insn *insn = env->prog->insnsi;
11537         int insn_cnt = env->prog->len;
11538         int i;
11539
11540         for (i = 0; i < insn_cnt; i++, insn++) {
11541                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11542                         continue;
11543                 if (insn->src_reg == BPF_PSEUDO_FUNC)
11544                         continue;
11545                 insn->src_reg = 0;
11546         }
11547 }
11548
11549 /* single env->prog->insni[off] instruction was replaced with the range
11550  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11551  * [0, off) and [off, end) to new locations, so the patched range stays zero
11552  */
11553 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
11554                                  struct bpf_insn_aux_data *new_data,
11555                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
11556 {
11557         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
11558         struct bpf_insn *insn = new_prog->insnsi;
11559         u32 old_seen = old_data[off].seen;
11560         u32 prog_len;
11561         int i;
11562
11563         /* aux info at OFF always needs adjustment, no matter fast path
11564          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11565          * original insn at old prog.
11566          */
11567         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11568
11569         if (cnt == 1)
11570                 return;
11571         prog_len = new_prog->len;
11572
11573         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11574         memcpy(new_data + off + cnt - 1, old_data + off,
11575                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11576         for (i = off; i < off + cnt - 1; i++) {
11577                 /* Expand insni[off]'s seen count to the patched range. */
11578                 new_data[i].seen = old_seen;
11579                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11580         }
11581         env->insn_aux_data = new_data;
11582         vfree(old_data);
11583 }
11584
11585 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11586 {
11587         int i;
11588
11589         if (len == 1)
11590                 return;
11591         /* NOTE: fake 'exit' subprog should be updated as well. */
11592         for (i = 0; i <= env->subprog_cnt; i++) {
11593                 if (env->subprog_info[i].start <= off)
11594                         continue;
11595                 env->subprog_info[i].start += len - 1;
11596         }
11597 }
11598
11599 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
11600 {
11601         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11602         int i, sz = prog->aux->size_poke_tab;
11603         struct bpf_jit_poke_descriptor *desc;
11604
11605         for (i = 0; i < sz; i++) {
11606                 desc = &tab[i];
11607                 if (desc->insn_idx <= off)
11608                         continue;
11609                 desc->insn_idx += len - 1;
11610         }
11611 }
11612
11613 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11614                                             const struct bpf_insn *patch, u32 len)
11615 {
11616         struct bpf_prog *new_prog;
11617         struct bpf_insn_aux_data *new_data = NULL;
11618
11619         if (len > 1) {
11620                 new_data = vzalloc(array_size(env->prog->len + len - 1,
11621                                               sizeof(struct bpf_insn_aux_data)));
11622                 if (!new_data)
11623                         return NULL;
11624         }
11625
11626         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
11627         if (IS_ERR(new_prog)) {
11628                 if (PTR_ERR(new_prog) == -ERANGE)
11629                         verbose(env,
11630                                 "insn %d cannot be patched due to 16-bit range\n",
11631                                 env->insn_aux_data[off].orig_idx);
11632                 vfree(new_data);
11633                 return NULL;
11634         }
11635         adjust_insn_aux_data(env, new_data, new_prog, off, len);
11636         adjust_subprog_starts(env, off, len);
11637         adjust_poke_descs(new_prog, off, len);
11638         return new_prog;
11639 }
11640
11641 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11642                                               u32 off, u32 cnt)
11643 {
11644         int i, j;
11645
11646         /* find first prog starting at or after off (first to remove) */
11647         for (i = 0; i < env->subprog_cnt; i++)
11648                 if (env->subprog_info[i].start >= off)
11649                         break;
11650         /* find first prog starting at or after off + cnt (first to stay) */
11651         for (j = i; j < env->subprog_cnt; j++)
11652                 if (env->subprog_info[j].start >= off + cnt)
11653                         break;
11654         /* if j doesn't start exactly at off + cnt, we are just removing
11655          * the front of previous prog
11656          */
11657         if (env->subprog_info[j].start != off + cnt)
11658                 j--;
11659
11660         if (j > i) {
11661                 struct bpf_prog_aux *aux = env->prog->aux;
11662                 int move;
11663
11664                 /* move fake 'exit' subprog as well */
11665                 move = env->subprog_cnt + 1 - j;
11666
11667                 memmove(env->subprog_info + i,
11668                         env->subprog_info + j,
11669                         sizeof(*env->subprog_info) * move);
11670                 env->subprog_cnt -= j - i;
11671
11672                 /* remove func_info */
11673                 if (aux->func_info) {
11674                         move = aux->func_info_cnt - j;
11675
11676                         memmove(aux->func_info + i,
11677                                 aux->func_info + j,
11678                                 sizeof(*aux->func_info) * move);
11679                         aux->func_info_cnt -= j - i;
11680                         /* func_info->insn_off is set after all code rewrites,
11681                          * in adjust_btf_func() - no need to adjust
11682                          */
11683                 }
11684         } else {
11685                 /* convert i from "first prog to remove" to "first to adjust" */
11686                 if (env->subprog_info[i].start == off)
11687                         i++;
11688         }
11689
11690         /* update fake 'exit' subprog as well */
11691         for (; i <= env->subprog_cnt; i++)
11692                 env->subprog_info[i].start -= cnt;
11693
11694         return 0;
11695 }
11696
11697 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11698                                       u32 cnt)
11699 {
11700         struct bpf_prog *prog = env->prog;
11701         u32 i, l_off, l_cnt, nr_linfo;
11702         struct bpf_line_info *linfo;
11703
11704         nr_linfo = prog->aux->nr_linfo;
11705         if (!nr_linfo)
11706                 return 0;
11707
11708         linfo = prog->aux->linfo;
11709
11710         /* find first line info to remove, count lines to be removed */
11711         for (i = 0; i < nr_linfo; i++)
11712                 if (linfo[i].insn_off >= off)
11713                         break;
11714
11715         l_off = i;
11716         l_cnt = 0;
11717         for (; i < nr_linfo; i++)
11718                 if (linfo[i].insn_off < off + cnt)
11719                         l_cnt++;
11720                 else
11721                         break;
11722
11723         /* First live insn doesn't match first live linfo, it needs to "inherit"
11724          * last removed linfo.  prog is already modified, so prog->len == off
11725          * means no live instructions after (tail of the program was removed).
11726          */
11727         if (prog->len != off && l_cnt &&
11728             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11729                 l_cnt--;
11730                 linfo[--i].insn_off = off + cnt;
11731         }
11732
11733         /* remove the line info which refer to the removed instructions */
11734         if (l_cnt) {
11735                 memmove(linfo + l_off, linfo + i,
11736                         sizeof(*linfo) * (nr_linfo - i));
11737
11738                 prog->aux->nr_linfo -= l_cnt;
11739                 nr_linfo = prog->aux->nr_linfo;
11740         }
11741
11742         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11743         for (i = l_off; i < nr_linfo; i++)
11744                 linfo[i].insn_off -= cnt;
11745
11746         /* fix up all subprogs (incl. 'exit') which start >= off */
11747         for (i = 0; i <= env->subprog_cnt; i++)
11748                 if (env->subprog_info[i].linfo_idx > l_off) {
11749                         /* program may have started in the removed region but
11750                          * may not be fully removed
11751                          */
11752                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11753                                 env->subprog_info[i].linfo_idx -= l_cnt;
11754                         else
11755                                 env->subprog_info[i].linfo_idx = l_off;
11756                 }
11757
11758         return 0;
11759 }
11760
11761 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11762 {
11763         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11764         unsigned int orig_prog_len = env->prog->len;
11765         int err;
11766
11767         if (bpf_prog_is_dev_bound(env->prog->aux))
11768                 bpf_prog_offload_remove_insns(env, off, cnt);
11769
11770         err = bpf_remove_insns(env->prog, off, cnt);
11771         if (err)
11772                 return err;
11773
11774         err = adjust_subprog_starts_after_remove(env, off, cnt);
11775         if (err)
11776                 return err;
11777
11778         err = bpf_adj_linfo_after_remove(env, off, cnt);
11779         if (err)
11780                 return err;
11781
11782         memmove(aux_data + off, aux_data + off + cnt,
11783                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11784
11785         return 0;
11786 }
11787
11788 /* The verifier does more data flow analysis than llvm and will not
11789  * explore branches that are dead at run time. Malicious programs can
11790  * have dead code too. Therefore replace all dead at-run-time code
11791  * with 'ja -1'.
11792  *
11793  * Just nops are not optimal, e.g. if they would sit at the end of the
11794  * program and through another bug we would manage to jump there, then
11795  * we'd execute beyond program memory otherwise. Returning exception
11796  * code also wouldn't work since we can have subprogs where the dead
11797  * code could be located.
11798  */
11799 static void sanitize_dead_code(struct bpf_verifier_env *env)
11800 {
11801         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11802         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11803         struct bpf_insn *insn = env->prog->insnsi;
11804         const int insn_cnt = env->prog->len;
11805         int i;
11806
11807         for (i = 0; i < insn_cnt; i++) {
11808                 if (aux_data[i].seen)
11809                         continue;
11810                 memcpy(insn + i, &trap, sizeof(trap));
11811         }
11812 }
11813
11814 static bool insn_is_cond_jump(u8 code)
11815 {
11816         u8 op;
11817
11818         if (BPF_CLASS(code) == BPF_JMP32)
11819                 return true;
11820
11821         if (BPF_CLASS(code) != BPF_JMP)
11822                 return false;
11823
11824         op = BPF_OP(code);
11825         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11826 }
11827
11828 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11829 {
11830         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11831         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11832         struct bpf_insn *insn = env->prog->insnsi;
11833         const int insn_cnt = env->prog->len;
11834         int i;
11835
11836         for (i = 0; i < insn_cnt; i++, insn++) {
11837                 if (!insn_is_cond_jump(insn->code))
11838                         continue;
11839
11840                 if (!aux_data[i + 1].seen)
11841                         ja.off = insn->off;
11842                 else if (!aux_data[i + 1 + insn->off].seen)
11843                         ja.off = 0;
11844                 else
11845                         continue;
11846
11847                 if (bpf_prog_is_dev_bound(env->prog->aux))
11848                         bpf_prog_offload_replace_insn(env, i, &ja);
11849
11850                 memcpy(insn, &ja, sizeof(ja));
11851         }
11852 }
11853
11854 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11855 {
11856         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11857         int insn_cnt = env->prog->len;
11858         int i, err;
11859
11860         for (i = 0; i < insn_cnt; i++) {
11861                 int j;
11862
11863                 j = 0;
11864                 while (i + j < insn_cnt && !aux_data[i + j].seen)
11865                         j++;
11866                 if (!j)
11867                         continue;
11868
11869                 err = verifier_remove_insns(env, i, j);
11870                 if (err)
11871                         return err;
11872                 insn_cnt = env->prog->len;
11873         }
11874
11875         return 0;
11876 }
11877
11878 static int opt_remove_nops(struct bpf_verifier_env *env)
11879 {
11880         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11881         struct bpf_insn *insn = env->prog->insnsi;
11882         int insn_cnt = env->prog->len;
11883         int i, err;
11884
11885         for (i = 0; i < insn_cnt; i++) {
11886                 if (memcmp(&insn[i], &ja, sizeof(ja)))
11887                         continue;
11888
11889                 err = verifier_remove_insns(env, i, 1);
11890                 if (err)
11891                         return err;
11892                 insn_cnt--;
11893                 i--;
11894         }
11895
11896         return 0;
11897 }
11898
11899 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11900                                          const union bpf_attr *attr)
11901 {
11902         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11903         struct bpf_insn_aux_data *aux = env->insn_aux_data;
11904         int i, patch_len, delta = 0, len = env->prog->len;
11905         struct bpf_insn *insns = env->prog->insnsi;
11906         struct bpf_prog *new_prog;
11907         bool rnd_hi32;
11908
11909         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11910         zext_patch[1] = BPF_ZEXT_REG(0);
11911         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11912         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11913         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11914         for (i = 0; i < len; i++) {
11915                 int adj_idx = i + delta;
11916                 struct bpf_insn insn;
11917                 int load_reg;
11918
11919                 insn = insns[adj_idx];
11920                 load_reg = insn_def_regno(&insn);
11921                 if (!aux[adj_idx].zext_dst) {
11922                         u8 code, class;
11923                         u32 imm_rnd;
11924
11925                         if (!rnd_hi32)
11926                                 continue;
11927
11928                         code = insn.code;
11929                         class = BPF_CLASS(code);
11930                         if (load_reg == -1)
11931                                 continue;
11932
11933                         /* NOTE: arg "reg" (the fourth one) is only used for
11934                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
11935                          *       here.
11936                          */
11937                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
11938                                 if (class == BPF_LD &&
11939                                     BPF_MODE(code) == BPF_IMM)
11940                                         i++;
11941                                 continue;
11942                         }
11943
11944                         /* ctx load could be transformed into wider load. */
11945                         if (class == BPF_LDX &&
11946                             aux[adj_idx].ptr_type == PTR_TO_CTX)
11947                                 continue;
11948
11949                         imm_rnd = get_random_int();
11950                         rnd_hi32_patch[0] = insn;
11951                         rnd_hi32_patch[1].imm = imm_rnd;
11952                         rnd_hi32_patch[3].dst_reg = load_reg;
11953                         patch = rnd_hi32_patch;
11954                         patch_len = 4;
11955                         goto apply_patch_buffer;
11956                 }
11957
11958                 /* Add in an zero-extend instruction if a) the JIT has requested
11959                  * it or b) it's a CMPXCHG.
11960                  *
11961                  * The latter is because: BPF_CMPXCHG always loads a value into
11962                  * R0, therefore always zero-extends. However some archs'
11963                  * equivalent instruction only does this load when the
11964                  * comparison is successful. This detail of CMPXCHG is
11965                  * orthogonal to the general zero-extension behaviour of the
11966                  * CPU, so it's treated independently of bpf_jit_needs_zext.
11967                  */
11968                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
11969                         continue;
11970
11971                 if (WARN_ON(load_reg == -1)) {
11972                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11973                         return -EFAULT;
11974                 }
11975
11976                 zext_patch[0] = insn;
11977                 zext_patch[1].dst_reg = load_reg;
11978                 zext_patch[1].src_reg = load_reg;
11979                 patch = zext_patch;
11980                 patch_len = 2;
11981 apply_patch_buffer:
11982                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11983                 if (!new_prog)
11984                         return -ENOMEM;
11985                 env->prog = new_prog;
11986                 insns = new_prog->insnsi;
11987                 aux = env->insn_aux_data;
11988                 delta += patch_len - 1;
11989         }
11990
11991         return 0;
11992 }
11993
11994 /* convert load instructions that access fields of a context type into a
11995  * sequence of instructions that access fields of the underlying structure:
11996  *     struct __sk_buff    -> struct sk_buff
11997  *     struct bpf_sock_ops -> struct sock
11998  */
11999 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12000 {
12001         const struct bpf_verifier_ops *ops = env->ops;
12002         int i, cnt, size, ctx_field_size, delta = 0;
12003         const int insn_cnt = env->prog->len;
12004         struct bpf_insn insn_buf[16], *insn;
12005         u32 target_size, size_default, off;
12006         struct bpf_prog *new_prog;
12007         enum bpf_access_type type;
12008         bool is_narrower_load;
12009
12010         if (ops->gen_prologue || env->seen_direct_write) {
12011                 if (!ops->gen_prologue) {
12012                         verbose(env, "bpf verifier is misconfigured\n");
12013                         return -EINVAL;
12014                 }
12015                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12016                                         env->prog);
12017                 if (cnt >= ARRAY_SIZE(insn_buf)) {
12018                         verbose(env, "bpf verifier is misconfigured\n");
12019                         return -EINVAL;
12020                 } else if (cnt) {
12021                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12022                         if (!new_prog)
12023                                 return -ENOMEM;
12024
12025                         env->prog = new_prog;
12026                         delta += cnt - 1;
12027                 }
12028         }
12029
12030         if (bpf_prog_is_dev_bound(env->prog->aux))
12031                 return 0;
12032
12033         insn = env->prog->insnsi + delta;
12034
12035         for (i = 0; i < insn_cnt; i++, insn++) {
12036                 bpf_convert_ctx_access_t convert_ctx_access;
12037
12038                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12039                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12040                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12041                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
12042                         type = BPF_READ;
12043                 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12044                          insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12045                          insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12046                          insn->code == (BPF_STX | BPF_MEM | BPF_DW))
12047                         type = BPF_WRITE;
12048                 else
12049                         continue;
12050
12051                 if (type == BPF_WRITE &&
12052                     env->insn_aux_data[i + delta].sanitize_stack_off) {
12053                         struct bpf_insn patch[] = {
12054                                 /* Sanitize suspicious stack slot with zero.
12055                                  * There are no memory dependencies for this store,
12056                                  * since it's only using frame pointer and immediate
12057                                  * constant of zero
12058                                  */
12059                                 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
12060                                            env->insn_aux_data[i + delta].sanitize_stack_off,
12061                                            0),
12062                                 /* the original STX instruction will immediately
12063                                  * overwrite the same stack slot with appropriate value
12064                                  */
12065                                 *insn,
12066                         };
12067
12068                         cnt = ARRAY_SIZE(patch);
12069                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12070                         if (!new_prog)
12071                                 return -ENOMEM;
12072
12073                         delta    += cnt - 1;
12074                         env->prog = new_prog;
12075                         insn      = new_prog->insnsi + i + delta;
12076                         continue;
12077                 }
12078
12079                 switch (env->insn_aux_data[i + delta].ptr_type) {
12080                 case PTR_TO_CTX:
12081                         if (!ops->convert_ctx_access)
12082                                 continue;
12083                         convert_ctx_access = ops->convert_ctx_access;
12084                         break;
12085                 case PTR_TO_SOCKET:
12086                 case PTR_TO_SOCK_COMMON:
12087                         convert_ctx_access = bpf_sock_convert_ctx_access;
12088                         break;
12089                 case PTR_TO_TCP_SOCK:
12090                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12091                         break;
12092                 case PTR_TO_XDP_SOCK:
12093                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12094                         break;
12095                 case PTR_TO_BTF_ID:
12096                         if (type == BPF_READ) {
12097                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
12098                                         BPF_SIZE((insn)->code);
12099                                 env->prog->aux->num_exentries++;
12100                         } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12101                                 verbose(env, "Writes through BTF pointers are not allowed\n");
12102                                 return -EINVAL;
12103                         }
12104                         continue;
12105                 default:
12106                         continue;
12107                 }
12108
12109                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12110                 size = BPF_LDST_BYTES(insn);
12111
12112                 /* If the read access is a narrower load of the field,
12113                  * convert to a 4/8-byte load, to minimum program type specific
12114                  * convert_ctx_access changes. If conversion is successful,
12115                  * we will apply proper mask to the result.
12116                  */
12117                 is_narrower_load = size < ctx_field_size;
12118                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12119                 off = insn->off;
12120                 if (is_narrower_load) {
12121                         u8 size_code;
12122
12123                         if (type == BPF_WRITE) {
12124                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12125                                 return -EINVAL;
12126                         }
12127
12128                         size_code = BPF_H;
12129                         if (ctx_field_size == 4)
12130                                 size_code = BPF_W;
12131                         else if (ctx_field_size == 8)
12132                                 size_code = BPF_DW;
12133
12134                         insn->off = off & ~(size_default - 1);
12135                         insn->code = BPF_LDX | BPF_MEM | size_code;
12136                 }
12137
12138                 target_size = 0;
12139                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12140                                          &target_size);
12141                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12142                     (ctx_field_size && !target_size)) {
12143                         verbose(env, "bpf verifier is misconfigured\n");
12144                         return -EINVAL;
12145                 }
12146
12147                 if (is_narrower_load && size < target_size) {
12148                         u8 shift = bpf_ctx_narrow_access_offset(
12149                                 off, size, size_default) * 8;
12150                         if (ctx_field_size <= 4) {
12151                                 if (shift)
12152                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12153                                                                         insn->dst_reg,
12154                                                                         shift);
12155                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12156                                                                 (1 << size * 8) - 1);
12157                         } else {
12158                                 if (shift)
12159                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12160                                                                         insn->dst_reg,
12161                                                                         shift);
12162                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12163                                                                 (1ULL << size * 8) - 1);
12164                         }
12165                 }
12166
12167                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12168                 if (!new_prog)
12169                         return -ENOMEM;
12170
12171                 delta += cnt - 1;
12172
12173                 /* keep walking new program and skip insns we just inserted */
12174                 env->prog = new_prog;
12175                 insn      = new_prog->insnsi + i + delta;
12176         }
12177
12178         return 0;
12179 }
12180
12181 static int jit_subprogs(struct bpf_verifier_env *env)
12182 {
12183         struct bpf_prog *prog = env->prog, **func, *tmp;
12184         int i, j, subprog_start, subprog_end = 0, len, subprog;
12185         struct bpf_map *map_ptr;
12186         struct bpf_insn *insn;
12187         void *old_bpf_func;
12188         int err, num_exentries;
12189
12190         if (env->subprog_cnt <= 1)
12191                 return 0;
12192
12193         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12194                 if (bpf_pseudo_func(insn)) {
12195                         env->insn_aux_data[i].call_imm = insn->imm;
12196                         /* subprog is encoded in insn[1].imm */
12197                         continue;
12198                 }
12199
12200                 if (!bpf_pseudo_call(insn))
12201                         continue;
12202                 /* Upon error here we cannot fall back to interpreter but
12203                  * need a hard reject of the program. Thus -EFAULT is
12204                  * propagated in any case.
12205                  */
12206                 subprog = find_subprog(env, i + insn->imm + 1);
12207                 if (subprog < 0) {
12208                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12209                                   i + insn->imm + 1);
12210                         return -EFAULT;
12211                 }
12212                 /* temporarily remember subprog id inside insn instead of
12213                  * aux_data, since next loop will split up all insns into funcs
12214                  */
12215                 insn->off = subprog;
12216                 /* remember original imm in case JIT fails and fallback
12217                  * to interpreter will be needed
12218                  */
12219                 env->insn_aux_data[i].call_imm = insn->imm;
12220                 /* point imm to __bpf_call_base+1 from JITs point of view */
12221                 insn->imm = 1;
12222         }
12223
12224         err = bpf_prog_alloc_jited_linfo(prog);
12225         if (err)
12226                 goto out_undo_insn;
12227
12228         err = -ENOMEM;
12229         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12230         if (!func)
12231                 goto out_undo_insn;
12232
12233         for (i = 0; i < env->subprog_cnt; i++) {
12234                 subprog_start = subprog_end;
12235                 subprog_end = env->subprog_info[i + 1].start;
12236
12237                 len = subprog_end - subprog_start;
12238                 /* BPF_PROG_RUN doesn't call subprogs directly,
12239                  * hence main prog stats include the runtime of subprogs.
12240                  * subprogs don't have IDs and not reachable via prog_get_next_id
12241                  * func[i]->stats will never be accessed and stays NULL
12242                  */
12243                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12244                 if (!func[i])
12245                         goto out_free;
12246                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12247                        len * sizeof(struct bpf_insn));
12248                 func[i]->type = prog->type;
12249                 func[i]->len = len;
12250                 if (bpf_prog_calc_tag(func[i]))
12251                         goto out_free;
12252                 func[i]->is_func = 1;
12253                 func[i]->aux->func_idx = i;
12254                 /* the btf and func_info will be freed only at prog->aux */
12255                 func[i]->aux->btf = prog->aux->btf;
12256                 func[i]->aux->func_info = prog->aux->func_info;
12257
12258                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
12259                         u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
12260                         int ret;
12261
12262                         if (!(insn_idx >= subprog_start &&
12263                               insn_idx <= subprog_end))
12264                                 continue;
12265
12266                         ret = bpf_jit_add_poke_descriptor(func[i],
12267                                                           &prog->aux->poke_tab[j]);
12268                         if (ret < 0) {
12269                                 verbose(env, "adding tail call poke descriptor failed\n");
12270                                 goto out_free;
12271                         }
12272
12273                         func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
12274
12275                         map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
12276                         ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
12277                         if (ret < 0) {
12278                                 verbose(env, "tracking tail call prog failed\n");
12279                                 goto out_free;
12280                         }
12281                 }
12282
12283                 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12284                  * Long term would need debug info to populate names
12285                  */
12286                 func[i]->aux->name[0] = 'F';
12287                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12288                 func[i]->jit_requested = 1;
12289                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12290                 func[i]->aux->linfo = prog->aux->linfo;
12291                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12292                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12293                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12294                 num_exentries = 0;
12295                 insn = func[i]->insnsi;
12296                 for (j = 0; j < func[i]->len; j++, insn++) {
12297                         if (BPF_CLASS(insn->code) == BPF_LDX &&
12298                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
12299                                 num_exentries++;
12300                 }
12301                 func[i]->aux->num_exentries = num_exentries;
12302                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12303                 func[i] = bpf_int_jit_compile(func[i]);
12304                 if (!func[i]->jited) {
12305                         err = -ENOTSUPP;
12306                         goto out_free;
12307                 }
12308                 cond_resched();
12309         }
12310
12311         /* Untrack main program's aux structs so that during map_poke_run()
12312          * we will not stumble upon the unfilled poke descriptors; each
12313          * of the main program's poke descs got distributed across subprogs
12314          * and got tracked onto map, so we are sure that none of them will
12315          * be missed after the operation below
12316          */
12317         for (i = 0; i < prog->aux->size_poke_tab; i++) {
12318                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12319
12320                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12321         }
12322
12323         /* at this point all bpf functions were successfully JITed
12324          * now populate all bpf_calls with correct addresses and
12325          * run last pass of JIT
12326          */
12327         for (i = 0; i < env->subprog_cnt; i++) {
12328                 insn = func[i]->insnsi;
12329                 for (j = 0; j < func[i]->len; j++, insn++) {
12330                         if (bpf_pseudo_func(insn)) {
12331                                 subprog = insn[1].imm;
12332                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12333                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12334                                 continue;
12335                         }
12336                         if (!bpf_pseudo_call(insn))
12337                                 continue;
12338                         subprog = insn->off;
12339                         insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12340                                     __bpf_call_base;
12341                 }
12342
12343                 /* we use the aux data to keep a list of the start addresses
12344                  * of the JITed images for each function in the program
12345                  *
12346                  * for some architectures, such as powerpc64, the imm field
12347                  * might not be large enough to hold the offset of the start
12348                  * address of the callee's JITed image from __bpf_call_base
12349                  *
12350                  * in such cases, we can lookup the start address of a callee
12351                  * by using its subprog id, available from the off field of
12352                  * the call instruction, as an index for this list
12353                  */
12354                 func[i]->aux->func = func;
12355                 func[i]->aux->func_cnt = env->subprog_cnt;
12356         }
12357         for (i = 0; i < env->subprog_cnt; i++) {
12358                 old_bpf_func = func[i]->bpf_func;
12359                 tmp = bpf_int_jit_compile(func[i]);
12360                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12361                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12362                         err = -ENOTSUPP;
12363                         goto out_free;
12364                 }
12365                 cond_resched();
12366         }
12367
12368         /* finally lock prog and jit images for all functions and
12369          * populate kallsysm
12370          */
12371         for (i = 0; i < env->subprog_cnt; i++) {
12372                 bpf_prog_lock_ro(func[i]);
12373                 bpf_prog_kallsyms_add(func[i]);
12374         }
12375
12376         /* Last step: make now unused interpreter insns from main
12377          * prog consistent for later dump requests, so they can
12378          * later look the same as if they were interpreted only.
12379          */
12380         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12381                 if (bpf_pseudo_func(insn)) {
12382                         insn[0].imm = env->insn_aux_data[i].call_imm;
12383                         insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12384                         continue;
12385                 }
12386                 if (!bpf_pseudo_call(insn))
12387                         continue;
12388                 insn->off = env->insn_aux_data[i].call_imm;
12389                 subprog = find_subprog(env, i + insn->off + 1);
12390                 insn->imm = subprog;
12391         }
12392
12393         prog->jited = 1;
12394         prog->bpf_func = func[0]->bpf_func;
12395         prog->aux->func = func;
12396         prog->aux->func_cnt = env->subprog_cnt;
12397         bpf_prog_jit_attempt_done(prog);
12398         return 0;
12399 out_free:
12400         for (i = 0; i < env->subprog_cnt; i++) {
12401                 if (!func[i])
12402                         continue;
12403
12404                 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
12405                         map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
12406                         map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
12407                 }
12408                 bpf_jit_free(func[i]);
12409         }
12410         kfree(func);
12411 out_undo_insn:
12412         /* cleanup main prog to be interpreted */
12413         prog->jit_requested = 0;
12414         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12415                 if (!bpf_pseudo_call(insn))
12416                         continue;
12417                 insn->off = 0;
12418                 insn->imm = env->insn_aux_data[i].call_imm;
12419         }
12420         bpf_prog_jit_attempt_done(prog);
12421         return err;
12422 }
12423
12424 static int fixup_call_args(struct bpf_verifier_env *env)
12425 {
12426 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12427         struct bpf_prog *prog = env->prog;
12428         struct bpf_insn *insn = prog->insnsi;
12429         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12430         int i, depth;
12431 #endif
12432         int err = 0;
12433
12434         if (env->prog->jit_requested &&
12435             !bpf_prog_is_dev_bound(env->prog->aux)) {
12436                 err = jit_subprogs(env);
12437                 if (err == 0)
12438                         return 0;
12439                 if (err == -EFAULT)
12440                         return err;
12441         }
12442 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12443         if (has_kfunc_call) {
12444                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12445                 return -EINVAL;
12446         }
12447         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12448                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12449                  * have to be rejected, since interpreter doesn't support them yet.
12450                  */
12451                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12452                 return -EINVAL;
12453         }
12454         for (i = 0; i < prog->len; i++, insn++) {
12455                 if (bpf_pseudo_func(insn)) {
12456                         /* When JIT fails the progs with callback calls
12457                          * have to be rejected, since interpreter doesn't support them yet.
12458                          */
12459                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
12460                         return -EINVAL;
12461                 }
12462
12463                 if (!bpf_pseudo_call(insn))
12464                         continue;
12465                 depth = get_callee_stack_depth(env, insn, i);
12466                 if (depth < 0)
12467                         return depth;
12468                 bpf_patch_call_args(insn, depth);
12469         }
12470         err = 0;
12471 #endif
12472         return err;
12473 }
12474
12475 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12476                             struct bpf_insn *insn)
12477 {
12478         const struct bpf_kfunc_desc *desc;
12479
12480         /* insn->imm has the btf func_id. Replace it with
12481          * an address (relative to __bpf_base_call).
12482          */
12483         desc = find_kfunc_desc(env->prog, insn->imm);
12484         if (!desc) {
12485                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12486                         insn->imm);
12487                 return -EFAULT;
12488         }
12489
12490         insn->imm = desc->imm;
12491
12492         return 0;
12493 }
12494
12495 /* Do various post-verification rewrites in a single program pass.
12496  * These rewrites simplify JIT and interpreter implementations.
12497  */
12498 static int do_misc_fixups(struct bpf_verifier_env *env)
12499 {
12500         struct bpf_prog *prog = env->prog;
12501         bool expect_blinding = bpf_jit_blinding_enabled(prog);
12502         struct bpf_insn *insn = prog->insnsi;
12503         const struct bpf_func_proto *fn;
12504         const int insn_cnt = prog->len;
12505         const struct bpf_map_ops *ops;
12506         struct bpf_insn_aux_data *aux;
12507         struct bpf_insn insn_buf[16];
12508         struct bpf_prog *new_prog;
12509         struct bpf_map *map_ptr;
12510         int i, ret, cnt, delta = 0;
12511
12512         for (i = 0; i < insn_cnt; i++, insn++) {
12513                 /* Make divide-by-zero exceptions impossible. */
12514                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12515                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12516                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12517                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12518                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12519                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12520                         struct bpf_insn *patchlet;
12521                         struct bpf_insn chk_and_div[] = {
12522                                 /* [R,W]x div 0 -> 0 */
12523                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12524                                              BPF_JNE | BPF_K, insn->src_reg,
12525                                              0, 2, 0),
12526                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12527                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12528                                 *insn,
12529                         };
12530                         struct bpf_insn chk_and_mod[] = {
12531                                 /* [R,W]x mod 0 -> [R,W]x */
12532                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12533                                              BPF_JEQ | BPF_K, insn->src_reg,
12534                                              0, 1 + (is64 ? 0 : 1), 0),
12535                                 *insn,
12536                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12537                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12538                         };
12539
12540                         patchlet = isdiv ? chk_and_div : chk_and_mod;
12541                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12542                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12543
12544                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12545                         if (!new_prog)
12546                                 return -ENOMEM;
12547
12548                         delta    += cnt - 1;
12549                         env->prog = prog = new_prog;
12550                         insn      = new_prog->insnsi + i + delta;
12551                         continue;
12552                 }
12553
12554                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12555                 if (BPF_CLASS(insn->code) == BPF_LD &&
12556                     (BPF_MODE(insn->code) == BPF_ABS ||
12557                      BPF_MODE(insn->code) == BPF_IND)) {
12558                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
12559                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12560                                 verbose(env, "bpf verifier is misconfigured\n");
12561                                 return -EINVAL;
12562                         }
12563
12564                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12565                         if (!new_prog)
12566                                 return -ENOMEM;
12567
12568                         delta    += cnt - 1;
12569                         env->prog = prog = new_prog;
12570                         insn      = new_prog->insnsi + i + delta;
12571                         continue;
12572                 }
12573
12574                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
12575                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12576                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12577                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12578                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12579                         struct bpf_insn *patch = &insn_buf[0];
12580                         bool issrc, isneg, isimm;
12581                         u32 off_reg;
12582
12583                         aux = &env->insn_aux_data[i + delta];
12584                         if (!aux->alu_state ||
12585                             aux->alu_state == BPF_ALU_NON_POINTER)
12586                                 continue;
12587
12588                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12589                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12590                                 BPF_ALU_SANITIZE_SRC;
12591                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12592
12593                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
12594                         if (isimm) {
12595                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12596                         } else {
12597                                 if (isneg)
12598                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12599                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12600                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12601                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12602                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12603                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12604                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12605                         }
12606                         if (!issrc)
12607                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12608                         insn->src_reg = BPF_REG_AX;
12609                         if (isneg)
12610                                 insn->code = insn->code == code_add ?
12611                                              code_sub : code_add;
12612                         *patch++ = *insn;
12613                         if (issrc && isneg && !isimm)
12614                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12615                         cnt = patch - insn_buf;
12616
12617                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12618                         if (!new_prog)
12619                                 return -ENOMEM;
12620
12621                         delta    += cnt - 1;
12622                         env->prog = prog = new_prog;
12623                         insn      = new_prog->insnsi + i + delta;
12624                         continue;
12625                 }
12626
12627                 if (insn->code != (BPF_JMP | BPF_CALL))
12628                         continue;
12629                 if (insn->src_reg == BPF_PSEUDO_CALL)
12630                         continue;
12631                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12632                         ret = fixup_kfunc_call(env, insn);
12633                         if (ret)
12634                                 return ret;
12635                         continue;
12636                 }
12637
12638                 if (insn->imm == BPF_FUNC_get_route_realm)
12639                         prog->dst_needed = 1;
12640                 if (insn->imm == BPF_FUNC_get_prandom_u32)
12641                         bpf_user_rnd_init_once();
12642                 if (insn->imm == BPF_FUNC_override_return)
12643                         prog->kprobe_override = 1;
12644                 if (insn->imm == BPF_FUNC_tail_call) {
12645                         /* If we tail call into other programs, we
12646                          * cannot make any assumptions since they can
12647                          * be replaced dynamically during runtime in
12648                          * the program array.
12649                          */
12650                         prog->cb_access = 1;
12651                         if (!allow_tail_call_in_subprogs(env))
12652                                 prog->aux->stack_depth = MAX_BPF_STACK;
12653                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
12654
12655                         /* mark bpf_tail_call as different opcode to avoid
12656                          * conditional branch in the interpreter for every normal
12657                          * call and to prevent accidental JITing by JIT compiler
12658                          * that doesn't support bpf_tail_call yet
12659                          */
12660                         insn->imm = 0;
12661                         insn->code = BPF_JMP | BPF_TAIL_CALL;
12662
12663                         aux = &env->insn_aux_data[i + delta];
12664                         if (env->bpf_capable && !expect_blinding &&
12665                             prog->jit_requested &&
12666                             !bpf_map_key_poisoned(aux) &&
12667                             !bpf_map_ptr_poisoned(aux) &&
12668                             !bpf_map_ptr_unpriv(aux)) {
12669                                 struct bpf_jit_poke_descriptor desc = {
12670                                         .reason = BPF_POKE_REASON_TAIL_CALL,
12671                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12672                                         .tail_call.key = bpf_map_key_immediate(aux),
12673                                         .insn_idx = i + delta,
12674                                 };
12675
12676                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12677                                 if (ret < 0) {
12678                                         verbose(env, "adding tail call poke descriptor failed\n");
12679                                         return ret;
12680                                 }
12681
12682                                 insn->imm = ret + 1;
12683                                 continue;
12684                         }
12685
12686                         if (!bpf_map_ptr_unpriv(aux))
12687                                 continue;
12688
12689                         /* instead of changing every JIT dealing with tail_call
12690                          * emit two extra insns:
12691                          * if (index >= max_entries) goto out;
12692                          * index &= array->index_mask;
12693                          * to avoid out-of-bounds cpu speculation
12694                          */
12695                         if (bpf_map_ptr_poisoned(aux)) {
12696                                 verbose(env, "tail_call abusing map_ptr\n");
12697                                 return -EINVAL;
12698                         }
12699
12700                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12701                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12702                                                   map_ptr->max_entries, 2);
12703                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12704                                                     container_of(map_ptr,
12705                                                                  struct bpf_array,
12706                                                                  map)->index_mask);
12707                         insn_buf[2] = *insn;
12708                         cnt = 3;
12709                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12710                         if (!new_prog)
12711                                 return -ENOMEM;
12712
12713                         delta    += cnt - 1;
12714                         env->prog = prog = new_prog;
12715                         insn      = new_prog->insnsi + i + delta;
12716                         continue;
12717                 }
12718
12719                 if (insn->imm == BPF_FUNC_timer_set_callback) {
12720                         /* The verifier will process callback_fn as many times as necessary
12721                          * with different maps and the register states prepared by
12722                          * set_timer_callback_state will be accurate.
12723                          *
12724                          * The following use case is valid:
12725                          *   map1 is shared by prog1, prog2, prog3.
12726                          *   prog1 calls bpf_timer_init for some map1 elements
12727                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
12728                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
12729                          *   prog3 calls bpf_timer_start for some map1 elements.
12730                          *     Those that were not both bpf_timer_init-ed and
12731                          *     bpf_timer_set_callback-ed will return -EINVAL.
12732                          */
12733                         struct bpf_insn ld_addrs[2] = {
12734                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
12735                         };
12736
12737                         insn_buf[0] = ld_addrs[0];
12738                         insn_buf[1] = ld_addrs[1];
12739                         insn_buf[2] = *insn;
12740                         cnt = 3;
12741
12742                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12743                         if (!new_prog)
12744                                 return -ENOMEM;
12745
12746                         delta    += cnt - 1;
12747                         env->prog = prog = new_prog;
12748                         insn      = new_prog->insnsi + i + delta;
12749                         goto patch_call_imm;
12750                 }
12751
12752                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
12753                  * and other inlining handlers are currently limited to 64 bit
12754                  * only.
12755                  */
12756                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12757                     (insn->imm == BPF_FUNC_map_lookup_elem ||
12758                      insn->imm == BPF_FUNC_map_update_elem ||
12759                      insn->imm == BPF_FUNC_map_delete_elem ||
12760                      insn->imm == BPF_FUNC_map_push_elem   ||
12761                      insn->imm == BPF_FUNC_map_pop_elem    ||
12762                      insn->imm == BPF_FUNC_map_peek_elem   ||
12763                      insn->imm == BPF_FUNC_redirect_map)) {
12764                         aux = &env->insn_aux_data[i + delta];
12765                         if (bpf_map_ptr_poisoned(aux))
12766                                 goto patch_call_imm;
12767
12768                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12769                         ops = map_ptr->ops;
12770                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
12771                             ops->map_gen_lookup) {
12772                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
12773                                 if (cnt == -EOPNOTSUPP)
12774                                         goto patch_map_ops_generic;
12775                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12776                                         verbose(env, "bpf verifier is misconfigured\n");
12777                                         return -EINVAL;
12778                                 }
12779
12780                                 new_prog = bpf_patch_insn_data(env, i + delta,
12781                                                                insn_buf, cnt);
12782                                 if (!new_prog)
12783                                         return -ENOMEM;
12784
12785                                 delta    += cnt - 1;
12786                                 env->prog = prog = new_prog;
12787                                 insn      = new_prog->insnsi + i + delta;
12788                                 continue;
12789                         }
12790
12791                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12792                                      (void *(*)(struct bpf_map *map, void *key))NULL));
12793                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12794                                      (int (*)(struct bpf_map *map, void *key))NULL));
12795                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12796                                      (int (*)(struct bpf_map *map, void *key, void *value,
12797                                               u64 flags))NULL));
12798                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12799                                      (int (*)(struct bpf_map *map, void *value,
12800                                               u64 flags))NULL));
12801                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12802                                      (int (*)(struct bpf_map *map, void *value))NULL));
12803                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12804                                      (int (*)(struct bpf_map *map, void *value))NULL));
12805                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
12806                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12807
12808 patch_map_ops_generic:
12809                         switch (insn->imm) {
12810                         case BPF_FUNC_map_lookup_elem:
12811                                 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12812                                             __bpf_call_base;
12813                                 continue;
12814                         case BPF_FUNC_map_update_elem:
12815                                 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12816                                             __bpf_call_base;
12817                                 continue;
12818                         case BPF_FUNC_map_delete_elem:
12819                                 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12820                                             __bpf_call_base;
12821                                 continue;
12822                         case BPF_FUNC_map_push_elem:
12823                                 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12824                                             __bpf_call_base;
12825                                 continue;
12826                         case BPF_FUNC_map_pop_elem:
12827                                 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12828                                             __bpf_call_base;
12829                                 continue;
12830                         case BPF_FUNC_map_peek_elem:
12831                                 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12832                                             __bpf_call_base;
12833                                 continue;
12834                         case BPF_FUNC_redirect_map:
12835                                 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12836                                             __bpf_call_base;
12837                                 continue;
12838                         }
12839
12840                         goto patch_call_imm;
12841                 }
12842
12843                 /* Implement bpf_jiffies64 inline. */
12844                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12845                     insn->imm == BPF_FUNC_jiffies64) {
12846                         struct bpf_insn ld_jiffies_addr[2] = {
12847                                 BPF_LD_IMM64(BPF_REG_0,
12848                                              (unsigned long)&jiffies),
12849                         };
12850
12851                         insn_buf[0] = ld_jiffies_addr[0];
12852                         insn_buf[1] = ld_jiffies_addr[1];
12853                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12854                                                   BPF_REG_0, 0);
12855                         cnt = 3;
12856
12857                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12858                                                        cnt);
12859                         if (!new_prog)
12860                                 return -ENOMEM;
12861
12862                         delta    += cnt - 1;
12863                         env->prog = prog = new_prog;
12864                         insn      = new_prog->insnsi + i + delta;
12865                         continue;
12866                 }
12867
12868 patch_call_imm:
12869                 fn = env->ops->get_func_proto(insn->imm, env->prog);
12870                 /* all functions that have prototype and verifier allowed
12871                  * programs to call them, must be real in-kernel functions
12872                  */
12873                 if (!fn->func) {
12874                         verbose(env,
12875                                 "kernel subsystem misconfigured func %s#%d\n",
12876                                 func_id_name(insn->imm), insn->imm);
12877                         return -EFAULT;
12878                 }
12879                 insn->imm = fn->func - __bpf_call_base;
12880         }
12881
12882         /* Since poke tab is now finalized, publish aux to tracker. */
12883         for (i = 0; i < prog->aux->size_poke_tab; i++) {
12884                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12885                 if (!map_ptr->ops->map_poke_track ||
12886                     !map_ptr->ops->map_poke_untrack ||
12887                     !map_ptr->ops->map_poke_run) {
12888                         verbose(env, "bpf verifier is misconfigured\n");
12889                         return -EINVAL;
12890                 }
12891
12892                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12893                 if (ret < 0) {
12894                         verbose(env, "tracking tail call prog failed\n");
12895                         return ret;
12896                 }
12897         }
12898
12899         sort_kfunc_descs_by_imm(env->prog);
12900
12901         return 0;
12902 }
12903
12904 static void free_states(struct bpf_verifier_env *env)
12905 {
12906         struct bpf_verifier_state_list *sl, *sln;
12907         int i;
12908
12909         sl = env->free_list;
12910         while (sl) {
12911                 sln = sl->next;
12912                 free_verifier_state(&sl->state, false);
12913                 kfree(sl);
12914                 sl = sln;
12915         }
12916         env->free_list = NULL;
12917
12918         if (!env->explored_states)
12919                 return;
12920
12921         for (i = 0; i < state_htab_size(env); i++) {
12922                 sl = env->explored_states[i];
12923
12924                 while (sl) {
12925                         sln = sl->next;
12926                         free_verifier_state(&sl->state, false);
12927                         kfree(sl);
12928                         sl = sln;
12929                 }
12930                 env->explored_states[i] = NULL;
12931         }
12932 }
12933
12934 /* The verifier is using insn_aux_data[] to store temporary data during
12935  * verification and to store information for passes that run after the
12936  * verification like dead code sanitization. do_check_common() for subprogram N
12937  * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12938  * temporary data after do_check_common() finds that subprogram N cannot be
12939  * verified independently. pass_cnt counts the number of times
12940  * do_check_common() was run and insn->aux->seen tells the pass number
12941  * insn_aux_data was touched. These variables are compared to clear temporary
12942  * data from failed pass. For testing and experiments do_check_common() can be
12943  * run multiple times even when prior attempt to verify is unsuccessful.
12944  *
12945  * Note that special handling is needed on !env->bypass_spec_v1 if this is
12946  * ever called outside of error path with subsequent program rejection.
12947  */
12948 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12949 {
12950         struct bpf_insn *insn = env->prog->insnsi;
12951         struct bpf_insn_aux_data *aux;
12952         int i, class;
12953
12954         for (i = 0; i < env->prog->len; i++) {
12955                 class = BPF_CLASS(insn[i].code);
12956                 if (class != BPF_LDX && class != BPF_STX)
12957                         continue;
12958                 aux = &env->insn_aux_data[i];
12959                 if (aux->seen != env->pass_cnt)
12960                         continue;
12961                 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12962         }
12963 }
12964
12965 static int do_check_common(struct bpf_verifier_env *env, int subprog)
12966 {
12967         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12968         struct bpf_verifier_state *state;
12969         struct bpf_reg_state *regs;
12970         int ret, i;
12971
12972         env->prev_linfo = NULL;
12973         env->pass_cnt++;
12974
12975         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12976         if (!state)
12977                 return -ENOMEM;
12978         state->curframe = 0;
12979         state->speculative = false;
12980         state->branches = 1;
12981         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12982         if (!state->frame[0]) {
12983                 kfree(state);
12984                 return -ENOMEM;
12985         }
12986         env->cur_state = state;
12987         init_func_state(env, state->frame[0],
12988                         BPF_MAIN_FUNC /* callsite */,
12989                         0 /* frameno */,
12990                         subprog);
12991
12992         regs = state->frame[state->curframe]->regs;
12993         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12994                 ret = btf_prepare_func_args(env, subprog, regs);
12995                 if (ret)
12996                         goto out;
12997                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12998                         if (regs[i].type == PTR_TO_CTX)
12999                                 mark_reg_known_zero(env, regs, i);
13000                         else if (regs[i].type == SCALAR_VALUE)
13001                                 mark_reg_unknown(env, regs, i);
13002                         else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
13003                                 const u32 mem_size = regs[i].mem_size;
13004
13005                                 mark_reg_known_zero(env, regs, i);
13006                                 regs[i].mem_size = mem_size;
13007                                 regs[i].id = ++env->id_gen;
13008                         }
13009                 }
13010         } else {
13011                 /* 1st arg to a function */
13012                 regs[BPF_REG_1].type = PTR_TO_CTX;
13013                 mark_reg_known_zero(env, regs, BPF_REG_1);
13014                 ret = btf_check_subprog_arg_match(env, subprog, regs);
13015                 if (ret == -EFAULT)
13016                         /* unlikely verifier bug. abort.
13017                          * ret == 0 and ret < 0 are sadly acceptable for
13018                          * main() function due to backward compatibility.
13019                          * Like socket filter program may be written as:
13020                          * int bpf_prog(struct pt_regs *ctx)
13021                          * and never dereference that ctx in the program.
13022                          * 'struct pt_regs' is a type mismatch for socket
13023                          * filter that should be using 'struct __sk_buff'.
13024                          */
13025                         goto out;
13026         }
13027
13028         ret = do_check(env);
13029 out:
13030         /* check for NULL is necessary, since cur_state can be freed inside
13031          * do_check() under memory pressure.
13032          */
13033         if (env->cur_state) {
13034                 free_verifier_state(env->cur_state, true);
13035                 env->cur_state = NULL;
13036         }
13037         while (!pop_stack(env, NULL, NULL, false));
13038         if (!ret && pop_log)
13039                 bpf_vlog_reset(&env->log, 0);
13040         free_states(env);
13041         if (ret)
13042                 /* clean aux data in case subprog was rejected */
13043                 sanitize_insn_aux_data(env);
13044         return ret;
13045 }
13046
13047 /* Verify all global functions in a BPF program one by one based on their BTF.
13048  * All global functions must pass verification. Otherwise the whole program is rejected.
13049  * Consider:
13050  * int bar(int);
13051  * int foo(int f)
13052  * {
13053  *    return bar(f);
13054  * }
13055  * int bar(int b)
13056  * {
13057  *    ...
13058  * }
13059  * foo() will be verified first for R1=any_scalar_value. During verification it
13060  * will be assumed that bar() already verified successfully and call to bar()
13061  * from foo() will be checked for type match only. Later bar() will be verified
13062  * independently to check that it's safe for R1=any_scalar_value.
13063  */
13064 static int do_check_subprogs(struct bpf_verifier_env *env)
13065 {
13066         struct bpf_prog_aux *aux = env->prog->aux;
13067         int i, ret;
13068
13069         if (!aux->func_info)
13070                 return 0;
13071
13072         for (i = 1; i < env->subprog_cnt; i++) {
13073                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13074                         continue;
13075                 env->insn_idx = env->subprog_info[i].start;
13076                 WARN_ON_ONCE(env->insn_idx == 0);
13077                 ret = do_check_common(env, i);
13078                 if (ret) {
13079                         return ret;
13080                 } else if (env->log.level & BPF_LOG_LEVEL) {
13081                         verbose(env,
13082                                 "Func#%d is safe for any args that match its prototype\n",
13083                                 i);
13084                 }
13085         }
13086         return 0;
13087 }
13088
13089 static int do_check_main(struct bpf_verifier_env *env)
13090 {
13091         int ret;
13092
13093         env->insn_idx = 0;
13094         ret = do_check_common(env, 0);
13095         if (!ret)
13096                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13097         return ret;
13098 }
13099
13100
13101 static void print_verification_stats(struct bpf_verifier_env *env)
13102 {
13103         int i;
13104
13105         if (env->log.level & BPF_LOG_STATS) {
13106                 verbose(env, "verification time %lld usec\n",
13107                         div_u64(env->verification_time, 1000));
13108                 verbose(env, "stack depth ");
13109                 for (i = 0; i < env->subprog_cnt; i++) {
13110                         u32 depth = env->subprog_info[i].stack_depth;
13111
13112                         verbose(env, "%d", depth);
13113                         if (i + 1 < env->subprog_cnt)
13114                                 verbose(env, "+");
13115                 }
13116                 verbose(env, "\n");
13117         }
13118         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13119                 "total_states %d peak_states %d mark_read %d\n",
13120                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13121                 env->max_states_per_insn, env->total_states,
13122                 env->peak_states, env->longest_mark_read_walk);
13123 }
13124
13125 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13126 {
13127         const struct btf_type *t, *func_proto;
13128         const struct bpf_struct_ops *st_ops;
13129         const struct btf_member *member;
13130         struct bpf_prog *prog = env->prog;
13131         u32 btf_id, member_idx;
13132         const char *mname;
13133
13134         if (!prog->gpl_compatible) {
13135                 verbose(env, "struct ops programs must have a GPL compatible license\n");
13136                 return -EINVAL;
13137         }
13138
13139         btf_id = prog->aux->attach_btf_id;
13140         st_ops = bpf_struct_ops_find(btf_id);
13141         if (!st_ops) {
13142                 verbose(env, "attach_btf_id %u is not a supported struct\n",
13143                         btf_id);
13144                 return -ENOTSUPP;
13145         }
13146
13147         t = st_ops->type;
13148         member_idx = prog->expected_attach_type;
13149         if (member_idx >= btf_type_vlen(t)) {
13150                 verbose(env, "attach to invalid member idx %u of struct %s\n",
13151                         member_idx, st_ops->name);
13152                 return -EINVAL;
13153         }
13154
13155         member = &btf_type_member(t)[member_idx];
13156         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13157         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13158                                                NULL);
13159         if (!func_proto) {
13160                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13161                         mname, member_idx, st_ops->name);
13162                 return -EINVAL;
13163         }
13164
13165         if (st_ops->check_member) {
13166                 int err = st_ops->check_member(t, member);
13167
13168                 if (err) {
13169                         verbose(env, "attach to unsupported member %s of struct %s\n",
13170                                 mname, st_ops->name);
13171                         return err;
13172                 }
13173         }
13174
13175         prog->aux->attach_func_proto = func_proto;
13176         prog->aux->attach_func_name = mname;
13177         env->ops = st_ops->verifier_ops;
13178
13179         return 0;
13180 }
13181 #define SECURITY_PREFIX "security_"
13182
13183 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13184 {
13185         if (within_error_injection_list(addr) ||
13186             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13187                 return 0;
13188
13189         return -EINVAL;
13190 }
13191
13192 /* list of non-sleepable functions that are otherwise on
13193  * ALLOW_ERROR_INJECTION list
13194  */
13195 BTF_SET_START(btf_non_sleepable_error_inject)
13196 /* Three functions below can be called from sleepable and non-sleepable context.
13197  * Assume non-sleepable from bpf safety point of view.
13198  */
13199 BTF_ID(func, __add_to_page_cache_locked)
13200 BTF_ID(func, should_fail_alloc_page)
13201 BTF_ID(func, should_failslab)
13202 BTF_SET_END(btf_non_sleepable_error_inject)
13203
13204 static int check_non_sleepable_error_inject(u32 btf_id)
13205 {
13206         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13207 }
13208
13209 int bpf_check_attach_target(struct bpf_verifier_log *log,
13210                             const struct bpf_prog *prog,
13211                             const struct bpf_prog *tgt_prog,
13212                             u32 btf_id,
13213                             struct bpf_attach_target_info *tgt_info)
13214 {
13215         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13216         const char prefix[] = "btf_trace_";
13217         int ret = 0, subprog = -1, i;
13218         const struct btf_type *t;
13219         bool conservative = true;
13220         const char *tname;
13221         struct btf *btf;
13222         long addr = 0;
13223
13224         if (!btf_id) {
13225                 bpf_log(log, "Tracing programs must provide btf_id\n");
13226                 return -EINVAL;
13227         }
13228         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13229         if (!btf) {
13230                 bpf_log(log,
13231                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13232                 return -EINVAL;
13233         }
13234         t = btf_type_by_id(btf, btf_id);
13235         if (!t) {
13236                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13237                 return -EINVAL;
13238         }
13239         tname = btf_name_by_offset(btf, t->name_off);
13240         if (!tname) {
13241                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13242                 return -EINVAL;
13243         }
13244         if (tgt_prog) {
13245                 struct bpf_prog_aux *aux = tgt_prog->aux;
13246
13247                 for (i = 0; i < aux->func_info_cnt; i++)
13248                         if (aux->func_info[i].type_id == btf_id) {
13249                                 subprog = i;
13250                                 break;
13251                         }
13252                 if (subprog == -1) {
13253                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
13254                         return -EINVAL;
13255                 }
13256                 conservative = aux->func_info_aux[subprog].unreliable;
13257                 if (prog_extension) {
13258                         if (conservative) {
13259                                 bpf_log(log,
13260                                         "Cannot replace static functions\n");
13261                                 return -EINVAL;
13262                         }
13263                         if (!prog->jit_requested) {
13264                                 bpf_log(log,
13265                                         "Extension programs should be JITed\n");
13266                                 return -EINVAL;
13267                         }
13268                 }
13269                 if (!tgt_prog->jited) {
13270                         bpf_log(log, "Can attach to only JITed progs\n");
13271                         return -EINVAL;
13272                 }
13273                 if (tgt_prog->type == prog->type) {
13274                         /* Cannot fentry/fexit another fentry/fexit program.
13275                          * Cannot attach program extension to another extension.
13276                          * It's ok to attach fentry/fexit to extension program.
13277                          */
13278                         bpf_log(log, "Cannot recursively attach\n");
13279                         return -EINVAL;
13280                 }
13281                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13282                     prog_extension &&
13283                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13284                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13285                         /* Program extensions can extend all program types
13286                          * except fentry/fexit. The reason is the following.
13287                          * The fentry/fexit programs are used for performance
13288                          * analysis, stats and can be attached to any program
13289                          * type except themselves. When extension program is
13290                          * replacing XDP function it is necessary to allow
13291                          * performance analysis of all functions. Both original
13292                          * XDP program and its program extension. Hence
13293                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13294                          * allowed. If extending of fentry/fexit was allowed it
13295                          * would be possible to create long call chain
13296                          * fentry->extension->fentry->extension beyond
13297                          * reasonable stack size. Hence extending fentry is not
13298                          * allowed.
13299                          */
13300                         bpf_log(log, "Cannot extend fentry/fexit\n");
13301                         return -EINVAL;
13302                 }
13303         } else {
13304                 if (prog_extension) {
13305                         bpf_log(log, "Cannot replace kernel functions\n");
13306                         return -EINVAL;
13307                 }
13308         }
13309
13310         switch (prog->expected_attach_type) {
13311         case BPF_TRACE_RAW_TP:
13312                 if (tgt_prog) {
13313                         bpf_log(log,
13314                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13315                         return -EINVAL;
13316                 }
13317                 if (!btf_type_is_typedef(t)) {
13318                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
13319                                 btf_id);
13320                         return -EINVAL;
13321                 }
13322                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13323                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13324                                 btf_id, tname);
13325                         return -EINVAL;
13326                 }
13327                 tname += sizeof(prefix) - 1;
13328                 t = btf_type_by_id(btf, t->type);
13329                 if (!btf_type_is_ptr(t))
13330                         /* should never happen in valid vmlinux build */
13331                         return -EINVAL;
13332                 t = btf_type_by_id(btf, t->type);
13333                 if (!btf_type_is_func_proto(t))
13334                         /* should never happen in valid vmlinux build */
13335                         return -EINVAL;
13336
13337                 break;
13338         case BPF_TRACE_ITER:
13339                 if (!btf_type_is_func(t)) {
13340                         bpf_log(log, "attach_btf_id %u is not a function\n",
13341                                 btf_id);
13342                         return -EINVAL;
13343                 }
13344                 t = btf_type_by_id(btf, t->type);
13345                 if (!btf_type_is_func_proto(t))
13346                         return -EINVAL;
13347                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13348                 if (ret)
13349                         return ret;
13350                 break;
13351         default:
13352                 if (!prog_extension)
13353                         return -EINVAL;
13354                 fallthrough;
13355         case BPF_MODIFY_RETURN:
13356         case BPF_LSM_MAC:
13357         case BPF_TRACE_FENTRY:
13358         case BPF_TRACE_FEXIT:
13359                 if (!btf_type_is_func(t)) {
13360                         bpf_log(log, "attach_btf_id %u is not a function\n",
13361                                 btf_id);
13362                         return -EINVAL;
13363                 }
13364                 if (prog_extension &&
13365                     btf_check_type_match(log, prog, btf, t))
13366                         return -EINVAL;
13367                 t = btf_type_by_id(btf, t->type);
13368                 if (!btf_type_is_func_proto(t))
13369                         return -EINVAL;
13370
13371                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13372                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13373                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13374                         return -EINVAL;
13375
13376                 if (tgt_prog && conservative)
13377                         t = NULL;
13378
13379                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13380                 if (ret < 0)
13381                         return ret;
13382
13383                 if (tgt_prog) {
13384                         if (subprog == 0)
13385                                 addr = (long) tgt_prog->bpf_func;
13386                         else
13387                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13388                 } else {
13389                         addr = kallsyms_lookup_name(tname);
13390                         if (!addr) {
13391                                 bpf_log(log,
13392                                         "The address of function %s cannot be found\n",
13393                                         tname);
13394                                 return -ENOENT;
13395                         }
13396                 }
13397
13398                 if (prog->aux->sleepable) {
13399                         ret = -EINVAL;
13400                         switch (prog->type) {
13401                         case BPF_PROG_TYPE_TRACING:
13402                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13403                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13404                                  */
13405                                 if (!check_non_sleepable_error_inject(btf_id) &&
13406                                     within_error_injection_list(addr))
13407                                         ret = 0;
13408                                 break;
13409                         case BPF_PROG_TYPE_LSM:
13410                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13411                                  * Only some of them are sleepable.
13412                                  */
13413                                 if (bpf_lsm_is_sleepable_hook(btf_id))
13414                                         ret = 0;
13415                                 break;
13416                         default:
13417                                 break;
13418                         }
13419                         if (ret) {
13420                                 bpf_log(log, "%s is not sleepable\n", tname);
13421                                 return ret;
13422                         }
13423                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13424                         if (tgt_prog) {
13425                                 bpf_log(log, "can't modify return codes of BPF programs\n");
13426                                 return -EINVAL;
13427                         }
13428                         ret = check_attach_modify_return(addr, tname);
13429                         if (ret) {
13430                                 bpf_log(log, "%s() is not modifiable\n", tname);
13431                                 return ret;
13432                         }
13433                 }
13434
13435                 break;
13436         }
13437         tgt_info->tgt_addr = addr;
13438         tgt_info->tgt_name = tname;
13439         tgt_info->tgt_type = t;
13440         return 0;
13441 }
13442
13443 BTF_SET_START(btf_id_deny)
13444 BTF_ID_UNUSED
13445 #ifdef CONFIG_SMP
13446 BTF_ID(func, migrate_disable)
13447 BTF_ID(func, migrate_enable)
13448 #endif
13449 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13450 BTF_ID(func, rcu_read_unlock_strict)
13451 #endif
13452 BTF_SET_END(btf_id_deny)
13453
13454 static int check_attach_btf_id(struct bpf_verifier_env *env)
13455 {
13456         struct bpf_prog *prog = env->prog;
13457         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13458         struct bpf_attach_target_info tgt_info = {};
13459         u32 btf_id = prog->aux->attach_btf_id;
13460         struct bpf_trampoline *tr;
13461         int ret;
13462         u64 key;
13463
13464         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13465                 if (prog->aux->sleepable)
13466                         /* attach_btf_id checked to be zero already */
13467                         return 0;
13468                 verbose(env, "Syscall programs can only be sleepable\n");
13469                 return -EINVAL;
13470         }
13471
13472         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13473             prog->type != BPF_PROG_TYPE_LSM) {
13474                 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13475                 return -EINVAL;
13476         }
13477
13478         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13479                 return check_struct_ops_btf_id(env);
13480
13481         if (prog->type != BPF_PROG_TYPE_TRACING &&
13482             prog->type != BPF_PROG_TYPE_LSM &&
13483             prog->type != BPF_PROG_TYPE_EXT)
13484                 return 0;
13485
13486         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13487         if (ret)
13488                 return ret;
13489
13490         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13491                 /* to make freplace equivalent to their targets, they need to
13492                  * inherit env->ops and expected_attach_type for the rest of the
13493                  * verification
13494                  */
13495                 env->ops = bpf_verifier_ops[tgt_prog->type];
13496                 prog->expected_attach_type = tgt_prog->expected_attach_type;
13497         }
13498
13499         /* store info about the attachment target that will be used later */
13500         prog->aux->attach_func_proto = tgt_info.tgt_type;
13501         prog->aux->attach_func_name = tgt_info.tgt_name;
13502
13503         if (tgt_prog) {
13504                 prog->aux->saved_dst_prog_type = tgt_prog->type;
13505                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13506         }
13507
13508         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13509                 prog->aux->attach_btf_trace = true;
13510                 return 0;
13511         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13512                 if (!bpf_iter_prog_supported(prog))
13513                         return -EINVAL;
13514                 return 0;
13515         }
13516
13517         if (prog->type == BPF_PROG_TYPE_LSM) {
13518                 ret = bpf_lsm_verify_prog(&env->log, prog);
13519                 if (ret < 0)
13520                         return ret;
13521         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
13522                    btf_id_set_contains(&btf_id_deny, btf_id)) {
13523                 return -EINVAL;
13524         }
13525
13526         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13527         tr = bpf_trampoline_get(key, &tgt_info);
13528         if (!tr)
13529                 return -ENOMEM;
13530
13531         prog->aux->dst_trampoline = tr;
13532         return 0;
13533 }
13534
13535 struct btf *bpf_get_btf_vmlinux(void)
13536 {
13537         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13538                 mutex_lock(&bpf_verifier_lock);
13539                 if (!btf_vmlinux)
13540                         btf_vmlinux = btf_parse_vmlinux();
13541                 mutex_unlock(&bpf_verifier_lock);
13542         }
13543         return btf_vmlinux;
13544 }
13545
13546 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
13547 {
13548         u64 start_time = ktime_get_ns();
13549         struct bpf_verifier_env *env;
13550         struct bpf_verifier_log *log;
13551         int i, len, ret = -EINVAL;
13552         bool is_priv;
13553
13554         /* no program is valid */
13555         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13556                 return -EINVAL;
13557
13558         /* 'struct bpf_verifier_env' can be global, but since it's not small,
13559          * allocate/free it every time bpf_check() is called
13560          */
13561         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13562         if (!env)
13563                 return -ENOMEM;
13564         log = &env->log;
13565
13566         len = (*prog)->len;
13567         env->insn_aux_data =
13568                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13569         ret = -ENOMEM;
13570         if (!env->insn_aux_data)
13571                 goto err_free_env;
13572         for (i = 0; i < len; i++)
13573                 env->insn_aux_data[i].orig_idx = i;
13574         env->prog = *prog;
13575         env->ops = bpf_verifier_ops[env->prog->type];
13576         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
13577         is_priv = bpf_capable();
13578
13579         bpf_get_btf_vmlinux();
13580
13581         /* grab the mutex to protect few globals used by verifier */
13582         if (!is_priv)
13583                 mutex_lock(&bpf_verifier_lock);
13584
13585         if (attr->log_level || attr->log_buf || attr->log_size) {
13586                 /* user requested verbose verifier output
13587                  * and supplied buffer to store the verification trace
13588                  */
13589                 log->level = attr->log_level;
13590                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13591                 log->len_total = attr->log_size;
13592
13593                 ret = -EINVAL;
13594                 /* log attributes have to be sane */
13595                 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
13596                     !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
13597                         goto err_unlock;
13598         }
13599
13600         if (IS_ERR(btf_vmlinux)) {
13601                 /* Either gcc or pahole or kernel are broken. */
13602                 verbose(env, "in-kernel BTF is malformed\n");
13603                 ret = PTR_ERR(btf_vmlinux);
13604                 goto skip_full_check;
13605         }
13606
13607         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13608         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13609                 env->strict_alignment = true;
13610         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13611                 env->strict_alignment = false;
13612
13613         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13614         env->allow_uninit_stack = bpf_allow_uninit_stack();
13615         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13616         env->bypass_spec_v1 = bpf_bypass_spec_v1();
13617         env->bypass_spec_v4 = bpf_bypass_spec_v4();
13618         env->bpf_capable = bpf_capable();
13619
13620         if (is_priv)
13621                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13622
13623         env->explored_states = kvcalloc(state_htab_size(env),
13624                                        sizeof(struct bpf_verifier_state_list *),
13625                                        GFP_USER);
13626         ret = -ENOMEM;
13627         if (!env->explored_states)
13628                 goto skip_full_check;
13629
13630         ret = add_subprog_and_kfunc(env);
13631         if (ret < 0)
13632                 goto skip_full_check;
13633
13634         ret = check_subprogs(env);
13635         if (ret < 0)
13636                 goto skip_full_check;
13637
13638         ret = check_btf_info(env, attr, uattr);
13639         if (ret < 0)
13640                 goto skip_full_check;
13641
13642         ret = check_attach_btf_id(env);
13643         if (ret)
13644                 goto skip_full_check;
13645
13646         ret = resolve_pseudo_ldimm64(env);
13647         if (ret < 0)
13648                 goto skip_full_check;
13649
13650         if (bpf_prog_is_dev_bound(env->prog->aux)) {
13651                 ret = bpf_prog_offload_verifier_prep(env->prog);
13652                 if (ret)
13653                         goto skip_full_check;
13654         }
13655
13656         ret = check_cfg(env);
13657         if (ret < 0)
13658                 goto skip_full_check;
13659
13660         ret = do_check_subprogs(env);
13661         ret = ret ?: do_check_main(env);
13662
13663         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13664                 ret = bpf_prog_offload_finalize(env);
13665
13666 skip_full_check:
13667         kvfree(env->explored_states);
13668
13669         if (ret == 0)
13670                 ret = check_max_stack_depth(env);
13671
13672         /* instruction rewrites happen after this point */
13673         if (is_priv) {
13674                 if (ret == 0)
13675                         opt_hard_wire_dead_code_branches(env);
13676                 if (ret == 0)
13677                         ret = opt_remove_dead_code(env);
13678                 if (ret == 0)
13679                         ret = opt_remove_nops(env);
13680         } else {
13681                 if (ret == 0)
13682                         sanitize_dead_code(env);
13683         }
13684
13685         if (ret == 0)
13686                 /* program is valid, convert *(u32*)(ctx + off) accesses */
13687                 ret = convert_ctx_accesses(env);
13688
13689         if (ret == 0)
13690                 ret = do_misc_fixups(env);
13691
13692         /* do 32-bit optimization after insn patching has done so those patched
13693          * insns could be handled correctly.
13694          */
13695         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13696                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13697                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13698                                                                      : false;
13699         }
13700
13701         if (ret == 0)
13702                 ret = fixup_call_args(env);
13703
13704         env->verification_time = ktime_get_ns() - start_time;
13705         print_verification_stats(env);
13706
13707         if (log->level && bpf_verifier_log_full(log))
13708                 ret = -ENOSPC;
13709         if (log->level && !log->ubuf) {
13710                 ret = -EFAULT;
13711                 goto err_release_maps;
13712         }
13713
13714         if (ret)
13715                 goto err_release_maps;
13716
13717         if (env->used_map_cnt) {
13718                 /* if program passed verifier, update used_maps in bpf_prog_info */
13719                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13720                                                           sizeof(env->used_maps[0]),
13721                                                           GFP_KERNEL);
13722
13723                 if (!env->prog->aux->used_maps) {
13724                         ret = -ENOMEM;
13725                         goto err_release_maps;
13726                 }
13727
13728                 memcpy(env->prog->aux->used_maps, env->used_maps,
13729                        sizeof(env->used_maps[0]) * env->used_map_cnt);
13730                 env->prog->aux->used_map_cnt = env->used_map_cnt;
13731         }
13732         if (env->used_btf_cnt) {
13733                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13734                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13735                                                           sizeof(env->used_btfs[0]),
13736                                                           GFP_KERNEL);
13737                 if (!env->prog->aux->used_btfs) {
13738                         ret = -ENOMEM;
13739                         goto err_release_maps;
13740                 }
13741
13742                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13743                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13744                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13745         }
13746         if (env->used_map_cnt || env->used_btf_cnt) {
13747                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13748                  * bpf_ld_imm64 instructions
13749                  */
13750                 convert_pseudo_ld_imm64(env);
13751         }
13752
13753         adjust_btf_func(env);
13754
13755 err_release_maps:
13756         if (!env->prog->aux->used_maps)
13757                 /* if we didn't copy map pointers into bpf_prog_info, release
13758                  * them now. Otherwise free_used_maps() will release them.
13759                  */
13760                 release_maps(env);
13761         if (!env->prog->aux->used_btfs)
13762                 release_btfs(env);
13763
13764         /* extension progs temporarily inherit the attach_type of their targets
13765            for verification purposes, so set it back to zero before returning
13766          */
13767         if (env->prog->type == BPF_PROG_TYPE_EXT)
13768                 env->prog->expected_attach_type = 0;
13769
13770         *prog = env->prog;
13771 err_unlock:
13772         if (!is_priv)
13773                 mutex_unlock(&bpf_verifier_lock);
13774         vfree(env->insn_aux_data);
13775 err_free_env:
13776         kfree(env);
13777         return ret;
13778 }