bpf: Fix incorrect verifier simulation around jmp32's jeq/jne
[platform/kernel/linux-rpi.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/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_may_point_to_spin_lock(const struct bpf_reg_state *reg)
449 {
450         return reg->type == PTR_TO_MAP_VALUE &&
451                 map_value_has_spin_lock(reg->map_ptr);
452 }
453
454 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
455 {
456         return base_type(type) == PTR_TO_SOCKET ||
457                 base_type(type) == PTR_TO_TCP_SOCK ||
458                 base_type(type) == PTR_TO_MEM;
459 }
460
461 static bool type_is_rdonly_mem(u32 type)
462 {
463         return type & MEM_RDONLY;
464 }
465
466 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
467 {
468         return type == ARG_PTR_TO_SOCK_COMMON;
469 }
470
471 static bool type_may_be_null(u32 type)
472 {
473         return type & PTR_MAYBE_NULL;
474 }
475
476 /* Determine whether the function releases some resources allocated by another
477  * function call. The first reference type argument will be assumed to be
478  * released by release_reference().
479  */
480 static bool is_release_function(enum bpf_func_id func_id)
481 {
482         return func_id == BPF_FUNC_sk_release ||
483                func_id == BPF_FUNC_ringbuf_submit ||
484                func_id == BPF_FUNC_ringbuf_discard;
485 }
486
487 static bool may_be_acquire_function(enum bpf_func_id func_id)
488 {
489         return func_id == BPF_FUNC_sk_lookup_tcp ||
490                 func_id == BPF_FUNC_sk_lookup_udp ||
491                 func_id == BPF_FUNC_skc_lookup_tcp ||
492                 func_id == BPF_FUNC_map_lookup_elem ||
493                 func_id == BPF_FUNC_ringbuf_reserve;
494 }
495
496 static bool is_acquire_function(enum bpf_func_id func_id,
497                                 const struct bpf_map *map)
498 {
499         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
500
501         if (func_id == BPF_FUNC_sk_lookup_tcp ||
502             func_id == BPF_FUNC_sk_lookup_udp ||
503             func_id == BPF_FUNC_skc_lookup_tcp ||
504             func_id == BPF_FUNC_ringbuf_reserve)
505                 return true;
506
507         if (func_id == BPF_FUNC_map_lookup_elem &&
508             (map_type == BPF_MAP_TYPE_SOCKMAP ||
509              map_type == BPF_MAP_TYPE_SOCKHASH))
510                 return true;
511
512         return false;
513 }
514
515 static bool is_ptr_cast_function(enum bpf_func_id func_id)
516 {
517         return func_id == BPF_FUNC_tcp_sock ||
518                 func_id == BPF_FUNC_sk_fullsock ||
519                 func_id == BPF_FUNC_skc_to_tcp_sock ||
520                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
521                 func_id == BPF_FUNC_skc_to_udp6_sock ||
522                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
523                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
524 }
525
526 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
527 {
528         return BPF_CLASS(insn->code) == BPF_STX &&
529                BPF_MODE(insn->code) == BPF_ATOMIC &&
530                insn->imm == BPF_CMPXCHG;
531 }
532
533 /* string representation of 'enum bpf_reg_type'
534  *
535  * Note that reg_type_str() can not appear more than once in a single verbose()
536  * statement.
537  */
538 static const char *reg_type_str(struct bpf_verifier_env *env,
539                                 enum bpf_reg_type type)
540 {
541         char postfix[16] = {0}, prefix[16] = {0};
542         static const char * const str[] = {
543                 [NOT_INIT]              = "?",
544                 [SCALAR_VALUE]          = "inv",
545                 [PTR_TO_CTX]            = "ctx",
546                 [CONST_PTR_TO_MAP]      = "map_ptr",
547                 [PTR_TO_MAP_VALUE]      = "map_value",
548                 [PTR_TO_STACK]          = "fp",
549                 [PTR_TO_PACKET]         = "pkt",
550                 [PTR_TO_PACKET_META]    = "pkt_meta",
551                 [PTR_TO_PACKET_END]     = "pkt_end",
552                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
553                 [PTR_TO_SOCKET]         = "sock",
554                 [PTR_TO_SOCK_COMMON]    = "sock_common",
555                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
556                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
557                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
558                 [PTR_TO_BTF_ID]         = "ptr_",
559                 [PTR_TO_PERCPU_BTF_ID]  = "percpu_ptr_",
560                 [PTR_TO_MEM]            = "mem",
561                 [PTR_TO_BUF]            = "buf",
562                 [PTR_TO_FUNC]           = "func",
563                 [PTR_TO_MAP_KEY]        = "map_key",
564         };
565
566         if (type & PTR_MAYBE_NULL) {
567                 if (base_type(type) == PTR_TO_BTF_ID ||
568                     base_type(type) == PTR_TO_PERCPU_BTF_ID)
569                         strncpy(postfix, "or_null_", 16);
570                 else
571                         strncpy(postfix, "_or_null", 16);
572         }
573
574         if (type & MEM_RDONLY)
575                 strncpy(prefix, "rdonly_", 16);
576
577         snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
578                  prefix, str[base_type(type)], postfix);
579         return env->type_str_buf;
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(env, 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 (base_type(t) == PTR_TO_BTF_ID ||
640                             base_type(t) == PTR_TO_PERCPU_BTF_ID)
641                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
642                         verbose(env, "(id=%d", reg->id);
643                         if (reg_type_may_be_refcounted_or_null(t))
644                                 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
645                         if (t != SCALAR_VALUE)
646                                 verbose(env, ",off=%d", reg->off);
647                         if (type_is_pkt_pointer(t))
648                                 verbose(env, ",r=%d", reg->range);
649                         else if (base_type(t) == CONST_PTR_TO_MAP ||
650                                  base_type(t) == PTR_TO_MAP_KEY ||
651                                  base_type(t) == PTR_TO_MAP_VALUE)
652                                 verbose(env, ",ks=%d,vs=%d",
653                                         reg->map_ptr->key_size,
654                                         reg->map_ptr->value_size);
655                         if (tnum_is_const(reg->var_off)) {
656                                 /* Typically an immediate SCALAR_VALUE, but
657                                  * could be a pointer whose offset is too big
658                                  * for reg->off
659                                  */
660                                 verbose(env, ",imm=%llx", reg->var_off.value);
661                         } else {
662                                 if (reg->smin_value != reg->umin_value &&
663                                     reg->smin_value != S64_MIN)
664                                         verbose(env, ",smin_value=%lld",
665                                                 (long long)reg->smin_value);
666                                 if (reg->smax_value != reg->umax_value &&
667                                     reg->smax_value != S64_MAX)
668                                         verbose(env, ",smax_value=%lld",
669                                                 (long long)reg->smax_value);
670                                 if (reg->umin_value != 0)
671                                         verbose(env, ",umin_value=%llu",
672                                                 (unsigned long long)reg->umin_value);
673                                 if (reg->umax_value != U64_MAX)
674                                         verbose(env, ",umax_value=%llu",
675                                                 (unsigned long long)reg->umax_value);
676                                 if (!tnum_is_unknown(reg->var_off)) {
677                                         char tn_buf[48];
678
679                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
680                                         verbose(env, ",var_off=%s", tn_buf);
681                                 }
682                                 if (reg->s32_min_value != reg->smin_value &&
683                                     reg->s32_min_value != S32_MIN)
684                                         verbose(env, ",s32_min_value=%d",
685                                                 (int)(reg->s32_min_value));
686                                 if (reg->s32_max_value != reg->smax_value &&
687                                     reg->s32_max_value != S32_MAX)
688                                         verbose(env, ",s32_max_value=%d",
689                                                 (int)(reg->s32_max_value));
690                                 if (reg->u32_min_value != reg->umin_value &&
691                                     reg->u32_min_value != U32_MIN)
692                                         verbose(env, ",u32_min_value=%d",
693                                                 (int)(reg->u32_min_value));
694                                 if (reg->u32_max_value != reg->umax_value &&
695                                     reg->u32_max_value != U32_MAX)
696                                         verbose(env, ",u32_max_value=%d",
697                                                 (int)(reg->u32_max_value));
698                         }
699                         verbose(env, ")");
700                 }
701         }
702         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
703                 char types_buf[BPF_REG_SIZE + 1];
704                 bool valid = false;
705                 int j;
706
707                 for (j = 0; j < BPF_REG_SIZE; j++) {
708                         if (state->stack[i].slot_type[j] != STACK_INVALID)
709                                 valid = true;
710                         types_buf[j] = slot_type_char[
711                                         state->stack[i].slot_type[j]];
712                 }
713                 types_buf[BPF_REG_SIZE] = 0;
714                 if (!valid)
715                         continue;
716                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
717                 print_liveness(env, state->stack[i].spilled_ptr.live);
718                 if (state->stack[i].slot_type[0] == STACK_SPILL) {
719                         reg = &state->stack[i].spilled_ptr;
720                         t = reg->type;
721                         verbose(env, "=%s", reg_type_str(env, t));
722                         if (t == SCALAR_VALUE && reg->precise)
723                                 verbose(env, "P");
724                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
725                                 verbose(env, "%lld", reg->var_off.value + reg->off);
726                 } else {
727                         verbose(env, "=%s", types_buf);
728                 }
729         }
730         if (state->acquired_refs && state->refs[0].id) {
731                 verbose(env, " refs=%d", state->refs[0].id);
732                 for (i = 1; i < state->acquired_refs; i++)
733                         if (state->refs[i].id)
734                                 verbose(env, ",%d", state->refs[i].id);
735         }
736         if (state->in_callback_fn)
737                 verbose(env, " cb");
738         if (state->in_async_callback_fn)
739                 verbose(env, " async_cb");
740         verbose(env, "\n");
741 }
742
743 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
744  * small to hold src. This is different from krealloc since we don't want to preserve
745  * the contents of dst.
746  *
747  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
748  * not be allocated.
749  */
750 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
751 {
752         size_t bytes;
753
754         if (ZERO_OR_NULL_PTR(src))
755                 goto out;
756
757         if (unlikely(check_mul_overflow(n, size, &bytes)))
758                 return NULL;
759
760         if (ksize(dst) < bytes) {
761                 kfree(dst);
762                 dst = kmalloc_track_caller(bytes, flags);
763                 if (!dst)
764                         return NULL;
765         }
766
767         memcpy(dst, src, bytes);
768 out:
769         return dst ? dst : ZERO_SIZE_PTR;
770 }
771
772 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
773  * small to hold new_n items. new items are zeroed out if the array grows.
774  *
775  * Contrary to krealloc_array, does not free arr if new_n is zero.
776  */
777 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
778 {
779         if (!new_n || old_n == new_n)
780                 goto out;
781
782         arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
783         if (!arr)
784                 return NULL;
785
786         if (new_n > old_n)
787                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
788
789 out:
790         return arr ? arr : ZERO_SIZE_PTR;
791 }
792
793 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
794 {
795         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
796                                sizeof(struct bpf_reference_state), GFP_KERNEL);
797         if (!dst->refs)
798                 return -ENOMEM;
799
800         dst->acquired_refs = src->acquired_refs;
801         return 0;
802 }
803
804 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
805 {
806         size_t n = src->allocated_stack / BPF_REG_SIZE;
807
808         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
809                                 GFP_KERNEL);
810         if (!dst->stack)
811                 return -ENOMEM;
812
813         dst->allocated_stack = src->allocated_stack;
814         return 0;
815 }
816
817 static int resize_reference_state(struct bpf_func_state *state, size_t n)
818 {
819         state->refs = realloc_array(state->refs, state->acquired_refs, n,
820                                     sizeof(struct bpf_reference_state));
821         if (!state->refs)
822                 return -ENOMEM;
823
824         state->acquired_refs = n;
825         return 0;
826 }
827
828 static int grow_stack_state(struct bpf_func_state *state, int size)
829 {
830         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
831
832         if (old_n >= n)
833                 return 0;
834
835         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
836         if (!state->stack)
837                 return -ENOMEM;
838
839         state->allocated_stack = size;
840         return 0;
841 }
842
843 /* Acquire a pointer id from the env and update the state->refs to include
844  * this new pointer reference.
845  * On success, returns a valid pointer id to associate with the register
846  * On failure, returns a negative errno.
847  */
848 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
849 {
850         struct bpf_func_state *state = cur_func(env);
851         int new_ofs = state->acquired_refs;
852         int id, err;
853
854         err = resize_reference_state(state, state->acquired_refs + 1);
855         if (err)
856                 return err;
857         id = ++env->id_gen;
858         state->refs[new_ofs].id = id;
859         state->refs[new_ofs].insn_idx = insn_idx;
860
861         return id;
862 }
863
864 /* release function corresponding to acquire_reference_state(). Idempotent. */
865 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
866 {
867         int i, last_idx;
868
869         last_idx = state->acquired_refs - 1;
870         for (i = 0; i < state->acquired_refs; i++) {
871                 if (state->refs[i].id == ptr_id) {
872                         if (last_idx && i != last_idx)
873                                 memcpy(&state->refs[i], &state->refs[last_idx],
874                                        sizeof(*state->refs));
875                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
876                         state->acquired_refs--;
877                         return 0;
878                 }
879         }
880         return -EINVAL;
881 }
882
883 static void free_func_state(struct bpf_func_state *state)
884 {
885         if (!state)
886                 return;
887         kfree(state->refs);
888         kfree(state->stack);
889         kfree(state);
890 }
891
892 static void clear_jmp_history(struct bpf_verifier_state *state)
893 {
894         kfree(state->jmp_history);
895         state->jmp_history = NULL;
896         state->jmp_history_cnt = 0;
897 }
898
899 static void free_verifier_state(struct bpf_verifier_state *state,
900                                 bool free_self)
901 {
902         int i;
903
904         for (i = 0; i <= state->curframe; i++) {
905                 free_func_state(state->frame[i]);
906                 state->frame[i] = NULL;
907         }
908         clear_jmp_history(state);
909         if (free_self)
910                 kfree(state);
911 }
912
913 /* copy verifier state from src to dst growing dst stack space
914  * when necessary to accommodate larger src stack
915  */
916 static int copy_func_state(struct bpf_func_state *dst,
917                            const struct bpf_func_state *src)
918 {
919         int err;
920
921         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
922         err = copy_reference_state(dst, src);
923         if (err)
924                 return err;
925         return copy_stack_state(dst, src);
926 }
927
928 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
929                                const struct bpf_verifier_state *src)
930 {
931         struct bpf_func_state *dst;
932         int i, err;
933
934         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
935                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
936                                             GFP_USER);
937         if (!dst_state->jmp_history)
938                 return -ENOMEM;
939         dst_state->jmp_history_cnt = src->jmp_history_cnt;
940
941         /* if dst has more stack frames then src frame, free them */
942         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
943                 free_func_state(dst_state->frame[i]);
944                 dst_state->frame[i] = NULL;
945         }
946         dst_state->speculative = src->speculative;
947         dst_state->curframe = src->curframe;
948         dst_state->active_spin_lock = src->active_spin_lock;
949         dst_state->branches = src->branches;
950         dst_state->parent = src->parent;
951         dst_state->first_insn_idx = src->first_insn_idx;
952         dst_state->last_insn_idx = src->last_insn_idx;
953         for (i = 0; i <= src->curframe; i++) {
954                 dst = dst_state->frame[i];
955                 if (!dst) {
956                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
957                         if (!dst)
958                                 return -ENOMEM;
959                         dst_state->frame[i] = dst;
960                 }
961                 err = copy_func_state(dst, src->frame[i]);
962                 if (err)
963                         return err;
964         }
965         return 0;
966 }
967
968 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
969 {
970         while (st) {
971                 u32 br = --st->branches;
972
973                 /* WARN_ON(br > 1) technically makes sense here,
974                  * but see comment in push_stack(), hence:
975                  */
976                 WARN_ONCE((int)br < 0,
977                           "BUG update_branch_counts:branches_to_explore=%d\n",
978                           br);
979                 if (br)
980                         break;
981                 st = st->parent;
982         }
983 }
984
985 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
986                      int *insn_idx, bool pop_log)
987 {
988         struct bpf_verifier_state *cur = env->cur_state;
989         struct bpf_verifier_stack_elem *elem, *head = env->head;
990         int err;
991
992         if (env->head == NULL)
993                 return -ENOENT;
994
995         if (cur) {
996                 err = copy_verifier_state(cur, &head->st);
997                 if (err)
998                         return err;
999         }
1000         if (pop_log)
1001                 bpf_vlog_reset(&env->log, head->log_pos);
1002         if (insn_idx)
1003                 *insn_idx = head->insn_idx;
1004         if (prev_insn_idx)
1005                 *prev_insn_idx = head->prev_insn_idx;
1006         elem = head->next;
1007         free_verifier_state(&head->st, false);
1008         kfree(head);
1009         env->head = elem;
1010         env->stack_size--;
1011         return 0;
1012 }
1013
1014 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1015                                              int insn_idx, int prev_insn_idx,
1016                                              bool speculative)
1017 {
1018         struct bpf_verifier_state *cur = env->cur_state;
1019         struct bpf_verifier_stack_elem *elem;
1020         int err;
1021
1022         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1023         if (!elem)
1024                 goto err;
1025
1026         elem->insn_idx = insn_idx;
1027         elem->prev_insn_idx = prev_insn_idx;
1028         elem->next = env->head;
1029         elem->log_pos = env->log.len_used;
1030         env->head = elem;
1031         env->stack_size++;
1032         err = copy_verifier_state(&elem->st, cur);
1033         if (err)
1034                 goto err;
1035         elem->st.speculative |= speculative;
1036         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1037                 verbose(env, "The sequence of %d jumps is too complex.\n",
1038                         env->stack_size);
1039                 goto err;
1040         }
1041         if (elem->st.parent) {
1042                 ++elem->st.parent->branches;
1043                 /* WARN_ON(branches > 2) technically makes sense here,
1044                  * but
1045                  * 1. speculative states will bump 'branches' for non-branch
1046                  * instructions
1047                  * 2. is_state_visited() heuristics may decide not to create
1048                  * a new state for a sequence of branches and all such current
1049                  * and cloned states will be pointing to a single parent state
1050                  * which might have large 'branches' count.
1051                  */
1052         }
1053         return &elem->st;
1054 err:
1055         free_verifier_state(env->cur_state, true);
1056         env->cur_state = NULL;
1057         /* pop all elements and return */
1058         while (!pop_stack(env, NULL, NULL, false));
1059         return NULL;
1060 }
1061
1062 #define CALLER_SAVED_REGS 6
1063 static const int caller_saved[CALLER_SAVED_REGS] = {
1064         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1065 };
1066
1067 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1068                                 struct bpf_reg_state *reg);
1069
1070 /* This helper doesn't clear reg->id */
1071 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1072 {
1073         reg->var_off = tnum_const(imm);
1074         reg->smin_value = (s64)imm;
1075         reg->smax_value = (s64)imm;
1076         reg->umin_value = imm;
1077         reg->umax_value = imm;
1078
1079         reg->s32_min_value = (s32)imm;
1080         reg->s32_max_value = (s32)imm;
1081         reg->u32_min_value = (u32)imm;
1082         reg->u32_max_value = (u32)imm;
1083 }
1084
1085 /* Mark the unknown part of a register (variable offset or scalar value) as
1086  * known to have the value @imm.
1087  */
1088 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1089 {
1090         /* Clear id, off, and union(map_ptr, range) */
1091         memset(((u8 *)reg) + sizeof(reg->type), 0,
1092                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1093         ___mark_reg_known(reg, imm);
1094 }
1095
1096 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1097 {
1098         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1099         reg->s32_min_value = (s32)imm;
1100         reg->s32_max_value = (s32)imm;
1101         reg->u32_min_value = (u32)imm;
1102         reg->u32_max_value = (u32)imm;
1103 }
1104
1105 /* Mark the 'variable offset' part of a register as zero.  This should be
1106  * used only on registers holding a pointer type.
1107  */
1108 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1109 {
1110         __mark_reg_known(reg, 0);
1111 }
1112
1113 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1114 {
1115         __mark_reg_known(reg, 0);
1116         reg->type = SCALAR_VALUE;
1117 }
1118
1119 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1120                                 struct bpf_reg_state *regs, u32 regno)
1121 {
1122         if (WARN_ON(regno >= MAX_BPF_REG)) {
1123                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1124                 /* Something bad happened, let's kill all regs */
1125                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1126                         __mark_reg_not_init(env, regs + regno);
1127                 return;
1128         }
1129         __mark_reg_known_zero(regs + regno);
1130 }
1131
1132 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1133 {
1134         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1135                 const struct bpf_map *map = reg->map_ptr;
1136
1137                 if (map->inner_map_meta) {
1138                         reg->type = CONST_PTR_TO_MAP;
1139                         reg->map_ptr = map->inner_map_meta;
1140                         /* transfer reg's id which is unique for every map_lookup_elem
1141                          * as UID of the inner map.
1142                          */
1143                         if (map_value_has_timer(map->inner_map_meta))
1144                                 reg->map_uid = reg->id;
1145                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1146                         reg->type = PTR_TO_XDP_SOCK;
1147                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1148                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1149                         reg->type = PTR_TO_SOCKET;
1150                 } else {
1151                         reg->type = PTR_TO_MAP_VALUE;
1152                 }
1153                 return;
1154         }
1155
1156         reg->type &= ~PTR_MAYBE_NULL;
1157 }
1158
1159 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1160 {
1161         return type_is_pkt_pointer(reg->type);
1162 }
1163
1164 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1165 {
1166         return reg_is_pkt_pointer(reg) ||
1167                reg->type == PTR_TO_PACKET_END;
1168 }
1169
1170 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1171 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1172                                     enum bpf_reg_type which)
1173 {
1174         /* The register can already have a range from prior markings.
1175          * This is fine as long as it hasn't been advanced from its
1176          * origin.
1177          */
1178         return reg->type == which &&
1179                reg->id == 0 &&
1180                reg->off == 0 &&
1181                tnum_equals_const(reg->var_off, 0);
1182 }
1183
1184 /* Reset the min/max bounds of a register */
1185 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1186 {
1187         reg->smin_value = S64_MIN;
1188         reg->smax_value = S64_MAX;
1189         reg->umin_value = 0;
1190         reg->umax_value = U64_MAX;
1191
1192         reg->s32_min_value = S32_MIN;
1193         reg->s32_max_value = S32_MAX;
1194         reg->u32_min_value = 0;
1195         reg->u32_max_value = U32_MAX;
1196 }
1197
1198 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1199 {
1200         reg->smin_value = S64_MIN;
1201         reg->smax_value = S64_MAX;
1202         reg->umin_value = 0;
1203         reg->umax_value = U64_MAX;
1204 }
1205
1206 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1207 {
1208         reg->s32_min_value = S32_MIN;
1209         reg->s32_max_value = S32_MAX;
1210         reg->u32_min_value = 0;
1211         reg->u32_max_value = U32_MAX;
1212 }
1213
1214 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1215 {
1216         struct tnum var32_off = tnum_subreg(reg->var_off);
1217
1218         /* min signed is max(sign bit) | min(other bits) */
1219         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1220                         var32_off.value | (var32_off.mask & S32_MIN));
1221         /* max signed is min(sign bit) | max(other bits) */
1222         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1223                         var32_off.value | (var32_off.mask & S32_MAX));
1224         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1225         reg->u32_max_value = min(reg->u32_max_value,
1226                                  (u32)(var32_off.value | var32_off.mask));
1227 }
1228
1229 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1230 {
1231         /* min signed is max(sign bit) | min(other bits) */
1232         reg->smin_value = max_t(s64, reg->smin_value,
1233                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1234         /* max signed is min(sign bit) | max(other bits) */
1235         reg->smax_value = min_t(s64, reg->smax_value,
1236                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1237         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1238         reg->umax_value = min(reg->umax_value,
1239                               reg->var_off.value | reg->var_off.mask);
1240 }
1241
1242 static void __update_reg_bounds(struct bpf_reg_state *reg)
1243 {
1244         __update_reg32_bounds(reg);
1245         __update_reg64_bounds(reg);
1246 }
1247
1248 /* Uses signed min/max values to inform unsigned, and vice-versa */
1249 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1250 {
1251         /* Learn sign from signed bounds.
1252          * If we cannot cross the sign boundary, then signed and unsigned bounds
1253          * are the same, so combine.  This works even in the negative case, e.g.
1254          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1255          */
1256         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1257                 reg->s32_min_value = reg->u32_min_value =
1258                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1259                 reg->s32_max_value = reg->u32_max_value =
1260                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1261                 return;
1262         }
1263         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1264          * boundary, so we must be careful.
1265          */
1266         if ((s32)reg->u32_max_value >= 0) {
1267                 /* Positive.  We can't learn anything from the smin, but smax
1268                  * is positive, hence safe.
1269                  */
1270                 reg->s32_min_value = reg->u32_min_value;
1271                 reg->s32_max_value = reg->u32_max_value =
1272                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1273         } else if ((s32)reg->u32_min_value < 0) {
1274                 /* Negative.  We can't learn anything from the smax, but smin
1275                  * is negative, hence safe.
1276                  */
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         }
1281 }
1282
1283 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1284 {
1285         /* Learn sign from signed bounds.
1286          * If we cannot cross the sign boundary, then signed and unsigned bounds
1287          * are the same, so combine.  This works even in the negative case, e.g.
1288          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1289          */
1290         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1291                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1292                                                           reg->umin_value);
1293                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1294                                                           reg->umax_value);
1295                 return;
1296         }
1297         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1298          * boundary, so we must be careful.
1299          */
1300         if ((s64)reg->umax_value >= 0) {
1301                 /* Positive.  We can't learn anything from the smin, but smax
1302                  * is positive, hence safe.
1303                  */
1304                 reg->smin_value = reg->umin_value;
1305                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1306                                                           reg->umax_value);
1307         } else if ((s64)reg->umin_value < 0) {
1308                 /* Negative.  We can't learn anything from the smax, but smin
1309                  * is negative, hence safe.
1310                  */
1311                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1312                                                           reg->umin_value);
1313                 reg->smax_value = reg->umax_value;
1314         }
1315 }
1316
1317 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1318 {
1319         __reg32_deduce_bounds(reg);
1320         __reg64_deduce_bounds(reg);
1321 }
1322
1323 /* Attempts to improve var_off based on unsigned min/max information */
1324 static void __reg_bound_offset(struct bpf_reg_state *reg)
1325 {
1326         struct tnum var64_off = tnum_intersect(reg->var_off,
1327                                                tnum_range(reg->umin_value,
1328                                                           reg->umax_value));
1329         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1330                                                 tnum_range(reg->u32_min_value,
1331                                                            reg->u32_max_value));
1332
1333         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1334 }
1335
1336 static bool __reg32_bound_s64(s32 a)
1337 {
1338         return a >= 0 && a <= S32_MAX;
1339 }
1340
1341 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1342 {
1343         reg->umin_value = reg->u32_min_value;
1344         reg->umax_value = reg->u32_max_value;
1345
1346         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1347          * be positive otherwise set to worse case bounds and refine later
1348          * from tnum.
1349          */
1350         if (__reg32_bound_s64(reg->s32_min_value) &&
1351             __reg32_bound_s64(reg->s32_max_value)) {
1352                 reg->smin_value = reg->s32_min_value;
1353                 reg->smax_value = reg->s32_max_value;
1354         } else {
1355                 reg->smin_value = 0;
1356                 reg->smax_value = U32_MAX;
1357         }
1358 }
1359
1360 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1361 {
1362         /* special case when 64-bit register has upper 32-bit register
1363          * zeroed. Typically happens after zext or <<32, >>32 sequence
1364          * allowing us to use 32-bit bounds directly,
1365          */
1366         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1367                 __reg_assign_32_into_64(reg);
1368         } else {
1369                 /* Otherwise the best we can do is push lower 32bit known and
1370                  * unknown bits into register (var_off set from jmp logic)
1371                  * then learn as much as possible from the 64-bit tnum
1372                  * known and unknown bits. The previous smin/smax bounds are
1373                  * invalid here because of jmp32 compare so mark them unknown
1374                  * so they do not impact tnum bounds calculation.
1375                  */
1376                 __mark_reg64_unbounded(reg);
1377                 __update_reg_bounds(reg);
1378         }
1379
1380         /* Intersecting with the old var_off might have improved our bounds
1381          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1382          * then new var_off is (0; 0x7f...fc) which improves our umax.
1383          */
1384         __reg_deduce_bounds(reg);
1385         __reg_bound_offset(reg);
1386         __update_reg_bounds(reg);
1387 }
1388
1389 static bool __reg64_bound_s32(s64 a)
1390 {
1391         return a >= S32_MIN && a <= S32_MAX;
1392 }
1393
1394 static bool __reg64_bound_u32(u64 a)
1395 {
1396         return a >= U32_MIN && a <= U32_MAX;
1397 }
1398
1399 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1400 {
1401         __mark_reg32_unbounded(reg);
1402
1403         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1404                 reg->s32_min_value = (s32)reg->smin_value;
1405                 reg->s32_max_value = (s32)reg->smax_value;
1406         }
1407         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1408                 reg->u32_min_value = (u32)reg->umin_value;
1409                 reg->u32_max_value = (u32)reg->umax_value;
1410         }
1411
1412         /* Intersecting with the old var_off might have improved our bounds
1413          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1414          * then new var_off is (0; 0x7f...fc) which improves our umax.
1415          */
1416         __reg_deduce_bounds(reg);
1417         __reg_bound_offset(reg);
1418         __update_reg_bounds(reg);
1419 }
1420
1421 /* Mark a register as having a completely unknown (scalar) value. */
1422 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1423                                struct bpf_reg_state *reg)
1424 {
1425         /*
1426          * Clear type, id, off, and union(map_ptr, range) and
1427          * padding between 'type' and union
1428          */
1429         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1430         reg->type = SCALAR_VALUE;
1431         reg->var_off = tnum_unknown;
1432         reg->frameno = 0;
1433         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1434         __mark_reg_unbounded(reg);
1435 }
1436
1437 static void mark_reg_unknown(struct bpf_verifier_env *env,
1438                              struct bpf_reg_state *regs, u32 regno)
1439 {
1440         if (WARN_ON(regno >= MAX_BPF_REG)) {
1441                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1442                 /* Something bad happened, let's kill all regs except FP */
1443                 for (regno = 0; regno < BPF_REG_FP; regno++)
1444                         __mark_reg_not_init(env, regs + regno);
1445                 return;
1446         }
1447         __mark_reg_unknown(env, regs + regno);
1448 }
1449
1450 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1451                                 struct bpf_reg_state *reg)
1452 {
1453         __mark_reg_unknown(env, reg);
1454         reg->type = NOT_INIT;
1455 }
1456
1457 static void mark_reg_not_init(struct bpf_verifier_env *env,
1458                               struct bpf_reg_state *regs, u32 regno)
1459 {
1460         if (WARN_ON(regno >= MAX_BPF_REG)) {
1461                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1462                 /* Something bad happened, let's kill all regs except FP */
1463                 for (regno = 0; regno < BPF_REG_FP; regno++)
1464                         __mark_reg_not_init(env, regs + regno);
1465                 return;
1466         }
1467         __mark_reg_not_init(env, regs + regno);
1468 }
1469
1470 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1471                             struct bpf_reg_state *regs, u32 regno,
1472                             enum bpf_reg_type reg_type,
1473                             struct btf *btf, u32 btf_id)
1474 {
1475         if (reg_type == SCALAR_VALUE) {
1476                 mark_reg_unknown(env, regs, regno);
1477                 return;
1478         }
1479         mark_reg_known_zero(env, regs, regno);
1480         regs[regno].type = PTR_TO_BTF_ID;
1481         regs[regno].btf = btf;
1482         regs[regno].btf_id = btf_id;
1483 }
1484
1485 #define DEF_NOT_SUBREG  (0)
1486 static void init_reg_state(struct bpf_verifier_env *env,
1487                            struct bpf_func_state *state)
1488 {
1489         struct bpf_reg_state *regs = state->regs;
1490         int i;
1491
1492         for (i = 0; i < MAX_BPF_REG; i++) {
1493                 mark_reg_not_init(env, regs, i);
1494                 regs[i].live = REG_LIVE_NONE;
1495                 regs[i].parent = NULL;
1496                 regs[i].subreg_def = DEF_NOT_SUBREG;
1497         }
1498
1499         /* frame pointer */
1500         regs[BPF_REG_FP].type = PTR_TO_STACK;
1501         mark_reg_known_zero(env, regs, BPF_REG_FP);
1502         regs[BPF_REG_FP].frameno = state->frameno;
1503 }
1504
1505 #define BPF_MAIN_FUNC (-1)
1506 static void init_func_state(struct bpf_verifier_env *env,
1507                             struct bpf_func_state *state,
1508                             int callsite, int frameno, int subprogno)
1509 {
1510         state->callsite = callsite;
1511         state->frameno = frameno;
1512         state->subprogno = subprogno;
1513         init_reg_state(env, state);
1514 }
1515
1516 /* Similar to push_stack(), but for async callbacks */
1517 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1518                                                 int insn_idx, int prev_insn_idx,
1519                                                 int subprog)
1520 {
1521         struct bpf_verifier_stack_elem *elem;
1522         struct bpf_func_state *frame;
1523
1524         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1525         if (!elem)
1526                 goto err;
1527
1528         elem->insn_idx = insn_idx;
1529         elem->prev_insn_idx = prev_insn_idx;
1530         elem->next = env->head;
1531         elem->log_pos = env->log.len_used;
1532         env->head = elem;
1533         env->stack_size++;
1534         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1535                 verbose(env,
1536                         "The sequence of %d jumps is too complex for async cb.\n",
1537                         env->stack_size);
1538                 goto err;
1539         }
1540         /* Unlike push_stack() do not copy_verifier_state().
1541          * The caller state doesn't matter.
1542          * This is async callback. It starts in a fresh stack.
1543          * Initialize it similar to do_check_common().
1544          */
1545         elem->st.branches = 1;
1546         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1547         if (!frame)
1548                 goto err;
1549         init_func_state(env, frame,
1550                         BPF_MAIN_FUNC /* callsite */,
1551                         0 /* frameno within this callchain */,
1552                         subprog /* subprog number within this prog */);
1553         elem->st.frame[0] = frame;
1554         return &elem->st;
1555 err:
1556         free_verifier_state(env->cur_state, true);
1557         env->cur_state = NULL;
1558         /* pop all elements and return */
1559         while (!pop_stack(env, NULL, NULL, false));
1560         return NULL;
1561 }
1562
1563
1564 enum reg_arg_type {
1565         SRC_OP,         /* register is used as source operand */
1566         DST_OP,         /* register is used as destination operand */
1567         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1568 };
1569
1570 static int cmp_subprogs(const void *a, const void *b)
1571 {
1572         return ((struct bpf_subprog_info *)a)->start -
1573                ((struct bpf_subprog_info *)b)->start;
1574 }
1575
1576 static int find_subprog(struct bpf_verifier_env *env, int off)
1577 {
1578         struct bpf_subprog_info *p;
1579
1580         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1581                     sizeof(env->subprog_info[0]), cmp_subprogs);
1582         if (!p)
1583                 return -ENOENT;
1584         return p - env->subprog_info;
1585
1586 }
1587
1588 static int add_subprog(struct bpf_verifier_env *env, int off)
1589 {
1590         int insn_cnt = env->prog->len;
1591         int ret;
1592
1593         if (off >= insn_cnt || off < 0) {
1594                 verbose(env, "call to invalid destination\n");
1595                 return -EINVAL;
1596         }
1597         ret = find_subprog(env, off);
1598         if (ret >= 0)
1599                 return ret;
1600         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1601                 verbose(env, "too many subprograms\n");
1602                 return -E2BIG;
1603         }
1604         /* determine subprog starts. The end is one before the next starts */
1605         env->subprog_info[env->subprog_cnt++].start = off;
1606         sort(env->subprog_info, env->subprog_cnt,
1607              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1608         return env->subprog_cnt - 1;
1609 }
1610
1611 struct bpf_kfunc_desc {
1612         struct btf_func_model func_model;
1613         u32 func_id;
1614         s32 imm;
1615 };
1616
1617 #define MAX_KFUNC_DESCS 256
1618 struct bpf_kfunc_desc_tab {
1619         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1620         u32 nr_descs;
1621 };
1622
1623 static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1624 {
1625         const struct bpf_kfunc_desc *d0 = a;
1626         const struct bpf_kfunc_desc *d1 = b;
1627
1628         /* func_id is not greater than BTF_MAX_TYPE */
1629         return d0->func_id - d1->func_id;
1630 }
1631
1632 static const struct bpf_kfunc_desc *
1633 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1634 {
1635         struct bpf_kfunc_desc desc = {
1636                 .func_id = func_id,
1637         };
1638         struct bpf_kfunc_desc_tab *tab;
1639
1640         tab = prog->aux->kfunc_tab;
1641         return bsearch(&desc, tab->descs, tab->nr_descs,
1642                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1643 }
1644
1645 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1646 {
1647         const struct btf_type *func, *func_proto;
1648         struct bpf_kfunc_desc_tab *tab;
1649         struct bpf_prog_aux *prog_aux;
1650         struct bpf_kfunc_desc *desc;
1651         const char *func_name;
1652         unsigned long addr;
1653         int err;
1654
1655         prog_aux = env->prog->aux;
1656         tab = prog_aux->kfunc_tab;
1657         if (!tab) {
1658                 if (!btf_vmlinux) {
1659                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1660                         return -ENOTSUPP;
1661                 }
1662
1663                 if (!env->prog->jit_requested) {
1664                         verbose(env, "JIT is required for calling kernel function\n");
1665                         return -ENOTSUPP;
1666                 }
1667
1668                 if (!bpf_jit_supports_kfunc_call()) {
1669                         verbose(env, "JIT does not support calling kernel function\n");
1670                         return -ENOTSUPP;
1671                 }
1672
1673                 if (!env->prog->gpl_compatible) {
1674                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1675                         return -EINVAL;
1676                 }
1677
1678                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1679                 if (!tab)
1680                         return -ENOMEM;
1681                 prog_aux->kfunc_tab = tab;
1682         }
1683
1684         if (find_kfunc_desc(env->prog, func_id))
1685                 return 0;
1686
1687         if (tab->nr_descs == MAX_KFUNC_DESCS) {
1688                 verbose(env, "too many different kernel function calls\n");
1689                 return -E2BIG;
1690         }
1691
1692         func = btf_type_by_id(btf_vmlinux, func_id);
1693         if (!func || !btf_type_is_func(func)) {
1694                 verbose(env, "kernel btf_id %u is not a function\n",
1695                         func_id);
1696                 return -EINVAL;
1697         }
1698         func_proto = btf_type_by_id(btf_vmlinux, func->type);
1699         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1700                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1701                         func_id);
1702                 return -EINVAL;
1703         }
1704
1705         func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1706         addr = kallsyms_lookup_name(func_name);
1707         if (!addr) {
1708                 verbose(env, "cannot find address for kernel function %s\n",
1709                         func_name);
1710                 return -EINVAL;
1711         }
1712
1713         desc = &tab->descs[tab->nr_descs++];
1714         desc->func_id = func_id;
1715         desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1716         err = btf_distill_func_proto(&env->log, btf_vmlinux,
1717                                      func_proto, func_name,
1718                                      &desc->func_model);
1719         if (!err)
1720                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1721                      kfunc_desc_cmp_by_id, NULL);
1722         return err;
1723 }
1724
1725 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1726 {
1727         const struct bpf_kfunc_desc *d0 = a;
1728         const struct bpf_kfunc_desc *d1 = b;
1729
1730         if (d0->imm > d1->imm)
1731                 return 1;
1732         else if (d0->imm < d1->imm)
1733                 return -1;
1734         return 0;
1735 }
1736
1737 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1738 {
1739         struct bpf_kfunc_desc_tab *tab;
1740
1741         tab = prog->aux->kfunc_tab;
1742         if (!tab)
1743                 return;
1744
1745         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1746              kfunc_desc_cmp_by_imm, NULL);
1747 }
1748
1749 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1750 {
1751         return !!prog->aux->kfunc_tab;
1752 }
1753
1754 const struct btf_func_model *
1755 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1756                          const struct bpf_insn *insn)
1757 {
1758         const struct bpf_kfunc_desc desc = {
1759                 .imm = insn->imm,
1760         };
1761         const struct bpf_kfunc_desc *res;
1762         struct bpf_kfunc_desc_tab *tab;
1763
1764         tab = prog->aux->kfunc_tab;
1765         res = bsearch(&desc, tab->descs, tab->nr_descs,
1766                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1767
1768         return res ? &res->func_model : NULL;
1769 }
1770
1771 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1772 {
1773         struct bpf_subprog_info *subprog = env->subprog_info;
1774         struct bpf_insn *insn = env->prog->insnsi;
1775         int i, ret, insn_cnt = env->prog->len;
1776
1777         /* Add entry function. */
1778         ret = add_subprog(env, 0);
1779         if (ret)
1780                 return ret;
1781
1782         for (i = 0; i < insn_cnt; i++, insn++) {
1783                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1784                     !bpf_pseudo_kfunc_call(insn))
1785                         continue;
1786
1787                 if (!env->bpf_capable) {
1788                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1789                         return -EPERM;
1790                 }
1791
1792                 if (bpf_pseudo_func(insn)) {
1793                         ret = add_subprog(env, i + insn->imm + 1);
1794                         if (ret >= 0)
1795                                 /* remember subprog */
1796                                 insn[1].imm = ret;
1797                 } else if (bpf_pseudo_call(insn)) {
1798                         ret = add_subprog(env, i + insn->imm + 1);
1799                 } else {
1800                         ret = add_kfunc_call(env, insn->imm);
1801                 }
1802
1803                 if (ret < 0)
1804                         return ret;
1805         }
1806
1807         /* Add a fake 'exit' subprog which could simplify subprog iteration
1808          * logic. 'subprog_cnt' should not be increased.
1809          */
1810         subprog[env->subprog_cnt].start = insn_cnt;
1811
1812         if (env->log.level & BPF_LOG_LEVEL2)
1813                 for (i = 0; i < env->subprog_cnt; i++)
1814                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
1815
1816         return 0;
1817 }
1818
1819 static int check_subprogs(struct bpf_verifier_env *env)
1820 {
1821         int i, subprog_start, subprog_end, off, cur_subprog = 0;
1822         struct bpf_subprog_info *subprog = env->subprog_info;
1823         struct bpf_insn *insn = env->prog->insnsi;
1824         int insn_cnt = env->prog->len;
1825
1826         /* now check that all jumps are within the same subprog */
1827         subprog_start = subprog[cur_subprog].start;
1828         subprog_end = subprog[cur_subprog + 1].start;
1829         for (i = 0; i < insn_cnt; i++) {
1830                 u8 code = insn[i].code;
1831
1832                 if (code == (BPF_JMP | BPF_CALL) &&
1833                     insn[i].imm == BPF_FUNC_tail_call &&
1834                     insn[i].src_reg != BPF_PSEUDO_CALL)
1835                         subprog[cur_subprog].has_tail_call = true;
1836                 if (BPF_CLASS(code) == BPF_LD &&
1837                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1838                         subprog[cur_subprog].has_ld_abs = true;
1839                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1840                         goto next;
1841                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1842                         goto next;
1843                 off = i + insn[i].off + 1;
1844                 if (off < subprog_start || off >= subprog_end) {
1845                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
1846                         return -EINVAL;
1847                 }
1848 next:
1849                 if (i == subprog_end - 1) {
1850                         /* to avoid fall-through from one subprog into another
1851                          * the last insn of the subprog should be either exit
1852                          * or unconditional jump back
1853                          */
1854                         if (code != (BPF_JMP | BPF_EXIT) &&
1855                             code != (BPF_JMP | BPF_JA)) {
1856                                 verbose(env, "last insn is not an exit or jmp\n");
1857                                 return -EINVAL;
1858                         }
1859                         subprog_start = subprog_end;
1860                         cur_subprog++;
1861                         if (cur_subprog < env->subprog_cnt)
1862                                 subprog_end = subprog[cur_subprog + 1].start;
1863                 }
1864         }
1865         return 0;
1866 }
1867
1868 /* Parentage chain of this register (or stack slot) should take care of all
1869  * issues like callee-saved registers, stack slot allocation time, etc.
1870  */
1871 static int mark_reg_read(struct bpf_verifier_env *env,
1872                          const struct bpf_reg_state *state,
1873                          struct bpf_reg_state *parent, u8 flag)
1874 {
1875         bool writes = parent == state->parent; /* Observe write marks */
1876         int cnt = 0;
1877
1878         while (parent) {
1879                 /* if read wasn't screened by an earlier write ... */
1880                 if (writes && state->live & REG_LIVE_WRITTEN)
1881                         break;
1882                 if (parent->live & REG_LIVE_DONE) {
1883                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1884                                 reg_type_str(env, parent->type),
1885                                 parent->var_off.value, parent->off);
1886                         return -EFAULT;
1887                 }
1888                 /* The first condition is more likely to be true than the
1889                  * second, checked it first.
1890                  */
1891                 if ((parent->live & REG_LIVE_READ) == flag ||
1892                     parent->live & REG_LIVE_READ64)
1893                         /* The parentage chain never changes and
1894                          * this parent was already marked as LIVE_READ.
1895                          * There is no need to keep walking the chain again and
1896                          * keep re-marking all parents as LIVE_READ.
1897                          * This case happens when the same register is read
1898                          * multiple times without writes into it in-between.
1899                          * Also, if parent has the stronger REG_LIVE_READ64 set,
1900                          * then no need to set the weak REG_LIVE_READ32.
1901                          */
1902                         break;
1903                 /* ... then we depend on parent's value */
1904                 parent->live |= flag;
1905                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1906                 if (flag == REG_LIVE_READ64)
1907                         parent->live &= ~REG_LIVE_READ32;
1908                 state = parent;
1909                 parent = state->parent;
1910                 writes = true;
1911                 cnt++;
1912         }
1913
1914         if (env->longest_mark_read_walk < cnt)
1915                 env->longest_mark_read_walk = cnt;
1916         return 0;
1917 }
1918
1919 /* This function is supposed to be used by the following 32-bit optimization
1920  * code only. It returns TRUE if the source or destination register operates
1921  * on 64-bit, otherwise return FALSE.
1922  */
1923 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1924                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1925 {
1926         u8 code, class, op;
1927
1928         code = insn->code;
1929         class = BPF_CLASS(code);
1930         op = BPF_OP(code);
1931         if (class == BPF_JMP) {
1932                 /* BPF_EXIT for "main" will reach here. Return TRUE
1933                  * conservatively.
1934                  */
1935                 if (op == BPF_EXIT)
1936                         return true;
1937                 if (op == BPF_CALL) {
1938                         /* BPF to BPF call will reach here because of marking
1939                          * caller saved clobber with DST_OP_NO_MARK for which we
1940                          * don't care the register def because they are anyway
1941                          * marked as NOT_INIT already.
1942                          */
1943                         if (insn->src_reg == BPF_PSEUDO_CALL)
1944                                 return false;
1945                         /* Helper call will reach here because of arg type
1946                          * check, conservatively return TRUE.
1947                          */
1948                         if (t == SRC_OP)
1949                                 return true;
1950
1951                         return false;
1952                 }
1953         }
1954
1955         if (class == BPF_ALU64 || class == BPF_JMP ||
1956             /* BPF_END always use BPF_ALU class. */
1957             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1958                 return true;
1959
1960         if (class == BPF_ALU || class == BPF_JMP32)
1961                 return false;
1962
1963         if (class == BPF_LDX) {
1964                 if (t != SRC_OP)
1965                         return BPF_SIZE(code) == BPF_DW;
1966                 /* LDX source must be ptr. */
1967                 return true;
1968         }
1969
1970         if (class == BPF_STX) {
1971                 /* BPF_STX (including atomic variants) has multiple source
1972                  * operands, one of which is a ptr. Check whether the caller is
1973                  * asking about it.
1974                  */
1975                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
1976                         return true;
1977                 return BPF_SIZE(code) == BPF_DW;
1978         }
1979
1980         if (class == BPF_LD) {
1981                 u8 mode = BPF_MODE(code);
1982
1983                 /* LD_IMM64 */
1984                 if (mode == BPF_IMM)
1985                         return true;
1986
1987                 /* Both LD_IND and LD_ABS return 32-bit data. */
1988                 if (t != SRC_OP)
1989                         return  false;
1990
1991                 /* Implicit ctx ptr. */
1992                 if (regno == BPF_REG_6)
1993                         return true;
1994
1995                 /* Explicit source could be any width. */
1996                 return true;
1997         }
1998
1999         if (class == BPF_ST)
2000                 /* The only source register for BPF_ST is a ptr. */
2001                 return true;
2002
2003         /* Conservatively return true at default. */
2004         return true;
2005 }
2006
2007 /* Return the regno defined by the insn, or -1. */
2008 static int insn_def_regno(const struct bpf_insn *insn)
2009 {
2010         switch (BPF_CLASS(insn->code)) {
2011         case BPF_JMP:
2012         case BPF_JMP32:
2013         case BPF_ST:
2014                 return -1;
2015         case BPF_STX:
2016                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2017                     (insn->imm & BPF_FETCH)) {
2018                         if (insn->imm == BPF_CMPXCHG)
2019                                 return BPF_REG_0;
2020                         else
2021                                 return insn->src_reg;
2022                 } else {
2023                         return -1;
2024                 }
2025         default:
2026                 return insn->dst_reg;
2027         }
2028 }
2029
2030 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2031 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2032 {
2033         int dst_reg = insn_def_regno(insn);
2034
2035         if (dst_reg == -1)
2036                 return false;
2037
2038         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2039 }
2040
2041 static void mark_insn_zext(struct bpf_verifier_env *env,
2042                            struct bpf_reg_state *reg)
2043 {
2044         s32 def_idx = reg->subreg_def;
2045
2046         if (def_idx == DEF_NOT_SUBREG)
2047                 return;
2048
2049         env->insn_aux_data[def_idx - 1].zext_dst = true;
2050         /* The dst will be zero extended, so won't be sub-register anymore. */
2051         reg->subreg_def = DEF_NOT_SUBREG;
2052 }
2053
2054 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2055                          enum reg_arg_type t)
2056 {
2057         struct bpf_verifier_state *vstate = env->cur_state;
2058         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2059         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2060         struct bpf_reg_state *reg, *regs = state->regs;
2061         bool rw64;
2062
2063         if (regno >= MAX_BPF_REG) {
2064                 verbose(env, "R%d is invalid\n", regno);
2065                 return -EINVAL;
2066         }
2067
2068         reg = &regs[regno];
2069         rw64 = is_reg64(env, insn, regno, reg, t);
2070         if (t == SRC_OP) {
2071                 /* check whether register used as source operand can be read */
2072                 if (reg->type == NOT_INIT) {
2073                         verbose(env, "R%d !read_ok\n", regno);
2074                         return -EACCES;
2075                 }
2076                 /* We don't need to worry about FP liveness because it's read-only */
2077                 if (regno == BPF_REG_FP)
2078                         return 0;
2079
2080                 if (rw64)
2081                         mark_insn_zext(env, reg);
2082
2083                 return mark_reg_read(env, reg, reg->parent,
2084                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2085         } else {
2086                 /* check whether register used as dest operand can be written to */
2087                 if (regno == BPF_REG_FP) {
2088                         verbose(env, "frame pointer is read only\n");
2089                         return -EACCES;
2090                 }
2091                 reg->live |= REG_LIVE_WRITTEN;
2092                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2093                 if (t == DST_OP)
2094                         mark_reg_unknown(env, regs, regno);
2095         }
2096         return 0;
2097 }
2098
2099 /* for any branch, call, exit record the history of jmps in the given state */
2100 static int push_jmp_history(struct bpf_verifier_env *env,
2101                             struct bpf_verifier_state *cur)
2102 {
2103         u32 cnt = cur->jmp_history_cnt;
2104         struct bpf_idx_pair *p;
2105
2106         cnt++;
2107         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2108         if (!p)
2109                 return -ENOMEM;
2110         p[cnt - 1].idx = env->insn_idx;
2111         p[cnt - 1].prev_idx = env->prev_insn_idx;
2112         cur->jmp_history = p;
2113         cur->jmp_history_cnt = cnt;
2114         return 0;
2115 }
2116
2117 /* Backtrack one insn at a time. If idx is not at the top of recorded
2118  * history then previous instruction came from straight line execution.
2119  */
2120 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2121                              u32 *history)
2122 {
2123         u32 cnt = *history;
2124
2125         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2126                 i = st->jmp_history[cnt - 1].prev_idx;
2127                 (*history)--;
2128         } else {
2129                 i--;
2130         }
2131         return i;
2132 }
2133
2134 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2135 {
2136         const struct btf_type *func;
2137
2138         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2139                 return NULL;
2140
2141         func = btf_type_by_id(btf_vmlinux, insn->imm);
2142         return btf_name_by_offset(btf_vmlinux, func->name_off);
2143 }
2144
2145 /* For given verifier state backtrack_insn() is called from the last insn to
2146  * the first insn. Its purpose is to compute a bitmask of registers and
2147  * stack slots that needs precision in the parent verifier state.
2148  */
2149 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2150                           u32 *reg_mask, u64 *stack_mask)
2151 {
2152         const struct bpf_insn_cbs cbs = {
2153                 .cb_call        = disasm_kfunc_name,
2154                 .cb_print       = verbose,
2155                 .private_data   = env,
2156         };
2157         struct bpf_insn *insn = env->prog->insnsi + idx;
2158         u8 class = BPF_CLASS(insn->code);
2159         u8 opcode = BPF_OP(insn->code);
2160         u8 mode = BPF_MODE(insn->code);
2161         u32 dreg = 1u << insn->dst_reg;
2162         u32 sreg = 1u << insn->src_reg;
2163         u32 spi;
2164
2165         if (insn->code == 0)
2166                 return 0;
2167         if (env->log.level & BPF_LOG_LEVEL) {
2168                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2169                 verbose(env, "%d: ", idx);
2170                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2171         }
2172
2173         if (class == BPF_ALU || class == BPF_ALU64) {
2174                 if (!(*reg_mask & dreg))
2175                         return 0;
2176                 if (opcode == BPF_MOV) {
2177                         if (BPF_SRC(insn->code) == BPF_X) {
2178                                 /* dreg = sreg
2179                                  * dreg needs precision after this insn
2180                                  * sreg needs precision before this insn
2181                                  */
2182                                 *reg_mask &= ~dreg;
2183                                 *reg_mask |= sreg;
2184                         } else {
2185                                 /* dreg = K
2186                                  * dreg needs precision after this insn.
2187                                  * Corresponding register is already marked
2188                                  * as precise=true in this verifier state.
2189                                  * No further markings in parent are necessary
2190                                  */
2191                                 *reg_mask &= ~dreg;
2192                         }
2193                 } else {
2194                         if (BPF_SRC(insn->code) == BPF_X) {
2195                                 /* dreg += sreg
2196                                  * both dreg and sreg need precision
2197                                  * before this insn
2198                                  */
2199                                 *reg_mask |= sreg;
2200                         } /* else dreg += K
2201                            * dreg still needs precision before this insn
2202                            */
2203                 }
2204         } else if (class == BPF_LDX) {
2205                 if (!(*reg_mask & dreg))
2206                         return 0;
2207                 *reg_mask &= ~dreg;
2208
2209                 /* scalars can only be spilled into stack w/o losing precision.
2210                  * Load from any other memory can be zero extended.
2211                  * The desire to keep that precision is already indicated
2212                  * by 'precise' mark in corresponding register of this state.
2213                  * No further tracking necessary.
2214                  */
2215                 if (insn->src_reg != BPF_REG_FP)
2216                         return 0;
2217                 if (BPF_SIZE(insn->code) != BPF_DW)
2218                         return 0;
2219
2220                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2221                  * that [fp - off] slot contains scalar that needs to be
2222                  * tracked with precision
2223                  */
2224                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2225                 if (spi >= 64) {
2226                         verbose(env, "BUG spi %d\n", spi);
2227                         WARN_ONCE(1, "verifier backtracking bug");
2228                         return -EFAULT;
2229                 }
2230                 *stack_mask |= 1ull << spi;
2231         } else if (class == BPF_STX || class == BPF_ST) {
2232                 if (*reg_mask & dreg)
2233                         /* stx & st shouldn't be using _scalar_ dst_reg
2234                          * to access memory. It means backtracking
2235                          * encountered a case of pointer subtraction.
2236                          */
2237                         return -ENOTSUPP;
2238                 /* scalars can only be spilled into stack */
2239                 if (insn->dst_reg != BPF_REG_FP)
2240                         return 0;
2241                 if (BPF_SIZE(insn->code) != BPF_DW)
2242                         return 0;
2243                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2244                 if (spi >= 64) {
2245                         verbose(env, "BUG spi %d\n", spi);
2246                         WARN_ONCE(1, "verifier backtracking bug");
2247                         return -EFAULT;
2248                 }
2249                 if (!(*stack_mask & (1ull << spi)))
2250                         return 0;
2251                 *stack_mask &= ~(1ull << spi);
2252                 if (class == BPF_STX)
2253                         *reg_mask |= sreg;
2254         } else if (class == BPF_JMP || class == BPF_JMP32) {
2255                 if (opcode == BPF_CALL) {
2256                         if (insn->src_reg == BPF_PSEUDO_CALL)
2257                                 return -ENOTSUPP;
2258                         /* regular helper call sets R0 */
2259                         *reg_mask &= ~1;
2260                         if (*reg_mask & 0x3f) {
2261                                 /* if backtracing was looking for registers R1-R5
2262                                  * they should have been found already.
2263                                  */
2264                                 verbose(env, "BUG regs %x\n", *reg_mask);
2265                                 WARN_ONCE(1, "verifier backtracking bug");
2266                                 return -EFAULT;
2267                         }
2268                 } else if (opcode == BPF_EXIT) {
2269                         return -ENOTSUPP;
2270                 }
2271         } else if (class == BPF_LD) {
2272                 if (!(*reg_mask & dreg))
2273                         return 0;
2274                 *reg_mask &= ~dreg;
2275                 /* It's ld_imm64 or ld_abs or ld_ind.
2276                  * For ld_imm64 no further tracking of precision
2277                  * into parent is necessary
2278                  */
2279                 if (mode == BPF_IND || mode == BPF_ABS)
2280                         /* to be analyzed */
2281                         return -ENOTSUPP;
2282         }
2283         return 0;
2284 }
2285
2286 /* the scalar precision tracking algorithm:
2287  * . at the start all registers have precise=false.
2288  * . scalar ranges are tracked as normal through alu and jmp insns.
2289  * . once precise value of the scalar register is used in:
2290  *   .  ptr + scalar alu
2291  *   . if (scalar cond K|scalar)
2292  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2293  *   backtrack through the verifier states and mark all registers and
2294  *   stack slots with spilled constants that these scalar regisers
2295  *   should be precise.
2296  * . during state pruning two registers (or spilled stack slots)
2297  *   are equivalent if both are not precise.
2298  *
2299  * Note the verifier cannot simply walk register parentage chain,
2300  * since many different registers and stack slots could have been
2301  * used to compute single precise scalar.
2302  *
2303  * The approach of starting with precise=true for all registers and then
2304  * backtrack to mark a register as not precise when the verifier detects
2305  * that program doesn't care about specific value (e.g., when helper
2306  * takes register as ARG_ANYTHING parameter) is not safe.
2307  *
2308  * It's ok to walk single parentage chain of the verifier states.
2309  * It's possible that this backtracking will go all the way till 1st insn.
2310  * All other branches will be explored for needing precision later.
2311  *
2312  * The backtracking needs to deal with cases like:
2313  *   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)
2314  * r9 -= r8
2315  * r5 = r9
2316  * if r5 > 0x79f goto pc+7
2317  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2318  * r5 += 1
2319  * ...
2320  * call bpf_perf_event_output#25
2321  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2322  *
2323  * and this case:
2324  * r6 = 1
2325  * call foo // uses callee's r6 inside to compute r0
2326  * r0 += r6
2327  * if r0 == 0 goto
2328  *
2329  * to track above reg_mask/stack_mask needs to be independent for each frame.
2330  *
2331  * Also if parent's curframe > frame where backtracking started,
2332  * the verifier need to mark registers in both frames, otherwise callees
2333  * may incorrectly prune callers. This is similar to
2334  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2335  *
2336  * For now backtracking falls back into conservative marking.
2337  */
2338 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2339                                      struct bpf_verifier_state *st)
2340 {
2341         struct bpf_func_state *func;
2342         struct bpf_reg_state *reg;
2343         int i, j;
2344
2345         /* big hammer: mark all scalars precise in this path.
2346          * pop_stack may still get !precise scalars.
2347          */
2348         for (; st; st = st->parent)
2349                 for (i = 0; i <= st->curframe; i++) {
2350                         func = st->frame[i];
2351                         for (j = 0; j < BPF_REG_FP; j++) {
2352                                 reg = &func->regs[j];
2353                                 if (reg->type != SCALAR_VALUE)
2354                                         continue;
2355                                 reg->precise = true;
2356                         }
2357                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2358                                 if (func->stack[j].slot_type[0] != STACK_SPILL)
2359                                         continue;
2360                                 reg = &func->stack[j].spilled_ptr;
2361                                 if (reg->type != SCALAR_VALUE)
2362                                         continue;
2363                                 reg->precise = true;
2364                         }
2365                 }
2366 }
2367
2368 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2369                                   int spi)
2370 {
2371         struct bpf_verifier_state *st = env->cur_state;
2372         int first_idx = st->first_insn_idx;
2373         int last_idx = env->insn_idx;
2374         struct bpf_func_state *func;
2375         struct bpf_reg_state *reg;
2376         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2377         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2378         bool skip_first = true;
2379         bool new_marks = false;
2380         int i, err;
2381
2382         if (!env->bpf_capable)
2383                 return 0;
2384
2385         func = st->frame[st->curframe];
2386         if (regno >= 0) {
2387                 reg = &func->regs[regno];
2388                 if (reg->type != SCALAR_VALUE) {
2389                         WARN_ONCE(1, "backtracing misuse");
2390                         return -EFAULT;
2391                 }
2392                 if (!reg->precise)
2393                         new_marks = true;
2394                 else
2395                         reg_mask = 0;
2396                 reg->precise = true;
2397         }
2398
2399         while (spi >= 0) {
2400                 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2401                         stack_mask = 0;
2402                         break;
2403                 }
2404                 reg = &func->stack[spi].spilled_ptr;
2405                 if (reg->type != SCALAR_VALUE) {
2406                         stack_mask = 0;
2407                         break;
2408                 }
2409                 if (!reg->precise)
2410                         new_marks = true;
2411                 else
2412                         stack_mask = 0;
2413                 reg->precise = true;
2414                 break;
2415         }
2416
2417         if (!new_marks)
2418                 return 0;
2419         if (!reg_mask && !stack_mask)
2420                 return 0;
2421         for (;;) {
2422                 DECLARE_BITMAP(mask, 64);
2423                 u32 history = st->jmp_history_cnt;
2424
2425                 if (env->log.level & BPF_LOG_LEVEL)
2426                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2427                 for (i = last_idx;;) {
2428                         if (skip_first) {
2429                                 err = 0;
2430                                 skip_first = false;
2431                         } else {
2432                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2433                         }
2434                         if (err == -ENOTSUPP) {
2435                                 mark_all_scalars_precise(env, st);
2436                                 return 0;
2437                         } else if (err) {
2438                                 return err;
2439                         }
2440                         if (!reg_mask && !stack_mask)
2441                                 /* Found assignment(s) into tracked register in this state.
2442                                  * Since this state is already marked, just return.
2443                                  * Nothing to be tracked further in the parent state.
2444                                  */
2445                                 return 0;
2446                         if (i == first_idx)
2447                                 break;
2448                         i = get_prev_insn_idx(st, i, &history);
2449                         if (i >= env->prog->len) {
2450                                 /* This can happen if backtracking reached insn 0
2451                                  * and there are still reg_mask or stack_mask
2452                                  * to backtrack.
2453                                  * It means the backtracking missed the spot where
2454                                  * particular register was initialized with a constant.
2455                                  */
2456                                 verbose(env, "BUG backtracking idx %d\n", i);
2457                                 WARN_ONCE(1, "verifier backtracking bug");
2458                                 return -EFAULT;
2459                         }
2460                 }
2461                 st = st->parent;
2462                 if (!st)
2463                         break;
2464
2465                 new_marks = false;
2466                 func = st->frame[st->curframe];
2467                 bitmap_from_u64(mask, reg_mask);
2468                 for_each_set_bit(i, mask, 32) {
2469                         reg = &func->regs[i];
2470                         if (reg->type != SCALAR_VALUE) {
2471                                 reg_mask &= ~(1u << i);
2472                                 continue;
2473                         }
2474                         if (!reg->precise)
2475                                 new_marks = true;
2476                         reg->precise = true;
2477                 }
2478
2479                 bitmap_from_u64(mask, stack_mask);
2480                 for_each_set_bit(i, mask, 64) {
2481                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2482                                 /* the sequence of instructions:
2483                                  * 2: (bf) r3 = r10
2484                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2485                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2486                                  * doesn't contain jmps. It's backtracked
2487                                  * as a single block.
2488                                  * During backtracking insn 3 is not recognized as
2489                                  * stack access, so at the end of backtracking
2490                                  * stack slot fp-8 is still marked in stack_mask.
2491                                  * However the parent state may not have accessed
2492                                  * fp-8 and it's "unallocated" stack space.
2493                                  * In such case fallback to conservative.
2494                                  */
2495                                 mark_all_scalars_precise(env, st);
2496                                 return 0;
2497                         }
2498
2499                         if (func->stack[i].slot_type[0] != STACK_SPILL) {
2500                                 stack_mask &= ~(1ull << i);
2501                                 continue;
2502                         }
2503                         reg = &func->stack[i].spilled_ptr;
2504                         if (reg->type != SCALAR_VALUE) {
2505                                 stack_mask &= ~(1ull << i);
2506                                 continue;
2507                         }
2508                         if (!reg->precise)
2509                                 new_marks = true;
2510                         reg->precise = true;
2511                 }
2512                 if (env->log.level & BPF_LOG_LEVEL) {
2513                         print_verifier_state(env, func);
2514                         verbose(env, "parent %s regs=%x stack=%llx marks\n",
2515                                 new_marks ? "didn't have" : "already had",
2516                                 reg_mask, stack_mask);
2517                 }
2518
2519                 if (!reg_mask && !stack_mask)
2520                         break;
2521                 if (!new_marks)
2522                         break;
2523
2524                 last_idx = st->last_insn_idx;
2525                 first_idx = st->first_insn_idx;
2526         }
2527         return 0;
2528 }
2529
2530 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2531 {
2532         return __mark_chain_precision(env, regno, -1);
2533 }
2534
2535 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2536 {
2537         return __mark_chain_precision(env, -1, spi);
2538 }
2539
2540 static bool is_spillable_regtype(enum bpf_reg_type type)
2541 {
2542         switch (base_type(type)) {
2543         case PTR_TO_MAP_VALUE:
2544         case PTR_TO_STACK:
2545         case PTR_TO_CTX:
2546         case PTR_TO_PACKET:
2547         case PTR_TO_PACKET_META:
2548         case PTR_TO_PACKET_END:
2549         case PTR_TO_FLOW_KEYS:
2550         case CONST_PTR_TO_MAP:
2551         case PTR_TO_SOCKET:
2552         case PTR_TO_SOCK_COMMON:
2553         case PTR_TO_TCP_SOCK:
2554         case PTR_TO_XDP_SOCK:
2555         case PTR_TO_BTF_ID:
2556         case PTR_TO_BUF:
2557         case PTR_TO_PERCPU_BTF_ID:
2558         case PTR_TO_MEM:
2559         case PTR_TO_FUNC:
2560         case PTR_TO_MAP_KEY:
2561                 return true;
2562         default:
2563                 return false;
2564         }
2565 }
2566
2567 /* Does this register contain a constant zero? */
2568 static bool register_is_null(struct bpf_reg_state *reg)
2569 {
2570         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2571 }
2572
2573 static bool register_is_const(struct bpf_reg_state *reg)
2574 {
2575         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2576 }
2577
2578 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2579 {
2580         return tnum_is_unknown(reg->var_off) &&
2581                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2582                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2583                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2584                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2585 }
2586
2587 static bool register_is_bounded(struct bpf_reg_state *reg)
2588 {
2589         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2590 }
2591
2592 static bool __is_pointer_value(bool allow_ptr_leaks,
2593                                const struct bpf_reg_state *reg)
2594 {
2595         if (allow_ptr_leaks)
2596                 return false;
2597
2598         return reg->type != SCALAR_VALUE;
2599 }
2600
2601 static void save_register_state(struct bpf_func_state *state,
2602                                 int spi, struct bpf_reg_state *reg)
2603 {
2604         int i;
2605
2606         state->stack[spi].spilled_ptr = *reg;
2607         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2608
2609         for (i = 0; i < BPF_REG_SIZE; i++)
2610                 state->stack[spi].slot_type[i] = STACK_SPILL;
2611 }
2612
2613 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2614  * stack boundary and alignment are checked in check_mem_access()
2615  */
2616 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2617                                        /* stack frame we're writing to */
2618                                        struct bpf_func_state *state,
2619                                        int off, int size, int value_regno,
2620                                        int insn_idx)
2621 {
2622         struct bpf_func_state *cur; /* state of the current function */
2623         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2624         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2625         struct bpf_reg_state *reg = NULL;
2626
2627         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2628         if (err)
2629                 return err;
2630         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2631          * so it's aligned access and [off, off + size) are within stack limits
2632          */
2633         if (!env->allow_ptr_leaks &&
2634             state->stack[spi].slot_type[0] == STACK_SPILL &&
2635             size != BPF_REG_SIZE) {
2636                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2637                 return -EACCES;
2638         }
2639
2640         cur = env->cur_state->frame[env->cur_state->curframe];
2641         if (value_regno >= 0)
2642                 reg = &cur->regs[value_regno];
2643         if (!env->bypass_spec_v4) {
2644                 bool sanitize = reg && is_spillable_regtype(reg->type);
2645
2646                 for (i = 0; i < size; i++) {
2647                         if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2648                                 sanitize = true;
2649                                 break;
2650                         }
2651                 }
2652
2653                 if (sanitize)
2654                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2655         }
2656
2657         if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2658             !register_is_null(reg) && env->bpf_capable) {
2659                 if (dst_reg != BPF_REG_FP) {
2660                         /* The backtracking logic can only recognize explicit
2661                          * stack slot address like [fp - 8]. Other spill of
2662                          * scalar via different register has to be conservative.
2663                          * Backtrack from here and mark all registers as precise
2664                          * that contributed into 'reg' being a constant.
2665                          */
2666                         err = mark_chain_precision(env, value_regno);
2667                         if (err)
2668                                 return err;
2669                 }
2670                 save_register_state(state, spi, reg);
2671         } else if (reg && is_spillable_regtype(reg->type)) {
2672                 /* register containing pointer is being spilled into stack */
2673                 if (size != BPF_REG_SIZE) {
2674                         verbose_linfo(env, insn_idx, "; ");
2675                         verbose(env, "invalid size of register spill\n");
2676                         return -EACCES;
2677                 }
2678                 if (state != cur && reg->type == PTR_TO_STACK) {
2679                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2680                         return -EINVAL;
2681                 }
2682                 save_register_state(state, spi, reg);
2683         } else {
2684                 u8 type = STACK_MISC;
2685
2686                 /* regular write of data into stack destroys any spilled ptr */
2687                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2688                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2689                 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2690                         for (i = 0; i < BPF_REG_SIZE; i++)
2691                                 state->stack[spi].slot_type[i] = STACK_MISC;
2692
2693                 /* only mark the slot as written if all 8 bytes were written
2694                  * otherwise read propagation may incorrectly stop too soon
2695                  * when stack slots are partially written.
2696                  * This heuristic means that read propagation will be
2697                  * conservative, since it will add reg_live_read marks
2698                  * to stack slots all the way to first state when programs
2699                  * writes+reads less than 8 bytes
2700                  */
2701                 if (size == BPF_REG_SIZE)
2702                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2703
2704                 /* when we zero initialize stack slots mark them as such */
2705                 if (reg && register_is_null(reg)) {
2706                         /* backtracking doesn't work for STACK_ZERO yet. */
2707                         err = mark_chain_precision(env, value_regno);
2708                         if (err)
2709                                 return err;
2710                         type = STACK_ZERO;
2711                 }
2712
2713                 /* Mark slots affected by this stack write. */
2714                 for (i = 0; i < size; i++)
2715                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2716                                 type;
2717         }
2718         return 0;
2719 }
2720
2721 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2722  * known to contain a variable offset.
2723  * This function checks whether the write is permitted and conservatively
2724  * tracks the effects of the write, considering that each stack slot in the
2725  * dynamic range is potentially written to.
2726  *
2727  * 'off' includes 'regno->off'.
2728  * 'value_regno' can be -1, meaning that an unknown value is being written to
2729  * the stack.
2730  *
2731  * Spilled pointers in range are not marked as written because we don't know
2732  * what's going to be actually written. This means that read propagation for
2733  * future reads cannot be terminated by this write.
2734  *
2735  * For privileged programs, uninitialized stack slots are considered
2736  * initialized by this write (even though we don't know exactly what offsets
2737  * are going to be written to). The idea is that we don't want the verifier to
2738  * reject future reads that access slots written to through variable offsets.
2739  */
2740 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2741                                      /* func where register points to */
2742                                      struct bpf_func_state *state,
2743                                      int ptr_regno, int off, int size,
2744                                      int value_regno, int insn_idx)
2745 {
2746         struct bpf_func_state *cur; /* state of the current function */
2747         int min_off, max_off;
2748         int i, err;
2749         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2750         bool writing_zero = false;
2751         /* set if the fact that we're writing a zero is used to let any
2752          * stack slots remain STACK_ZERO
2753          */
2754         bool zero_used = false;
2755
2756         cur = env->cur_state->frame[env->cur_state->curframe];
2757         ptr_reg = &cur->regs[ptr_regno];
2758         min_off = ptr_reg->smin_value + off;
2759         max_off = ptr_reg->smax_value + off + size;
2760         if (value_regno >= 0)
2761                 value_reg = &cur->regs[value_regno];
2762         if (value_reg && register_is_null(value_reg))
2763                 writing_zero = true;
2764
2765         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2766         if (err)
2767                 return err;
2768
2769
2770         /* Variable offset writes destroy any spilled pointers in range. */
2771         for (i = min_off; i < max_off; i++) {
2772                 u8 new_type, *stype;
2773                 int slot, spi;
2774
2775                 slot = -i - 1;
2776                 spi = slot / BPF_REG_SIZE;
2777                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2778
2779                 if (!env->allow_ptr_leaks
2780                                 && *stype != NOT_INIT
2781                                 && *stype != SCALAR_VALUE) {
2782                         /* Reject the write if there's are spilled pointers in
2783                          * range. If we didn't reject here, the ptr status
2784                          * would be erased below (even though not all slots are
2785                          * actually overwritten), possibly opening the door to
2786                          * leaks.
2787                          */
2788                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2789                                 insn_idx, i);
2790                         return -EINVAL;
2791                 }
2792
2793                 /* Erase all spilled pointers. */
2794                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2795
2796                 /* Update the slot type. */
2797                 new_type = STACK_MISC;
2798                 if (writing_zero && *stype == STACK_ZERO) {
2799                         new_type = STACK_ZERO;
2800                         zero_used = true;
2801                 }
2802                 /* If the slot is STACK_INVALID, we check whether it's OK to
2803                  * pretend that it will be initialized by this write. The slot
2804                  * might not actually be written to, and so if we mark it as
2805                  * initialized future reads might leak uninitialized memory.
2806                  * For privileged programs, we will accept such reads to slots
2807                  * that may or may not be written because, if we're reject
2808                  * them, the error would be too confusing.
2809                  */
2810                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2811                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2812                                         insn_idx, i);
2813                         return -EINVAL;
2814                 }
2815                 *stype = new_type;
2816         }
2817         if (zero_used) {
2818                 /* backtracking doesn't work for STACK_ZERO yet. */
2819                 err = mark_chain_precision(env, value_regno);
2820                 if (err)
2821                         return err;
2822         }
2823         return 0;
2824 }
2825
2826 /* When register 'dst_regno' is assigned some values from stack[min_off,
2827  * max_off), we set the register's type according to the types of the
2828  * respective stack slots. If all the stack values are known to be zeros, then
2829  * so is the destination reg. Otherwise, the register is considered to be
2830  * SCALAR. This function does not deal with register filling; the caller must
2831  * ensure that all spilled registers in the stack range have been marked as
2832  * read.
2833  */
2834 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2835                                 /* func where src register points to */
2836                                 struct bpf_func_state *ptr_state,
2837                                 int min_off, int max_off, int dst_regno)
2838 {
2839         struct bpf_verifier_state *vstate = env->cur_state;
2840         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2841         int i, slot, spi;
2842         u8 *stype;
2843         int zeros = 0;
2844
2845         for (i = min_off; i < max_off; i++) {
2846                 slot = -i - 1;
2847                 spi = slot / BPF_REG_SIZE;
2848                 stype = ptr_state->stack[spi].slot_type;
2849                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2850                         break;
2851                 zeros++;
2852         }
2853         if (zeros == max_off - min_off) {
2854                 /* any access_size read into register is zero extended,
2855                  * so the whole register == const_zero
2856                  */
2857                 __mark_reg_const_zero(&state->regs[dst_regno]);
2858                 /* backtracking doesn't support STACK_ZERO yet,
2859                  * so mark it precise here, so that later
2860                  * backtracking can stop here.
2861                  * Backtracking may not need this if this register
2862                  * doesn't participate in pointer adjustment.
2863                  * Forward propagation of precise flag is not
2864                  * necessary either. This mark is only to stop
2865                  * backtracking. Any register that contributed
2866                  * to const 0 was marked precise before spill.
2867                  */
2868                 state->regs[dst_regno].precise = true;
2869         } else {
2870                 /* have read misc data from the stack */
2871                 mark_reg_unknown(env, state->regs, dst_regno);
2872         }
2873         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2874 }
2875
2876 /* Read the stack at 'off' and put the results into the register indicated by
2877  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2878  * spilled reg.
2879  *
2880  * 'dst_regno' can be -1, meaning that the read value is not going to a
2881  * register.
2882  *
2883  * The access is assumed to be within the current stack bounds.
2884  */
2885 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2886                                       /* func where src register points to */
2887                                       struct bpf_func_state *reg_state,
2888                                       int off, int size, int dst_regno)
2889 {
2890         struct bpf_verifier_state *vstate = env->cur_state;
2891         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2892         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2893         struct bpf_reg_state *reg;
2894         u8 *stype;
2895
2896         stype = reg_state->stack[spi].slot_type;
2897         reg = &reg_state->stack[spi].spilled_ptr;
2898
2899         if (stype[0] == STACK_SPILL) {
2900                 if (size != BPF_REG_SIZE) {
2901                         if (reg->type != SCALAR_VALUE) {
2902                                 verbose_linfo(env, env->insn_idx, "; ");
2903                                 verbose(env, "invalid size of register fill\n");
2904                                 return -EACCES;
2905                         }
2906                         if (dst_regno >= 0) {
2907                                 mark_reg_unknown(env, state->regs, dst_regno);
2908                                 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2909                         }
2910                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2911                         return 0;
2912                 }
2913                 for (i = 1; i < BPF_REG_SIZE; i++) {
2914                         if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2915                                 verbose(env, "corrupted spill memory\n");
2916                                 return -EACCES;
2917                         }
2918                 }
2919
2920                 if (dst_regno >= 0) {
2921                         /* restore register state from stack */
2922                         state->regs[dst_regno] = *reg;
2923                         /* mark reg as written since spilled pointer state likely
2924                          * has its liveness marks cleared by is_state_visited()
2925                          * which resets stack/reg liveness for state transitions
2926                          */
2927                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2928                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2929                         /* If dst_regno==-1, the caller is asking us whether
2930                          * it is acceptable to use this value as a SCALAR_VALUE
2931                          * (e.g. for XADD).
2932                          * We must not allow unprivileged callers to do that
2933                          * with spilled pointers.
2934                          */
2935                         verbose(env, "leaking pointer from stack off %d\n",
2936                                 off);
2937                         return -EACCES;
2938                 }
2939                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2940         } else {
2941                 u8 type;
2942
2943                 for (i = 0; i < size; i++) {
2944                         type = stype[(slot - i) % BPF_REG_SIZE];
2945                         if (type == STACK_MISC)
2946                                 continue;
2947                         if (type == STACK_ZERO)
2948                                 continue;
2949                         verbose(env, "invalid read from stack off %d+%d size %d\n",
2950                                 off, i, size);
2951                         return -EACCES;
2952                 }
2953                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2954                 if (dst_regno >= 0)
2955                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2956         }
2957         return 0;
2958 }
2959
2960 enum stack_access_src {
2961         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2962         ACCESS_HELPER = 2,  /* the access is performed by a helper */
2963 };
2964
2965 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2966                                          int regno, int off, int access_size,
2967                                          bool zero_size_allowed,
2968                                          enum stack_access_src type,
2969                                          struct bpf_call_arg_meta *meta);
2970
2971 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2972 {
2973         return cur_regs(env) + regno;
2974 }
2975
2976 /* Read the stack at 'ptr_regno + off' and put the result into the register
2977  * 'dst_regno'.
2978  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2979  * but not its variable offset.
2980  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2981  *
2982  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2983  * filling registers (i.e. reads of spilled register cannot be detected when
2984  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2985  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2986  * offset; for a fixed offset check_stack_read_fixed_off should be used
2987  * instead.
2988  */
2989 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2990                                     int ptr_regno, int off, int size, int dst_regno)
2991 {
2992         /* The state of the source register. */
2993         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2994         struct bpf_func_state *ptr_state = func(env, reg);
2995         int err;
2996         int min_off, max_off;
2997
2998         /* Note that we pass a NULL meta, so raw access will not be permitted.
2999          */
3000         err = check_stack_range_initialized(env, ptr_regno, off, size,
3001                                             false, ACCESS_DIRECT, NULL);
3002         if (err)
3003                 return err;
3004
3005         min_off = reg->smin_value + off;
3006         max_off = reg->smax_value + off;
3007         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3008         return 0;
3009 }
3010
3011 /* check_stack_read dispatches to check_stack_read_fixed_off or
3012  * check_stack_read_var_off.
3013  *
3014  * The caller must ensure that the offset falls within the allocated stack
3015  * bounds.
3016  *
3017  * 'dst_regno' is a register which will receive the value from the stack. It
3018  * can be -1, meaning that the read value is not going to a register.
3019  */
3020 static int check_stack_read(struct bpf_verifier_env *env,
3021                             int ptr_regno, int off, int size,
3022                             int dst_regno)
3023 {
3024         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3025         struct bpf_func_state *state = func(env, reg);
3026         int err;
3027         /* Some accesses are only permitted with a static offset. */
3028         bool var_off = !tnum_is_const(reg->var_off);
3029
3030         /* The offset is required to be static when reads don't go to a
3031          * register, in order to not leak pointers (see
3032          * check_stack_read_fixed_off).
3033          */
3034         if (dst_regno < 0 && var_off) {
3035                 char tn_buf[48];
3036
3037                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3038                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3039                         tn_buf, off, size);
3040                 return -EACCES;
3041         }
3042         /* Variable offset is prohibited for unprivileged mode for simplicity
3043          * since it requires corresponding support in Spectre masking for stack
3044          * ALU. See also retrieve_ptr_limit().
3045          */
3046         if (!env->bypass_spec_v1 && var_off) {
3047                 char tn_buf[48];
3048
3049                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3050                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3051                                 ptr_regno, tn_buf);
3052                 return -EACCES;
3053         }
3054
3055         if (!var_off) {
3056                 off += reg->var_off.value;
3057                 err = check_stack_read_fixed_off(env, state, off, size,
3058                                                  dst_regno);
3059         } else {
3060                 /* Variable offset stack reads need more conservative handling
3061                  * than fixed offset ones. Note that dst_regno >= 0 on this
3062                  * branch.
3063                  */
3064                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3065                                                dst_regno);
3066         }
3067         return err;
3068 }
3069
3070
3071 /* check_stack_write dispatches to check_stack_write_fixed_off or
3072  * check_stack_write_var_off.
3073  *
3074  * 'ptr_regno' is the register used as a pointer into the stack.
3075  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3076  * 'value_regno' is the register whose value we're writing to the stack. It can
3077  * be -1, meaning that we're not writing from a register.
3078  *
3079  * The caller must ensure that the offset falls within the maximum stack size.
3080  */
3081 static int check_stack_write(struct bpf_verifier_env *env,
3082                              int ptr_regno, int off, int size,
3083                              int value_regno, int insn_idx)
3084 {
3085         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3086         struct bpf_func_state *state = func(env, reg);
3087         int err;
3088
3089         if (tnum_is_const(reg->var_off)) {
3090                 off += reg->var_off.value;
3091                 err = check_stack_write_fixed_off(env, state, off, size,
3092                                                   value_regno, insn_idx);
3093         } else {
3094                 /* Variable offset stack reads need more conservative handling
3095                  * than fixed offset ones.
3096                  */
3097                 err = check_stack_write_var_off(env, state,
3098                                                 ptr_regno, off, size,
3099                                                 value_regno, insn_idx);
3100         }
3101         return err;
3102 }
3103
3104 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3105                                  int off, int size, enum bpf_access_type type)
3106 {
3107         struct bpf_reg_state *regs = cur_regs(env);
3108         struct bpf_map *map = regs[regno].map_ptr;
3109         u32 cap = bpf_map_flags_to_cap(map);
3110
3111         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3112                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3113                         map->value_size, off, size);
3114                 return -EACCES;
3115         }
3116
3117         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3118                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3119                         map->value_size, off, size);
3120                 return -EACCES;
3121         }
3122
3123         return 0;
3124 }
3125
3126 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3127 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3128                               int off, int size, u32 mem_size,
3129                               bool zero_size_allowed)
3130 {
3131         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3132         struct bpf_reg_state *reg;
3133
3134         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3135                 return 0;
3136
3137         reg = &cur_regs(env)[regno];
3138         switch (reg->type) {
3139         case PTR_TO_MAP_KEY:
3140                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3141                         mem_size, off, size);
3142                 break;
3143         case PTR_TO_MAP_VALUE:
3144                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3145                         mem_size, off, size);
3146                 break;
3147         case PTR_TO_PACKET:
3148         case PTR_TO_PACKET_META:
3149         case PTR_TO_PACKET_END:
3150                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3151                         off, size, regno, reg->id, off, mem_size);
3152                 break;
3153         case PTR_TO_MEM:
3154         default:
3155                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3156                         mem_size, off, size);
3157         }
3158
3159         return -EACCES;
3160 }
3161
3162 /* check read/write into a memory region with possible variable offset */
3163 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3164                                    int off, int size, u32 mem_size,
3165                                    bool zero_size_allowed)
3166 {
3167         struct bpf_verifier_state *vstate = env->cur_state;
3168         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3169         struct bpf_reg_state *reg = &state->regs[regno];
3170         int err;
3171
3172         /* We may have adjusted the register pointing to memory region, so we
3173          * need to try adding each of min_value and max_value to off
3174          * to make sure our theoretical access will be safe.
3175          */
3176         if (env->log.level & BPF_LOG_LEVEL)
3177                 print_verifier_state(env, state);
3178
3179         /* The minimum value is only important with signed
3180          * comparisons where we can't assume the floor of a
3181          * value is 0.  If we are using signed variables for our
3182          * index'es we need to make sure that whatever we use
3183          * will have a set floor within our range.
3184          */
3185         if (reg->smin_value < 0 &&
3186             (reg->smin_value == S64_MIN ||
3187              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3188               reg->smin_value + off < 0)) {
3189                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3190                         regno);
3191                 return -EACCES;
3192         }
3193         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3194                                  mem_size, zero_size_allowed);
3195         if (err) {
3196                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3197                         regno);
3198                 return err;
3199         }
3200
3201         /* If we haven't set a max value then we need to bail since we can't be
3202          * sure we won't do bad things.
3203          * If reg->umax_value + off could overflow, treat that as unbounded too.
3204          */
3205         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3206                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3207                         regno);
3208                 return -EACCES;
3209         }
3210         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3211                                  mem_size, zero_size_allowed);
3212         if (err) {
3213                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3214                         regno);
3215                 return err;
3216         }
3217
3218         return 0;
3219 }
3220
3221 /* check read/write into a map element with possible variable offset */
3222 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3223                             int off, int size, bool zero_size_allowed)
3224 {
3225         struct bpf_verifier_state *vstate = env->cur_state;
3226         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3227         struct bpf_reg_state *reg = &state->regs[regno];
3228         struct bpf_map *map = reg->map_ptr;
3229         int err;
3230
3231         err = check_mem_region_access(env, regno, off, size, map->value_size,
3232                                       zero_size_allowed);
3233         if (err)
3234                 return err;
3235
3236         if (map_value_has_spin_lock(map)) {
3237                 u32 lock = map->spin_lock_off;
3238
3239                 /* if any part of struct bpf_spin_lock can be touched by
3240                  * load/store reject this program.
3241                  * To check that [x1, x2) overlaps with [y1, y2)
3242                  * it is sufficient to check x1 < y2 && y1 < x2.
3243                  */
3244                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3245                      lock < reg->umax_value + off + size) {
3246                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3247                         return -EACCES;
3248                 }
3249         }
3250         if (map_value_has_timer(map)) {
3251                 u32 t = map->timer_off;
3252
3253                 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3254                      t < reg->umax_value + off + size) {
3255                         verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3256                         return -EACCES;
3257                 }
3258         }
3259         return err;
3260 }
3261
3262 #define MAX_PACKET_OFF 0xffff
3263
3264 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3265 {
3266         return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3267 }
3268
3269 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3270                                        const struct bpf_call_arg_meta *meta,
3271                                        enum bpf_access_type t)
3272 {
3273         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3274
3275         switch (prog_type) {
3276         /* Program types only with direct read access go here! */
3277         case BPF_PROG_TYPE_LWT_IN:
3278         case BPF_PROG_TYPE_LWT_OUT:
3279         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3280         case BPF_PROG_TYPE_SK_REUSEPORT:
3281         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3282         case BPF_PROG_TYPE_CGROUP_SKB:
3283                 if (t == BPF_WRITE)
3284                         return false;
3285                 fallthrough;
3286
3287         /* Program types with direct read + write access go here! */
3288         case BPF_PROG_TYPE_SCHED_CLS:
3289         case BPF_PROG_TYPE_SCHED_ACT:
3290         case BPF_PROG_TYPE_XDP:
3291         case BPF_PROG_TYPE_LWT_XMIT:
3292         case BPF_PROG_TYPE_SK_SKB:
3293         case BPF_PROG_TYPE_SK_MSG:
3294                 if (meta)
3295                         return meta->pkt_access;
3296
3297                 env->seen_direct_write = true;
3298                 return true;
3299
3300         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3301                 if (t == BPF_WRITE)
3302                         env->seen_direct_write = true;
3303
3304                 return true;
3305
3306         default:
3307                 return false;
3308         }
3309 }
3310
3311 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3312                                int size, bool zero_size_allowed)
3313 {
3314         struct bpf_reg_state *regs = cur_regs(env);
3315         struct bpf_reg_state *reg = &regs[regno];
3316         int err;
3317
3318         /* We may have added a variable offset to the packet pointer; but any
3319          * reg->range we have comes after that.  We are only checking the fixed
3320          * offset.
3321          */
3322
3323         /* We don't allow negative numbers, because we aren't tracking enough
3324          * detail to prove they're safe.
3325          */
3326         if (reg->smin_value < 0) {
3327                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3328                         regno);
3329                 return -EACCES;
3330         }
3331
3332         err = reg->range < 0 ? -EINVAL :
3333               __check_mem_access(env, regno, off, size, reg->range,
3334                                  zero_size_allowed);
3335         if (err) {
3336                 verbose(env, "R%d offset is outside of the packet\n", regno);
3337                 return err;
3338         }
3339
3340         /* __check_mem_access has made sure "off + size - 1" is within u16.
3341          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3342          * otherwise find_good_pkt_pointers would have refused to set range info
3343          * that __check_mem_access would have rejected this pkt access.
3344          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3345          */
3346         env->prog->aux->max_pkt_offset =
3347                 max_t(u32, env->prog->aux->max_pkt_offset,
3348                       off + reg->umax_value + size - 1);
3349
3350         return err;
3351 }
3352
3353 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3354 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3355                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
3356                             struct btf **btf, u32 *btf_id)
3357 {
3358         struct bpf_insn_access_aux info = {
3359                 .reg_type = *reg_type,
3360                 .log = &env->log,
3361         };
3362
3363         if (env->ops->is_valid_access &&
3364             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3365                 /* A non zero info.ctx_field_size indicates that this field is a
3366                  * candidate for later verifier transformation to load the whole
3367                  * field and then apply a mask when accessed with a narrower
3368                  * access than actual ctx access size. A zero info.ctx_field_size
3369                  * will only allow for whole field access and rejects any other
3370                  * type of narrower access.
3371                  */
3372                 *reg_type = info.reg_type;
3373
3374                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3375                         *btf = info.btf;
3376                         *btf_id = info.btf_id;
3377                 } else {
3378                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3379                 }
3380                 /* remember the offset of last byte accessed in ctx */
3381                 if (env->prog->aux->max_ctx_offset < off + size)
3382                         env->prog->aux->max_ctx_offset = off + size;
3383                 return 0;
3384         }
3385
3386         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3387         return -EACCES;
3388 }
3389
3390 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3391                                   int size)
3392 {
3393         if (size < 0 || off < 0 ||
3394             (u64)off + size > sizeof(struct bpf_flow_keys)) {
3395                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3396                         off, size);
3397                 return -EACCES;
3398         }
3399         return 0;
3400 }
3401
3402 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3403                              u32 regno, int off, int size,
3404                              enum bpf_access_type t)
3405 {
3406         struct bpf_reg_state *regs = cur_regs(env);
3407         struct bpf_reg_state *reg = &regs[regno];
3408         struct bpf_insn_access_aux info = {};
3409         bool valid;
3410
3411         if (reg->smin_value < 0) {
3412                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3413                         regno);
3414                 return -EACCES;
3415         }
3416
3417         switch (reg->type) {
3418         case PTR_TO_SOCK_COMMON:
3419                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3420                 break;
3421         case PTR_TO_SOCKET:
3422                 valid = bpf_sock_is_valid_access(off, size, t, &info);
3423                 break;
3424         case PTR_TO_TCP_SOCK:
3425                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3426                 break;
3427         case PTR_TO_XDP_SOCK:
3428                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3429                 break;
3430         default:
3431                 valid = false;
3432         }
3433
3434
3435         if (valid) {
3436                 env->insn_aux_data[insn_idx].ctx_field_size =
3437                         info.ctx_field_size;
3438                 return 0;
3439         }
3440
3441         verbose(env, "R%d invalid %s access off=%d size=%d\n",
3442                 regno, reg_type_str(env, reg->type), off, size);
3443
3444         return -EACCES;
3445 }
3446
3447 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3448 {
3449         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3450 }
3451
3452 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3453 {
3454         const struct bpf_reg_state *reg = reg_state(env, regno);
3455
3456         return reg->type == PTR_TO_CTX;
3457 }
3458
3459 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3460 {
3461         const struct bpf_reg_state *reg = reg_state(env, regno);
3462
3463         return type_is_sk_pointer(reg->type);
3464 }
3465
3466 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3467 {
3468         const struct bpf_reg_state *reg = reg_state(env, regno);
3469
3470         return type_is_pkt_pointer(reg->type);
3471 }
3472
3473 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3474 {
3475         const struct bpf_reg_state *reg = reg_state(env, regno);
3476
3477         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3478         return reg->type == PTR_TO_FLOW_KEYS;
3479 }
3480
3481 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3482                                    const struct bpf_reg_state *reg,
3483                                    int off, int size, bool strict)
3484 {
3485         struct tnum reg_off;
3486         int ip_align;
3487
3488         /* Byte size accesses are always allowed. */
3489         if (!strict || size == 1)
3490                 return 0;
3491
3492         /* For platforms that do not have a Kconfig enabling
3493          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3494          * NET_IP_ALIGN is universally set to '2'.  And on platforms
3495          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3496          * to this code only in strict mode where we want to emulate
3497          * the NET_IP_ALIGN==2 checking.  Therefore use an
3498          * unconditional IP align value of '2'.
3499          */
3500         ip_align = 2;
3501
3502         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3503         if (!tnum_is_aligned(reg_off, size)) {
3504                 char tn_buf[48];
3505
3506                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3507                 verbose(env,
3508                         "misaligned packet access off %d+%s+%d+%d size %d\n",
3509                         ip_align, tn_buf, reg->off, off, size);
3510                 return -EACCES;
3511         }
3512
3513         return 0;
3514 }
3515
3516 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3517                                        const struct bpf_reg_state *reg,
3518                                        const char *pointer_desc,
3519                                        int off, int size, bool strict)
3520 {
3521         struct tnum reg_off;
3522
3523         /* Byte size accesses are always allowed. */
3524         if (!strict || size == 1)
3525                 return 0;
3526
3527         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3528         if (!tnum_is_aligned(reg_off, size)) {
3529                 char tn_buf[48];
3530
3531                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3532                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3533                         pointer_desc, tn_buf, reg->off, off, size);
3534                 return -EACCES;
3535         }
3536
3537         return 0;
3538 }
3539
3540 static int check_ptr_alignment(struct bpf_verifier_env *env,
3541                                const struct bpf_reg_state *reg, int off,
3542                                int size, bool strict_alignment_once)
3543 {
3544         bool strict = env->strict_alignment || strict_alignment_once;
3545         const char *pointer_desc = "";
3546
3547         switch (reg->type) {
3548         case PTR_TO_PACKET:
3549         case PTR_TO_PACKET_META:
3550                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3551                  * right in front, treat it the very same way.
3552                  */
3553                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3554         case PTR_TO_FLOW_KEYS:
3555                 pointer_desc = "flow keys ";
3556                 break;
3557         case PTR_TO_MAP_KEY:
3558                 pointer_desc = "key ";
3559                 break;
3560         case PTR_TO_MAP_VALUE:
3561                 pointer_desc = "value ";
3562                 break;
3563         case PTR_TO_CTX:
3564                 pointer_desc = "context ";
3565                 break;
3566         case PTR_TO_STACK:
3567                 pointer_desc = "stack ";
3568                 /* The stack spill tracking logic in check_stack_write_fixed_off()
3569                  * and check_stack_read_fixed_off() relies on stack accesses being
3570                  * aligned.
3571                  */
3572                 strict = true;
3573                 break;
3574         case PTR_TO_SOCKET:
3575                 pointer_desc = "sock ";
3576                 break;
3577         case PTR_TO_SOCK_COMMON:
3578                 pointer_desc = "sock_common ";
3579                 break;
3580         case PTR_TO_TCP_SOCK:
3581                 pointer_desc = "tcp_sock ";
3582                 break;
3583         case PTR_TO_XDP_SOCK:
3584                 pointer_desc = "xdp_sock ";
3585                 break;
3586         default:
3587                 break;
3588         }
3589         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3590                                            strict);
3591 }
3592
3593 static int update_stack_depth(struct bpf_verifier_env *env,
3594                               const struct bpf_func_state *func,
3595                               int off)
3596 {
3597         u16 stack = env->subprog_info[func->subprogno].stack_depth;
3598
3599         if (stack >= -off)
3600                 return 0;
3601
3602         /* update known max for given subprogram */
3603         env->subprog_info[func->subprogno].stack_depth = -off;
3604         return 0;
3605 }
3606
3607 /* starting from main bpf function walk all instructions of the function
3608  * and recursively walk all callees that given function can call.
3609  * Ignore jump and exit insns.
3610  * Since recursion is prevented by check_cfg() this algorithm
3611  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3612  */
3613 static int check_max_stack_depth(struct bpf_verifier_env *env)
3614 {
3615         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3616         struct bpf_subprog_info *subprog = env->subprog_info;
3617         struct bpf_insn *insn = env->prog->insnsi;
3618         bool tail_call_reachable = false;
3619         int ret_insn[MAX_CALL_FRAMES];
3620         int ret_prog[MAX_CALL_FRAMES];
3621         int j;
3622
3623 process_func:
3624         /* protect against potential stack overflow that might happen when
3625          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3626          * depth for such case down to 256 so that the worst case scenario
3627          * would result in 8k stack size (32 which is tailcall limit * 256 =
3628          * 8k).
3629          *
3630          * To get the idea what might happen, see an example:
3631          * func1 -> sub rsp, 128
3632          *  subfunc1 -> sub rsp, 256
3633          *  tailcall1 -> add rsp, 256
3634          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3635          *   subfunc2 -> sub rsp, 64
3636          *   subfunc22 -> sub rsp, 128
3637          *   tailcall2 -> add rsp, 128
3638          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3639          *
3640          * tailcall will unwind the current stack frame but it will not get rid
3641          * of caller's stack as shown on the example above.
3642          */
3643         if (idx && subprog[idx].has_tail_call && depth >= 256) {
3644                 verbose(env,
3645                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3646                         depth);
3647                 return -EACCES;
3648         }
3649         /* round up to 32-bytes, since this is granularity
3650          * of interpreter stack size
3651          */
3652         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3653         if (depth > MAX_BPF_STACK) {
3654                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3655                         frame + 1, depth);
3656                 return -EACCES;
3657         }
3658 continue_func:
3659         subprog_end = subprog[idx + 1].start;
3660         for (; i < subprog_end; i++) {
3661                 int next_insn;
3662
3663                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3664                         continue;
3665                 /* remember insn and function to return to */
3666                 ret_insn[frame] = i + 1;
3667                 ret_prog[frame] = idx;
3668
3669                 /* find the callee */
3670                 next_insn = i + insn[i].imm + 1;
3671                 idx = find_subprog(env, next_insn);
3672                 if (idx < 0) {
3673                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3674                                   next_insn);
3675                         return -EFAULT;
3676                 }
3677                 if (subprog[idx].is_async_cb) {
3678                         if (subprog[idx].has_tail_call) {
3679                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3680                                 return -EFAULT;
3681                         }
3682                          /* async callbacks don't increase bpf prog stack size */
3683                         continue;
3684                 }
3685                 i = next_insn;
3686
3687                 if (subprog[idx].has_tail_call)
3688                         tail_call_reachable = true;
3689
3690                 frame++;
3691                 if (frame >= MAX_CALL_FRAMES) {
3692                         verbose(env, "the call stack of %d frames is too deep !\n",
3693                                 frame);
3694                         return -E2BIG;
3695                 }
3696                 goto process_func;
3697         }
3698         /* if tail call got detected across bpf2bpf calls then mark each of the
3699          * currently present subprog frames as tail call reachable subprogs;
3700          * this info will be utilized by JIT so that we will be preserving the
3701          * tail call counter throughout bpf2bpf calls combined with tailcalls
3702          */
3703         if (tail_call_reachable)
3704                 for (j = 0; j < frame; j++)
3705                         subprog[ret_prog[j]].tail_call_reachable = true;
3706         if (subprog[0].tail_call_reachable)
3707                 env->prog->aux->tail_call_reachable = true;
3708
3709         /* end of for() loop means the last insn of the 'subprog'
3710          * was reached. Doesn't matter whether it was JA or EXIT
3711          */
3712         if (frame == 0)
3713                 return 0;
3714         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3715         frame--;
3716         i = ret_insn[frame];
3717         idx = ret_prog[frame];
3718         goto continue_func;
3719 }
3720
3721 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3722 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3723                                   const struct bpf_insn *insn, int idx)
3724 {
3725         int start = idx + insn->imm + 1, subprog;
3726
3727         subprog = find_subprog(env, start);
3728         if (subprog < 0) {
3729                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3730                           start);
3731                 return -EFAULT;
3732         }
3733         return env->subprog_info[subprog].stack_depth;
3734 }
3735 #endif
3736
3737 int check_ctx_reg(struct bpf_verifier_env *env,
3738                   const struct bpf_reg_state *reg, int regno)
3739 {
3740         /* Access to ctx or passing it to a helper is only allowed in
3741          * its original, unmodified form.
3742          */
3743
3744         if (reg->off) {
3745                 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3746                         regno, reg->off);
3747                 return -EACCES;
3748         }
3749
3750         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3751                 char tn_buf[48];
3752
3753                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3754                 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3755                 return -EACCES;
3756         }
3757
3758         return 0;
3759 }
3760
3761 static int __check_buffer_access(struct bpf_verifier_env *env,
3762                                  const char *buf_info,
3763                                  const struct bpf_reg_state *reg,
3764                                  int regno, int off, int size)
3765 {
3766         if (off < 0) {
3767                 verbose(env,
3768                         "R%d invalid %s buffer access: off=%d, size=%d\n",
3769                         regno, buf_info, off, size);
3770                 return -EACCES;
3771         }
3772         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3773                 char tn_buf[48];
3774
3775                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3776                 verbose(env,
3777                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3778                         regno, off, tn_buf);
3779                 return -EACCES;
3780         }
3781
3782         return 0;
3783 }
3784
3785 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3786                                   const struct bpf_reg_state *reg,
3787                                   int regno, int off, int size)
3788 {
3789         int err;
3790
3791         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3792         if (err)
3793                 return err;
3794
3795         if (off + size > env->prog->aux->max_tp_access)
3796                 env->prog->aux->max_tp_access = off + size;
3797
3798         return 0;
3799 }
3800
3801 static int check_buffer_access(struct bpf_verifier_env *env,
3802                                const struct bpf_reg_state *reg,
3803                                int regno, int off, int size,
3804                                bool zero_size_allowed,
3805                                const char *buf_info,
3806                                u32 *max_access)
3807 {
3808         int err;
3809
3810         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3811         if (err)
3812                 return err;
3813
3814         if (off + size > *max_access)
3815                 *max_access = off + size;
3816
3817         return 0;
3818 }
3819
3820 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3821 static void zext_32_to_64(struct bpf_reg_state *reg)
3822 {
3823         reg->var_off = tnum_subreg(reg->var_off);
3824         __reg_assign_32_into_64(reg);
3825 }
3826
3827 /* truncate register to smaller size (in bytes)
3828  * must be called with size < BPF_REG_SIZE
3829  */
3830 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3831 {
3832         u64 mask;
3833
3834         /* clear high bits in bit representation */
3835         reg->var_off = tnum_cast(reg->var_off, size);
3836
3837         /* fix arithmetic bounds */
3838         mask = ((u64)1 << (size * 8)) - 1;
3839         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3840                 reg->umin_value &= mask;
3841                 reg->umax_value &= mask;
3842         } else {
3843                 reg->umin_value = 0;
3844                 reg->umax_value = mask;
3845         }
3846         reg->smin_value = reg->umin_value;
3847         reg->smax_value = reg->umax_value;
3848
3849         /* If size is smaller than 32bit register the 32bit register
3850          * values are also truncated so we push 64-bit bounds into
3851          * 32-bit bounds. Above were truncated < 32-bits already.
3852          */
3853         if (size >= 4)
3854                 return;
3855         __reg_combine_64_into_32(reg);
3856 }
3857
3858 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3859 {
3860         /* A map is considered read-only if the following condition are true:
3861          *
3862          * 1) BPF program side cannot change any of the map content. The
3863          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
3864          *    and was set at map creation time.
3865          * 2) The map value(s) have been initialized from user space by a
3866          *    loader and then "frozen", such that no new map update/delete
3867          *    operations from syscall side are possible for the rest of
3868          *    the map's lifetime from that point onwards.
3869          * 3) Any parallel/pending map update/delete operations from syscall
3870          *    side have been completed. Only after that point, it's safe to
3871          *    assume that map value(s) are immutable.
3872          */
3873         return (map->map_flags & BPF_F_RDONLY_PROG) &&
3874                READ_ONCE(map->frozen) &&
3875                !bpf_map_write_active(map);
3876 }
3877
3878 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3879 {
3880         void *ptr;
3881         u64 addr;
3882         int err;
3883
3884         err = map->ops->map_direct_value_addr(map, &addr, off);
3885         if (err)
3886                 return err;
3887         ptr = (void *)(long)addr + off;
3888
3889         switch (size) {
3890         case sizeof(u8):
3891                 *val = (u64)*(u8 *)ptr;
3892                 break;
3893         case sizeof(u16):
3894                 *val = (u64)*(u16 *)ptr;
3895                 break;
3896         case sizeof(u32):
3897                 *val = (u64)*(u32 *)ptr;
3898                 break;
3899         case sizeof(u64):
3900                 *val = *(u64 *)ptr;
3901                 break;
3902         default:
3903                 return -EINVAL;
3904         }
3905         return 0;
3906 }
3907
3908 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3909                                    struct bpf_reg_state *regs,
3910                                    int regno, int off, int size,
3911                                    enum bpf_access_type atype,
3912                                    int value_regno)
3913 {
3914         struct bpf_reg_state *reg = regs + regno;
3915         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3916         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3917         u32 btf_id;
3918         int ret;
3919
3920         if (off < 0) {
3921                 verbose(env,
3922                         "R%d is ptr_%s invalid negative access: off=%d\n",
3923                         regno, tname, off);
3924                 return -EACCES;
3925         }
3926         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3927                 char tn_buf[48];
3928
3929                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3930                 verbose(env,
3931                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3932                         regno, tname, off, tn_buf);
3933                 return -EACCES;
3934         }
3935
3936         if (env->ops->btf_struct_access) {
3937                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3938                                                   off, size, atype, &btf_id);
3939         } else {
3940                 if (atype != BPF_READ) {
3941                         verbose(env, "only read is supported\n");
3942                         return -EACCES;
3943                 }
3944
3945                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3946                                         atype, &btf_id);
3947         }
3948
3949         if (ret < 0)
3950                 return ret;
3951
3952         if (atype == BPF_READ && value_regno >= 0)
3953                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3954
3955         return 0;
3956 }
3957
3958 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3959                                    struct bpf_reg_state *regs,
3960                                    int regno, int off, int size,
3961                                    enum bpf_access_type atype,
3962                                    int value_regno)
3963 {
3964         struct bpf_reg_state *reg = regs + regno;
3965         struct bpf_map *map = reg->map_ptr;
3966         const struct btf_type *t;
3967         const char *tname;
3968         u32 btf_id;
3969         int ret;
3970
3971         if (!btf_vmlinux) {
3972                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3973                 return -ENOTSUPP;
3974         }
3975
3976         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3977                 verbose(env, "map_ptr access not supported for map type %d\n",
3978                         map->map_type);
3979                 return -ENOTSUPP;
3980         }
3981
3982         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3983         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3984
3985         if (!env->allow_ptr_to_map_access) {
3986                 verbose(env,
3987                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3988                         tname);
3989                 return -EPERM;
3990         }
3991
3992         if (off < 0) {
3993                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3994                         regno, tname, off);
3995                 return -EACCES;
3996         }
3997
3998         if (atype != BPF_READ) {
3999                 verbose(env, "only read from %s is supported\n", tname);
4000                 return -EACCES;
4001         }
4002
4003         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
4004         if (ret < 0)
4005                 return ret;
4006
4007         if (value_regno >= 0)
4008                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
4009
4010         return 0;
4011 }
4012
4013 /* Check that the stack access at the given offset is within bounds. The
4014  * maximum valid offset is -1.
4015  *
4016  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4017  * -state->allocated_stack for reads.
4018  */
4019 static int check_stack_slot_within_bounds(int off,
4020                                           struct bpf_func_state *state,
4021                                           enum bpf_access_type t)
4022 {
4023         int min_valid_off;
4024
4025         if (t == BPF_WRITE)
4026                 min_valid_off = -MAX_BPF_STACK;
4027         else
4028                 min_valid_off = -state->allocated_stack;
4029
4030         if (off < min_valid_off || off > -1)
4031                 return -EACCES;
4032         return 0;
4033 }
4034
4035 /* Check that the stack access at 'regno + off' falls within the maximum stack
4036  * bounds.
4037  *
4038  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4039  */
4040 static int check_stack_access_within_bounds(
4041                 struct bpf_verifier_env *env,
4042                 int regno, int off, int access_size,
4043                 enum stack_access_src src, enum bpf_access_type type)
4044 {
4045         struct bpf_reg_state *regs = cur_regs(env);
4046         struct bpf_reg_state *reg = regs + regno;
4047         struct bpf_func_state *state = func(env, reg);
4048         int min_off, max_off;
4049         int err;
4050         char *err_extra;
4051
4052         if (src == ACCESS_HELPER)
4053                 /* We don't know if helpers are reading or writing (or both). */
4054                 err_extra = " indirect access to";
4055         else if (type == BPF_READ)
4056                 err_extra = " read from";
4057         else
4058                 err_extra = " write to";
4059
4060         if (tnum_is_const(reg->var_off)) {
4061                 min_off = reg->var_off.value + off;
4062                 if (access_size > 0)
4063                         max_off = min_off + access_size - 1;
4064                 else
4065                         max_off = min_off;
4066         } else {
4067                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4068                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4069                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4070                                 err_extra, regno);
4071                         return -EACCES;
4072                 }
4073                 min_off = reg->smin_value + off;
4074                 if (access_size > 0)
4075                         max_off = reg->smax_value + off + access_size - 1;
4076                 else
4077                         max_off = min_off;
4078         }
4079
4080         err = check_stack_slot_within_bounds(min_off, state, type);
4081         if (!err)
4082                 err = check_stack_slot_within_bounds(max_off, state, type);
4083
4084         if (err) {
4085                 if (tnum_is_const(reg->var_off)) {
4086                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4087                                 err_extra, regno, off, access_size);
4088                 } else {
4089                         char tn_buf[48];
4090
4091                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4092                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4093                                 err_extra, regno, tn_buf, access_size);
4094                 }
4095         }
4096         return err;
4097 }
4098
4099 /* check whether memory at (regno + off) is accessible for t = (read | write)
4100  * if t==write, value_regno is a register which value is stored into memory
4101  * if t==read, value_regno is a register which will receive the value from memory
4102  * if t==write && value_regno==-1, some unknown value is stored into memory
4103  * if t==read && value_regno==-1, don't care what we read from memory
4104  */
4105 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4106                             int off, int bpf_size, enum bpf_access_type t,
4107                             int value_regno, bool strict_alignment_once)
4108 {
4109         struct bpf_reg_state *regs = cur_regs(env);
4110         struct bpf_reg_state *reg = regs + regno;
4111         struct bpf_func_state *state;
4112         int size, err = 0;
4113
4114         size = bpf_size_to_bytes(bpf_size);
4115         if (size < 0)
4116                 return size;
4117
4118         /* alignment checks will add in reg->off themselves */
4119         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4120         if (err)
4121                 return err;
4122
4123         /* for access checks, reg->off is just part of off */
4124         off += reg->off;
4125
4126         if (reg->type == PTR_TO_MAP_KEY) {
4127                 if (t == BPF_WRITE) {
4128                         verbose(env, "write to change key R%d not allowed\n", regno);
4129                         return -EACCES;
4130                 }
4131
4132                 err = check_mem_region_access(env, regno, off, size,
4133                                               reg->map_ptr->key_size, false);
4134                 if (err)
4135                         return err;
4136                 if (value_regno >= 0)
4137                         mark_reg_unknown(env, regs, value_regno);
4138         } else if (reg->type == PTR_TO_MAP_VALUE) {
4139                 if (t == BPF_WRITE && value_regno >= 0 &&
4140                     is_pointer_value(env, value_regno)) {
4141                         verbose(env, "R%d leaks addr into map\n", value_regno);
4142                         return -EACCES;
4143                 }
4144                 err = check_map_access_type(env, regno, off, size, t);
4145                 if (err)
4146                         return err;
4147                 err = check_map_access(env, regno, off, size, false);
4148                 if (!err && t == BPF_READ && value_regno >= 0) {
4149                         struct bpf_map *map = reg->map_ptr;
4150
4151                         /* if map is read-only, track its contents as scalars */
4152                         if (tnum_is_const(reg->var_off) &&
4153                             bpf_map_is_rdonly(map) &&
4154                             map->ops->map_direct_value_addr) {
4155                                 int map_off = off + reg->var_off.value;
4156                                 u64 val = 0;
4157
4158                                 err = bpf_map_direct_read(map, map_off, size,
4159                                                           &val);
4160                                 if (err)
4161                                         return err;
4162
4163                                 regs[value_regno].type = SCALAR_VALUE;
4164                                 __mark_reg_known(&regs[value_regno], val);
4165                         } else {
4166                                 mark_reg_unknown(env, regs, value_regno);
4167                         }
4168                 }
4169         } else if (base_type(reg->type) == PTR_TO_MEM) {
4170                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4171
4172                 if (type_may_be_null(reg->type)) {
4173                         verbose(env, "R%d invalid mem access '%s'\n", regno,
4174                                 reg_type_str(env, reg->type));
4175                         return -EACCES;
4176                 }
4177
4178                 if (t == BPF_WRITE && rdonly_mem) {
4179                         verbose(env, "R%d cannot write into %s\n",
4180                                 regno, reg_type_str(env, reg->type));
4181                         return -EACCES;
4182                 }
4183
4184                 if (t == BPF_WRITE && value_regno >= 0 &&
4185                     is_pointer_value(env, value_regno)) {
4186                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4187                         return -EACCES;
4188                 }
4189
4190                 err = check_mem_region_access(env, regno, off, size,
4191                                               reg->mem_size, false);
4192                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4193                         mark_reg_unknown(env, regs, value_regno);
4194         } else if (reg->type == PTR_TO_CTX) {
4195                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4196                 struct btf *btf = NULL;
4197                 u32 btf_id = 0;
4198
4199                 if (t == BPF_WRITE && value_regno >= 0 &&
4200                     is_pointer_value(env, value_regno)) {
4201                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4202                         return -EACCES;
4203                 }
4204
4205                 err = check_ctx_reg(env, reg, regno);
4206                 if (err < 0)
4207                         return err;
4208
4209                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4210                 if (err)
4211                         verbose_linfo(env, insn_idx, "; ");
4212                 if (!err && t == BPF_READ && value_regno >= 0) {
4213                         /* ctx access returns either a scalar, or a
4214                          * PTR_TO_PACKET[_META,_END]. In the latter
4215                          * case, we know the offset is zero.
4216                          */
4217                         if (reg_type == SCALAR_VALUE) {
4218                                 mark_reg_unknown(env, regs, value_regno);
4219                         } else {
4220                                 mark_reg_known_zero(env, regs,
4221                                                     value_regno);
4222                                 if (type_may_be_null(reg_type))
4223                                         regs[value_regno].id = ++env->id_gen;
4224                                 /* A load of ctx field could have different
4225                                  * actual load size with the one encoded in the
4226                                  * insn. When the dst is PTR, it is for sure not
4227                                  * a sub-register.
4228                                  */
4229                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4230                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4231                                         regs[value_regno].btf = btf;
4232                                         regs[value_regno].btf_id = btf_id;
4233                                 }
4234                         }
4235                         regs[value_regno].type = reg_type;
4236                 }
4237
4238         } else if (reg->type == PTR_TO_STACK) {
4239                 /* Basic bounds checks. */
4240                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4241                 if (err)
4242                         return err;
4243
4244                 state = func(env, reg);
4245                 err = update_stack_depth(env, state, off);
4246                 if (err)
4247                         return err;
4248
4249                 if (t == BPF_READ)
4250                         err = check_stack_read(env, regno, off, size,
4251                                                value_regno);
4252                 else
4253                         err = check_stack_write(env, regno, off, size,
4254                                                 value_regno, insn_idx);
4255         } else if (reg_is_pkt_pointer(reg)) {
4256                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4257                         verbose(env, "cannot write into packet\n");
4258                         return -EACCES;
4259                 }
4260                 if (t == BPF_WRITE && value_regno >= 0 &&
4261                     is_pointer_value(env, value_regno)) {
4262                         verbose(env, "R%d leaks addr into packet\n",
4263                                 value_regno);
4264                         return -EACCES;
4265                 }
4266                 err = check_packet_access(env, regno, off, size, false);
4267                 if (!err && t == BPF_READ && value_regno >= 0)
4268                         mark_reg_unknown(env, regs, value_regno);
4269         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4270                 if (t == BPF_WRITE && value_regno >= 0 &&
4271                     is_pointer_value(env, value_regno)) {
4272                         verbose(env, "R%d leaks addr into flow keys\n",
4273                                 value_regno);
4274                         return -EACCES;
4275                 }
4276
4277                 err = check_flow_keys_access(env, off, size);
4278                 if (!err && t == BPF_READ && value_regno >= 0)
4279                         mark_reg_unknown(env, regs, value_regno);
4280         } else if (type_is_sk_pointer(reg->type)) {
4281                 if (t == BPF_WRITE) {
4282                         verbose(env, "R%d cannot write into %s\n",
4283                                 regno, reg_type_str(env, reg->type));
4284                         return -EACCES;
4285                 }
4286                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4287                 if (!err && value_regno >= 0)
4288                         mark_reg_unknown(env, regs, value_regno);
4289         } else if (reg->type == PTR_TO_TP_BUFFER) {
4290                 err = check_tp_buffer_access(env, reg, regno, off, size);
4291                 if (!err && t == BPF_READ && value_regno >= 0)
4292                         mark_reg_unknown(env, regs, value_regno);
4293         } else if (reg->type == PTR_TO_BTF_ID) {
4294                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4295                                               value_regno);
4296         } else if (reg->type == CONST_PTR_TO_MAP) {
4297                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4298                                               value_regno);
4299         } else if (base_type(reg->type) == PTR_TO_BUF) {
4300                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4301                 const char *buf_info;
4302                 u32 *max_access;
4303
4304                 if (rdonly_mem) {
4305                         if (t == BPF_WRITE) {
4306                                 verbose(env, "R%d cannot write into %s\n",
4307                                         regno, reg_type_str(env, reg->type));
4308                                 return -EACCES;
4309                         }
4310                         buf_info = "rdonly";
4311                         max_access = &env->prog->aux->max_rdonly_access;
4312                 } else {
4313                         buf_info = "rdwr";
4314                         max_access = &env->prog->aux->max_rdwr_access;
4315                 }
4316
4317                 err = check_buffer_access(env, reg, regno, off, size, false,
4318                                           buf_info, max_access);
4319
4320                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4321                         mark_reg_unknown(env, regs, value_regno);
4322         } else {
4323                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4324                         reg_type_str(env, reg->type));
4325                 return -EACCES;
4326         }
4327
4328         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4329             regs[value_regno].type == SCALAR_VALUE) {
4330                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4331                 coerce_reg_to_size(&regs[value_regno], size);
4332         }
4333         return err;
4334 }
4335
4336 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4337 {
4338         int load_reg;
4339         int err;
4340
4341         switch (insn->imm) {
4342         case BPF_ADD:
4343         case BPF_ADD | BPF_FETCH:
4344         case BPF_AND:
4345         case BPF_AND | BPF_FETCH:
4346         case BPF_OR:
4347         case BPF_OR | BPF_FETCH:
4348         case BPF_XOR:
4349         case BPF_XOR | BPF_FETCH:
4350         case BPF_XCHG:
4351         case BPF_CMPXCHG:
4352                 break;
4353         default:
4354                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4355                 return -EINVAL;
4356         }
4357
4358         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4359                 verbose(env, "invalid atomic operand size\n");
4360                 return -EINVAL;
4361         }
4362
4363         /* check src1 operand */
4364         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4365         if (err)
4366                 return err;
4367
4368         /* check src2 operand */
4369         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4370         if (err)
4371                 return err;
4372
4373         if (insn->imm == BPF_CMPXCHG) {
4374                 /* Check comparison of R0 with memory location */
4375                 const u32 aux_reg = BPF_REG_0;
4376
4377                 err = check_reg_arg(env, aux_reg, SRC_OP);
4378                 if (err)
4379                         return err;
4380
4381                 if (is_pointer_value(env, aux_reg)) {
4382                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
4383                         return -EACCES;
4384                 }
4385         }
4386
4387         if (is_pointer_value(env, insn->src_reg)) {
4388                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4389                 return -EACCES;
4390         }
4391
4392         if (is_ctx_reg(env, insn->dst_reg) ||
4393             is_pkt_reg(env, insn->dst_reg) ||
4394             is_flow_key_reg(env, insn->dst_reg) ||
4395             is_sk_reg(env, insn->dst_reg)) {
4396                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4397                         insn->dst_reg,
4398                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4399                 return -EACCES;
4400         }
4401
4402         if (insn->imm & BPF_FETCH) {
4403                 if (insn->imm == BPF_CMPXCHG)
4404                         load_reg = BPF_REG_0;
4405                 else
4406                         load_reg = insn->src_reg;
4407
4408                 /* check and record load of old value */
4409                 err = check_reg_arg(env, load_reg, DST_OP);
4410                 if (err)
4411                         return err;
4412         } else {
4413                 /* This instruction accesses a memory location but doesn't
4414                  * actually load it into a register.
4415                  */
4416                 load_reg = -1;
4417         }
4418
4419         /* Check whether we can read the memory, with second call for fetch
4420          * case to simulate the register fill.
4421          */
4422         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4423                                BPF_SIZE(insn->code), BPF_READ, -1, true);
4424         if (!err && load_reg >= 0)
4425                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4426                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
4427                                        true);
4428         if (err)
4429                 return err;
4430
4431         /* Check whether we can write into the same memory. */
4432         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4433                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4434         if (err)
4435                 return err;
4436
4437         return 0;
4438 }
4439
4440 /* When register 'regno' is used to read the stack (either directly or through
4441  * a helper function) make sure that it's within stack boundary and, depending
4442  * on the access type, that all elements of the stack are initialized.
4443  *
4444  * 'off' includes 'regno->off', but not its dynamic part (if any).
4445  *
4446  * All registers that have been spilled on the stack in the slots within the
4447  * read offsets are marked as read.
4448  */
4449 static int check_stack_range_initialized(
4450                 struct bpf_verifier_env *env, int regno, int off,
4451                 int access_size, bool zero_size_allowed,
4452                 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4453 {
4454         struct bpf_reg_state *reg = reg_state(env, regno);
4455         struct bpf_func_state *state = func(env, reg);
4456         int err, min_off, max_off, i, j, slot, spi;
4457         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4458         enum bpf_access_type bounds_check_type;
4459         /* Some accesses can write anything into the stack, others are
4460          * read-only.
4461          */
4462         bool clobber = false;
4463
4464         if (access_size == 0 && !zero_size_allowed) {
4465                 verbose(env, "invalid zero-sized read\n");
4466                 return -EACCES;
4467         }
4468
4469         if (type == ACCESS_HELPER) {
4470                 /* The bounds checks for writes are more permissive than for
4471                  * reads. However, if raw_mode is not set, we'll do extra
4472                  * checks below.
4473                  */
4474                 bounds_check_type = BPF_WRITE;
4475                 clobber = true;
4476         } else {
4477                 bounds_check_type = BPF_READ;
4478         }
4479         err = check_stack_access_within_bounds(env, regno, off, access_size,
4480                                                type, bounds_check_type);
4481         if (err)
4482                 return err;
4483
4484
4485         if (tnum_is_const(reg->var_off)) {
4486                 min_off = max_off = reg->var_off.value + off;
4487         } else {
4488                 /* Variable offset is prohibited for unprivileged mode for
4489                  * simplicity since it requires corresponding support in
4490                  * Spectre masking for stack ALU.
4491                  * See also retrieve_ptr_limit().
4492                  */
4493                 if (!env->bypass_spec_v1) {
4494                         char tn_buf[48];
4495
4496                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4497                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4498                                 regno, err_extra, tn_buf);
4499                         return -EACCES;
4500                 }
4501                 /* Only initialized buffer on stack is allowed to be accessed
4502                  * with variable offset. With uninitialized buffer it's hard to
4503                  * guarantee that whole memory is marked as initialized on
4504                  * helper return since specific bounds are unknown what may
4505                  * cause uninitialized stack leaking.
4506                  */
4507                 if (meta && meta->raw_mode)
4508                         meta = NULL;
4509
4510                 min_off = reg->smin_value + off;
4511                 max_off = reg->smax_value + off;
4512         }
4513
4514         if (meta && meta->raw_mode) {
4515                 meta->access_size = access_size;
4516                 meta->regno = regno;
4517                 return 0;
4518         }
4519
4520         for (i = min_off; i < max_off + access_size; i++) {
4521                 u8 *stype;
4522
4523                 slot = -i - 1;
4524                 spi = slot / BPF_REG_SIZE;
4525                 if (state->allocated_stack <= slot)
4526                         goto err;
4527                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4528                 if (*stype == STACK_MISC)
4529                         goto mark;
4530                 if (*stype == STACK_ZERO) {
4531                         if (clobber) {
4532                                 /* helper can write anything into the stack */
4533                                 *stype = STACK_MISC;
4534                         }
4535                         goto mark;
4536                 }
4537
4538                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4539                     state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4540                         goto mark;
4541
4542                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4543                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4544                      env->allow_ptr_leaks)) {
4545                         if (clobber) {
4546                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4547                                 for (j = 0; j < BPF_REG_SIZE; j++)
4548                                         state->stack[spi].slot_type[j] = STACK_MISC;
4549                         }
4550                         goto mark;
4551                 }
4552
4553 err:
4554                 if (tnum_is_const(reg->var_off)) {
4555                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4556                                 err_extra, regno, min_off, i - min_off, access_size);
4557                 } else {
4558                         char tn_buf[48];
4559
4560                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4561                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4562                                 err_extra, regno, tn_buf, i - min_off, access_size);
4563                 }
4564                 return -EACCES;
4565 mark:
4566                 /* reading any byte out of 8-byte 'spill_slot' will cause
4567                  * the whole slot to be marked as 'read'
4568                  */
4569                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4570                               state->stack[spi].spilled_ptr.parent,
4571                               REG_LIVE_READ64);
4572         }
4573         return update_stack_depth(env, state, min_off);
4574 }
4575
4576 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4577                                    int access_size, bool zero_size_allowed,
4578                                    struct bpf_call_arg_meta *meta)
4579 {
4580         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4581         const char *buf_info;
4582         u32 *max_access;
4583
4584         switch (base_type(reg->type)) {
4585         case PTR_TO_PACKET:
4586         case PTR_TO_PACKET_META:
4587                 return check_packet_access(env, regno, reg->off, access_size,
4588                                            zero_size_allowed);
4589         case PTR_TO_MAP_KEY:
4590                 if (meta && meta->raw_mode) {
4591                         verbose(env, "R%d cannot write into %s\n", regno,
4592                                 reg_type_str(env, reg->type));
4593                         return -EACCES;
4594                 }
4595                 return check_mem_region_access(env, regno, reg->off, access_size,
4596                                                reg->map_ptr->key_size, false);
4597         case PTR_TO_MAP_VALUE:
4598                 if (check_map_access_type(env, regno, reg->off, access_size,
4599                                           meta && meta->raw_mode ? BPF_WRITE :
4600                                           BPF_READ))
4601                         return -EACCES;
4602                 return check_map_access(env, regno, reg->off, access_size,
4603                                         zero_size_allowed);
4604         case PTR_TO_MEM:
4605                 if (type_is_rdonly_mem(reg->type)) {
4606                         if (meta && meta->raw_mode) {
4607                                 verbose(env, "R%d cannot write into %s\n", regno,
4608                                         reg_type_str(env, reg->type));
4609                                 return -EACCES;
4610                         }
4611                 }
4612                 return check_mem_region_access(env, regno, reg->off,
4613                                                access_size, reg->mem_size,
4614                                                zero_size_allowed);
4615         case PTR_TO_BUF:
4616                 if (type_is_rdonly_mem(reg->type)) {
4617                         if (meta && meta->raw_mode) {
4618                                 verbose(env, "R%d cannot write into %s\n", regno,
4619                                         reg_type_str(env, reg->type));
4620                                 return -EACCES;
4621                         }
4622
4623                         buf_info = "rdonly";
4624                         max_access = &env->prog->aux->max_rdonly_access;
4625                 } else {
4626                         buf_info = "rdwr";
4627                         max_access = &env->prog->aux->max_rdwr_access;
4628                 }
4629                 return check_buffer_access(env, reg, regno, reg->off,
4630                                            access_size, zero_size_allowed,
4631                                            buf_info, max_access);
4632         case PTR_TO_STACK:
4633                 return check_stack_range_initialized(
4634                                 env,
4635                                 regno, reg->off, access_size,
4636                                 zero_size_allowed, ACCESS_HELPER, meta);
4637         default: /* scalar_value or invalid ptr */
4638                 /* Allow zero-byte read from NULL, regardless of pointer type */
4639                 if (zero_size_allowed && access_size == 0 &&
4640                     register_is_null(reg))
4641                         return 0;
4642
4643                 verbose(env, "R%d type=%s ", regno,
4644                         reg_type_str(env, reg->type));
4645                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
4646                 return -EACCES;
4647         }
4648 }
4649
4650 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4651                    u32 regno, u32 mem_size)
4652 {
4653         if (register_is_null(reg))
4654                 return 0;
4655
4656         if (type_may_be_null(reg->type)) {
4657                 /* Assuming that the register contains a value check if the memory
4658                  * access is safe. Temporarily save and restore the register's state as
4659                  * the conversion shouldn't be visible to a caller.
4660                  */
4661                 const struct bpf_reg_state saved_reg = *reg;
4662                 int rv;
4663
4664                 mark_ptr_not_null_reg(reg);
4665                 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4666                 *reg = saved_reg;
4667                 return rv;
4668         }
4669
4670         return check_helper_mem_access(env, regno, mem_size, true, NULL);
4671 }
4672
4673 /* Implementation details:
4674  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4675  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4676  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4677  * value_or_null->value transition, since the verifier only cares about
4678  * the range of access to valid map value pointer and doesn't care about actual
4679  * address of the map element.
4680  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4681  * reg->id > 0 after value_or_null->value transition. By doing so
4682  * two bpf_map_lookups will be considered two different pointers that
4683  * point to different bpf_spin_locks.
4684  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4685  * dead-locks.
4686  * Since only one bpf_spin_lock is allowed the checks are simpler than
4687  * reg_is_refcounted() logic. The verifier needs to remember only
4688  * one spin_lock instead of array of acquired_refs.
4689  * cur_state->active_spin_lock remembers which map value element got locked
4690  * and clears it after bpf_spin_unlock.
4691  */
4692 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4693                              bool is_lock)
4694 {
4695         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4696         struct bpf_verifier_state *cur = env->cur_state;
4697         bool is_const = tnum_is_const(reg->var_off);
4698         struct bpf_map *map = reg->map_ptr;
4699         u64 val = reg->var_off.value;
4700
4701         if (!is_const) {
4702                 verbose(env,
4703                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4704                         regno);
4705                 return -EINVAL;
4706         }
4707         if (!map->btf) {
4708                 verbose(env,
4709                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4710                         map->name);
4711                 return -EINVAL;
4712         }
4713         if (!map_value_has_spin_lock(map)) {
4714                 if (map->spin_lock_off == -E2BIG)
4715                         verbose(env,
4716                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4717                                 map->name);
4718                 else if (map->spin_lock_off == -ENOENT)
4719                         verbose(env,
4720                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4721                                 map->name);
4722                 else
4723                         verbose(env,
4724                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4725                                 map->name);
4726                 return -EINVAL;
4727         }
4728         if (map->spin_lock_off != val + reg->off) {
4729                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4730                         val + reg->off);
4731                 return -EINVAL;
4732         }
4733         if (is_lock) {
4734                 if (cur->active_spin_lock) {
4735                         verbose(env,
4736                                 "Locking two bpf_spin_locks are not allowed\n");
4737                         return -EINVAL;
4738                 }
4739                 cur->active_spin_lock = reg->id;
4740         } else {
4741                 if (!cur->active_spin_lock) {
4742                         verbose(env, "bpf_spin_unlock without taking a lock\n");
4743                         return -EINVAL;
4744                 }
4745                 if (cur->active_spin_lock != reg->id) {
4746                         verbose(env, "bpf_spin_unlock of different lock\n");
4747                         return -EINVAL;
4748                 }
4749                 cur->active_spin_lock = 0;
4750         }
4751         return 0;
4752 }
4753
4754 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4755                               struct bpf_call_arg_meta *meta)
4756 {
4757         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4758         bool is_const = tnum_is_const(reg->var_off);
4759         struct bpf_map *map = reg->map_ptr;
4760         u64 val = reg->var_off.value;
4761
4762         if (!is_const) {
4763                 verbose(env,
4764                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
4765                         regno);
4766                 return -EINVAL;
4767         }
4768         if (!map->btf) {
4769                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
4770                         map->name);
4771                 return -EINVAL;
4772         }
4773         if (!map_value_has_timer(map)) {
4774                 if (map->timer_off == -E2BIG)
4775                         verbose(env,
4776                                 "map '%s' has more than one 'struct bpf_timer'\n",
4777                                 map->name);
4778                 else if (map->timer_off == -ENOENT)
4779                         verbose(env,
4780                                 "map '%s' doesn't have 'struct bpf_timer'\n",
4781                                 map->name);
4782                 else
4783                         verbose(env,
4784                                 "map '%s' is not a struct type or bpf_timer is mangled\n",
4785                                 map->name);
4786                 return -EINVAL;
4787         }
4788         if (map->timer_off != val + reg->off) {
4789                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
4790                         val + reg->off, map->timer_off);
4791                 return -EINVAL;
4792         }
4793         if (meta->map_ptr) {
4794                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
4795                 return -EFAULT;
4796         }
4797         meta->map_uid = reg->map_uid;
4798         meta->map_ptr = map;
4799         return 0;
4800 }
4801
4802 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4803 {
4804         return base_type(type) == ARG_PTR_TO_MEM ||
4805                base_type(type) == ARG_PTR_TO_UNINIT_MEM;
4806 }
4807
4808 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4809 {
4810         return type == ARG_CONST_SIZE ||
4811                type == ARG_CONST_SIZE_OR_ZERO;
4812 }
4813
4814 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4815 {
4816         return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4817 }
4818
4819 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4820 {
4821         return type == ARG_PTR_TO_INT ||
4822                type == ARG_PTR_TO_LONG;
4823 }
4824
4825 static int int_ptr_type_to_size(enum bpf_arg_type type)
4826 {
4827         if (type == ARG_PTR_TO_INT)
4828                 return sizeof(u32);
4829         else if (type == ARG_PTR_TO_LONG)
4830                 return sizeof(u64);
4831
4832         return -EINVAL;
4833 }
4834
4835 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4836                                  const struct bpf_call_arg_meta *meta,
4837                                  enum bpf_arg_type *arg_type)
4838 {
4839         if (!meta->map_ptr) {
4840                 /* kernel subsystem misconfigured verifier */
4841                 verbose(env, "invalid map_ptr to access map->type\n");
4842                 return -EACCES;
4843         }
4844
4845         switch (meta->map_ptr->map_type) {
4846         case BPF_MAP_TYPE_SOCKMAP:
4847         case BPF_MAP_TYPE_SOCKHASH:
4848                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4849                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4850                 } else {
4851                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
4852                         return -EINVAL;
4853                 }
4854                 break;
4855
4856         default:
4857                 break;
4858         }
4859         return 0;
4860 }
4861
4862 struct bpf_reg_types {
4863         const enum bpf_reg_type types[10];
4864         u32 *btf_id;
4865 };
4866
4867 static const struct bpf_reg_types map_key_value_types = {
4868         .types = {
4869                 PTR_TO_STACK,
4870                 PTR_TO_PACKET,
4871                 PTR_TO_PACKET_META,
4872                 PTR_TO_MAP_KEY,
4873                 PTR_TO_MAP_VALUE,
4874         },
4875 };
4876
4877 static const struct bpf_reg_types sock_types = {
4878         .types = {
4879                 PTR_TO_SOCK_COMMON,
4880                 PTR_TO_SOCKET,
4881                 PTR_TO_TCP_SOCK,
4882                 PTR_TO_XDP_SOCK,
4883         },
4884 };
4885
4886 #ifdef CONFIG_NET
4887 static const struct bpf_reg_types btf_id_sock_common_types = {
4888         .types = {
4889                 PTR_TO_SOCK_COMMON,
4890                 PTR_TO_SOCKET,
4891                 PTR_TO_TCP_SOCK,
4892                 PTR_TO_XDP_SOCK,
4893                 PTR_TO_BTF_ID,
4894         },
4895         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4896 };
4897 #endif
4898
4899 static const struct bpf_reg_types mem_types = {
4900         .types = {
4901                 PTR_TO_STACK,
4902                 PTR_TO_PACKET,
4903                 PTR_TO_PACKET_META,
4904                 PTR_TO_MAP_KEY,
4905                 PTR_TO_MAP_VALUE,
4906                 PTR_TO_MEM,
4907                 PTR_TO_BUF,
4908         },
4909 };
4910
4911 static const struct bpf_reg_types int_ptr_types = {
4912         .types = {
4913                 PTR_TO_STACK,
4914                 PTR_TO_PACKET,
4915                 PTR_TO_PACKET_META,
4916                 PTR_TO_MAP_KEY,
4917                 PTR_TO_MAP_VALUE,
4918         },
4919 };
4920
4921 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4922 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4923 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4924 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4925 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4926 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4927 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4928 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4929 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4930 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
4931 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
4932 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
4933
4934 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4935         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
4936         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
4937         [ARG_PTR_TO_UNINIT_MAP_VALUE]   = &map_key_value_types,
4938         [ARG_CONST_SIZE]                = &scalar_types,
4939         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
4940         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
4941         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
4942         [ARG_PTR_TO_CTX]                = &context_types,
4943         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
4944 #ifdef CONFIG_NET
4945         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4946 #endif
4947         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
4948         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
4949         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
4950         [ARG_PTR_TO_MEM]                = &mem_types,
4951         [ARG_PTR_TO_UNINIT_MEM]         = &mem_types,
4952         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
4953         [ARG_PTR_TO_INT]                = &int_ptr_types,
4954         [ARG_PTR_TO_LONG]               = &int_ptr_types,
4955         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
4956         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
4957         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
4958         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
4959         [ARG_PTR_TO_TIMER]              = &timer_types,
4960 };
4961
4962 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4963                           enum bpf_arg_type arg_type,
4964                           const u32 *arg_btf_id)
4965 {
4966         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4967         enum bpf_reg_type expected, type = reg->type;
4968         const struct bpf_reg_types *compatible;
4969         int i, j;
4970
4971         compatible = compatible_reg_types[base_type(arg_type)];
4972         if (!compatible) {
4973                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4974                 return -EFAULT;
4975         }
4976
4977         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
4978          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
4979          *
4980          * Same for MAYBE_NULL:
4981          *
4982          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
4983          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
4984          *
4985          * Therefore we fold these flags depending on the arg_type before comparison.
4986          */
4987         if (arg_type & MEM_RDONLY)
4988                 type &= ~MEM_RDONLY;
4989         if (arg_type & PTR_MAYBE_NULL)
4990                 type &= ~PTR_MAYBE_NULL;
4991
4992         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4993                 expected = compatible->types[i];
4994                 if (expected == NOT_INIT)
4995                         break;
4996
4997                 if (type == expected)
4998                         goto found;
4999         }
5000
5001         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5002         for (j = 0; j + 1 < i; j++)
5003                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5004         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5005         return -EACCES;
5006
5007 found:
5008         if (reg->type == PTR_TO_BTF_ID) {
5009                 if (!arg_btf_id) {
5010                         if (!compatible->btf_id) {
5011                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5012                                 return -EFAULT;
5013                         }
5014                         arg_btf_id = compatible->btf_id;
5015                 }
5016
5017                 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5018                                           btf_vmlinux, *arg_btf_id)) {
5019                         verbose(env, "R%d is of type %s but %s is expected\n",
5020                                 regno, kernel_type_name(reg->btf, reg->btf_id),
5021                                 kernel_type_name(btf_vmlinux, *arg_btf_id));
5022                         return -EACCES;
5023                 }
5024
5025                 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5026                         verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
5027                                 regno);
5028                         return -EACCES;
5029                 }
5030         }
5031
5032         return 0;
5033 }
5034
5035 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5036                           struct bpf_call_arg_meta *meta,
5037                           const struct bpf_func_proto *fn)
5038 {
5039         u32 regno = BPF_REG_1 + arg;
5040         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5041         enum bpf_arg_type arg_type = fn->arg_type[arg];
5042         enum bpf_reg_type type = reg->type;
5043         int err = 0;
5044
5045         if (arg_type == ARG_DONTCARE)
5046                 return 0;
5047
5048         err = check_reg_arg(env, regno, SRC_OP);
5049         if (err)
5050                 return err;
5051
5052         if (arg_type == ARG_ANYTHING) {
5053                 if (is_pointer_value(env, regno)) {
5054                         verbose(env, "R%d leaks addr into helper function\n",
5055                                 regno);
5056                         return -EACCES;
5057                 }
5058                 return 0;
5059         }
5060
5061         if (type_is_pkt_pointer(type) &&
5062             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5063                 verbose(env, "helper access to the packet is not allowed\n");
5064                 return -EACCES;
5065         }
5066
5067         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5068             base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5069                 err = resolve_map_arg_type(env, meta, &arg_type);
5070                 if (err)
5071                         return err;
5072         }
5073
5074         if (register_is_null(reg) && type_may_be_null(arg_type))
5075                 /* A NULL register has a SCALAR_VALUE type, so skip
5076                  * type checking.
5077                  */
5078                 goto skip_type_check;
5079
5080         err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5081         if (err)
5082                 return err;
5083
5084         if (type == PTR_TO_CTX) {
5085                 err = check_ctx_reg(env, reg, regno);
5086                 if (err < 0)
5087                         return err;
5088         }
5089
5090 skip_type_check:
5091         if (reg->ref_obj_id) {
5092                 if (meta->ref_obj_id) {
5093                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5094                                 regno, reg->ref_obj_id,
5095                                 meta->ref_obj_id);
5096                         return -EFAULT;
5097                 }
5098                 meta->ref_obj_id = reg->ref_obj_id;
5099         }
5100
5101         if (arg_type == ARG_CONST_MAP_PTR) {
5102                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5103                 if (meta->map_ptr) {
5104                         /* Use map_uid (which is unique id of inner map) to reject:
5105                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5106                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5107                          * if (inner_map1 && inner_map2) {
5108                          *     timer = bpf_map_lookup_elem(inner_map1);
5109                          *     if (timer)
5110                          *         // mismatch would have been allowed
5111                          *         bpf_timer_init(timer, inner_map2);
5112                          * }
5113                          *
5114                          * Comparing map_ptr is enough to distinguish normal and outer maps.
5115                          */
5116                         if (meta->map_ptr != reg->map_ptr ||
5117                             meta->map_uid != reg->map_uid) {
5118                                 verbose(env,
5119                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5120                                         meta->map_uid, reg->map_uid);
5121                                 return -EINVAL;
5122                         }
5123                 }
5124                 meta->map_ptr = reg->map_ptr;
5125                 meta->map_uid = reg->map_uid;
5126         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5127                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
5128                  * check that [key, key + map->key_size) are within
5129                  * stack limits and initialized
5130                  */
5131                 if (!meta->map_ptr) {
5132                         /* in function declaration map_ptr must come before
5133                          * map_key, so that it's verified and known before
5134                          * we have to check map_key here. Otherwise it means
5135                          * that kernel subsystem misconfigured verifier
5136                          */
5137                         verbose(env, "invalid map_ptr to access map->key\n");
5138                         return -EACCES;
5139                 }
5140                 err = check_helper_mem_access(env, regno,
5141                                               meta->map_ptr->key_size, false,
5142                                               NULL);
5143         } else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5144                    base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5145                 if (type_may_be_null(arg_type) && register_is_null(reg))
5146                         return 0;
5147
5148                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
5149                  * check [value, value + map->value_size) validity
5150                  */
5151                 if (!meta->map_ptr) {
5152                         /* kernel subsystem misconfigured verifier */
5153                         verbose(env, "invalid map_ptr to access map->value\n");
5154                         return -EACCES;
5155                 }
5156                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5157                 err = check_helper_mem_access(env, regno,
5158                                               meta->map_ptr->value_size, false,
5159                                               meta);
5160         } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5161                 if (!reg->btf_id) {
5162                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5163                         return -EACCES;
5164                 }
5165                 meta->ret_btf = reg->btf;
5166                 meta->ret_btf_id = reg->btf_id;
5167         } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5168                 if (meta->func_id == BPF_FUNC_spin_lock) {
5169                         if (process_spin_lock(env, regno, true))
5170                                 return -EACCES;
5171                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
5172                         if (process_spin_lock(env, regno, false))
5173                                 return -EACCES;
5174                 } else {
5175                         verbose(env, "verifier internal error\n");
5176                         return -EFAULT;
5177                 }
5178         } else if (arg_type == ARG_PTR_TO_TIMER) {
5179                 if (process_timer_func(env, regno, meta))
5180                         return -EACCES;
5181         } else if (arg_type == ARG_PTR_TO_FUNC) {
5182                 meta->subprogno = reg->subprogno;
5183         } else if (arg_type_is_mem_ptr(arg_type)) {
5184                 /* The access to this pointer is only checked when we hit the
5185                  * next is_mem_size argument below.
5186                  */
5187                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5188         } else if (arg_type_is_mem_size(arg_type)) {
5189                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5190
5191                 /* This is used to refine r0 return value bounds for helpers
5192                  * that enforce this value as an upper bound on return values.
5193                  * See do_refine_retval_range() for helpers that can refine
5194                  * the return value. C type of helper is u32 so we pull register
5195                  * bound from umax_value however, if negative verifier errors
5196                  * out. Only upper bounds can be learned because retval is an
5197                  * int type and negative retvals are allowed.
5198                  */
5199                 meta->msize_max_value = reg->umax_value;
5200
5201                 /* The register is SCALAR_VALUE; the access check
5202                  * happens using its boundaries.
5203                  */
5204                 if (!tnum_is_const(reg->var_off))
5205                         /* For unprivileged variable accesses, disable raw
5206                          * mode so that the program is required to
5207                          * initialize all the memory that the helper could
5208                          * just partially fill up.
5209                          */
5210                         meta = NULL;
5211
5212                 if (reg->smin_value < 0) {
5213                         verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5214                                 regno);
5215                         return -EACCES;
5216                 }
5217
5218                 if (reg->umin_value == 0) {
5219                         err = check_helper_mem_access(env, regno - 1, 0,
5220                                                       zero_size_allowed,
5221                                                       meta);
5222                         if (err)
5223                                 return err;
5224                 }
5225
5226                 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5227                         verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5228                                 regno);
5229                         return -EACCES;
5230                 }
5231                 err = check_helper_mem_access(env, regno - 1,
5232                                               reg->umax_value,
5233                                               zero_size_allowed, meta);
5234                 if (!err)
5235                         err = mark_chain_precision(env, regno);
5236         } else if (arg_type_is_alloc_size(arg_type)) {
5237                 if (!tnum_is_const(reg->var_off)) {
5238                         verbose(env, "R%d is not a known constant'\n",
5239                                 regno);
5240                         return -EACCES;
5241                 }
5242                 meta->mem_size = reg->var_off.value;
5243         } else if (arg_type_is_int_ptr(arg_type)) {
5244                 int size = int_ptr_type_to_size(arg_type);
5245
5246                 err = check_helper_mem_access(env, regno, size, false, meta);
5247                 if (err)
5248                         return err;
5249                 err = check_ptr_alignment(env, reg, 0, size, true);
5250         } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5251                 struct bpf_map *map = reg->map_ptr;
5252                 int map_off;
5253                 u64 map_addr;
5254                 char *str_ptr;
5255
5256                 if (!bpf_map_is_rdonly(map)) {
5257                         verbose(env, "R%d does not point to a readonly map'\n", regno);
5258                         return -EACCES;
5259                 }
5260
5261                 if (!tnum_is_const(reg->var_off)) {
5262                         verbose(env, "R%d is not a constant address'\n", regno);
5263                         return -EACCES;
5264                 }
5265
5266                 if (!map->ops->map_direct_value_addr) {
5267                         verbose(env, "no direct value access support for this map type\n");
5268                         return -EACCES;
5269                 }
5270
5271                 err = check_map_access(env, regno, reg->off,
5272                                        map->value_size - reg->off, false);
5273                 if (err)
5274                         return err;
5275
5276                 map_off = reg->off + reg->var_off.value;
5277                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5278                 if (err) {
5279                         verbose(env, "direct value access on string failed\n");
5280                         return err;
5281                 }
5282
5283                 str_ptr = (char *)(long)(map_addr);
5284                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5285                         verbose(env, "string is not zero-terminated\n");
5286                         return -EINVAL;
5287                 }
5288         }
5289
5290         return err;
5291 }
5292
5293 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5294 {
5295         enum bpf_attach_type eatype = env->prog->expected_attach_type;
5296         enum bpf_prog_type type = resolve_prog_type(env->prog);
5297
5298         if (func_id != BPF_FUNC_map_update_elem)
5299                 return false;
5300
5301         /* It's not possible to get access to a locked struct sock in these
5302          * contexts, so updating is safe.
5303          */
5304         switch (type) {
5305         case BPF_PROG_TYPE_TRACING:
5306                 if (eatype == BPF_TRACE_ITER)
5307                         return true;
5308                 break;
5309         case BPF_PROG_TYPE_SOCKET_FILTER:
5310         case BPF_PROG_TYPE_SCHED_CLS:
5311         case BPF_PROG_TYPE_SCHED_ACT:
5312         case BPF_PROG_TYPE_XDP:
5313         case BPF_PROG_TYPE_SK_REUSEPORT:
5314         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5315         case BPF_PROG_TYPE_SK_LOOKUP:
5316                 return true;
5317         default:
5318                 break;
5319         }
5320
5321         verbose(env, "cannot update sockmap in this context\n");
5322         return false;
5323 }
5324
5325 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5326 {
5327         return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5328 }
5329
5330 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5331                                         struct bpf_map *map, int func_id)
5332 {
5333         if (!map)
5334                 return 0;
5335
5336         /* We need a two way check, first is from map perspective ... */
5337         switch (map->map_type) {
5338         case BPF_MAP_TYPE_PROG_ARRAY:
5339                 if (func_id != BPF_FUNC_tail_call)
5340                         goto error;
5341                 break;
5342         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5343                 if (func_id != BPF_FUNC_perf_event_read &&
5344                     func_id != BPF_FUNC_perf_event_output &&
5345                     func_id != BPF_FUNC_skb_output &&
5346                     func_id != BPF_FUNC_perf_event_read_value &&
5347                     func_id != BPF_FUNC_xdp_output)
5348                         goto error;
5349                 break;
5350         case BPF_MAP_TYPE_RINGBUF:
5351                 if (func_id != BPF_FUNC_ringbuf_output &&
5352                     func_id != BPF_FUNC_ringbuf_reserve &&
5353                     func_id != BPF_FUNC_ringbuf_query)
5354                         goto error;
5355                 break;
5356         case BPF_MAP_TYPE_STACK_TRACE:
5357                 if (func_id != BPF_FUNC_get_stackid)
5358                         goto error;
5359                 break;
5360         case BPF_MAP_TYPE_CGROUP_ARRAY:
5361                 if (func_id != BPF_FUNC_skb_under_cgroup &&
5362                     func_id != BPF_FUNC_current_task_under_cgroup)
5363                         goto error;
5364                 break;
5365         case BPF_MAP_TYPE_CGROUP_STORAGE:
5366         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5367                 if (func_id != BPF_FUNC_get_local_storage)
5368                         goto error;
5369                 break;
5370         case BPF_MAP_TYPE_DEVMAP:
5371         case BPF_MAP_TYPE_DEVMAP_HASH:
5372                 if (func_id != BPF_FUNC_redirect_map &&
5373                     func_id != BPF_FUNC_map_lookup_elem)
5374                         goto error;
5375                 break;
5376         /* Restrict bpf side of cpumap and xskmap, open when use-cases
5377          * appear.
5378          */
5379         case BPF_MAP_TYPE_CPUMAP:
5380                 if (func_id != BPF_FUNC_redirect_map)
5381                         goto error;
5382                 break;
5383         case BPF_MAP_TYPE_XSKMAP:
5384                 if (func_id != BPF_FUNC_redirect_map &&
5385                     func_id != BPF_FUNC_map_lookup_elem)
5386                         goto error;
5387                 break;
5388         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5389         case BPF_MAP_TYPE_HASH_OF_MAPS:
5390                 if (func_id != BPF_FUNC_map_lookup_elem)
5391                         goto error;
5392                 break;
5393         case BPF_MAP_TYPE_SOCKMAP:
5394                 if (func_id != BPF_FUNC_sk_redirect_map &&
5395                     func_id != BPF_FUNC_sock_map_update &&
5396                     func_id != BPF_FUNC_map_delete_elem &&
5397                     func_id != BPF_FUNC_msg_redirect_map &&
5398                     func_id != BPF_FUNC_sk_select_reuseport &&
5399                     func_id != BPF_FUNC_map_lookup_elem &&
5400                     !may_update_sockmap(env, func_id))
5401                         goto error;
5402                 break;
5403         case BPF_MAP_TYPE_SOCKHASH:
5404                 if (func_id != BPF_FUNC_sk_redirect_hash &&
5405                     func_id != BPF_FUNC_sock_hash_update &&
5406                     func_id != BPF_FUNC_map_delete_elem &&
5407                     func_id != BPF_FUNC_msg_redirect_hash &&
5408                     func_id != BPF_FUNC_sk_select_reuseport &&
5409                     func_id != BPF_FUNC_map_lookup_elem &&
5410                     !may_update_sockmap(env, func_id))
5411                         goto error;
5412                 break;
5413         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5414                 if (func_id != BPF_FUNC_sk_select_reuseport)
5415                         goto error;
5416                 break;
5417         case BPF_MAP_TYPE_QUEUE:
5418         case BPF_MAP_TYPE_STACK:
5419                 if (func_id != BPF_FUNC_map_peek_elem &&
5420                     func_id != BPF_FUNC_map_pop_elem &&
5421                     func_id != BPF_FUNC_map_push_elem)
5422                         goto error;
5423                 break;
5424         case BPF_MAP_TYPE_SK_STORAGE:
5425                 if (func_id != BPF_FUNC_sk_storage_get &&
5426                     func_id != BPF_FUNC_sk_storage_delete)
5427                         goto error;
5428                 break;
5429         case BPF_MAP_TYPE_INODE_STORAGE:
5430                 if (func_id != BPF_FUNC_inode_storage_get &&
5431                     func_id != BPF_FUNC_inode_storage_delete)
5432                         goto error;
5433                 break;
5434         case BPF_MAP_TYPE_TASK_STORAGE:
5435                 if (func_id != BPF_FUNC_task_storage_get &&
5436                     func_id != BPF_FUNC_task_storage_delete)
5437                         goto error;
5438                 break;
5439         default:
5440                 break;
5441         }
5442
5443         /* ... and second from the function itself. */
5444         switch (func_id) {
5445         case BPF_FUNC_tail_call:
5446                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5447                         goto error;
5448                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5449                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5450                         return -EINVAL;
5451                 }
5452                 break;
5453         case BPF_FUNC_perf_event_read:
5454         case BPF_FUNC_perf_event_output:
5455         case BPF_FUNC_perf_event_read_value:
5456         case BPF_FUNC_skb_output:
5457         case BPF_FUNC_xdp_output:
5458                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5459                         goto error;
5460                 break;
5461         case BPF_FUNC_ringbuf_output:
5462         case BPF_FUNC_ringbuf_reserve:
5463         case BPF_FUNC_ringbuf_query:
5464                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5465                         goto error;
5466                 break;
5467         case BPF_FUNC_get_stackid:
5468                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5469                         goto error;
5470                 break;
5471         case BPF_FUNC_current_task_under_cgroup:
5472         case BPF_FUNC_skb_under_cgroup:
5473                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5474                         goto error;
5475                 break;
5476         case BPF_FUNC_redirect_map:
5477                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5478                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5479                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
5480                     map->map_type != BPF_MAP_TYPE_XSKMAP)
5481                         goto error;
5482                 break;
5483         case BPF_FUNC_sk_redirect_map:
5484         case BPF_FUNC_msg_redirect_map:
5485         case BPF_FUNC_sock_map_update:
5486                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5487                         goto error;
5488                 break;
5489         case BPF_FUNC_sk_redirect_hash:
5490         case BPF_FUNC_msg_redirect_hash:
5491         case BPF_FUNC_sock_hash_update:
5492                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5493                         goto error;
5494                 break;
5495         case BPF_FUNC_get_local_storage:
5496                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5497                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5498                         goto error;
5499                 break;
5500         case BPF_FUNC_sk_select_reuseport:
5501                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5502                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5503                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
5504                         goto error;
5505                 break;
5506         case BPF_FUNC_map_peek_elem:
5507         case BPF_FUNC_map_pop_elem:
5508         case BPF_FUNC_map_push_elem:
5509                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5510                     map->map_type != BPF_MAP_TYPE_STACK)
5511                         goto error;
5512                 break;
5513         case BPF_FUNC_sk_storage_get:
5514         case BPF_FUNC_sk_storage_delete:
5515                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5516                         goto error;
5517                 break;
5518         case BPF_FUNC_inode_storage_get:
5519         case BPF_FUNC_inode_storage_delete:
5520                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5521                         goto error;
5522                 break;
5523         case BPF_FUNC_task_storage_get:
5524         case BPF_FUNC_task_storage_delete:
5525                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5526                         goto error;
5527                 break;
5528         default:
5529                 break;
5530         }
5531
5532         return 0;
5533 error:
5534         verbose(env, "cannot pass map_type %d into func %s#%d\n",
5535                 map->map_type, func_id_name(func_id), func_id);
5536         return -EINVAL;
5537 }
5538
5539 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5540 {
5541         int count = 0;
5542
5543         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5544                 count++;
5545         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5546                 count++;
5547         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5548                 count++;
5549         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5550                 count++;
5551         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5552                 count++;
5553
5554         /* We only support one arg being in raw mode at the moment,
5555          * which is sufficient for the helper functions we have
5556          * right now.
5557          */
5558         return count <= 1;
5559 }
5560
5561 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5562                                     enum bpf_arg_type arg_next)
5563 {
5564         return (arg_type_is_mem_ptr(arg_curr) &&
5565                 !arg_type_is_mem_size(arg_next)) ||
5566                (!arg_type_is_mem_ptr(arg_curr) &&
5567                 arg_type_is_mem_size(arg_next));
5568 }
5569
5570 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5571 {
5572         /* bpf_xxx(..., buf, len) call will access 'len'
5573          * bytes from memory 'buf'. Both arg types need
5574          * to be paired, so make sure there's no buggy
5575          * helper function specification.
5576          */
5577         if (arg_type_is_mem_size(fn->arg1_type) ||
5578             arg_type_is_mem_ptr(fn->arg5_type)  ||
5579             check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5580             check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5581             check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5582             check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5583                 return false;
5584
5585         return true;
5586 }
5587
5588 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5589 {
5590         int count = 0;
5591
5592         if (arg_type_may_be_refcounted(fn->arg1_type))
5593                 count++;
5594         if (arg_type_may_be_refcounted(fn->arg2_type))
5595                 count++;
5596         if (arg_type_may_be_refcounted(fn->arg3_type))
5597                 count++;
5598         if (arg_type_may_be_refcounted(fn->arg4_type))
5599                 count++;
5600         if (arg_type_may_be_refcounted(fn->arg5_type))
5601                 count++;
5602
5603         /* A reference acquiring function cannot acquire
5604          * another refcounted ptr.
5605          */
5606         if (may_be_acquire_function(func_id) && count)
5607                 return false;
5608
5609         /* We only support one arg being unreferenced at the moment,
5610          * which is sufficient for the helper functions we have right now.
5611          */
5612         return count <= 1;
5613 }
5614
5615 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5616 {
5617         int i;
5618
5619         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5620                 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5621                         return false;
5622
5623                 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5624                         return false;
5625         }
5626
5627         return true;
5628 }
5629
5630 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5631 {
5632         return check_raw_mode_ok(fn) &&
5633                check_arg_pair_ok(fn) &&
5634                check_btf_id_ok(fn) &&
5635                check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5636 }
5637
5638 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5639  * are now invalid, so turn them into unknown SCALAR_VALUE.
5640  */
5641 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5642                                      struct bpf_func_state *state)
5643 {
5644         struct bpf_reg_state *regs = state->regs, *reg;
5645         int i;
5646
5647         for (i = 0; i < MAX_BPF_REG; i++)
5648                 if (reg_is_pkt_pointer_any(&regs[i]))
5649                         mark_reg_unknown(env, regs, i);
5650
5651         bpf_for_each_spilled_reg(i, state, reg) {
5652                 if (!reg)
5653                         continue;
5654                 if (reg_is_pkt_pointer_any(reg))
5655                         __mark_reg_unknown(env, reg);
5656         }
5657 }
5658
5659 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5660 {
5661         struct bpf_verifier_state *vstate = env->cur_state;
5662         int i;
5663
5664         for (i = 0; i <= vstate->curframe; i++)
5665                 __clear_all_pkt_pointers(env, vstate->frame[i]);
5666 }
5667
5668 enum {
5669         AT_PKT_END = -1,
5670         BEYOND_PKT_END = -2,
5671 };
5672
5673 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5674 {
5675         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5676         struct bpf_reg_state *reg = &state->regs[regn];
5677
5678         if (reg->type != PTR_TO_PACKET)
5679                 /* PTR_TO_PACKET_META is not supported yet */
5680                 return;
5681
5682         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5683          * How far beyond pkt_end it goes is unknown.
5684          * if (!range_open) it's the case of pkt >= pkt_end
5685          * if (range_open) it's the case of pkt > pkt_end
5686          * hence this pointer is at least 1 byte bigger than pkt_end
5687          */
5688         if (range_open)
5689                 reg->range = BEYOND_PKT_END;
5690         else
5691                 reg->range = AT_PKT_END;
5692 }
5693
5694 static void release_reg_references(struct bpf_verifier_env *env,
5695                                    struct bpf_func_state *state,
5696                                    int ref_obj_id)
5697 {
5698         struct bpf_reg_state *regs = state->regs, *reg;
5699         int i;
5700
5701         for (i = 0; i < MAX_BPF_REG; i++)
5702                 if (regs[i].ref_obj_id == ref_obj_id)
5703                         mark_reg_unknown(env, regs, i);
5704
5705         bpf_for_each_spilled_reg(i, state, reg) {
5706                 if (!reg)
5707                         continue;
5708                 if (reg->ref_obj_id == ref_obj_id)
5709                         __mark_reg_unknown(env, reg);
5710         }
5711 }
5712
5713 /* The pointer with the specified id has released its reference to kernel
5714  * resources. Identify all copies of the same pointer and clear the reference.
5715  */
5716 static int release_reference(struct bpf_verifier_env *env,
5717                              int ref_obj_id)
5718 {
5719         struct bpf_verifier_state *vstate = env->cur_state;
5720         int err;
5721         int i;
5722
5723         err = release_reference_state(cur_func(env), ref_obj_id);
5724         if (err)
5725                 return err;
5726
5727         for (i = 0; i <= vstate->curframe; i++)
5728                 release_reg_references(env, vstate->frame[i], ref_obj_id);
5729
5730         return 0;
5731 }
5732
5733 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5734                                     struct bpf_reg_state *regs)
5735 {
5736         int i;
5737
5738         /* after the call registers r0 - r5 were scratched */
5739         for (i = 0; i < CALLER_SAVED_REGS; i++) {
5740                 mark_reg_not_init(env, regs, caller_saved[i]);
5741                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5742         }
5743 }
5744
5745 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5746                                    struct bpf_func_state *caller,
5747                                    struct bpf_func_state *callee,
5748                                    int insn_idx);
5749
5750 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5751                              int *insn_idx, int subprog,
5752                              set_callee_state_fn set_callee_state_cb)
5753 {
5754         struct bpf_verifier_state *state = env->cur_state;
5755         struct bpf_func_info_aux *func_info_aux;
5756         struct bpf_func_state *caller, *callee;
5757         int err;
5758         bool is_global = false;
5759
5760         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5761                 verbose(env, "the call stack of %d frames is too deep\n",
5762                         state->curframe + 2);
5763                 return -E2BIG;
5764         }
5765
5766         caller = state->frame[state->curframe];
5767         if (state->frame[state->curframe + 1]) {
5768                 verbose(env, "verifier bug. Frame %d already allocated\n",
5769                         state->curframe + 1);
5770                 return -EFAULT;
5771         }
5772
5773         func_info_aux = env->prog->aux->func_info_aux;
5774         if (func_info_aux)
5775                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5776         err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5777         if (err == -EFAULT)
5778                 return err;
5779         if (is_global) {
5780                 if (err) {
5781                         verbose(env, "Caller passes invalid args into func#%d\n",
5782                                 subprog);
5783                         return err;
5784                 } else {
5785                         if (env->log.level & BPF_LOG_LEVEL)
5786                                 verbose(env,
5787                                         "Func#%d is global and valid. Skipping.\n",
5788                                         subprog);
5789                         clear_caller_saved_regs(env, caller->regs);
5790
5791                         /* All global functions return a 64-bit SCALAR_VALUE */
5792                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
5793                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5794
5795                         /* continue with next insn after call */
5796                         return 0;
5797                 }
5798         }
5799
5800         if (insn->code == (BPF_JMP | BPF_CALL) &&
5801             insn->src_reg == 0 &&
5802             insn->imm == BPF_FUNC_timer_set_callback) {
5803                 struct bpf_verifier_state *async_cb;
5804
5805                 /* there is no real recursion here. timer callbacks are async */
5806                 env->subprog_info[subprog].is_async_cb = true;
5807                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
5808                                          *insn_idx, subprog);
5809                 if (!async_cb)
5810                         return -EFAULT;
5811                 callee = async_cb->frame[0];
5812                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
5813
5814                 /* Convert bpf_timer_set_callback() args into timer callback args */
5815                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5816                 if (err)
5817                         return err;
5818
5819                 clear_caller_saved_regs(env, caller->regs);
5820                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5821                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5822                 /* continue with next insn after call */
5823                 return 0;
5824         }
5825
5826         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5827         if (!callee)
5828                 return -ENOMEM;
5829         state->frame[state->curframe + 1] = callee;
5830
5831         /* callee cannot access r0, r6 - r9 for reading and has to write
5832          * into its own stack before reading from it.
5833          * callee can read/write into caller's stack
5834          */
5835         init_func_state(env, callee,
5836                         /* remember the callsite, it will be used by bpf_exit */
5837                         *insn_idx /* callsite */,
5838                         state->curframe + 1 /* frameno within this callchain */,
5839                         subprog /* subprog number within this prog */);
5840
5841         /* Transfer references to the callee */
5842         err = copy_reference_state(callee, caller);
5843         if (err)
5844                 return err;
5845
5846         err = set_callee_state_cb(env, caller, callee, *insn_idx);
5847         if (err)
5848                 return err;
5849
5850         clear_caller_saved_regs(env, caller->regs);
5851
5852         /* only increment it after check_reg_arg() finished */
5853         state->curframe++;
5854
5855         /* and go analyze first insn of the callee */
5856         *insn_idx = env->subprog_info[subprog].start - 1;
5857
5858         if (env->log.level & BPF_LOG_LEVEL) {
5859                 verbose(env, "caller:\n");
5860                 print_verifier_state(env, caller);
5861                 verbose(env, "callee:\n");
5862                 print_verifier_state(env, callee);
5863         }
5864         return 0;
5865 }
5866
5867 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5868                                    struct bpf_func_state *caller,
5869                                    struct bpf_func_state *callee)
5870 {
5871         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5872          *      void *callback_ctx, u64 flags);
5873          * callback_fn(struct bpf_map *map, void *key, void *value,
5874          *      void *callback_ctx);
5875          */
5876         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5877
5878         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5879         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5880         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5881
5882         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5883         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5884         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5885
5886         /* pointer to stack or null */
5887         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5888
5889         /* unused */
5890         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5891         return 0;
5892 }
5893
5894 static int set_callee_state(struct bpf_verifier_env *env,
5895                             struct bpf_func_state *caller,
5896                             struct bpf_func_state *callee, int insn_idx)
5897 {
5898         int i;
5899
5900         /* copy r1 - r5 args that callee can access.  The copy includes parent
5901          * pointers, which connects us up to the liveness chain
5902          */
5903         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5904                 callee->regs[i] = caller->regs[i];
5905         return 0;
5906 }
5907
5908 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5909                            int *insn_idx)
5910 {
5911         int subprog, target_insn;
5912
5913         target_insn = *insn_idx + insn->imm + 1;
5914         subprog = find_subprog(env, target_insn);
5915         if (subprog < 0) {
5916                 verbose(env, "verifier bug. No program starts at insn %d\n",
5917                         target_insn);
5918                 return -EFAULT;
5919         }
5920
5921         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5922 }
5923
5924 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5925                                        struct bpf_func_state *caller,
5926                                        struct bpf_func_state *callee,
5927                                        int insn_idx)
5928 {
5929         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5930         struct bpf_map *map;
5931         int err;
5932
5933         if (bpf_map_ptr_poisoned(insn_aux)) {
5934                 verbose(env, "tail_call abusing map_ptr\n");
5935                 return -EINVAL;
5936         }
5937
5938         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5939         if (!map->ops->map_set_for_each_callback_args ||
5940             !map->ops->map_for_each_callback) {
5941                 verbose(env, "callback function not allowed for map\n");
5942                 return -ENOTSUPP;
5943         }
5944
5945         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5946         if (err)
5947                 return err;
5948
5949         callee->in_callback_fn = true;
5950         return 0;
5951 }
5952
5953 static int set_timer_callback_state(struct bpf_verifier_env *env,
5954                                     struct bpf_func_state *caller,
5955                                     struct bpf_func_state *callee,
5956                                     int insn_idx)
5957 {
5958         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
5959
5960         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
5961          * callback_fn(struct bpf_map *map, void *key, void *value);
5962          */
5963         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
5964         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
5965         callee->regs[BPF_REG_1].map_ptr = map_ptr;
5966
5967         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5968         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5969         callee->regs[BPF_REG_2].map_ptr = map_ptr;
5970
5971         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5972         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5973         callee->regs[BPF_REG_3].map_ptr = map_ptr;
5974
5975         /* unused */
5976         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
5977         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5978         callee->in_async_callback_fn = true;
5979         return 0;
5980 }
5981
5982 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5983 {
5984         struct bpf_verifier_state *state = env->cur_state;
5985         struct bpf_func_state *caller, *callee;
5986         struct bpf_reg_state *r0;
5987         int err;
5988
5989         callee = state->frame[state->curframe];
5990         r0 = &callee->regs[BPF_REG_0];
5991         if (r0->type == PTR_TO_STACK) {
5992                 /* technically it's ok to return caller's stack pointer
5993                  * (or caller's caller's pointer) back to the caller,
5994                  * since these pointers are valid. Only current stack
5995                  * pointer will be invalid as soon as function exits,
5996                  * but let's be conservative
5997                  */
5998                 verbose(env, "cannot return stack pointer to the caller\n");
5999                 return -EINVAL;
6000         }
6001
6002         state->curframe--;
6003         caller = state->frame[state->curframe];
6004         if (callee->in_callback_fn) {
6005                 /* enforce R0 return value range [0, 1]. */
6006                 struct tnum range = tnum_range(0, 1);
6007
6008                 if (r0->type != SCALAR_VALUE) {
6009                         verbose(env, "R0 not a scalar value\n");
6010                         return -EACCES;
6011                 }
6012                 if (!tnum_in(range, r0->var_off)) {
6013                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6014                         return -EINVAL;
6015                 }
6016         } else {
6017                 /* return to the caller whatever r0 had in the callee */
6018                 caller->regs[BPF_REG_0] = *r0;
6019         }
6020
6021         /* Transfer references to the caller */
6022         err = copy_reference_state(caller, callee);
6023         if (err)
6024                 return err;
6025
6026         *insn_idx = callee->callsite + 1;
6027         if (env->log.level & BPF_LOG_LEVEL) {
6028                 verbose(env, "returning from callee:\n");
6029                 print_verifier_state(env, callee);
6030                 verbose(env, "to caller at %d:\n", *insn_idx);
6031                 print_verifier_state(env, caller);
6032         }
6033         /* clear everything in the callee */
6034         free_func_state(callee);
6035         state->frame[state->curframe + 1] = NULL;
6036         return 0;
6037 }
6038
6039 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6040                                    int func_id,
6041                                    struct bpf_call_arg_meta *meta)
6042 {
6043         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6044
6045         if (ret_type != RET_INTEGER ||
6046             (func_id != BPF_FUNC_get_stack &&
6047              func_id != BPF_FUNC_get_task_stack &&
6048              func_id != BPF_FUNC_probe_read_str &&
6049              func_id != BPF_FUNC_probe_read_kernel_str &&
6050              func_id != BPF_FUNC_probe_read_user_str))
6051                 return;
6052
6053         ret_reg->smax_value = meta->msize_max_value;
6054         ret_reg->s32_max_value = meta->msize_max_value;
6055         ret_reg->smin_value = -MAX_ERRNO;
6056         ret_reg->s32_min_value = -MAX_ERRNO;
6057         __reg_deduce_bounds(ret_reg);
6058         __reg_bound_offset(ret_reg);
6059         __update_reg_bounds(ret_reg);
6060 }
6061
6062 static int
6063 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6064                 int func_id, int insn_idx)
6065 {
6066         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6067         struct bpf_map *map = meta->map_ptr;
6068
6069         if (func_id != BPF_FUNC_tail_call &&
6070             func_id != BPF_FUNC_map_lookup_elem &&
6071             func_id != BPF_FUNC_map_update_elem &&
6072             func_id != BPF_FUNC_map_delete_elem &&
6073             func_id != BPF_FUNC_map_push_elem &&
6074             func_id != BPF_FUNC_map_pop_elem &&
6075             func_id != BPF_FUNC_map_peek_elem &&
6076             func_id != BPF_FUNC_for_each_map_elem &&
6077             func_id != BPF_FUNC_redirect_map)
6078                 return 0;
6079
6080         if (map == NULL) {
6081                 verbose(env, "kernel subsystem misconfigured verifier\n");
6082                 return -EINVAL;
6083         }
6084
6085         /* In case of read-only, some additional restrictions
6086          * need to be applied in order to prevent altering the
6087          * state of the map from program side.
6088          */
6089         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6090             (func_id == BPF_FUNC_map_delete_elem ||
6091              func_id == BPF_FUNC_map_update_elem ||
6092              func_id == BPF_FUNC_map_push_elem ||
6093              func_id == BPF_FUNC_map_pop_elem)) {
6094                 verbose(env, "write into map forbidden\n");
6095                 return -EACCES;
6096         }
6097
6098         if (!BPF_MAP_PTR(aux->map_ptr_state))
6099                 bpf_map_ptr_store(aux, meta->map_ptr,
6100                                   !meta->map_ptr->bypass_spec_v1);
6101         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6102                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6103                                   !meta->map_ptr->bypass_spec_v1);
6104         return 0;
6105 }
6106
6107 static int
6108 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6109                 int func_id, int insn_idx)
6110 {
6111         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6112         struct bpf_reg_state *regs = cur_regs(env), *reg;
6113         struct bpf_map *map = meta->map_ptr;
6114         struct tnum range;
6115         u64 val;
6116         int err;
6117
6118         if (func_id != BPF_FUNC_tail_call)
6119                 return 0;
6120         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6121                 verbose(env, "kernel subsystem misconfigured verifier\n");
6122                 return -EINVAL;
6123         }
6124
6125         range = tnum_range(0, map->max_entries - 1);
6126         reg = &regs[BPF_REG_3];
6127
6128         if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6129                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6130                 return 0;
6131         }
6132
6133         err = mark_chain_precision(env, BPF_REG_3);
6134         if (err)
6135                 return err;
6136
6137         val = reg->var_off.value;
6138         if (bpf_map_key_unseen(aux))
6139                 bpf_map_key_store(aux, val);
6140         else if (!bpf_map_key_poisoned(aux) &&
6141                   bpf_map_key_immediate(aux) != val)
6142                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6143         return 0;
6144 }
6145
6146 static int check_reference_leak(struct bpf_verifier_env *env)
6147 {
6148         struct bpf_func_state *state = cur_func(env);
6149         int i;
6150
6151         for (i = 0; i < state->acquired_refs; i++) {
6152                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6153                         state->refs[i].id, state->refs[i].insn_idx);
6154         }
6155         return state->acquired_refs ? -EINVAL : 0;
6156 }
6157
6158 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6159                                    struct bpf_reg_state *regs)
6160 {
6161         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6162         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6163         struct bpf_map *fmt_map = fmt_reg->map_ptr;
6164         int err, fmt_map_off, num_args;
6165         u64 fmt_addr;
6166         char *fmt;
6167
6168         /* data must be an array of u64 */
6169         if (data_len_reg->var_off.value % 8)
6170                 return -EINVAL;
6171         num_args = data_len_reg->var_off.value / 8;
6172
6173         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6174          * and map_direct_value_addr is set.
6175          */
6176         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6177         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6178                                                   fmt_map_off);
6179         if (err) {
6180                 verbose(env, "verifier bug\n");
6181                 return -EFAULT;
6182         }
6183         fmt = (char *)(long)fmt_addr + fmt_map_off;
6184
6185         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6186          * can focus on validating the format specifiers.
6187          */
6188         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6189         if (err < 0)
6190                 verbose(env, "Invalid format string\n");
6191
6192         return err;
6193 }
6194
6195 static int check_get_func_ip(struct bpf_verifier_env *env)
6196 {
6197         enum bpf_attach_type eatype = env->prog->expected_attach_type;
6198         enum bpf_prog_type type = resolve_prog_type(env->prog);
6199         int func_id = BPF_FUNC_get_func_ip;
6200
6201         if (type == BPF_PROG_TYPE_TRACING) {
6202                 if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT &&
6203                     eatype != BPF_MODIFY_RETURN) {
6204                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6205                                 func_id_name(func_id), func_id);
6206                         return -ENOTSUPP;
6207                 }
6208                 return 0;
6209         } else if (type == BPF_PROG_TYPE_KPROBE) {
6210                 return 0;
6211         }
6212
6213         verbose(env, "func %s#%d not supported for program type %d\n",
6214                 func_id_name(func_id), func_id, type);
6215         return -ENOTSUPP;
6216 }
6217
6218 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6219                              int *insn_idx_p)
6220 {
6221         const struct bpf_func_proto *fn = NULL;
6222         enum bpf_return_type ret_type;
6223         enum bpf_type_flag ret_flag;
6224         struct bpf_reg_state *regs;
6225         struct bpf_call_arg_meta meta;
6226         int insn_idx = *insn_idx_p;
6227         bool changes_data;
6228         int i, err, func_id;
6229
6230         /* find function prototype */
6231         func_id = insn->imm;
6232         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6233                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6234                         func_id);
6235                 return -EINVAL;
6236         }
6237
6238         if (env->ops->get_func_proto)
6239                 fn = env->ops->get_func_proto(func_id, env->prog);
6240         if (!fn) {
6241                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6242                         func_id);
6243                 return -EINVAL;
6244         }
6245
6246         /* eBPF programs must be GPL compatible to use GPL-ed functions */
6247         if (!env->prog->gpl_compatible && fn->gpl_only) {
6248                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6249                 return -EINVAL;
6250         }
6251
6252         if (fn->allowed && !fn->allowed(env->prog)) {
6253                 verbose(env, "helper call is not allowed in probe\n");
6254                 return -EINVAL;
6255         }
6256
6257         /* With LD_ABS/IND some JITs save/restore skb from r1. */
6258         changes_data = bpf_helper_changes_pkt_data(fn->func);
6259         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6260                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6261                         func_id_name(func_id), func_id);
6262                 return -EINVAL;
6263         }
6264
6265         memset(&meta, 0, sizeof(meta));
6266         meta.pkt_access = fn->pkt_access;
6267
6268         err = check_func_proto(fn, func_id);
6269         if (err) {
6270                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6271                         func_id_name(func_id), func_id);
6272                 return err;
6273         }
6274
6275         meta.func_id = func_id;
6276         /* check args */
6277         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6278                 err = check_func_arg(env, i, &meta, fn);
6279                 if (err)
6280                         return err;
6281         }
6282
6283         err = record_func_map(env, &meta, func_id, insn_idx);
6284         if (err)
6285                 return err;
6286
6287         err = record_func_key(env, &meta, func_id, insn_idx);
6288         if (err)
6289                 return err;
6290
6291         /* Mark slots with STACK_MISC in case of raw mode, stack offset
6292          * is inferred from register state.
6293          */
6294         for (i = 0; i < meta.access_size; i++) {
6295                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6296                                        BPF_WRITE, -1, false);
6297                 if (err)
6298                         return err;
6299         }
6300
6301         if (func_id == BPF_FUNC_tail_call) {
6302                 err = check_reference_leak(env);
6303                 if (err) {
6304                         verbose(env, "tail_call would lead to reference leak\n");
6305                         return err;
6306                 }
6307         } else if (is_release_function(func_id)) {
6308                 err = release_reference(env, meta.ref_obj_id);
6309                 if (err) {
6310                         verbose(env, "func %s#%d reference has not been acquired before\n",
6311                                 func_id_name(func_id), func_id);
6312                         return err;
6313                 }
6314         }
6315
6316         regs = cur_regs(env);
6317
6318         /* check that flags argument in get_local_storage(map, flags) is 0,
6319          * this is required because get_local_storage() can't return an error.
6320          */
6321         if (func_id == BPF_FUNC_get_local_storage &&
6322             !register_is_null(&regs[BPF_REG_2])) {
6323                 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6324                 return -EINVAL;
6325         }
6326
6327         if (func_id == BPF_FUNC_for_each_map_elem) {
6328                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6329                                         set_map_elem_callback_state);
6330                 if (err < 0)
6331                         return -EINVAL;
6332         }
6333
6334         if (func_id == BPF_FUNC_timer_set_callback) {
6335                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6336                                         set_timer_callback_state);
6337                 if (err < 0)
6338                         return -EINVAL;
6339         }
6340
6341         if (func_id == BPF_FUNC_snprintf) {
6342                 err = check_bpf_snprintf_call(env, regs);
6343                 if (err < 0)
6344                         return err;
6345         }
6346
6347         /* reset caller saved regs */
6348         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6349                 mark_reg_not_init(env, regs, caller_saved[i]);
6350                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6351         }
6352
6353         /* helper call returns 64-bit value. */
6354         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6355
6356         /* update return register (already marked as written above) */
6357         ret_type = fn->ret_type;
6358         ret_flag = type_flag(fn->ret_type);
6359         if (ret_type == RET_INTEGER) {
6360                 /* sets type to SCALAR_VALUE */
6361                 mark_reg_unknown(env, regs, BPF_REG_0);
6362         } else if (ret_type == RET_VOID) {
6363                 regs[BPF_REG_0].type = NOT_INIT;
6364         } else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
6365                 /* There is no offset yet applied, variable or fixed */
6366                 mark_reg_known_zero(env, regs, BPF_REG_0);
6367                 /* remember map_ptr, so that check_map_access()
6368                  * can check 'value_size' boundary of memory access
6369                  * to map element returned from bpf_map_lookup_elem()
6370                  */
6371                 if (meta.map_ptr == NULL) {
6372                         verbose(env,
6373                                 "kernel subsystem misconfigured verifier\n");
6374                         return -EINVAL;
6375                 }
6376                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
6377                 regs[BPF_REG_0].map_uid = meta.map_uid;
6378                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
6379                 if (!type_may_be_null(ret_type) &&
6380                     map_value_has_spin_lock(meta.map_ptr)) {
6381                         regs[BPF_REG_0].id = ++env->id_gen;
6382                 }
6383         } else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
6384                 mark_reg_known_zero(env, regs, BPF_REG_0);
6385                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
6386         } else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
6387                 mark_reg_known_zero(env, regs, BPF_REG_0);
6388                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
6389         } else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
6390                 mark_reg_known_zero(env, regs, BPF_REG_0);
6391                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
6392         } else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
6393                 mark_reg_known_zero(env, regs, BPF_REG_0);
6394                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6395                 regs[BPF_REG_0].mem_size = meta.mem_size;
6396         } else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
6397                 const struct btf_type *t;
6398
6399                 mark_reg_known_zero(env, regs, BPF_REG_0);
6400                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6401                 if (!btf_type_is_struct(t)) {
6402                         u32 tsize;
6403                         const struct btf_type *ret;
6404                         const char *tname;
6405
6406                         /* resolve the type size of ksym. */
6407                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6408                         if (IS_ERR(ret)) {
6409                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6410                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6411                                         tname, PTR_ERR(ret));
6412                                 return -EINVAL;
6413                         }
6414                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6415                         regs[BPF_REG_0].mem_size = tsize;
6416                 } else {
6417                         /* MEM_RDONLY may be carried from ret_flag, but it
6418                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
6419                          * it will confuse the check of PTR_TO_BTF_ID in
6420                          * check_mem_access().
6421                          */
6422                         ret_flag &= ~MEM_RDONLY;
6423
6424                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6425                         regs[BPF_REG_0].btf = meta.ret_btf;
6426                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6427                 }
6428         } else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
6429                 int ret_btf_id;
6430
6431                 mark_reg_known_zero(env, regs, BPF_REG_0);
6432                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6433                 ret_btf_id = *fn->ret_btf_id;
6434                 if (ret_btf_id == 0) {
6435                         verbose(env, "invalid return type %u of func %s#%d\n",
6436                                 base_type(ret_type), func_id_name(func_id),
6437                                 func_id);
6438                         return -EINVAL;
6439                 }
6440                 /* current BPF helper definitions are only coming from
6441                  * built-in code with type IDs from  vmlinux BTF
6442                  */
6443                 regs[BPF_REG_0].btf = btf_vmlinux;
6444                 regs[BPF_REG_0].btf_id = ret_btf_id;
6445         } else {
6446                 verbose(env, "unknown return type %u of func %s#%d\n",
6447                         base_type(ret_type), func_id_name(func_id), func_id);
6448                 return -EINVAL;
6449         }
6450
6451         if (type_may_be_null(regs[BPF_REG_0].type))
6452                 regs[BPF_REG_0].id = ++env->id_gen;
6453
6454         if (is_ptr_cast_function(func_id)) {
6455                 /* For release_reference() */
6456                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6457         } else if (is_acquire_function(func_id, meta.map_ptr)) {
6458                 int id = acquire_reference_state(env, insn_idx);
6459
6460                 if (id < 0)
6461                         return id;
6462                 /* For mark_ptr_or_null_reg() */
6463                 regs[BPF_REG_0].id = id;
6464                 /* For release_reference() */
6465                 regs[BPF_REG_0].ref_obj_id = id;
6466         }
6467
6468         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6469
6470         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6471         if (err)
6472                 return err;
6473
6474         if ((func_id == BPF_FUNC_get_stack ||
6475              func_id == BPF_FUNC_get_task_stack) &&
6476             !env->prog->has_callchain_buf) {
6477                 const char *err_str;
6478
6479 #ifdef CONFIG_PERF_EVENTS
6480                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6481                 err_str = "cannot get callchain buffer for func %s#%d\n";
6482 #else
6483                 err = -ENOTSUPP;
6484                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6485 #endif
6486                 if (err) {
6487                         verbose(env, err_str, func_id_name(func_id), func_id);
6488                         return err;
6489                 }
6490
6491                 env->prog->has_callchain_buf = true;
6492         }
6493
6494         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6495                 env->prog->call_get_stack = true;
6496
6497         if (func_id == BPF_FUNC_get_func_ip) {
6498                 if (check_get_func_ip(env))
6499                         return -ENOTSUPP;
6500                 env->prog->call_get_func_ip = true;
6501         }
6502
6503         if (changes_data)
6504                 clear_all_pkt_pointers(env);
6505         return 0;
6506 }
6507
6508 /* mark_btf_func_reg_size() is used when the reg size is determined by
6509  * the BTF func_proto's return value size and argument.
6510  */
6511 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6512                                    size_t reg_size)
6513 {
6514         struct bpf_reg_state *reg = &cur_regs(env)[regno];
6515
6516         if (regno == BPF_REG_0) {
6517                 /* Function return value */
6518                 reg->live |= REG_LIVE_WRITTEN;
6519                 reg->subreg_def = reg_size == sizeof(u64) ?
6520                         DEF_NOT_SUBREG : env->insn_idx + 1;
6521         } else {
6522                 /* Function argument */
6523                 if (reg_size == sizeof(u64)) {
6524                         mark_insn_zext(env, reg);
6525                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6526                 } else {
6527                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6528                 }
6529         }
6530 }
6531
6532 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6533 {
6534         const struct btf_type *t, *func, *func_proto, *ptr_type;
6535         struct bpf_reg_state *regs = cur_regs(env);
6536         const char *func_name, *ptr_type_name;
6537         u32 i, nargs, func_id, ptr_type_id;
6538         const struct btf_param *args;
6539         int err;
6540
6541         func_id = insn->imm;
6542         func = btf_type_by_id(btf_vmlinux, func_id);
6543         func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6544         func_proto = btf_type_by_id(btf_vmlinux, func->type);
6545
6546         if (!env->ops->check_kfunc_call ||
6547             !env->ops->check_kfunc_call(func_id)) {
6548                 verbose(env, "calling kernel function %s is not allowed\n",
6549                         func_name);
6550                 return -EACCES;
6551         }
6552
6553         /* Check the arguments */
6554         err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6555         if (err)
6556                 return err;
6557
6558         for (i = 0; i < CALLER_SAVED_REGS; i++)
6559                 mark_reg_not_init(env, regs, caller_saved[i]);
6560
6561         /* Check return type */
6562         t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6563         if (btf_type_is_scalar(t)) {
6564                 mark_reg_unknown(env, regs, BPF_REG_0);
6565                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6566         } else if (btf_type_is_ptr(t)) {
6567                 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6568                                                    &ptr_type_id);
6569                 if (!btf_type_is_struct(ptr_type)) {
6570                         ptr_type_name = btf_name_by_offset(btf_vmlinux,
6571                                                            ptr_type->name_off);
6572                         verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6573                                 func_name, btf_type_str(ptr_type),
6574                                 ptr_type_name);
6575                         return -EINVAL;
6576                 }
6577                 mark_reg_known_zero(env, regs, BPF_REG_0);
6578                 regs[BPF_REG_0].btf = btf_vmlinux;
6579                 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6580                 regs[BPF_REG_0].btf_id = ptr_type_id;
6581                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6582         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6583
6584         nargs = btf_type_vlen(func_proto);
6585         args = (const struct btf_param *)(func_proto + 1);
6586         for (i = 0; i < nargs; i++) {
6587                 u32 regno = i + 1;
6588
6589                 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6590                 if (btf_type_is_ptr(t))
6591                         mark_btf_func_reg_size(env, regno, sizeof(void *));
6592                 else
6593                         /* scalar. ensured by btf_check_kfunc_arg_match() */
6594                         mark_btf_func_reg_size(env, regno, t->size);
6595         }
6596
6597         return 0;
6598 }
6599
6600 static bool signed_add_overflows(s64 a, s64 b)
6601 {
6602         /* Do the add in u64, where overflow is well-defined */
6603         s64 res = (s64)((u64)a + (u64)b);
6604
6605         if (b < 0)
6606                 return res > a;
6607         return res < a;
6608 }
6609
6610 static bool signed_add32_overflows(s32 a, s32 b)
6611 {
6612         /* Do the add in u32, where overflow is well-defined */
6613         s32 res = (s32)((u32)a + (u32)b);
6614
6615         if (b < 0)
6616                 return res > a;
6617         return res < a;
6618 }
6619
6620 static bool signed_sub_overflows(s64 a, s64 b)
6621 {
6622         /* Do the sub in u64, where overflow is well-defined */
6623         s64 res = (s64)((u64)a - (u64)b);
6624
6625         if (b < 0)
6626                 return res < a;
6627         return res > a;
6628 }
6629
6630 static bool signed_sub32_overflows(s32 a, s32 b)
6631 {
6632         /* Do the sub in u32, where overflow is well-defined */
6633         s32 res = (s32)((u32)a - (u32)b);
6634
6635         if (b < 0)
6636                 return res < a;
6637         return res > a;
6638 }
6639
6640 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6641                                   const struct bpf_reg_state *reg,
6642                                   enum bpf_reg_type type)
6643 {
6644         bool known = tnum_is_const(reg->var_off);
6645         s64 val = reg->var_off.value;
6646         s64 smin = reg->smin_value;
6647
6648         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6649                 verbose(env, "math between %s pointer and %lld is not allowed\n",
6650                         reg_type_str(env, type), val);
6651                 return false;
6652         }
6653
6654         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6655                 verbose(env, "%s pointer offset %d is not allowed\n",
6656                         reg_type_str(env, type), reg->off);
6657                 return false;
6658         }
6659
6660         if (smin == S64_MIN) {
6661                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6662                         reg_type_str(env, type));
6663                 return false;
6664         }
6665
6666         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6667                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6668                         smin, reg_type_str(env, type));
6669                 return false;
6670         }
6671
6672         return true;
6673 }
6674
6675 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6676 {
6677         return &env->insn_aux_data[env->insn_idx];
6678 }
6679
6680 enum {
6681         REASON_BOUNDS   = -1,
6682         REASON_TYPE     = -2,
6683         REASON_PATHS    = -3,
6684         REASON_LIMIT    = -4,
6685         REASON_STACK    = -5,
6686 };
6687
6688 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6689                               u32 *alu_limit, bool mask_to_left)
6690 {
6691         u32 max = 0, ptr_limit = 0;
6692
6693         switch (ptr_reg->type) {
6694         case PTR_TO_STACK:
6695                 /* Offset 0 is out-of-bounds, but acceptable start for the
6696                  * left direction, see BPF_REG_FP. Also, unknown scalar
6697                  * offset where we would need to deal with min/max bounds is
6698                  * currently prohibited for unprivileged.
6699                  */
6700                 max = MAX_BPF_STACK + mask_to_left;
6701                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6702                 break;
6703         case PTR_TO_MAP_VALUE:
6704                 max = ptr_reg->map_ptr->value_size;
6705                 ptr_limit = (mask_to_left ?
6706                              ptr_reg->smin_value :
6707                              ptr_reg->umax_value) + ptr_reg->off;
6708                 break;
6709         default:
6710                 return REASON_TYPE;
6711         }
6712
6713         if (ptr_limit >= max)
6714                 return REASON_LIMIT;
6715         *alu_limit = ptr_limit;
6716         return 0;
6717 }
6718
6719 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6720                                     const struct bpf_insn *insn)
6721 {
6722         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6723 }
6724
6725 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6726                                        u32 alu_state, u32 alu_limit)
6727 {
6728         /* If we arrived here from different branches with different
6729          * state or limits to sanitize, then this won't work.
6730          */
6731         if (aux->alu_state &&
6732             (aux->alu_state != alu_state ||
6733              aux->alu_limit != alu_limit))
6734                 return REASON_PATHS;
6735
6736         /* Corresponding fixup done in do_misc_fixups(). */
6737         aux->alu_state = alu_state;
6738         aux->alu_limit = alu_limit;
6739         return 0;
6740 }
6741
6742 static int sanitize_val_alu(struct bpf_verifier_env *env,
6743                             struct bpf_insn *insn)
6744 {
6745         struct bpf_insn_aux_data *aux = cur_aux(env);
6746
6747         if (can_skip_alu_sanitation(env, insn))
6748                 return 0;
6749
6750         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6751 }
6752
6753 static bool sanitize_needed(u8 opcode)
6754 {
6755         return opcode == BPF_ADD || opcode == BPF_SUB;
6756 }
6757
6758 struct bpf_sanitize_info {
6759         struct bpf_insn_aux_data aux;
6760         bool mask_to_left;
6761 };
6762
6763 static struct bpf_verifier_state *
6764 sanitize_speculative_path(struct bpf_verifier_env *env,
6765                           const struct bpf_insn *insn,
6766                           u32 next_idx, u32 curr_idx)
6767 {
6768         struct bpf_verifier_state *branch;
6769         struct bpf_reg_state *regs;
6770
6771         branch = push_stack(env, next_idx, curr_idx, true);
6772         if (branch && insn) {
6773                 regs = branch->frame[branch->curframe]->regs;
6774                 if (BPF_SRC(insn->code) == BPF_K) {
6775                         mark_reg_unknown(env, regs, insn->dst_reg);
6776                 } else if (BPF_SRC(insn->code) == BPF_X) {
6777                         mark_reg_unknown(env, regs, insn->dst_reg);
6778                         mark_reg_unknown(env, regs, insn->src_reg);
6779                 }
6780         }
6781         return branch;
6782 }
6783
6784 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6785                             struct bpf_insn *insn,
6786                             const struct bpf_reg_state *ptr_reg,
6787                             const struct bpf_reg_state *off_reg,
6788                             struct bpf_reg_state *dst_reg,
6789                             struct bpf_sanitize_info *info,
6790                             const bool commit_window)
6791 {
6792         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6793         struct bpf_verifier_state *vstate = env->cur_state;
6794         bool off_is_imm = tnum_is_const(off_reg->var_off);
6795         bool off_is_neg = off_reg->smin_value < 0;
6796         bool ptr_is_dst_reg = ptr_reg == dst_reg;
6797         u8 opcode = BPF_OP(insn->code);
6798         u32 alu_state, alu_limit;
6799         struct bpf_reg_state tmp;
6800         bool ret;
6801         int err;
6802
6803         if (can_skip_alu_sanitation(env, insn))
6804                 return 0;
6805
6806         /* We already marked aux for masking from non-speculative
6807          * paths, thus we got here in the first place. We only care
6808          * to explore bad access from here.
6809          */
6810         if (vstate->speculative)
6811                 goto do_sim;
6812
6813         if (!commit_window) {
6814                 if (!tnum_is_const(off_reg->var_off) &&
6815                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6816                         return REASON_BOUNDS;
6817
6818                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6819                                      (opcode == BPF_SUB && !off_is_neg);
6820         }
6821
6822         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6823         if (err < 0)
6824                 return err;
6825
6826         if (commit_window) {
6827                 /* In commit phase we narrow the masking window based on
6828                  * the observed pointer move after the simulated operation.
6829                  */
6830                 alu_state = info->aux.alu_state;
6831                 alu_limit = abs(info->aux.alu_limit - alu_limit);
6832         } else {
6833                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6834                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6835                 alu_state |= ptr_is_dst_reg ?
6836                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6837
6838                 /* Limit pruning on unknown scalars to enable deep search for
6839                  * potential masking differences from other program paths.
6840                  */
6841                 if (!off_is_imm)
6842                         env->explore_alu_limits = true;
6843         }
6844
6845         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6846         if (err < 0)
6847                 return err;
6848 do_sim:
6849         /* If we're in commit phase, we're done here given we already
6850          * pushed the truncated dst_reg into the speculative verification
6851          * stack.
6852          *
6853          * Also, when register is a known constant, we rewrite register-based
6854          * operation to immediate-based, and thus do not need masking (and as
6855          * a consequence, do not need to simulate the zero-truncation either).
6856          */
6857         if (commit_window || off_is_imm)
6858                 return 0;
6859
6860         /* Simulate and find potential out-of-bounds access under
6861          * speculative execution from truncation as a result of
6862          * masking when off was not within expected range. If off
6863          * sits in dst, then we temporarily need to move ptr there
6864          * to simulate dst (== 0) +/-= ptr. Needed, for example,
6865          * for cases where we use K-based arithmetic in one direction
6866          * and truncated reg-based in the other in order to explore
6867          * bad access.
6868          */
6869         if (!ptr_is_dst_reg) {
6870                 tmp = *dst_reg;
6871                 *dst_reg = *ptr_reg;
6872         }
6873         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6874                                         env->insn_idx);
6875         if (!ptr_is_dst_reg && ret)
6876                 *dst_reg = tmp;
6877         return !ret ? REASON_STACK : 0;
6878 }
6879
6880 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6881 {
6882         struct bpf_verifier_state *vstate = env->cur_state;
6883
6884         /* If we simulate paths under speculation, we don't update the
6885          * insn as 'seen' such that when we verify unreachable paths in
6886          * the non-speculative domain, sanitize_dead_code() can still
6887          * rewrite/sanitize them.
6888          */
6889         if (!vstate->speculative)
6890                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6891 }
6892
6893 static int sanitize_err(struct bpf_verifier_env *env,
6894                         const struct bpf_insn *insn, int reason,
6895                         const struct bpf_reg_state *off_reg,
6896                         const struct bpf_reg_state *dst_reg)
6897 {
6898         static const char *err = "pointer arithmetic with it prohibited for !root";
6899         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6900         u32 dst = insn->dst_reg, src = insn->src_reg;
6901
6902         switch (reason) {
6903         case REASON_BOUNDS:
6904                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6905                         off_reg == dst_reg ? dst : src, err);
6906                 break;
6907         case REASON_TYPE:
6908                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6909                         off_reg == dst_reg ? src : dst, err);
6910                 break;
6911         case REASON_PATHS:
6912                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6913                         dst, op, err);
6914                 break;
6915         case REASON_LIMIT:
6916                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6917                         dst, op, err);
6918                 break;
6919         case REASON_STACK:
6920                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6921                         dst, err);
6922                 break;
6923         default:
6924                 verbose(env, "verifier internal error: unknown reason (%d)\n",
6925                         reason);
6926                 break;
6927         }
6928
6929         return -EACCES;
6930 }
6931
6932 /* check that stack access falls within stack limits and that 'reg' doesn't
6933  * have a variable offset.
6934  *
6935  * Variable offset is prohibited for unprivileged mode for simplicity since it
6936  * requires corresponding support in Spectre masking for stack ALU.  See also
6937  * retrieve_ptr_limit().
6938  *
6939  *
6940  * 'off' includes 'reg->off'.
6941  */
6942 static int check_stack_access_for_ptr_arithmetic(
6943                                 struct bpf_verifier_env *env,
6944                                 int regno,
6945                                 const struct bpf_reg_state *reg,
6946                                 int off)
6947 {
6948         if (!tnum_is_const(reg->var_off)) {
6949                 char tn_buf[48];
6950
6951                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6952                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6953                         regno, tn_buf, off);
6954                 return -EACCES;
6955         }
6956
6957         if (off >= 0 || off < -MAX_BPF_STACK) {
6958                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6959                         "prohibited for !root; off=%d\n", regno, off);
6960                 return -EACCES;
6961         }
6962
6963         return 0;
6964 }
6965
6966 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6967                                  const struct bpf_insn *insn,
6968                                  const struct bpf_reg_state *dst_reg)
6969 {
6970         u32 dst = insn->dst_reg;
6971
6972         /* For unprivileged we require that resulting offset must be in bounds
6973          * in order to be able to sanitize access later on.
6974          */
6975         if (env->bypass_spec_v1)
6976                 return 0;
6977
6978         switch (dst_reg->type) {
6979         case PTR_TO_STACK:
6980                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6981                                         dst_reg->off + dst_reg->var_off.value))
6982                         return -EACCES;
6983                 break;
6984         case PTR_TO_MAP_VALUE:
6985                 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6986                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6987                                 "prohibited for !root\n", dst);
6988                         return -EACCES;
6989                 }
6990                 break;
6991         default:
6992                 break;
6993         }
6994
6995         return 0;
6996 }
6997
6998 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6999  * Caller should also handle BPF_MOV case separately.
7000  * If we return -EACCES, caller may want to try again treating pointer as a
7001  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
7002  */
7003 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
7004                                    struct bpf_insn *insn,
7005                                    const struct bpf_reg_state *ptr_reg,
7006                                    const struct bpf_reg_state *off_reg)
7007 {
7008         struct bpf_verifier_state *vstate = env->cur_state;
7009         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7010         struct bpf_reg_state *regs = state->regs, *dst_reg;
7011         bool known = tnum_is_const(off_reg->var_off);
7012         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7013             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7014         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7015             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7016         struct bpf_sanitize_info info = {};
7017         u8 opcode = BPF_OP(insn->code);
7018         u32 dst = insn->dst_reg;
7019         int ret;
7020
7021         dst_reg = &regs[dst];
7022
7023         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7024             smin_val > smax_val || umin_val > umax_val) {
7025                 /* Taint dst register if offset had invalid bounds derived from
7026                  * e.g. dead branches.
7027                  */
7028                 __mark_reg_unknown(env, dst_reg);
7029                 return 0;
7030         }
7031
7032         if (BPF_CLASS(insn->code) != BPF_ALU64) {
7033                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
7034                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7035                         __mark_reg_unknown(env, dst_reg);
7036                         return 0;
7037                 }
7038
7039                 verbose(env,
7040                         "R%d 32-bit pointer arithmetic prohibited\n",
7041                         dst);
7042                 return -EACCES;
7043         }
7044
7045         if (ptr_reg->type & PTR_MAYBE_NULL) {
7046                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7047                         dst, reg_type_str(env, ptr_reg->type));
7048                 return -EACCES;
7049         }
7050
7051         switch (base_type(ptr_reg->type)) {
7052         case CONST_PTR_TO_MAP:
7053                 /* smin_val represents the known value */
7054                 if (known && smin_val == 0 && opcode == BPF_ADD)
7055                         break;
7056                 fallthrough;
7057         case PTR_TO_PACKET_END:
7058         case PTR_TO_SOCKET:
7059         case PTR_TO_SOCK_COMMON:
7060         case PTR_TO_TCP_SOCK:
7061         case PTR_TO_XDP_SOCK:
7062 reject:
7063                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7064                         dst, reg_type_str(env, ptr_reg->type));
7065                 return -EACCES;
7066         default:
7067                 if (type_may_be_null(ptr_reg->type))
7068                         goto reject;
7069                 break;
7070         }
7071
7072         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7073          * The id may be overwritten later if we create a new variable offset.
7074          */
7075         dst_reg->type = ptr_reg->type;
7076         dst_reg->id = ptr_reg->id;
7077
7078         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7079             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7080                 return -EINVAL;
7081
7082         /* pointer types do not carry 32-bit bounds at the moment. */
7083         __mark_reg32_unbounded(dst_reg);
7084
7085         if (sanitize_needed(opcode)) {
7086                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7087                                        &info, false);
7088                 if (ret < 0)
7089                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
7090         }
7091
7092         switch (opcode) {
7093         case BPF_ADD:
7094                 /* We can take a fixed offset as long as it doesn't overflow
7095                  * the s32 'off' field
7096                  */
7097                 if (known && (ptr_reg->off + smin_val ==
7098                               (s64)(s32)(ptr_reg->off + smin_val))) {
7099                         /* pointer += K.  Accumulate it into fixed offset */
7100                         dst_reg->smin_value = smin_ptr;
7101                         dst_reg->smax_value = smax_ptr;
7102                         dst_reg->umin_value = umin_ptr;
7103                         dst_reg->umax_value = umax_ptr;
7104                         dst_reg->var_off = ptr_reg->var_off;
7105                         dst_reg->off = ptr_reg->off + smin_val;
7106                         dst_reg->raw = ptr_reg->raw;
7107                         break;
7108                 }
7109                 /* A new variable offset is created.  Note that off_reg->off
7110                  * == 0, since it's a scalar.
7111                  * dst_reg gets the pointer type and since some positive
7112                  * integer value was added to the pointer, give it a new 'id'
7113                  * if it's a PTR_TO_PACKET.
7114                  * this creates a new 'base' pointer, off_reg (variable) gets
7115                  * added into the variable offset, and we copy the fixed offset
7116                  * from ptr_reg.
7117                  */
7118                 if (signed_add_overflows(smin_ptr, smin_val) ||
7119                     signed_add_overflows(smax_ptr, smax_val)) {
7120                         dst_reg->smin_value = S64_MIN;
7121                         dst_reg->smax_value = S64_MAX;
7122                 } else {
7123                         dst_reg->smin_value = smin_ptr + smin_val;
7124                         dst_reg->smax_value = smax_ptr + smax_val;
7125                 }
7126                 if (umin_ptr + umin_val < umin_ptr ||
7127                     umax_ptr + umax_val < umax_ptr) {
7128                         dst_reg->umin_value = 0;
7129                         dst_reg->umax_value = U64_MAX;
7130                 } else {
7131                         dst_reg->umin_value = umin_ptr + umin_val;
7132                         dst_reg->umax_value = umax_ptr + umax_val;
7133                 }
7134                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7135                 dst_reg->off = ptr_reg->off;
7136                 dst_reg->raw = ptr_reg->raw;
7137                 if (reg_is_pkt_pointer(ptr_reg)) {
7138                         dst_reg->id = ++env->id_gen;
7139                         /* something was added to pkt_ptr, set range to zero */
7140                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7141                 }
7142                 break;
7143         case BPF_SUB:
7144                 if (dst_reg == off_reg) {
7145                         /* scalar -= pointer.  Creates an unknown scalar */
7146                         verbose(env, "R%d tried to subtract pointer from scalar\n",
7147                                 dst);
7148                         return -EACCES;
7149                 }
7150                 /* We don't allow subtraction from FP, because (according to
7151                  * test_verifier.c test "invalid fp arithmetic", JITs might not
7152                  * be able to deal with it.
7153                  */
7154                 if (ptr_reg->type == PTR_TO_STACK) {
7155                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
7156                                 dst);
7157                         return -EACCES;
7158                 }
7159                 if (known && (ptr_reg->off - smin_val ==
7160                               (s64)(s32)(ptr_reg->off - smin_val))) {
7161                         /* pointer -= K.  Subtract it from fixed offset */
7162                         dst_reg->smin_value = smin_ptr;
7163                         dst_reg->smax_value = smax_ptr;
7164                         dst_reg->umin_value = umin_ptr;
7165                         dst_reg->umax_value = umax_ptr;
7166                         dst_reg->var_off = ptr_reg->var_off;
7167                         dst_reg->id = ptr_reg->id;
7168                         dst_reg->off = ptr_reg->off - smin_val;
7169                         dst_reg->raw = ptr_reg->raw;
7170                         break;
7171                 }
7172                 /* A new variable offset is created.  If the subtrahend is known
7173                  * nonnegative, then any reg->range we had before is still good.
7174                  */
7175                 if (signed_sub_overflows(smin_ptr, smax_val) ||
7176                     signed_sub_overflows(smax_ptr, smin_val)) {
7177                         /* Overflow possible, we know nothing */
7178                         dst_reg->smin_value = S64_MIN;
7179                         dst_reg->smax_value = S64_MAX;
7180                 } else {
7181                         dst_reg->smin_value = smin_ptr - smax_val;
7182                         dst_reg->smax_value = smax_ptr - smin_val;
7183                 }
7184                 if (umin_ptr < umax_val) {
7185                         /* Overflow possible, we know nothing */
7186                         dst_reg->umin_value = 0;
7187                         dst_reg->umax_value = U64_MAX;
7188                 } else {
7189                         /* Cannot overflow (as long as bounds are consistent) */
7190                         dst_reg->umin_value = umin_ptr - umax_val;
7191                         dst_reg->umax_value = umax_ptr - umin_val;
7192                 }
7193                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7194                 dst_reg->off = ptr_reg->off;
7195                 dst_reg->raw = ptr_reg->raw;
7196                 if (reg_is_pkt_pointer(ptr_reg)) {
7197                         dst_reg->id = ++env->id_gen;
7198                         /* something was added to pkt_ptr, set range to zero */
7199                         if (smin_val < 0)
7200                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7201                 }
7202                 break;
7203         case BPF_AND:
7204         case BPF_OR:
7205         case BPF_XOR:
7206                 /* bitwise ops on pointers are troublesome, prohibit. */
7207                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7208                         dst, bpf_alu_string[opcode >> 4]);
7209                 return -EACCES;
7210         default:
7211                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
7212                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7213                         dst, bpf_alu_string[opcode >> 4]);
7214                 return -EACCES;
7215         }
7216
7217         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7218                 return -EINVAL;
7219
7220         __update_reg_bounds(dst_reg);
7221         __reg_deduce_bounds(dst_reg);
7222         __reg_bound_offset(dst_reg);
7223
7224         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7225                 return -EACCES;
7226         if (sanitize_needed(opcode)) {
7227                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7228                                        &info, true);
7229                 if (ret < 0)
7230                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
7231         }
7232
7233         return 0;
7234 }
7235
7236 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7237                                  struct bpf_reg_state *src_reg)
7238 {
7239         s32 smin_val = src_reg->s32_min_value;
7240         s32 smax_val = src_reg->s32_max_value;
7241         u32 umin_val = src_reg->u32_min_value;
7242         u32 umax_val = src_reg->u32_max_value;
7243
7244         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7245             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7246                 dst_reg->s32_min_value = S32_MIN;
7247                 dst_reg->s32_max_value = S32_MAX;
7248         } else {
7249                 dst_reg->s32_min_value += smin_val;
7250                 dst_reg->s32_max_value += smax_val;
7251         }
7252         if (dst_reg->u32_min_value + umin_val < umin_val ||
7253             dst_reg->u32_max_value + umax_val < umax_val) {
7254                 dst_reg->u32_min_value = 0;
7255                 dst_reg->u32_max_value = U32_MAX;
7256         } else {
7257                 dst_reg->u32_min_value += umin_val;
7258                 dst_reg->u32_max_value += umax_val;
7259         }
7260 }
7261
7262 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7263                                struct bpf_reg_state *src_reg)
7264 {
7265         s64 smin_val = src_reg->smin_value;
7266         s64 smax_val = src_reg->smax_value;
7267         u64 umin_val = src_reg->umin_value;
7268         u64 umax_val = src_reg->umax_value;
7269
7270         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7271             signed_add_overflows(dst_reg->smax_value, smax_val)) {
7272                 dst_reg->smin_value = S64_MIN;
7273                 dst_reg->smax_value = S64_MAX;
7274         } else {
7275                 dst_reg->smin_value += smin_val;
7276                 dst_reg->smax_value += smax_val;
7277         }
7278         if (dst_reg->umin_value + umin_val < umin_val ||
7279             dst_reg->umax_value + umax_val < umax_val) {
7280                 dst_reg->umin_value = 0;
7281                 dst_reg->umax_value = U64_MAX;
7282         } else {
7283                 dst_reg->umin_value += umin_val;
7284                 dst_reg->umax_value += umax_val;
7285         }
7286 }
7287
7288 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7289                                  struct bpf_reg_state *src_reg)
7290 {
7291         s32 smin_val = src_reg->s32_min_value;
7292         s32 smax_val = src_reg->s32_max_value;
7293         u32 umin_val = src_reg->u32_min_value;
7294         u32 umax_val = src_reg->u32_max_value;
7295
7296         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7297             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7298                 /* Overflow possible, we know nothing */
7299                 dst_reg->s32_min_value = S32_MIN;
7300                 dst_reg->s32_max_value = S32_MAX;
7301         } else {
7302                 dst_reg->s32_min_value -= smax_val;
7303                 dst_reg->s32_max_value -= smin_val;
7304         }
7305         if (dst_reg->u32_min_value < umax_val) {
7306                 /* Overflow possible, we know nothing */
7307                 dst_reg->u32_min_value = 0;
7308                 dst_reg->u32_max_value = U32_MAX;
7309         } else {
7310                 /* Cannot overflow (as long as bounds are consistent) */
7311                 dst_reg->u32_min_value -= umax_val;
7312                 dst_reg->u32_max_value -= umin_val;
7313         }
7314 }
7315
7316 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7317                                struct bpf_reg_state *src_reg)
7318 {
7319         s64 smin_val = src_reg->smin_value;
7320         s64 smax_val = src_reg->smax_value;
7321         u64 umin_val = src_reg->umin_value;
7322         u64 umax_val = src_reg->umax_value;
7323
7324         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7325             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7326                 /* Overflow possible, we know nothing */
7327                 dst_reg->smin_value = S64_MIN;
7328                 dst_reg->smax_value = S64_MAX;
7329         } else {
7330                 dst_reg->smin_value -= smax_val;
7331                 dst_reg->smax_value -= smin_val;
7332         }
7333         if (dst_reg->umin_value < umax_val) {
7334                 /* Overflow possible, we know nothing */
7335                 dst_reg->umin_value = 0;
7336                 dst_reg->umax_value = U64_MAX;
7337         } else {
7338                 /* Cannot overflow (as long as bounds are consistent) */
7339                 dst_reg->umin_value -= umax_val;
7340                 dst_reg->umax_value -= umin_val;
7341         }
7342 }
7343
7344 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7345                                  struct bpf_reg_state *src_reg)
7346 {
7347         s32 smin_val = src_reg->s32_min_value;
7348         u32 umin_val = src_reg->u32_min_value;
7349         u32 umax_val = src_reg->u32_max_value;
7350
7351         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7352                 /* Ain't nobody got time to multiply that sign */
7353                 __mark_reg32_unbounded(dst_reg);
7354                 return;
7355         }
7356         /* Both values are positive, so we can work with unsigned and
7357          * copy the result to signed (unless it exceeds S32_MAX).
7358          */
7359         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7360                 /* Potential overflow, we know nothing */
7361                 __mark_reg32_unbounded(dst_reg);
7362                 return;
7363         }
7364         dst_reg->u32_min_value *= umin_val;
7365         dst_reg->u32_max_value *= umax_val;
7366         if (dst_reg->u32_max_value > S32_MAX) {
7367                 /* Overflow possible, we know nothing */
7368                 dst_reg->s32_min_value = S32_MIN;
7369                 dst_reg->s32_max_value = S32_MAX;
7370         } else {
7371                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7372                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7373         }
7374 }
7375
7376 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7377                                struct bpf_reg_state *src_reg)
7378 {
7379         s64 smin_val = src_reg->smin_value;
7380         u64 umin_val = src_reg->umin_value;
7381         u64 umax_val = src_reg->umax_value;
7382
7383         if (smin_val < 0 || dst_reg->smin_value < 0) {
7384                 /* Ain't nobody got time to multiply that sign */
7385                 __mark_reg64_unbounded(dst_reg);
7386                 return;
7387         }
7388         /* Both values are positive, so we can work with unsigned and
7389          * copy the result to signed (unless it exceeds S64_MAX).
7390          */
7391         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7392                 /* Potential overflow, we know nothing */
7393                 __mark_reg64_unbounded(dst_reg);
7394                 return;
7395         }
7396         dst_reg->umin_value *= umin_val;
7397         dst_reg->umax_value *= umax_val;
7398         if (dst_reg->umax_value > S64_MAX) {
7399                 /* Overflow possible, we know nothing */
7400                 dst_reg->smin_value = S64_MIN;
7401                 dst_reg->smax_value = S64_MAX;
7402         } else {
7403                 dst_reg->smin_value = dst_reg->umin_value;
7404                 dst_reg->smax_value = dst_reg->umax_value;
7405         }
7406 }
7407
7408 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7409                                  struct bpf_reg_state *src_reg)
7410 {
7411         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7412         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7413         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7414         s32 smin_val = src_reg->s32_min_value;
7415         u32 umax_val = src_reg->u32_max_value;
7416
7417         if (src_known && dst_known) {
7418                 __mark_reg32_known(dst_reg, var32_off.value);
7419                 return;
7420         }
7421
7422         /* We get our minimum from the var_off, since that's inherently
7423          * bitwise.  Our maximum is the minimum of the operands' maxima.
7424          */
7425         dst_reg->u32_min_value = var32_off.value;
7426         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7427         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7428                 /* Lose signed bounds when ANDing negative numbers,
7429                  * ain't nobody got time for that.
7430                  */
7431                 dst_reg->s32_min_value = S32_MIN;
7432                 dst_reg->s32_max_value = S32_MAX;
7433         } else {
7434                 /* ANDing two positives gives a positive, so safe to
7435                  * cast result into s64.
7436                  */
7437                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7438                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7439         }
7440 }
7441
7442 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7443                                struct bpf_reg_state *src_reg)
7444 {
7445         bool src_known = tnum_is_const(src_reg->var_off);
7446         bool dst_known = tnum_is_const(dst_reg->var_off);
7447         s64 smin_val = src_reg->smin_value;
7448         u64 umax_val = src_reg->umax_value;
7449
7450         if (src_known && dst_known) {
7451                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7452                 return;
7453         }
7454
7455         /* We get our minimum from the var_off, since that's inherently
7456          * bitwise.  Our maximum is the minimum of the operands' maxima.
7457          */
7458         dst_reg->umin_value = dst_reg->var_off.value;
7459         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7460         if (dst_reg->smin_value < 0 || smin_val < 0) {
7461                 /* Lose signed bounds when ANDing negative numbers,
7462                  * ain't nobody got time for that.
7463                  */
7464                 dst_reg->smin_value = S64_MIN;
7465                 dst_reg->smax_value = S64_MAX;
7466         } else {
7467                 /* ANDing two positives gives a positive, so safe to
7468                  * cast result into s64.
7469                  */
7470                 dst_reg->smin_value = dst_reg->umin_value;
7471                 dst_reg->smax_value = dst_reg->umax_value;
7472         }
7473         /* We may learn something more from the var_off */
7474         __update_reg_bounds(dst_reg);
7475 }
7476
7477 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7478                                 struct bpf_reg_state *src_reg)
7479 {
7480         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7481         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7482         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7483         s32 smin_val = src_reg->s32_min_value;
7484         u32 umin_val = src_reg->u32_min_value;
7485
7486         if (src_known && dst_known) {
7487                 __mark_reg32_known(dst_reg, var32_off.value);
7488                 return;
7489         }
7490
7491         /* We get our maximum from the var_off, and our minimum is the
7492          * maximum of the operands' minima
7493          */
7494         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7495         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7496         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7497                 /* Lose signed bounds when ORing negative numbers,
7498                  * ain't nobody got time for that.
7499                  */
7500                 dst_reg->s32_min_value = S32_MIN;
7501                 dst_reg->s32_max_value = S32_MAX;
7502         } else {
7503                 /* ORing two positives gives a positive, so safe to
7504                  * cast result into s64.
7505                  */
7506                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7507                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7508         }
7509 }
7510
7511 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7512                               struct bpf_reg_state *src_reg)
7513 {
7514         bool src_known = tnum_is_const(src_reg->var_off);
7515         bool dst_known = tnum_is_const(dst_reg->var_off);
7516         s64 smin_val = src_reg->smin_value;
7517         u64 umin_val = src_reg->umin_value;
7518
7519         if (src_known && dst_known) {
7520                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7521                 return;
7522         }
7523
7524         /* We get our maximum from the var_off, and our minimum is the
7525          * maximum of the operands' minima
7526          */
7527         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7528         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7529         if (dst_reg->smin_value < 0 || smin_val < 0) {
7530                 /* Lose signed bounds when ORing negative numbers,
7531                  * ain't nobody got time for that.
7532                  */
7533                 dst_reg->smin_value = S64_MIN;
7534                 dst_reg->smax_value = S64_MAX;
7535         } else {
7536                 /* ORing two positives gives a positive, so safe to
7537                  * cast result into s64.
7538                  */
7539                 dst_reg->smin_value = dst_reg->umin_value;
7540                 dst_reg->smax_value = dst_reg->umax_value;
7541         }
7542         /* We may learn something more from the var_off */
7543         __update_reg_bounds(dst_reg);
7544 }
7545
7546 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7547                                  struct bpf_reg_state *src_reg)
7548 {
7549         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7550         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7551         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7552         s32 smin_val = src_reg->s32_min_value;
7553
7554         if (src_known && dst_known) {
7555                 __mark_reg32_known(dst_reg, var32_off.value);
7556                 return;
7557         }
7558
7559         /* We get both minimum and maximum from the var32_off. */
7560         dst_reg->u32_min_value = var32_off.value;
7561         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7562
7563         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7564                 /* XORing two positive sign numbers gives a positive,
7565                  * so safe to cast u32 result into s32.
7566                  */
7567                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7568                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7569         } else {
7570                 dst_reg->s32_min_value = S32_MIN;
7571                 dst_reg->s32_max_value = S32_MAX;
7572         }
7573 }
7574
7575 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7576                                struct bpf_reg_state *src_reg)
7577 {
7578         bool src_known = tnum_is_const(src_reg->var_off);
7579         bool dst_known = tnum_is_const(dst_reg->var_off);
7580         s64 smin_val = src_reg->smin_value;
7581
7582         if (src_known && dst_known) {
7583                 /* dst_reg->var_off.value has been updated earlier */
7584                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7585                 return;
7586         }
7587
7588         /* We get both minimum and maximum from the var_off. */
7589         dst_reg->umin_value = dst_reg->var_off.value;
7590         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7591
7592         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7593                 /* XORing two positive sign numbers gives a positive,
7594                  * so safe to cast u64 result into s64.
7595                  */
7596                 dst_reg->smin_value = dst_reg->umin_value;
7597                 dst_reg->smax_value = dst_reg->umax_value;
7598         } else {
7599                 dst_reg->smin_value = S64_MIN;
7600                 dst_reg->smax_value = S64_MAX;
7601         }
7602
7603         __update_reg_bounds(dst_reg);
7604 }
7605
7606 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7607                                    u64 umin_val, u64 umax_val)
7608 {
7609         /* We lose all sign bit information (except what we can pick
7610          * up from var_off)
7611          */
7612         dst_reg->s32_min_value = S32_MIN;
7613         dst_reg->s32_max_value = S32_MAX;
7614         /* If we might shift our top bit out, then we know nothing */
7615         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7616                 dst_reg->u32_min_value = 0;
7617                 dst_reg->u32_max_value = U32_MAX;
7618         } else {
7619                 dst_reg->u32_min_value <<= umin_val;
7620                 dst_reg->u32_max_value <<= umax_val;
7621         }
7622 }
7623
7624 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7625                                  struct bpf_reg_state *src_reg)
7626 {
7627         u32 umax_val = src_reg->u32_max_value;
7628         u32 umin_val = src_reg->u32_min_value;
7629         /* u32 alu operation will zext upper bits */
7630         struct tnum subreg = tnum_subreg(dst_reg->var_off);
7631
7632         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7633         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7634         /* Not required but being careful mark reg64 bounds as unknown so
7635          * that we are forced to pick them up from tnum and zext later and
7636          * if some path skips this step we are still safe.
7637          */
7638         __mark_reg64_unbounded(dst_reg);
7639         __update_reg32_bounds(dst_reg);
7640 }
7641
7642 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7643                                    u64 umin_val, u64 umax_val)
7644 {
7645         /* Special case <<32 because it is a common compiler pattern to sign
7646          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7647          * positive we know this shift will also be positive so we can track
7648          * bounds correctly. Otherwise we lose all sign bit information except
7649          * what we can pick up from var_off. Perhaps we can generalize this
7650          * later to shifts of any length.
7651          */
7652         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7653                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7654         else
7655                 dst_reg->smax_value = S64_MAX;
7656
7657         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7658                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7659         else
7660                 dst_reg->smin_value = S64_MIN;
7661
7662         /* If we might shift our top bit out, then we know nothing */
7663         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7664                 dst_reg->umin_value = 0;
7665                 dst_reg->umax_value = U64_MAX;
7666         } else {
7667                 dst_reg->umin_value <<= umin_val;
7668                 dst_reg->umax_value <<= umax_val;
7669         }
7670 }
7671
7672 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7673                                struct bpf_reg_state *src_reg)
7674 {
7675         u64 umax_val = src_reg->umax_value;
7676         u64 umin_val = src_reg->umin_value;
7677
7678         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7679         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7680         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7681
7682         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7683         /* We may learn something more from the var_off */
7684         __update_reg_bounds(dst_reg);
7685 }
7686
7687 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7688                                  struct bpf_reg_state *src_reg)
7689 {
7690         struct tnum subreg = tnum_subreg(dst_reg->var_off);
7691         u32 umax_val = src_reg->u32_max_value;
7692         u32 umin_val = src_reg->u32_min_value;
7693
7694         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7695          * be negative, then either:
7696          * 1) src_reg might be zero, so the sign bit of the result is
7697          *    unknown, so we lose our signed bounds
7698          * 2) it's known negative, thus the unsigned bounds capture the
7699          *    signed bounds
7700          * 3) the signed bounds cross zero, so they tell us nothing
7701          *    about the result
7702          * If the value in dst_reg is known nonnegative, then again the
7703          * unsigned bounds capture the signed bounds.
7704          * Thus, in all cases it suffices to blow away our signed bounds
7705          * and rely on inferring new ones from the unsigned bounds and
7706          * var_off of the result.
7707          */
7708         dst_reg->s32_min_value = S32_MIN;
7709         dst_reg->s32_max_value = S32_MAX;
7710
7711         dst_reg->var_off = tnum_rshift(subreg, umin_val);
7712         dst_reg->u32_min_value >>= umax_val;
7713         dst_reg->u32_max_value >>= umin_val;
7714
7715         __mark_reg64_unbounded(dst_reg);
7716         __update_reg32_bounds(dst_reg);
7717 }
7718
7719 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7720                                struct bpf_reg_state *src_reg)
7721 {
7722         u64 umax_val = src_reg->umax_value;
7723         u64 umin_val = src_reg->umin_value;
7724
7725         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7726          * be negative, then either:
7727          * 1) src_reg might be zero, so the sign bit of the result is
7728          *    unknown, so we lose our signed bounds
7729          * 2) it's known negative, thus the unsigned bounds capture the
7730          *    signed bounds
7731          * 3) the signed bounds cross zero, so they tell us nothing
7732          *    about the result
7733          * If the value in dst_reg is known nonnegative, then again the
7734          * unsigned bounds capture the signed bounds.
7735          * Thus, in all cases it suffices to blow away our signed bounds
7736          * and rely on inferring new ones from the unsigned bounds and
7737          * var_off of the result.
7738          */
7739         dst_reg->smin_value = S64_MIN;
7740         dst_reg->smax_value = S64_MAX;
7741         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7742         dst_reg->umin_value >>= umax_val;
7743         dst_reg->umax_value >>= umin_val;
7744
7745         /* Its not easy to operate on alu32 bounds here because it depends
7746          * on bits being shifted in. Take easy way out and mark unbounded
7747          * so we can recalculate later from tnum.
7748          */
7749         __mark_reg32_unbounded(dst_reg);
7750         __update_reg_bounds(dst_reg);
7751 }
7752
7753 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7754                                   struct bpf_reg_state *src_reg)
7755 {
7756         u64 umin_val = src_reg->u32_min_value;
7757
7758         /* Upon reaching here, src_known is true and
7759          * umax_val is equal to umin_val.
7760          */
7761         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7762         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7763
7764         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7765
7766         /* blow away the dst_reg umin_value/umax_value and rely on
7767          * dst_reg var_off to refine the result.
7768          */
7769         dst_reg->u32_min_value = 0;
7770         dst_reg->u32_max_value = U32_MAX;
7771
7772         __mark_reg64_unbounded(dst_reg);
7773         __update_reg32_bounds(dst_reg);
7774 }
7775
7776 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7777                                 struct bpf_reg_state *src_reg)
7778 {
7779         u64 umin_val = src_reg->umin_value;
7780
7781         /* Upon reaching here, src_known is true and umax_val is equal
7782          * to umin_val.
7783          */
7784         dst_reg->smin_value >>= umin_val;
7785         dst_reg->smax_value >>= umin_val;
7786
7787         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7788
7789         /* blow away the dst_reg umin_value/umax_value and rely on
7790          * dst_reg var_off to refine the result.
7791          */
7792         dst_reg->umin_value = 0;
7793         dst_reg->umax_value = U64_MAX;
7794
7795         /* Its not easy to operate on alu32 bounds here because it depends
7796          * on bits being shifted in from upper 32-bits. Take easy way out
7797          * and mark unbounded so we can recalculate later from tnum.
7798          */
7799         __mark_reg32_unbounded(dst_reg);
7800         __update_reg_bounds(dst_reg);
7801 }
7802
7803 /* WARNING: This function does calculations on 64-bit values, but the actual
7804  * execution may occur on 32-bit values. Therefore, things like bitshifts
7805  * need extra checks in the 32-bit case.
7806  */
7807 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7808                                       struct bpf_insn *insn,
7809                                       struct bpf_reg_state *dst_reg,
7810                                       struct bpf_reg_state src_reg)
7811 {
7812         struct bpf_reg_state *regs = cur_regs(env);
7813         u8 opcode = BPF_OP(insn->code);
7814         bool src_known;
7815         s64 smin_val, smax_val;
7816         u64 umin_val, umax_val;
7817         s32 s32_min_val, s32_max_val;
7818         u32 u32_min_val, u32_max_val;
7819         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7820         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7821         int ret;
7822
7823         smin_val = src_reg.smin_value;
7824         smax_val = src_reg.smax_value;
7825         umin_val = src_reg.umin_value;
7826         umax_val = src_reg.umax_value;
7827
7828         s32_min_val = src_reg.s32_min_value;
7829         s32_max_val = src_reg.s32_max_value;
7830         u32_min_val = src_reg.u32_min_value;
7831         u32_max_val = src_reg.u32_max_value;
7832
7833         if (alu32) {
7834                 src_known = tnum_subreg_is_const(src_reg.var_off);
7835                 if ((src_known &&
7836                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7837                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7838                         /* Taint dst register if offset had invalid bounds
7839                          * derived from e.g. dead branches.
7840                          */
7841                         __mark_reg_unknown(env, dst_reg);
7842                         return 0;
7843                 }
7844         } else {
7845                 src_known = tnum_is_const(src_reg.var_off);
7846                 if ((src_known &&
7847                      (smin_val != smax_val || umin_val != umax_val)) ||
7848                     smin_val > smax_val || umin_val > umax_val) {
7849                         /* Taint dst register if offset had invalid bounds
7850                          * derived from e.g. dead branches.
7851                          */
7852                         __mark_reg_unknown(env, dst_reg);
7853                         return 0;
7854                 }
7855         }
7856
7857         if (!src_known &&
7858             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7859                 __mark_reg_unknown(env, dst_reg);
7860                 return 0;
7861         }
7862
7863         if (sanitize_needed(opcode)) {
7864                 ret = sanitize_val_alu(env, insn);
7865                 if (ret < 0)
7866                         return sanitize_err(env, insn, ret, NULL, NULL);
7867         }
7868
7869         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7870          * There are two classes of instructions: The first class we track both
7871          * alu32 and alu64 sign/unsigned bounds independently this provides the
7872          * greatest amount of precision when alu operations are mixed with jmp32
7873          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7874          * and BPF_OR. This is possible because these ops have fairly easy to
7875          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7876          * See alu32 verifier tests for examples. The second class of
7877          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7878          * with regards to tracking sign/unsigned bounds because the bits may
7879          * cross subreg boundaries in the alu64 case. When this happens we mark
7880          * the reg unbounded in the subreg bound space and use the resulting
7881          * tnum to calculate an approximation of the sign/unsigned bounds.
7882          */
7883         switch (opcode) {
7884         case BPF_ADD:
7885                 scalar32_min_max_add(dst_reg, &src_reg);
7886                 scalar_min_max_add(dst_reg, &src_reg);
7887                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7888                 break;
7889         case BPF_SUB:
7890                 scalar32_min_max_sub(dst_reg, &src_reg);
7891                 scalar_min_max_sub(dst_reg, &src_reg);
7892                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7893                 break;
7894         case BPF_MUL:
7895                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7896                 scalar32_min_max_mul(dst_reg, &src_reg);
7897                 scalar_min_max_mul(dst_reg, &src_reg);
7898                 break;
7899         case BPF_AND:
7900                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7901                 scalar32_min_max_and(dst_reg, &src_reg);
7902                 scalar_min_max_and(dst_reg, &src_reg);
7903                 break;
7904         case BPF_OR:
7905                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7906                 scalar32_min_max_or(dst_reg, &src_reg);
7907                 scalar_min_max_or(dst_reg, &src_reg);
7908                 break;
7909         case BPF_XOR:
7910                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7911                 scalar32_min_max_xor(dst_reg, &src_reg);
7912                 scalar_min_max_xor(dst_reg, &src_reg);
7913                 break;
7914         case BPF_LSH:
7915                 if (umax_val >= insn_bitness) {
7916                         /* Shifts greater than 31 or 63 are undefined.
7917                          * This includes shifts by a negative number.
7918                          */
7919                         mark_reg_unknown(env, regs, insn->dst_reg);
7920                         break;
7921                 }
7922                 if (alu32)
7923                         scalar32_min_max_lsh(dst_reg, &src_reg);
7924                 else
7925                         scalar_min_max_lsh(dst_reg, &src_reg);
7926                 break;
7927         case BPF_RSH:
7928                 if (umax_val >= insn_bitness) {
7929                         /* Shifts greater than 31 or 63 are undefined.
7930                          * This includes shifts by a negative number.
7931                          */
7932                         mark_reg_unknown(env, regs, insn->dst_reg);
7933                         break;
7934                 }
7935                 if (alu32)
7936                         scalar32_min_max_rsh(dst_reg, &src_reg);
7937                 else
7938                         scalar_min_max_rsh(dst_reg, &src_reg);
7939                 break;
7940         case BPF_ARSH:
7941                 if (umax_val >= insn_bitness) {
7942                         /* Shifts greater than 31 or 63 are undefined.
7943                          * This includes shifts by a negative number.
7944                          */
7945                         mark_reg_unknown(env, regs, insn->dst_reg);
7946                         break;
7947                 }
7948                 if (alu32)
7949                         scalar32_min_max_arsh(dst_reg, &src_reg);
7950                 else
7951                         scalar_min_max_arsh(dst_reg, &src_reg);
7952                 break;
7953         default:
7954                 mark_reg_unknown(env, regs, insn->dst_reg);
7955                 break;
7956         }
7957
7958         /* ALU32 ops are zero extended into 64bit register */
7959         if (alu32)
7960                 zext_32_to_64(dst_reg);
7961
7962         __update_reg_bounds(dst_reg);
7963         __reg_deduce_bounds(dst_reg);
7964         __reg_bound_offset(dst_reg);
7965         return 0;
7966 }
7967
7968 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7969  * and var_off.
7970  */
7971 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7972                                    struct bpf_insn *insn)
7973 {
7974         struct bpf_verifier_state *vstate = env->cur_state;
7975         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7976         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7977         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7978         u8 opcode = BPF_OP(insn->code);
7979         int err;
7980
7981         dst_reg = &regs[insn->dst_reg];
7982         src_reg = NULL;
7983         if (dst_reg->type != SCALAR_VALUE)
7984                 ptr_reg = dst_reg;
7985         else
7986                 /* Make sure ID is cleared otherwise dst_reg min/max could be
7987                  * incorrectly propagated into other registers by find_equal_scalars()
7988                  */
7989                 dst_reg->id = 0;
7990         if (BPF_SRC(insn->code) == BPF_X) {
7991                 src_reg = &regs[insn->src_reg];
7992                 if (src_reg->type != SCALAR_VALUE) {
7993                         if (dst_reg->type != SCALAR_VALUE) {
7994                                 /* Combining two pointers by any ALU op yields
7995                                  * an arbitrary scalar. Disallow all math except
7996                                  * pointer subtraction
7997                                  */
7998                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7999                                         mark_reg_unknown(env, regs, insn->dst_reg);
8000                                         return 0;
8001                                 }
8002                                 verbose(env, "R%d pointer %s pointer prohibited\n",
8003                                         insn->dst_reg,
8004                                         bpf_alu_string[opcode >> 4]);
8005                                 return -EACCES;
8006                         } else {
8007                                 /* scalar += pointer
8008                                  * This is legal, but we have to reverse our
8009                                  * src/dest handling in computing the range
8010                                  */
8011                                 err = mark_chain_precision(env, insn->dst_reg);
8012                                 if (err)
8013                                         return err;
8014                                 return adjust_ptr_min_max_vals(env, insn,
8015                                                                src_reg, dst_reg);
8016                         }
8017                 } else if (ptr_reg) {
8018                         /* pointer += scalar */
8019                         err = mark_chain_precision(env, insn->src_reg);
8020                         if (err)
8021                                 return err;
8022                         return adjust_ptr_min_max_vals(env, insn,
8023                                                        dst_reg, src_reg);
8024                 }
8025         } else {
8026                 /* Pretend the src is a reg with a known value, since we only
8027                  * need to be able to read from this state.
8028                  */
8029                 off_reg.type = SCALAR_VALUE;
8030                 __mark_reg_known(&off_reg, insn->imm);
8031                 src_reg = &off_reg;
8032                 if (ptr_reg) /* pointer += K */
8033                         return adjust_ptr_min_max_vals(env, insn,
8034                                                        ptr_reg, src_reg);
8035         }
8036
8037         /* Got here implies adding two SCALAR_VALUEs */
8038         if (WARN_ON_ONCE(ptr_reg)) {
8039                 print_verifier_state(env, state);
8040                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
8041                 return -EINVAL;
8042         }
8043         if (WARN_ON(!src_reg)) {
8044                 print_verifier_state(env, state);
8045                 verbose(env, "verifier internal error: no src_reg\n");
8046                 return -EINVAL;
8047         }
8048         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8049 }
8050
8051 /* check validity of 32-bit and 64-bit arithmetic operations */
8052 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8053 {
8054         struct bpf_reg_state *regs = cur_regs(env);
8055         u8 opcode = BPF_OP(insn->code);
8056         int err;
8057
8058         if (opcode == BPF_END || opcode == BPF_NEG) {
8059                 if (opcode == BPF_NEG) {
8060                         if (BPF_SRC(insn->code) != 0 ||
8061                             insn->src_reg != BPF_REG_0 ||
8062                             insn->off != 0 || insn->imm != 0) {
8063                                 verbose(env, "BPF_NEG uses reserved fields\n");
8064                                 return -EINVAL;
8065                         }
8066                 } else {
8067                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8068                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8069                             BPF_CLASS(insn->code) == BPF_ALU64) {
8070                                 verbose(env, "BPF_END uses reserved fields\n");
8071                                 return -EINVAL;
8072                         }
8073                 }
8074
8075                 /* check src operand */
8076                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8077                 if (err)
8078                         return err;
8079
8080                 if (is_pointer_value(env, insn->dst_reg)) {
8081                         verbose(env, "R%d pointer arithmetic prohibited\n",
8082                                 insn->dst_reg);
8083                         return -EACCES;
8084                 }
8085
8086                 /* check dest operand */
8087                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
8088                 if (err)
8089                         return err;
8090
8091         } else if (opcode == BPF_MOV) {
8092
8093                 if (BPF_SRC(insn->code) == BPF_X) {
8094                         if (insn->imm != 0 || insn->off != 0) {
8095                                 verbose(env, "BPF_MOV uses reserved fields\n");
8096                                 return -EINVAL;
8097                         }
8098
8099                         /* check src operand */
8100                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
8101                         if (err)
8102                                 return err;
8103                 } else {
8104                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8105                                 verbose(env, "BPF_MOV uses reserved fields\n");
8106                                 return -EINVAL;
8107                         }
8108                 }
8109
8110                 /* check dest operand, mark as required later */
8111                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8112                 if (err)
8113                         return err;
8114
8115                 if (BPF_SRC(insn->code) == BPF_X) {
8116                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
8117                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8118
8119                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
8120                                 /* case: R1 = R2
8121                                  * copy register state to dest reg
8122                                  */
8123                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8124                                         /* Assign src and dst registers the same ID
8125                                          * that will be used by find_equal_scalars()
8126                                          * to propagate min/max range.
8127                                          */
8128                                         src_reg->id = ++env->id_gen;
8129                                 *dst_reg = *src_reg;
8130                                 dst_reg->live |= REG_LIVE_WRITTEN;
8131                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
8132                         } else {
8133                                 /* R1 = (u32) R2 */
8134                                 if (is_pointer_value(env, insn->src_reg)) {
8135                                         verbose(env,
8136                                                 "R%d partial copy of pointer\n",
8137                                                 insn->src_reg);
8138                                         return -EACCES;
8139                                 } else if (src_reg->type == SCALAR_VALUE) {
8140                                         *dst_reg = *src_reg;
8141                                         /* Make sure ID is cleared otherwise
8142                                          * dst_reg min/max could be incorrectly
8143                                          * propagated into src_reg by find_equal_scalars()
8144                                          */
8145                                         dst_reg->id = 0;
8146                                         dst_reg->live |= REG_LIVE_WRITTEN;
8147                                         dst_reg->subreg_def = env->insn_idx + 1;
8148                                 } else {
8149                                         mark_reg_unknown(env, regs,
8150                                                          insn->dst_reg);
8151                                 }
8152                                 zext_32_to_64(dst_reg);
8153
8154                                 __update_reg_bounds(dst_reg);
8155                                 __reg_deduce_bounds(dst_reg);
8156                                 __reg_bound_offset(dst_reg);
8157                         }
8158                 } else {
8159                         /* case: R = imm
8160                          * remember the value we stored into this reg
8161                          */
8162                         /* clear any state __mark_reg_known doesn't set */
8163                         mark_reg_unknown(env, regs, insn->dst_reg);
8164                         regs[insn->dst_reg].type = SCALAR_VALUE;
8165                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
8166                                 __mark_reg_known(regs + insn->dst_reg,
8167                                                  insn->imm);
8168                         } else {
8169                                 __mark_reg_known(regs + insn->dst_reg,
8170                                                  (u32)insn->imm);
8171                         }
8172                 }
8173
8174         } else if (opcode > BPF_END) {
8175                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8176                 return -EINVAL;
8177
8178         } else {        /* all other ALU ops: and, sub, xor, add, ... */
8179
8180                 if (BPF_SRC(insn->code) == BPF_X) {
8181                         if (insn->imm != 0 || insn->off != 0) {
8182                                 verbose(env, "BPF_ALU uses reserved fields\n");
8183                                 return -EINVAL;
8184                         }
8185                         /* check src1 operand */
8186                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
8187                         if (err)
8188                                 return err;
8189                 } else {
8190                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8191                                 verbose(env, "BPF_ALU uses reserved fields\n");
8192                                 return -EINVAL;
8193                         }
8194                 }
8195
8196                 /* check src2 operand */
8197                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8198                 if (err)
8199                         return err;
8200
8201                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8202                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8203                         verbose(env, "div by zero\n");
8204                         return -EINVAL;
8205                 }
8206
8207                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8208                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8209                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8210
8211                         if (insn->imm < 0 || insn->imm >= size) {
8212                                 verbose(env, "invalid shift %d\n", insn->imm);
8213                                 return -EINVAL;
8214                         }
8215                 }
8216
8217                 /* check dest operand */
8218                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8219                 if (err)
8220                         return err;
8221
8222                 return adjust_reg_min_max_vals(env, insn);
8223         }
8224
8225         return 0;
8226 }
8227
8228 static void __find_good_pkt_pointers(struct bpf_func_state *state,
8229                                      struct bpf_reg_state *dst_reg,
8230                                      enum bpf_reg_type type, int new_range)
8231 {
8232         struct bpf_reg_state *reg;
8233         int i;
8234
8235         for (i = 0; i < MAX_BPF_REG; i++) {
8236                 reg = &state->regs[i];
8237                 if (reg->type == type && reg->id == dst_reg->id)
8238                         /* keep the maximum range already checked */
8239                         reg->range = max(reg->range, new_range);
8240         }
8241
8242         bpf_for_each_spilled_reg(i, state, reg) {
8243                 if (!reg)
8244                         continue;
8245                 if (reg->type == type && reg->id == dst_reg->id)
8246                         reg->range = max(reg->range, new_range);
8247         }
8248 }
8249
8250 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8251                                    struct bpf_reg_state *dst_reg,
8252                                    enum bpf_reg_type type,
8253                                    bool range_right_open)
8254 {
8255         int new_range, i;
8256
8257         if (dst_reg->off < 0 ||
8258             (dst_reg->off == 0 && range_right_open))
8259                 /* This doesn't give us any range */
8260                 return;
8261
8262         if (dst_reg->umax_value > MAX_PACKET_OFF ||
8263             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8264                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
8265                  * than pkt_end, but that's because it's also less than pkt.
8266                  */
8267                 return;
8268
8269         new_range = dst_reg->off;
8270         if (range_right_open)
8271                 new_range++;
8272
8273         /* Examples for register markings:
8274          *
8275          * pkt_data in dst register:
8276          *
8277          *   r2 = r3;
8278          *   r2 += 8;
8279          *   if (r2 > pkt_end) goto <handle exception>
8280          *   <access okay>
8281          *
8282          *   r2 = r3;
8283          *   r2 += 8;
8284          *   if (r2 < pkt_end) goto <access okay>
8285          *   <handle exception>
8286          *
8287          *   Where:
8288          *     r2 == dst_reg, pkt_end == src_reg
8289          *     r2=pkt(id=n,off=8,r=0)
8290          *     r3=pkt(id=n,off=0,r=0)
8291          *
8292          * pkt_data in src register:
8293          *
8294          *   r2 = r3;
8295          *   r2 += 8;
8296          *   if (pkt_end >= r2) goto <access okay>
8297          *   <handle exception>
8298          *
8299          *   r2 = r3;
8300          *   r2 += 8;
8301          *   if (pkt_end <= r2) goto <handle exception>
8302          *   <access okay>
8303          *
8304          *   Where:
8305          *     pkt_end == dst_reg, r2 == src_reg
8306          *     r2=pkt(id=n,off=8,r=0)
8307          *     r3=pkt(id=n,off=0,r=0)
8308          *
8309          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8310          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8311          * and [r3, r3 + 8-1) respectively is safe to access depending on
8312          * the check.
8313          */
8314
8315         /* If our ids match, then we must have the same max_value.  And we
8316          * don't care about the other reg's fixed offset, since if it's too big
8317          * the range won't allow anything.
8318          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8319          */
8320         for (i = 0; i <= vstate->curframe; i++)
8321                 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8322                                          new_range);
8323 }
8324
8325 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8326 {
8327         struct tnum subreg = tnum_subreg(reg->var_off);
8328         s32 sval = (s32)val;
8329
8330         switch (opcode) {
8331         case BPF_JEQ:
8332                 if (tnum_is_const(subreg))
8333                         return !!tnum_equals_const(subreg, val);
8334                 break;
8335         case BPF_JNE:
8336                 if (tnum_is_const(subreg))
8337                         return !tnum_equals_const(subreg, val);
8338                 break;
8339         case BPF_JSET:
8340                 if ((~subreg.mask & subreg.value) & val)
8341                         return 1;
8342                 if (!((subreg.mask | subreg.value) & val))
8343                         return 0;
8344                 break;
8345         case BPF_JGT:
8346                 if (reg->u32_min_value > val)
8347                         return 1;
8348                 else if (reg->u32_max_value <= val)
8349                         return 0;
8350                 break;
8351         case BPF_JSGT:
8352                 if (reg->s32_min_value > sval)
8353                         return 1;
8354                 else if (reg->s32_max_value <= sval)
8355                         return 0;
8356                 break;
8357         case BPF_JLT:
8358                 if (reg->u32_max_value < val)
8359                         return 1;
8360                 else if (reg->u32_min_value >= val)
8361                         return 0;
8362                 break;
8363         case BPF_JSLT:
8364                 if (reg->s32_max_value < sval)
8365                         return 1;
8366                 else if (reg->s32_min_value >= sval)
8367                         return 0;
8368                 break;
8369         case BPF_JGE:
8370                 if (reg->u32_min_value >= val)
8371                         return 1;
8372                 else if (reg->u32_max_value < val)
8373                         return 0;
8374                 break;
8375         case BPF_JSGE:
8376                 if (reg->s32_min_value >= sval)
8377                         return 1;
8378                 else if (reg->s32_max_value < sval)
8379                         return 0;
8380                 break;
8381         case BPF_JLE:
8382                 if (reg->u32_max_value <= val)
8383                         return 1;
8384                 else if (reg->u32_min_value > val)
8385                         return 0;
8386                 break;
8387         case BPF_JSLE:
8388                 if (reg->s32_max_value <= sval)
8389                         return 1;
8390                 else if (reg->s32_min_value > sval)
8391                         return 0;
8392                 break;
8393         }
8394
8395         return -1;
8396 }
8397
8398
8399 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8400 {
8401         s64 sval = (s64)val;
8402
8403         switch (opcode) {
8404         case BPF_JEQ:
8405                 if (tnum_is_const(reg->var_off))
8406                         return !!tnum_equals_const(reg->var_off, val);
8407                 break;
8408         case BPF_JNE:
8409                 if (tnum_is_const(reg->var_off))
8410                         return !tnum_equals_const(reg->var_off, val);
8411                 break;
8412         case BPF_JSET:
8413                 if ((~reg->var_off.mask & reg->var_off.value) & val)
8414                         return 1;
8415                 if (!((reg->var_off.mask | reg->var_off.value) & val))
8416                         return 0;
8417                 break;
8418         case BPF_JGT:
8419                 if (reg->umin_value > val)
8420                         return 1;
8421                 else if (reg->umax_value <= val)
8422                         return 0;
8423                 break;
8424         case BPF_JSGT:
8425                 if (reg->smin_value > sval)
8426                         return 1;
8427                 else if (reg->smax_value <= sval)
8428                         return 0;
8429                 break;
8430         case BPF_JLT:
8431                 if (reg->umax_value < val)
8432                         return 1;
8433                 else if (reg->umin_value >= val)
8434                         return 0;
8435                 break;
8436         case BPF_JSLT:
8437                 if (reg->smax_value < sval)
8438                         return 1;
8439                 else if (reg->smin_value >= sval)
8440                         return 0;
8441                 break;
8442         case BPF_JGE:
8443                 if (reg->umin_value >= val)
8444                         return 1;
8445                 else if (reg->umax_value < val)
8446                         return 0;
8447                 break;
8448         case BPF_JSGE:
8449                 if (reg->smin_value >= sval)
8450                         return 1;
8451                 else if (reg->smax_value < sval)
8452                         return 0;
8453                 break;
8454         case BPF_JLE:
8455                 if (reg->umax_value <= val)
8456                         return 1;
8457                 else if (reg->umin_value > val)
8458                         return 0;
8459                 break;
8460         case BPF_JSLE:
8461                 if (reg->smax_value <= sval)
8462                         return 1;
8463                 else if (reg->smin_value > sval)
8464                         return 0;
8465                 break;
8466         }
8467
8468         return -1;
8469 }
8470
8471 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8472  * and return:
8473  *  1 - branch will be taken and "goto target" will be executed
8474  *  0 - branch will not be taken and fall-through to next insn
8475  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8476  *      range [0,10]
8477  */
8478 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8479                            bool is_jmp32)
8480 {
8481         if (__is_pointer_value(false, reg)) {
8482                 if (!reg_type_not_null(reg->type))
8483                         return -1;
8484
8485                 /* If pointer is valid tests against zero will fail so we can
8486                  * use this to direct branch taken.
8487                  */
8488                 if (val != 0)
8489                         return -1;
8490
8491                 switch (opcode) {
8492                 case BPF_JEQ:
8493                         return 0;
8494                 case BPF_JNE:
8495                         return 1;
8496                 default:
8497                         return -1;
8498                 }
8499         }
8500
8501         if (is_jmp32)
8502                 return is_branch32_taken(reg, val, opcode);
8503         return is_branch64_taken(reg, val, opcode);
8504 }
8505
8506 static int flip_opcode(u32 opcode)
8507 {
8508         /* How can we transform "a <op> b" into "b <op> a"? */
8509         static const u8 opcode_flip[16] = {
8510                 /* these stay the same */
8511                 [BPF_JEQ  >> 4] = BPF_JEQ,
8512                 [BPF_JNE  >> 4] = BPF_JNE,
8513                 [BPF_JSET >> 4] = BPF_JSET,
8514                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8515                 [BPF_JGE  >> 4] = BPF_JLE,
8516                 [BPF_JGT  >> 4] = BPF_JLT,
8517                 [BPF_JLE  >> 4] = BPF_JGE,
8518                 [BPF_JLT  >> 4] = BPF_JGT,
8519                 [BPF_JSGE >> 4] = BPF_JSLE,
8520                 [BPF_JSGT >> 4] = BPF_JSLT,
8521                 [BPF_JSLE >> 4] = BPF_JSGE,
8522                 [BPF_JSLT >> 4] = BPF_JSGT
8523         };
8524         return opcode_flip[opcode >> 4];
8525 }
8526
8527 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8528                                    struct bpf_reg_state *src_reg,
8529                                    u8 opcode)
8530 {
8531         struct bpf_reg_state *pkt;
8532
8533         if (src_reg->type == PTR_TO_PACKET_END) {
8534                 pkt = dst_reg;
8535         } else if (dst_reg->type == PTR_TO_PACKET_END) {
8536                 pkt = src_reg;
8537                 opcode = flip_opcode(opcode);
8538         } else {
8539                 return -1;
8540         }
8541
8542         if (pkt->range >= 0)
8543                 return -1;
8544
8545         switch (opcode) {
8546         case BPF_JLE:
8547                 /* pkt <= pkt_end */
8548                 fallthrough;
8549         case BPF_JGT:
8550                 /* pkt > pkt_end */
8551                 if (pkt->range == BEYOND_PKT_END)
8552                         /* pkt has at last one extra byte beyond pkt_end */
8553                         return opcode == BPF_JGT;
8554                 break;
8555         case BPF_JLT:
8556                 /* pkt < pkt_end */
8557                 fallthrough;
8558         case BPF_JGE:
8559                 /* pkt >= pkt_end */
8560                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8561                         return opcode == BPF_JGE;
8562                 break;
8563         }
8564         return -1;
8565 }
8566
8567 /* Adjusts the register min/max values in the case that the dst_reg is the
8568  * variable register that we are working on, and src_reg is a constant or we're
8569  * simply doing a BPF_K check.
8570  * In JEQ/JNE cases we also adjust the var_off values.
8571  */
8572 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8573                             struct bpf_reg_state *false_reg,
8574                             u64 val, u32 val32,
8575                             u8 opcode, bool is_jmp32)
8576 {
8577         struct tnum false_32off = tnum_subreg(false_reg->var_off);
8578         struct tnum false_64off = false_reg->var_off;
8579         struct tnum true_32off = tnum_subreg(true_reg->var_off);
8580         struct tnum true_64off = true_reg->var_off;
8581         s64 sval = (s64)val;
8582         s32 sval32 = (s32)val32;
8583
8584         /* If the dst_reg is a pointer, we can't learn anything about its
8585          * variable offset from the compare (unless src_reg were a pointer into
8586          * the same object, but we don't bother with that.
8587          * Since false_reg and true_reg have the same type by construction, we
8588          * only need to check one of them for pointerness.
8589          */
8590         if (__is_pointer_value(false, false_reg))
8591                 return;
8592
8593         switch (opcode) {
8594         /* JEQ/JNE comparison doesn't change the register equivalence.
8595          *
8596          * r1 = r2;
8597          * if (r1 == 42) goto label;
8598          * ...
8599          * label: // here both r1 and r2 are known to be 42.
8600          *
8601          * Hence when marking register as known preserve it's ID.
8602          */
8603         case BPF_JEQ:
8604                 if (is_jmp32) {
8605                         __mark_reg32_known(true_reg, val32);
8606                         true_32off = tnum_subreg(true_reg->var_off);
8607                 } else {
8608                         ___mark_reg_known(true_reg, val);
8609                         true_64off = true_reg->var_off;
8610                 }
8611                 break;
8612         case BPF_JNE:
8613                 if (is_jmp32) {
8614                         __mark_reg32_known(false_reg, val32);
8615                         false_32off = tnum_subreg(false_reg->var_off);
8616                 } else {
8617                         ___mark_reg_known(false_reg, val);
8618                         false_64off = false_reg->var_off;
8619                 }
8620                 break;
8621         case BPF_JSET:
8622                 if (is_jmp32) {
8623                         false_32off = tnum_and(false_32off, tnum_const(~val32));
8624                         if (is_power_of_2(val32))
8625                                 true_32off = tnum_or(true_32off,
8626                                                      tnum_const(val32));
8627                 } else {
8628                         false_64off = tnum_and(false_64off, tnum_const(~val));
8629                         if (is_power_of_2(val))
8630                                 true_64off = tnum_or(true_64off,
8631                                                      tnum_const(val));
8632                 }
8633                 break;
8634         case BPF_JGE:
8635         case BPF_JGT:
8636         {
8637                 if (is_jmp32) {
8638                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8639                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8640
8641                         false_reg->u32_max_value = min(false_reg->u32_max_value,
8642                                                        false_umax);
8643                         true_reg->u32_min_value = max(true_reg->u32_min_value,
8644                                                       true_umin);
8645                 } else {
8646                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8647                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8648
8649                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
8650                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
8651                 }
8652                 break;
8653         }
8654         case BPF_JSGE:
8655         case BPF_JSGT:
8656         {
8657                 if (is_jmp32) {
8658                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8659                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8660
8661                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8662                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8663                 } else {
8664                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8665                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8666
8667                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
8668                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
8669                 }
8670                 break;
8671         }
8672         case BPF_JLE:
8673         case BPF_JLT:
8674         {
8675                 if (is_jmp32) {
8676                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8677                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8678
8679                         false_reg->u32_min_value = max(false_reg->u32_min_value,
8680                                                        false_umin);
8681                         true_reg->u32_max_value = min(true_reg->u32_max_value,
8682                                                       true_umax);
8683                 } else {
8684                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8685                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8686
8687                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
8688                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
8689                 }
8690                 break;
8691         }
8692         case BPF_JSLE:
8693         case BPF_JSLT:
8694         {
8695                 if (is_jmp32) {
8696                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8697                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8698
8699                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8700                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8701                 } else {
8702                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8703                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8704
8705                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
8706                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
8707                 }
8708                 break;
8709         }
8710         default:
8711                 return;
8712         }
8713
8714         if (is_jmp32) {
8715                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8716                                              tnum_subreg(false_32off));
8717                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8718                                             tnum_subreg(true_32off));
8719                 __reg_combine_32_into_64(false_reg);
8720                 __reg_combine_32_into_64(true_reg);
8721         } else {
8722                 false_reg->var_off = false_64off;
8723                 true_reg->var_off = true_64off;
8724                 __reg_combine_64_into_32(false_reg);
8725                 __reg_combine_64_into_32(true_reg);
8726         }
8727 }
8728
8729 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8730  * the variable reg.
8731  */
8732 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8733                                 struct bpf_reg_state *false_reg,
8734                                 u64 val, u32 val32,
8735                                 u8 opcode, bool is_jmp32)
8736 {
8737         opcode = flip_opcode(opcode);
8738         /* This uses zero as "not present in table"; luckily the zero opcode,
8739          * BPF_JA, can't get here.
8740          */
8741         if (opcode)
8742                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8743 }
8744
8745 /* Regs are known to be equal, so intersect their min/max/var_off */
8746 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8747                                   struct bpf_reg_state *dst_reg)
8748 {
8749         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8750                                                         dst_reg->umin_value);
8751         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8752                                                         dst_reg->umax_value);
8753         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8754                                                         dst_reg->smin_value);
8755         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8756                                                         dst_reg->smax_value);
8757         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8758                                                              dst_reg->var_off);
8759         /* We might have learned new bounds from the var_off. */
8760         __update_reg_bounds(src_reg);
8761         __update_reg_bounds(dst_reg);
8762         /* We might have learned something about the sign bit. */
8763         __reg_deduce_bounds(src_reg);
8764         __reg_deduce_bounds(dst_reg);
8765         /* We might have learned some bits from the bounds. */
8766         __reg_bound_offset(src_reg);
8767         __reg_bound_offset(dst_reg);
8768         /* Intersecting with the old var_off might have improved our bounds
8769          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8770          * then new var_off is (0; 0x7f...fc) which improves our umax.
8771          */
8772         __update_reg_bounds(src_reg);
8773         __update_reg_bounds(dst_reg);
8774 }
8775
8776 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8777                                 struct bpf_reg_state *true_dst,
8778                                 struct bpf_reg_state *false_src,
8779                                 struct bpf_reg_state *false_dst,
8780                                 u8 opcode)
8781 {
8782         switch (opcode) {
8783         case BPF_JEQ:
8784                 __reg_combine_min_max(true_src, true_dst);
8785                 break;
8786         case BPF_JNE:
8787                 __reg_combine_min_max(false_src, false_dst);
8788                 break;
8789         }
8790 }
8791
8792 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8793                                  struct bpf_reg_state *reg, u32 id,
8794                                  bool is_null)
8795 {
8796         if (type_may_be_null(reg->type) && reg->id == id &&
8797             !WARN_ON_ONCE(!reg->id)) {
8798                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8799                                  !tnum_equals_const(reg->var_off, 0) ||
8800                                  reg->off)) {
8801                         /* Old offset (both fixed and variable parts) should
8802                          * have been known-zero, because we don't allow pointer
8803                          * arithmetic on pointers that might be NULL. If we
8804                          * see this happening, don't convert the register.
8805                          */
8806                         return;
8807                 }
8808                 if (is_null) {
8809                         reg->type = SCALAR_VALUE;
8810                         /* We don't need id and ref_obj_id from this point
8811                          * onwards anymore, thus we should better reset it,
8812                          * so that state pruning has chances to take effect.
8813                          */
8814                         reg->id = 0;
8815                         reg->ref_obj_id = 0;
8816
8817                         return;
8818                 }
8819
8820                 mark_ptr_not_null_reg(reg);
8821
8822                 if (!reg_may_point_to_spin_lock(reg)) {
8823                         /* For not-NULL ptr, reg->ref_obj_id will be reset
8824                          * in release_reg_references().
8825                          *
8826                          * reg->id is still used by spin_lock ptr. Other
8827                          * than spin_lock ptr type, reg->id can be reset.
8828                          */
8829                         reg->id = 0;
8830                 }
8831         }
8832 }
8833
8834 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8835                                     bool is_null)
8836 {
8837         struct bpf_reg_state *reg;
8838         int i;
8839
8840         for (i = 0; i < MAX_BPF_REG; i++)
8841                 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8842
8843         bpf_for_each_spilled_reg(i, state, reg) {
8844                 if (!reg)
8845                         continue;
8846                 mark_ptr_or_null_reg(state, reg, id, is_null);
8847         }
8848 }
8849
8850 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8851  * be folded together at some point.
8852  */
8853 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8854                                   bool is_null)
8855 {
8856         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8857         struct bpf_reg_state *regs = state->regs;
8858         u32 ref_obj_id = regs[regno].ref_obj_id;
8859         u32 id = regs[regno].id;
8860         int i;
8861
8862         if (ref_obj_id && ref_obj_id == id && is_null)
8863                 /* regs[regno] is in the " == NULL" branch.
8864                  * No one could have freed the reference state before
8865                  * doing the NULL check.
8866                  */
8867                 WARN_ON_ONCE(release_reference_state(state, id));
8868
8869         for (i = 0; i <= vstate->curframe; i++)
8870                 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
8871 }
8872
8873 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8874                                    struct bpf_reg_state *dst_reg,
8875                                    struct bpf_reg_state *src_reg,
8876                                    struct bpf_verifier_state *this_branch,
8877                                    struct bpf_verifier_state *other_branch)
8878 {
8879         if (BPF_SRC(insn->code) != BPF_X)
8880                 return false;
8881
8882         /* Pointers are always 64-bit. */
8883         if (BPF_CLASS(insn->code) == BPF_JMP32)
8884                 return false;
8885
8886         switch (BPF_OP(insn->code)) {
8887         case BPF_JGT:
8888                 if ((dst_reg->type == PTR_TO_PACKET &&
8889                      src_reg->type == PTR_TO_PACKET_END) ||
8890                     (dst_reg->type == PTR_TO_PACKET_META &&
8891                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8892                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8893                         find_good_pkt_pointers(this_branch, dst_reg,
8894                                                dst_reg->type, false);
8895                         mark_pkt_end(other_branch, insn->dst_reg, true);
8896                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8897                             src_reg->type == PTR_TO_PACKET) ||
8898                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8899                             src_reg->type == PTR_TO_PACKET_META)) {
8900                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8901                         find_good_pkt_pointers(other_branch, src_reg,
8902                                                src_reg->type, true);
8903                         mark_pkt_end(this_branch, insn->src_reg, false);
8904                 } else {
8905                         return false;
8906                 }
8907                 break;
8908         case BPF_JLT:
8909                 if ((dst_reg->type == PTR_TO_PACKET &&
8910                      src_reg->type == PTR_TO_PACKET_END) ||
8911                     (dst_reg->type == PTR_TO_PACKET_META &&
8912                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8913                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8914                         find_good_pkt_pointers(other_branch, dst_reg,
8915                                                dst_reg->type, true);
8916                         mark_pkt_end(this_branch, insn->dst_reg, false);
8917                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8918                             src_reg->type == PTR_TO_PACKET) ||
8919                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8920                             src_reg->type == PTR_TO_PACKET_META)) {
8921                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8922                         find_good_pkt_pointers(this_branch, src_reg,
8923                                                src_reg->type, false);
8924                         mark_pkt_end(other_branch, insn->src_reg, true);
8925                 } else {
8926                         return false;
8927                 }
8928                 break;
8929         case BPF_JGE:
8930                 if ((dst_reg->type == PTR_TO_PACKET &&
8931                      src_reg->type == PTR_TO_PACKET_END) ||
8932                     (dst_reg->type == PTR_TO_PACKET_META &&
8933                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8934                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8935                         find_good_pkt_pointers(this_branch, dst_reg,
8936                                                dst_reg->type, true);
8937                         mark_pkt_end(other_branch, insn->dst_reg, false);
8938                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8939                             src_reg->type == PTR_TO_PACKET) ||
8940                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8941                             src_reg->type == PTR_TO_PACKET_META)) {
8942                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8943                         find_good_pkt_pointers(other_branch, src_reg,
8944                                                src_reg->type, false);
8945                         mark_pkt_end(this_branch, insn->src_reg, true);
8946                 } else {
8947                         return false;
8948                 }
8949                 break;
8950         case BPF_JLE:
8951                 if ((dst_reg->type == PTR_TO_PACKET &&
8952                      src_reg->type == PTR_TO_PACKET_END) ||
8953                     (dst_reg->type == PTR_TO_PACKET_META &&
8954                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8955                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8956                         find_good_pkt_pointers(other_branch, dst_reg,
8957                                                dst_reg->type, false);
8958                         mark_pkt_end(this_branch, insn->dst_reg, true);
8959                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8960                             src_reg->type == PTR_TO_PACKET) ||
8961                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8962                             src_reg->type == PTR_TO_PACKET_META)) {
8963                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8964                         find_good_pkt_pointers(this_branch, src_reg,
8965                                                src_reg->type, true);
8966                         mark_pkt_end(other_branch, insn->src_reg, false);
8967                 } else {
8968                         return false;
8969                 }
8970                 break;
8971         default:
8972                 return false;
8973         }
8974
8975         return true;
8976 }
8977
8978 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8979                                struct bpf_reg_state *known_reg)
8980 {
8981         struct bpf_func_state *state;
8982         struct bpf_reg_state *reg;
8983         int i, j;
8984
8985         for (i = 0; i <= vstate->curframe; i++) {
8986                 state = vstate->frame[i];
8987                 for (j = 0; j < MAX_BPF_REG; j++) {
8988                         reg = &state->regs[j];
8989                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8990                                 *reg = *known_reg;
8991                 }
8992
8993                 bpf_for_each_spilled_reg(j, state, reg) {
8994                         if (!reg)
8995                                 continue;
8996                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8997                                 *reg = *known_reg;
8998                 }
8999         }
9000 }
9001
9002 static int check_cond_jmp_op(struct bpf_verifier_env *env,
9003                              struct bpf_insn *insn, int *insn_idx)
9004 {
9005         struct bpf_verifier_state *this_branch = env->cur_state;
9006         struct bpf_verifier_state *other_branch;
9007         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
9008         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
9009         u8 opcode = BPF_OP(insn->code);
9010         bool is_jmp32;
9011         int pred = -1;
9012         int err;
9013
9014         /* Only conditional jumps are expected to reach here. */
9015         if (opcode == BPF_JA || opcode > BPF_JSLE) {
9016                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
9017                 return -EINVAL;
9018         }
9019
9020         if (BPF_SRC(insn->code) == BPF_X) {
9021                 if (insn->imm != 0) {
9022                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9023                         return -EINVAL;
9024                 }
9025
9026                 /* check src1 operand */
9027                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9028                 if (err)
9029                         return err;
9030
9031                 if (is_pointer_value(env, insn->src_reg)) {
9032                         verbose(env, "R%d pointer comparison prohibited\n",
9033                                 insn->src_reg);
9034                         return -EACCES;
9035                 }
9036                 src_reg = &regs[insn->src_reg];
9037         } else {
9038                 if (insn->src_reg != BPF_REG_0) {
9039                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9040                         return -EINVAL;
9041                 }
9042         }
9043
9044         /* check src2 operand */
9045         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9046         if (err)
9047                 return err;
9048
9049         dst_reg = &regs[insn->dst_reg];
9050         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9051
9052         if (BPF_SRC(insn->code) == BPF_K) {
9053                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9054         } else if (src_reg->type == SCALAR_VALUE &&
9055                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9056                 pred = is_branch_taken(dst_reg,
9057                                        tnum_subreg(src_reg->var_off).value,
9058                                        opcode,
9059                                        is_jmp32);
9060         } else if (src_reg->type == SCALAR_VALUE &&
9061                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9062                 pred = is_branch_taken(dst_reg,
9063                                        src_reg->var_off.value,
9064                                        opcode,
9065                                        is_jmp32);
9066         } else if (reg_is_pkt_pointer_any(dst_reg) &&
9067                    reg_is_pkt_pointer_any(src_reg) &&
9068                    !is_jmp32) {
9069                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9070         }
9071
9072         if (pred >= 0) {
9073                 /* If we get here with a dst_reg pointer type it is because
9074                  * above is_branch_taken() special cased the 0 comparison.
9075                  */
9076                 if (!__is_pointer_value(false, dst_reg))
9077                         err = mark_chain_precision(env, insn->dst_reg);
9078                 if (BPF_SRC(insn->code) == BPF_X && !err &&
9079                     !__is_pointer_value(false, src_reg))
9080                         err = mark_chain_precision(env, insn->src_reg);
9081                 if (err)
9082                         return err;
9083         }
9084
9085         if (pred == 1) {
9086                 /* Only follow the goto, ignore fall-through. If needed, push
9087                  * the fall-through branch for simulation under speculative
9088                  * execution.
9089                  */
9090                 if (!env->bypass_spec_v1 &&
9091                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
9092                                                *insn_idx))
9093                         return -EFAULT;
9094                 *insn_idx += insn->off;
9095                 return 0;
9096         } else if (pred == 0) {
9097                 /* Only follow the fall-through branch, since that's where the
9098                  * program will go. If needed, push the goto branch for
9099                  * simulation under speculative execution.
9100                  */
9101                 if (!env->bypass_spec_v1 &&
9102                     !sanitize_speculative_path(env, insn,
9103                                                *insn_idx + insn->off + 1,
9104                                                *insn_idx))
9105                         return -EFAULT;
9106                 return 0;
9107         }
9108
9109         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9110                                   false);
9111         if (!other_branch)
9112                 return -EFAULT;
9113         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9114
9115         /* detect if we are comparing against a constant value so we can adjust
9116          * our min/max values for our dst register.
9117          * this is only legit if both are scalars (or pointers to the same
9118          * object, I suppose, but we don't support that right now), because
9119          * otherwise the different base pointers mean the offsets aren't
9120          * comparable.
9121          */
9122         if (BPF_SRC(insn->code) == BPF_X) {
9123                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9124
9125                 if (dst_reg->type == SCALAR_VALUE &&
9126                     src_reg->type == SCALAR_VALUE) {
9127                         if (tnum_is_const(src_reg->var_off) ||
9128                             (is_jmp32 &&
9129                              tnum_is_const(tnum_subreg(src_reg->var_off))))
9130                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
9131                                                 dst_reg,
9132                                                 src_reg->var_off.value,
9133                                                 tnum_subreg(src_reg->var_off).value,
9134                                                 opcode, is_jmp32);
9135                         else if (tnum_is_const(dst_reg->var_off) ||
9136                                  (is_jmp32 &&
9137                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
9138                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9139                                                     src_reg,
9140                                                     dst_reg->var_off.value,
9141                                                     tnum_subreg(dst_reg->var_off).value,
9142                                                     opcode, is_jmp32);
9143                         else if (!is_jmp32 &&
9144                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
9145                                 /* Comparing for equality, we can combine knowledge */
9146                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
9147                                                     &other_branch_regs[insn->dst_reg],
9148                                                     src_reg, dst_reg, opcode);
9149                         if (src_reg->id &&
9150                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9151                                 find_equal_scalars(this_branch, src_reg);
9152                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9153                         }
9154
9155                 }
9156         } else if (dst_reg->type == SCALAR_VALUE) {
9157                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
9158                                         dst_reg, insn->imm, (u32)insn->imm,
9159                                         opcode, is_jmp32);
9160         }
9161
9162         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9163             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9164                 find_equal_scalars(this_branch, dst_reg);
9165                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9166         }
9167
9168         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9169          * NOTE: these optimizations below are related with pointer comparison
9170          *       which will never be JMP32.
9171          */
9172         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9173             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9174             type_may_be_null(dst_reg->type)) {
9175                 /* Mark all identical registers in each branch as either
9176                  * safe or unknown depending R == 0 or R != 0 conditional.
9177                  */
9178                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9179                                       opcode == BPF_JNE);
9180                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9181                                       opcode == BPF_JEQ);
9182         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9183                                            this_branch, other_branch) &&
9184                    is_pointer_value(env, insn->dst_reg)) {
9185                 verbose(env, "R%d pointer comparison prohibited\n",
9186                         insn->dst_reg);
9187                 return -EACCES;
9188         }
9189         if (env->log.level & BPF_LOG_LEVEL)
9190                 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9191         return 0;
9192 }
9193
9194 /* verify BPF_LD_IMM64 instruction */
9195 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9196 {
9197         struct bpf_insn_aux_data *aux = cur_aux(env);
9198         struct bpf_reg_state *regs = cur_regs(env);
9199         struct bpf_reg_state *dst_reg;
9200         struct bpf_map *map;
9201         int err;
9202
9203         if (BPF_SIZE(insn->code) != BPF_DW) {
9204                 verbose(env, "invalid BPF_LD_IMM insn\n");
9205                 return -EINVAL;
9206         }
9207         if (insn->off != 0) {
9208                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9209                 return -EINVAL;
9210         }
9211
9212         err = check_reg_arg(env, insn->dst_reg, DST_OP);
9213         if (err)
9214                 return err;
9215
9216         dst_reg = &regs[insn->dst_reg];
9217         if (insn->src_reg == 0) {
9218                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9219
9220                 dst_reg->type = SCALAR_VALUE;
9221                 __mark_reg_known(&regs[insn->dst_reg], imm);
9222                 return 0;
9223         }
9224
9225         /* All special src_reg cases are listed below. From this point onwards
9226          * we either succeed and assign a corresponding dst_reg->type after
9227          * zeroing the offset, or fail and reject the program.
9228          */
9229         mark_reg_known_zero(env, regs, insn->dst_reg);
9230
9231         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9232                 dst_reg->type = aux->btf_var.reg_type;
9233                 switch (base_type(dst_reg->type)) {
9234                 case PTR_TO_MEM:
9235                         dst_reg->mem_size = aux->btf_var.mem_size;
9236                         break;
9237                 case PTR_TO_BTF_ID:
9238                 case PTR_TO_PERCPU_BTF_ID:
9239                         dst_reg->btf = aux->btf_var.btf;
9240                         dst_reg->btf_id = aux->btf_var.btf_id;
9241                         break;
9242                 default:
9243                         verbose(env, "bpf verifier is misconfigured\n");
9244                         return -EFAULT;
9245                 }
9246                 return 0;
9247         }
9248
9249         if (insn->src_reg == BPF_PSEUDO_FUNC) {
9250                 struct bpf_prog_aux *aux = env->prog->aux;
9251                 u32 subprogno = insn[1].imm;
9252
9253                 if (!aux->func_info) {
9254                         verbose(env, "missing btf func_info\n");
9255                         return -EINVAL;
9256                 }
9257                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9258                         verbose(env, "callback function not static\n");
9259                         return -EINVAL;
9260                 }
9261
9262                 dst_reg->type = PTR_TO_FUNC;
9263                 dst_reg->subprogno = subprogno;
9264                 return 0;
9265         }
9266
9267         map = env->used_maps[aux->map_index];
9268         dst_reg->map_ptr = map;
9269
9270         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9271             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9272                 dst_reg->type = PTR_TO_MAP_VALUE;
9273                 dst_reg->off = aux->map_off;
9274                 if (map_value_has_spin_lock(map))
9275                         dst_reg->id = ++env->id_gen;
9276         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9277                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9278                 dst_reg->type = CONST_PTR_TO_MAP;
9279         } else {
9280                 verbose(env, "bpf verifier is misconfigured\n");
9281                 return -EINVAL;
9282         }
9283
9284         return 0;
9285 }
9286
9287 static bool may_access_skb(enum bpf_prog_type type)
9288 {
9289         switch (type) {
9290         case BPF_PROG_TYPE_SOCKET_FILTER:
9291         case BPF_PROG_TYPE_SCHED_CLS:
9292         case BPF_PROG_TYPE_SCHED_ACT:
9293                 return true;
9294         default:
9295                 return false;
9296         }
9297 }
9298
9299 /* verify safety of LD_ABS|LD_IND instructions:
9300  * - they can only appear in the programs where ctx == skb
9301  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9302  *   preserve R6-R9, and store return value into R0
9303  *
9304  * Implicit input:
9305  *   ctx == skb == R6 == CTX
9306  *
9307  * Explicit input:
9308  *   SRC == any register
9309  *   IMM == 32-bit immediate
9310  *
9311  * Output:
9312  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9313  */
9314 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9315 {
9316         struct bpf_reg_state *regs = cur_regs(env);
9317         static const int ctx_reg = BPF_REG_6;
9318         u8 mode = BPF_MODE(insn->code);
9319         int i, err;
9320
9321         if (!may_access_skb(resolve_prog_type(env->prog))) {
9322                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9323                 return -EINVAL;
9324         }
9325
9326         if (!env->ops->gen_ld_abs) {
9327                 verbose(env, "bpf verifier is misconfigured\n");
9328                 return -EINVAL;
9329         }
9330
9331         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9332             BPF_SIZE(insn->code) == BPF_DW ||
9333             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9334                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9335                 return -EINVAL;
9336         }
9337
9338         /* check whether implicit source operand (register R6) is readable */
9339         err = check_reg_arg(env, ctx_reg, SRC_OP);
9340         if (err)
9341                 return err;
9342
9343         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9344          * gen_ld_abs() may terminate the program at runtime, leading to
9345          * reference leak.
9346          */
9347         err = check_reference_leak(env);
9348         if (err) {
9349                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9350                 return err;
9351         }
9352
9353         if (env->cur_state->active_spin_lock) {
9354                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9355                 return -EINVAL;
9356         }
9357
9358         if (regs[ctx_reg].type != PTR_TO_CTX) {
9359                 verbose(env,
9360                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9361                 return -EINVAL;
9362         }
9363
9364         if (mode == BPF_IND) {
9365                 /* check explicit source operand */
9366                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9367                 if (err)
9368                         return err;
9369         }
9370
9371         err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9372         if (err < 0)
9373                 return err;
9374
9375         /* reset caller saved regs to unreadable */
9376         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9377                 mark_reg_not_init(env, regs, caller_saved[i]);
9378                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9379         }
9380
9381         /* mark destination R0 register as readable, since it contains
9382          * the value fetched from the packet.
9383          * Already marked as written above.
9384          */
9385         mark_reg_unknown(env, regs, BPF_REG_0);
9386         /* ld_abs load up to 32-bit skb data. */
9387         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9388         return 0;
9389 }
9390
9391 static int check_return_code(struct bpf_verifier_env *env)
9392 {
9393         struct tnum enforce_attach_type_range = tnum_unknown;
9394         const struct bpf_prog *prog = env->prog;
9395         struct bpf_reg_state *reg;
9396         struct tnum range = tnum_range(0, 1);
9397         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9398         int err;
9399         struct bpf_func_state *frame = env->cur_state->frame[0];
9400         const bool is_subprog = frame->subprogno;
9401
9402         /* LSM and struct_ops func-ptr's return type could be "void" */
9403         if (!is_subprog &&
9404             (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9405              prog_type == BPF_PROG_TYPE_LSM) &&
9406             !prog->aux->attach_func_proto->type)
9407                 return 0;
9408
9409         /* eBPF calling convention is such that R0 is used
9410          * to return the value from eBPF program.
9411          * Make sure that it's readable at this time
9412          * of bpf_exit, which means that program wrote
9413          * something into it earlier
9414          */
9415         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9416         if (err)
9417                 return err;
9418
9419         if (is_pointer_value(env, BPF_REG_0)) {
9420                 verbose(env, "R0 leaks addr as return value\n");
9421                 return -EACCES;
9422         }
9423
9424         reg = cur_regs(env) + BPF_REG_0;
9425
9426         if (frame->in_async_callback_fn) {
9427                 /* enforce return zero from async callbacks like timer */
9428                 if (reg->type != SCALAR_VALUE) {
9429                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9430                                 reg_type_str(env, reg->type));
9431                         return -EINVAL;
9432                 }
9433
9434                 if (!tnum_in(tnum_const(0), reg->var_off)) {
9435                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9436                         return -EINVAL;
9437                 }
9438                 return 0;
9439         }
9440
9441         if (is_subprog) {
9442                 if (reg->type != SCALAR_VALUE) {
9443                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9444                                 reg_type_str(env, reg->type));
9445                         return -EINVAL;
9446                 }
9447                 return 0;
9448         }
9449
9450         switch (prog_type) {
9451         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9452                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9453                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9454                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9455                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9456                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9457                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9458                         range = tnum_range(1, 1);
9459                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9460                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9461                         range = tnum_range(0, 3);
9462                 break;
9463         case BPF_PROG_TYPE_CGROUP_SKB:
9464                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9465                         range = tnum_range(0, 3);
9466                         enforce_attach_type_range = tnum_range(2, 3);
9467                 }
9468                 break;
9469         case BPF_PROG_TYPE_CGROUP_SOCK:
9470         case BPF_PROG_TYPE_SOCK_OPS:
9471         case BPF_PROG_TYPE_CGROUP_DEVICE:
9472         case BPF_PROG_TYPE_CGROUP_SYSCTL:
9473         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9474                 break;
9475         case BPF_PROG_TYPE_RAW_TRACEPOINT:
9476                 if (!env->prog->aux->attach_btf_id)
9477                         return 0;
9478                 range = tnum_const(0);
9479                 break;
9480         case BPF_PROG_TYPE_TRACING:
9481                 switch (env->prog->expected_attach_type) {
9482                 case BPF_TRACE_FENTRY:
9483                 case BPF_TRACE_FEXIT:
9484                         range = tnum_const(0);
9485                         break;
9486                 case BPF_TRACE_RAW_TP:
9487                 case BPF_MODIFY_RETURN:
9488                         return 0;
9489                 case BPF_TRACE_ITER:
9490                         break;
9491                 default:
9492                         return -ENOTSUPP;
9493                 }
9494                 break;
9495         case BPF_PROG_TYPE_SK_LOOKUP:
9496                 range = tnum_range(SK_DROP, SK_PASS);
9497                 break;
9498         case BPF_PROG_TYPE_EXT:
9499                 /* freplace program can return anything as its return value
9500                  * depends on the to-be-replaced kernel func or bpf program.
9501                  */
9502         default:
9503                 return 0;
9504         }
9505
9506         if (reg->type != SCALAR_VALUE) {
9507                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9508                         reg_type_str(env, reg->type));
9509                 return -EINVAL;
9510         }
9511
9512         if (!tnum_in(range, reg->var_off)) {
9513                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9514                 return -EINVAL;
9515         }
9516
9517         if (!tnum_is_unknown(enforce_attach_type_range) &&
9518             tnum_in(enforce_attach_type_range, reg->var_off))
9519                 env->prog->enforce_expected_attach_type = 1;
9520         return 0;
9521 }
9522
9523 /* non-recursive DFS pseudo code
9524  * 1  procedure DFS-iterative(G,v):
9525  * 2      label v as discovered
9526  * 3      let S be a stack
9527  * 4      S.push(v)
9528  * 5      while S is not empty
9529  * 6            t <- S.pop()
9530  * 7            if t is what we're looking for:
9531  * 8                return t
9532  * 9            for all edges e in G.adjacentEdges(t) do
9533  * 10               if edge e is already labelled
9534  * 11                   continue with the next edge
9535  * 12               w <- G.adjacentVertex(t,e)
9536  * 13               if vertex w is not discovered and not explored
9537  * 14                   label e as tree-edge
9538  * 15                   label w as discovered
9539  * 16                   S.push(w)
9540  * 17                   continue at 5
9541  * 18               else if vertex w is discovered
9542  * 19                   label e as back-edge
9543  * 20               else
9544  * 21                   // vertex w is explored
9545  * 22                   label e as forward- or cross-edge
9546  * 23           label t as explored
9547  * 24           S.pop()
9548  *
9549  * convention:
9550  * 0x10 - discovered
9551  * 0x11 - discovered and fall-through edge labelled
9552  * 0x12 - discovered and fall-through and branch edges labelled
9553  * 0x20 - explored
9554  */
9555
9556 enum {
9557         DISCOVERED = 0x10,
9558         EXPLORED = 0x20,
9559         FALLTHROUGH = 1,
9560         BRANCH = 2,
9561 };
9562
9563 static u32 state_htab_size(struct bpf_verifier_env *env)
9564 {
9565         return env->prog->len;
9566 }
9567
9568 static struct bpf_verifier_state_list **explored_state(
9569                                         struct bpf_verifier_env *env,
9570                                         int idx)
9571 {
9572         struct bpf_verifier_state *cur = env->cur_state;
9573         struct bpf_func_state *state = cur->frame[cur->curframe];
9574
9575         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9576 }
9577
9578 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9579 {
9580         env->insn_aux_data[idx].prune_point = true;
9581 }
9582
9583 enum {
9584         DONE_EXPLORING = 0,
9585         KEEP_EXPLORING = 1,
9586 };
9587
9588 /* t, w, e - match pseudo-code above:
9589  * t - index of current instruction
9590  * w - next instruction
9591  * e - edge
9592  */
9593 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9594                      bool loop_ok)
9595 {
9596         int *insn_stack = env->cfg.insn_stack;
9597         int *insn_state = env->cfg.insn_state;
9598
9599         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9600                 return DONE_EXPLORING;
9601
9602         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9603                 return DONE_EXPLORING;
9604
9605         if (w < 0 || w >= env->prog->len) {
9606                 verbose_linfo(env, t, "%d: ", t);
9607                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
9608                 return -EINVAL;
9609         }
9610
9611         if (e == BRANCH)
9612                 /* mark branch target for state pruning */
9613                 init_explored_state(env, w);
9614
9615         if (insn_state[w] == 0) {
9616                 /* tree-edge */
9617                 insn_state[t] = DISCOVERED | e;
9618                 insn_state[w] = DISCOVERED;
9619                 if (env->cfg.cur_stack >= env->prog->len)
9620                         return -E2BIG;
9621                 insn_stack[env->cfg.cur_stack++] = w;
9622                 return KEEP_EXPLORING;
9623         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9624                 if (loop_ok && env->bpf_capable)
9625                         return DONE_EXPLORING;
9626                 verbose_linfo(env, t, "%d: ", t);
9627                 verbose_linfo(env, w, "%d: ", w);
9628                 verbose(env, "back-edge from insn %d to %d\n", t, w);
9629                 return -EINVAL;
9630         } else if (insn_state[w] == EXPLORED) {
9631                 /* forward- or cross-edge */
9632                 insn_state[t] = DISCOVERED | e;
9633         } else {
9634                 verbose(env, "insn state internal bug\n");
9635                 return -EFAULT;
9636         }
9637         return DONE_EXPLORING;
9638 }
9639
9640 static int visit_func_call_insn(int t, int insn_cnt,
9641                                 struct bpf_insn *insns,
9642                                 struct bpf_verifier_env *env,
9643                                 bool visit_callee)
9644 {
9645         int ret;
9646
9647         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9648         if (ret)
9649                 return ret;
9650
9651         if (t + 1 < insn_cnt)
9652                 init_explored_state(env, t + 1);
9653         if (visit_callee) {
9654                 init_explored_state(env, t);
9655                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9656                                 /* It's ok to allow recursion from CFG point of
9657                                  * view. __check_func_call() will do the actual
9658                                  * check.
9659                                  */
9660                                 bpf_pseudo_func(insns + t));
9661         }
9662         return ret;
9663 }
9664
9665 /* Visits the instruction at index t and returns one of the following:
9666  *  < 0 - an error occurred
9667  *  DONE_EXPLORING - the instruction was fully explored
9668  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9669  */
9670 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9671 {
9672         struct bpf_insn *insns = env->prog->insnsi;
9673         int ret;
9674
9675         if (bpf_pseudo_func(insns + t))
9676                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9677
9678         /* All non-branch instructions have a single fall-through edge. */
9679         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9680             BPF_CLASS(insns[t].code) != BPF_JMP32)
9681                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9682
9683         switch (BPF_OP(insns[t].code)) {
9684         case BPF_EXIT:
9685                 return DONE_EXPLORING;
9686
9687         case BPF_CALL:
9688                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
9689                         /* Mark this call insn to trigger is_state_visited() check
9690                          * before call itself is processed by __check_func_call().
9691                          * Otherwise new async state will be pushed for further
9692                          * exploration.
9693                          */
9694                         init_explored_state(env, t);
9695                 return visit_func_call_insn(t, insn_cnt, insns, env,
9696                                             insns[t].src_reg == BPF_PSEUDO_CALL);
9697
9698         case BPF_JA:
9699                 if (BPF_SRC(insns[t].code) != BPF_K)
9700                         return -EINVAL;
9701
9702                 /* unconditional jump with single edge */
9703                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9704                                 true);
9705                 if (ret)
9706                         return ret;
9707
9708                 /* unconditional jmp is not a good pruning point,
9709                  * but it's marked, since backtracking needs
9710                  * to record jmp history in is_state_visited().
9711                  */
9712                 init_explored_state(env, t + insns[t].off + 1);
9713                 /* tell verifier to check for equivalent states
9714                  * after every call and jump
9715                  */
9716                 if (t + 1 < insn_cnt)
9717                         init_explored_state(env, t + 1);
9718
9719                 return ret;
9720
9721         default:
9722                 /* conditional jump with two edges */
9723                 init_explored_state(env, t);
9724                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9725                 if (ret)
9726                         return ret;
9727
9728                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9729         }
9730 }
9731
9732 /* non-recursive depth-first-search to detect loops in BPF program
9733  * loop == back-edge in directed graph
9734  */
9735 static int check_cfg(struct bpf_verifier_env *env)
9736 {
9737         int insn_cnt = env->prog->len;
9738         int *insn_stack, *insn_state;
9739         int ret = 0;
9740         int i;
9741
9742         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9743         if (!insn_state)
9744                 return -ENOMEM;
9745
9746         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9747         if (!insn_stack) {
9748                 kvfree(insn_state);
9749                 return -ENOMEM;
9750         }
9751
9752         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9753         insn_stack[0] = 0; /* 0 is the first instruction */
9754         env->cfg.cur_stack = 1;
9755
9756         while (env->cfg.cur_stack > 0) {
9757                 int t = insn_stack[env->cfg.cur_stack - 1];
9758
9759                 ret = visit_insn(t, insn_cnt, env);
9760                 switch (ret) {
9761                 case DONE_EXPLORING:
9762                         insn_state[t] = EXPLORED;
9763                         env->cfg.cur_stack--;
9764                         break;
9765                 case KEEP_EXPLORING:
9766                         break;
9767                 default:
9768                         if (ret > 0) {
9769                                 verbose(env, "visit_insn internal bug\n");
9770                                 ret = -EFAULT;
9771                         }
9772                         goto err_free;
9773                 }
9774         }
9775
9776         if (env->cfg.cur_stack < 0) {
9777                 verbose(env, "pop stack internal bug\n");
9778                 ret = -EFAULT;
9779                 goto err_free;
9780         }
9781
9782         for (i = 0; i < insn_cnt; i++) {
9783                 if (insn_state[i] != EXPLORED) {
9784                         verbose(env, "unreachable insn %d\n", i);
9785                         ret = -EINVAL;
9786                         goto err_free;
9787                 }
9788         }
9789         ret = 0; /* cfg looks good */
9790
9791 err_free:
9792         kvfree(insn_state);
9793         kvfree(insn_stack);
9794         env->cfg.insn_state = env->cfg.insn_stack = NULL;
9795         return ret;
9796 }
9797
9798 static int check_abnormal_return(struct bpf_verifier_env *env)
9799 {
9800         int i;
9801
9802         for (i = 1; i < env->subprog_cnt; i++) {
9803                 if (env->subprog_info[i].has_ld_abs) {
9804                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9805                         return -EINVAL;
9806                 }
9807                 if (env->subprog_info[i].has_tail_call) {
9808                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9809                         return -EINVAL;
9810                 }
9811         }
9812         return 0;
9813 }
9814
9815 /* The minimum supported BTF func info size */
9816 #define MIN_BPF_FUNCINFO_SIZE   8
9817 #define MAX_FUNCINFO_REC_SIZE   252
9818
9819 static int check_btf_func(struct bpf_verifier_env *env,
9820                           const union bpf_attr *attr,
9821                           bpfptr_t uattr)
9822 {
9823         const struct btf_type *type, *func_proto, *ret_type;
9824         u32 i, nfuncs, urec_size, min_size;
9825         u32 krec_size = sizeof(struct bpf_func_info);
9826         struct bpf_func_info *krecord;
9827         struct bpf_func_info_aux *info_aux = NULL;
9828         struct bpf_prog *prog;
9829         const struct btf *btf;
9830         bpfptr_t urecord;
9831         u32 prev_offset = 0;
9832         bool scalar_return;
9833         int ret = -ENOMEM;
9834
9835         nfuncs = attr->func_info_cnt;
9836         if (!nfuncs) {
9837                 if (check_abnormal_return(env))
9838                         return -EINVAL;
9839                 return 0;
9840         }
9841
9842         if (nfuncs != env->subprog_cnt) {
9843                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9844                 return -EINVAL;
9845         }
9846
9847         urec_size = attr->func_info_rec_size;
9848         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9849             urec_size > MAX_FUNCINFO_REC_SIZE ||
9850             urec_size % sizeof(u32)) {
9851                 verbose(env, "invalid func info rec size %u\n", urec_size);
9852                 return -EINVAL;
9853         }
9854
9855         prog = env->prog;
9856         btf = prog->aux->btf;
9857
9858         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
9859         min_size = min_t(u32, krec_size, urec_size);
9860
9861         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9862         if (!krecord)
9863                 return -ENOMEM;
9864         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9865         if (!info_aux)
9866                 goto err_free;
9867
9868         for (i = 0; i < nfuncs; i++) {
9869                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9870                 if (ret) {
9871                         if (ret == -E2BIG) {
9872                                 verbose(env, "nonzero tailing record in func info");
9873                                 /* set the size kernel expects so loader can zero
9874                                  * out the rest of the record.
9875                                  */
9876                                 if (copy_to_bpfptr_offset(uattr,
9877                                                           offsetof(union bpf_attr, func_info_rec_size),
9878                                                           &min_size, sizeof(min_size)))
9879                                         ret = -EFAULT;
9880                         }
9881                         goto err_free;
9882                 }
9883
9884                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
9885                         ret = -EFAULT;
9886                         goto err_free;
9887                 }
9888
9889                 /* check insn_off */
9890                 ret = -EINVAL;
9891                 if (i == 0) {
9892                         if (krecord[i].insn_off) {
9893                                 verbose(env,
9894                                         "nonzero insn_off %u for the first func info record",
9895                                         krecord[i].insn_off);
9896                                 goto err_free;
9897                         }
9898                 } else if (krecord[i].insn_off <= prev_offset) {
9899                         verbose(env,
9900                                 "same or smaller insn offset (%u) than previous func info record (%u)",
9901                                 krecord[i].insn_off, prev_offset);
9902                         goto err_free;
9903                 }
9904
9905                 if (env->subprog_info[i].start != krecord[i].insn_off) {
9906                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9907                         goto err_free;
9908                 }
9909
9910                 /* check type_id */
9911                 type = btf_type_by_id(btf, krecord[i].type_id);
9912                 if (!type || !btf_type_is_func(type)) {
9913                         verbose(env, "invalid type id %d in func info",
9914                                 krecord[i].type_id);
9915                         goto err_free;
9916                 }
9917                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9918
9919                 func_proto = btf_type_by_id(btf, type->type);
9920                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9921                         /* btf_func_check() already verified it during BTF load */
9922                         goto err_free;
9923                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9924                 scalar_return =
9925                         btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9926                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9927                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9928                         goto err_free;
9929                 }
9930                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9931                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9932                         goto err_free;
9933                 }
9934
9935                 prev_offset = krecord[i].insn_off;
9936                 bpfptr_add(&urecord, urec_size);
9937         }
9938
9939         prog->aux->func_info = krecord;
9940         prog->aux->func_info_cnt = nfuncs;
9941         prog->aux->func_info_aux = info_aux;
9942         return 0;
9943
9944 err_free:
9945         kvfree(krecord);
9946         kfree(info_aux);
9947         return ret;
9948 }
9949
9950 static void adjust_btf_func(struct bpf_verifier_env *env)
9951 {
9952         struct bpf_prog_aux *aux = env->prog->aux;
9953         int i;
9954
9955         if (!aux->func_info)
9956                 return;
9957
9958         for (i = 0; i < env->subprog_cnt; i++)
9959                 aux->func_info[i].insn_off = env->subprog_info[i].start;
9960 }
9961
9962 #define MIN_BPF_LINEINFO_SIZE   (offsetof(struct bpf_line_info, line_col) + \
9963                 sizeof(((struct bpf_line_info *)(0))->line_col))
9964 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
9965
9966 static int check_btf_line(struct bpf_verifier_env *env,
9967                           const union bpf_attr *attr,
9968                           bpfptr_t uattr)
9969 {
9970         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9971         struct bpf_subprog_info *sub;
9972         struct bpf_line_info *linfo;
9973         struct bpf_prog *prog;
9974         const struct btf *btf;
9975         bpfptr_t ulinfo;
9976         int err;
9977
9978         nr_linfo = attr->line_info_cnt;
9979         if (!nr_linfo)
9980                 return 0;
9981         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
9982                 return -EINVAL;
9983
9984         rec_size = attr->line_info_rec_size;
9985         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9986             rec_size > MAX_LINEINFO_REC_SIZE ||
9987             rec_size & (sizeof(u32) - 1))
9988                 return -EINVAL;
9989
9990         /* Need to zero it in case the userspace may
9991          * pass in a smaller bpf_line_info object.
9992          */
9993         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9994                          GFP_KERNEL | __GFP_NOWARN);
9995         if (!linfo)
9996                 return -ENOMEM;
9997
9998         prog = env->prog;
9999         btf = prog->aux->btf;
10000
10001         s = 0;
10002         sub = env->subprog_info;
10003         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
10004         expected_size = sizeof(struct bpf_line_info);
10005         ncopy = min_t(u32, expected_size, rec_size);
10006         for (i = 0; i < nr_linfo; i++) {
10007                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10008                 if (err) {
10009                         if (err == -E2BIG) {
10010                                 verbose(env, "nonzero tailing record in line_info");
10011                                 if (copy_to_bpfptr_offset(uattr,
10012                                                           offsetof(union bpf_attr, line_info_rec_size),
10013                                                           &expected_size, sizeof(expected_size)))
10014                                         err = -EFAULT;
10015                         }
10016                         goto err_free;
10017                 }
10018
10019                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
10020                         err = -EFAULT;
10021                         goto err_free;
10022                 }
10023
10024                 /*
10025                  * Check insn_off to ensure
10026                  * 1) strictly increasing AND
10027                  * 2) bounded by prog->len
10028                  *
10029                  * The linfo[0].insn_off == 0 check logically falls into
10030                  * the later "missing bpf_line_info for func..." case
10031                  * because the first linfo[0].insn_off must be the
10032                  * first sub also and the first sub must have
10033                  * subprog_info[0].start == 0.
10034                  */
10035                 if ((i && linfo[i].insn_off <= prev_offset) ||
10036                     linfo[i].insn_off >= prog->len) {
10037                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10038                                 i, linfo[i].insn_off, prev_offset,
10039                                 prog->len);
10040                         err = -EINVAL;
10041                         goto err_free;
10042                 }
10043
10044                 if (!prog->insnsi[linfo[i].insn_off].code) {
10045                         verbose(env,
10046                                 "Invalid insn code at line_info[%u].insn_off\n",
10047                                 i);
10048                         err = -EINVAL;
10049                         goto err_free;
10050                 }
10051
10052                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10053                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10054                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10055                         err = -EINVAL;
10056                         goto err_free;
10057                 }
10058
10059                 if (s != env->subprog_cnt) {
10060                         if (linfo[i].insn_off == sub[s].start) {
10061                                 sub[s].linfo_idx = i;
10062                                 s++;
10063                         } else if (sub[s].start < linfo[i].insn_off) {
10064                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
10065                                 err = -EINVAL;
10066                                 goto err_free;
10067                         }
10068                 }
10069
10070                 prev_offset = linfo[i].insn_off;
10071                 bpfptr_add(&ulinfo, rec_size);
10072         }
10073
10074         if (s != env->subprog_cnt) {
10075                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10076                         env->subprog_cnt - s, s);
10077                 err = -EINVAL;
10078                 goto err_free;
10079         }
10080
10081         prog->aux->linfo = linfo;
10082         prog->aux->nr_linfo = nr_linfo;
10083
10084         return 0;
10085
10086 err_free:
10087         kvfree(linfo);
10088         return err;
10089 }
10090
10091 static int check_btf_info(struct bpf_verifier_env *env,
10092                           const union bpf_attr *attr,
10093                           bpfptr_t uattr)
10094 {
10095         struct btf *btf;
10096         int err;
10097
10098         if (!attr->func_info_cnt && !attr->line_info_cnt) {
10099                 if (check_abnormal_return(env))
10100                         return -EINVAL;
10101                 return 0;
10102         }
10103
10104         btf = btf_get_by_fd(attr->prog_btf_fd);
10105         if (IS_ERR(btf))
10106                 return PTR_ERR(btf);
10107         if (btf_is_kernel(btf)) {
10108                 btf_put(btf);
10109                 return -EACCES;
10110         }
10111         env->prog->aux->btf = btf;
10112
10113         err = check_btf_func(env, attr, uattr);
10114         if (err)
10115                 return err;
10116
10117         err = check_btf_line(env, attr, uattr);
10118         if (err)
10119                 return err;
10120
10121         return 0;
10122 }
10123
10124 /* check %cur's range satisfies %old's */
10125 static bool range_within(struct bpf_reg_state *old,
10126                          struct bpf_reg_state *cur)
10127 {
10128         return old->umin_value <= cur->umin_value &&
10129                old->umax_value >= cur->umax_value &&
10130                old->smin_value <= cur->smin_value &&
10131                old->smax_value >= cur->smax_value &&
10132                old->u32_min_value <= cur->u32_min_value &&
10133                old->u32_max_value >= cur->u32_max_value &&
10134                old->s32_min_value <= cur->s32_min_value &&
10135                old->s32_max_value >= cur->s32_max_value;
10136 }
10137
10138 /* If in the old state two registers had the same id, then they need to have
10139  * the same id in the new state as well.  But that id could be different from
10140  * the old state, so we need to track the mapping from old to new ids.
10141  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10142  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10143  * regs with a different old id could still have new id 9, we don't care about
10144  * that.
10145  * So we look through our idmap to see if this old id has been seen before.  If
10146  * so, we require the new id to match; otherwise, we add the id pair to the map.
10147  */
10148 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10149 {
10150         unsigned int i;
10151
10152         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10153                 if (!idmap[i].old) {
10154                         /* Reached an empty slot; haven't seen this id before */
10155                         idmap[i].old = old_id;
10156                         idmap[i].cur = cur_id;
10157                         return true;
10158                 }
10159                 if (idmap[i].old == old_id)
10160                         return idmap[i].cur == cur_id;
10161         }
10162         /* We ran out of idmap slots, which should be impossible */
10163         WARN_ON_ONCE(1);
10164         return false;
10165 }
10166
10167 static void clean_func_state(struct bpf_verifier_env *env,
10168                              struct bpf_func_state *st)
10169 {
10170         enum bpf_reg_liveness live;
10171         int i, j;
10172
10173         for (i = 0; i < BPF_REG_FP; i++) {
10174                 live = st->regs[i].live;
10175                 /* liveness must not touch this register anymore */
10176                 st->regs[i].live |= REG_LIVE_DONE;
10177                 if (!(live & REG_LIVE_READ))
10178                         /* since the register is unused, clear its state
10179                          * to make further comparison simpler
10180                          */
10181                         __mark_reg_not_init(env, &st->regs[i]);
10182         }
10183
10184         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10185                 live = st->stack[i].spilled_ptr.live;
10186                 /* liveness must not touch this stack slot anymore */
10187                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10188                 if (!(live & REG_LIVE_READ)) {
10189                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10190                         for (j = 0; j < BPF_REG_SIZE; j++)
10191                                 st->stack[i].slot_type[j] = STACK_INVALID;
10192                 }
10193         }
10194 }
10195
10196 static void clean_verifier_state(struct bpf_verifier_env *env,
10197                                  struct bpf_verifier_state *st)
10198 {
10199         int i;
10200
10201         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10202                 /* all regs in this state in all frames were already marked */
10203                 return;
10204
10205         for (i = 0; i <= st->curframe; i++)
10206                 clean_func_state(env, st->frame[i]);
10207 }
10208
10209 /* the parentage chains form a tree.
10210  * the verifier states are added to state lists at given insn and
10211  * pushed into state stack for future exploration.
10212  * when the verifier reaches bpf_exit insn some of the verifer states
10213  * stored in the state lists have their final liveness state already,
10214  * but a lot of states will get revised from liveness point of view when
10215  * the verifier explores other branches.
10216  * Example:
10217  * 1: r0 = 1
10218  * 2: if r1 == 100 goto pc+1
10219  * 3: r0 = 2
10220  * 4: exit
10221  * when the verifier reaches exit insn the register r0 in the state list of
10222  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10223  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10224  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10225  *
10226  * Since the verifier pushes the branch states as it sees them while exploring
10227  * the program the condition of walking the branch instruction for the second
10228  * time means that all states below this branch were already explored and
10229  * their final liveness marks are already propagated.
10230  * Hence when the verifier completes the search of state list in is_state_visited()
10231  * we can call this clean_live_states() function to mark all liveness states
10232  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10233  * will not be used.
10234  * This function also clears the registers and stack for states that !READ
10235  * to simplify state merging.
10236  *
10237  * Important note here that walking the same branch instruction in the callee
10238  * doesn't meant that the states are DONE. The verifier has to compare
10239  * the callsites
10240  */
10241 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10242                               struct bpf_verifier_state *cur)
10243 {
10244         struct bpf_verifier_state_list *sl;
10245         int i;
10246
10247         sl = *explored_state(env, insn);
10248         while (sl) {
10249                 if (sl->state.branches)
10250                         goto next;
10251                 if (sl->state.insn_idx != insn ||
10252                     sl->state.curframe != cur->curframe)
10253                         goto next;
10254                 for (i = 0; i <= cur->curframe; i++)
10255                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10256                                 goto next;
10257                 clean_verifier_state(env, &sl->state);
10258 next:
10259                 sl = sl->next;
10260         }
10261 }
10262
10263 /* Returns true if (rold safe implies rcur safe) */
10264 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10265                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10266 {
10267         bool equal;
10268
10269         if (!(rold->live & REG_LIVE_READ))
10270                 /* explored state didn't use this */
10271                 return true;
10272
10273         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10274
10275         if (rold->type == PTR_TO_STACK)
10276                 /* two stack pointers are equal only if they're pointing to
10277                  * the same stack frame, since fp-8 in foo != fp-8 in bar
10278                  */
10279                 return equal && rold->frameno == rcur->frameno;
10280
10281         if (equal)
10282                 return true;
10283
10284         if (rold->type == NOT_INIT)
10285                 /* explored state can't have used this */
10286                 return true;
10287         if (rcur->type == NOT_INIT)
10288                 return false;
10289         switch (base_type(rold->type)) {
10290         case SCALAR_VALUE:
10291                 if (env->explore_alu_limits)
10292                         return false;
10293                 if (rcur->type == SCALAR_VALUE) {
10294                         if (!rold->precise && !rcur->precise)
10295                                 return true;
10296                         /* new val must satisfy old val knowledge */
10297                         return range_within(rold, rcur) &&
10298                                tnum_in(rold->var_off, rcur->var_off);
10299                 } else {
10300                         /* We're trying to use a pointer in place of a scalar.
10301                          * Even if the scalar was unbounded, this could lead to
10302                          * pointer leaks because scalars are allowed to leak
10303                          * while pointers are not. We could make this safe in
10304                          * special cases if root is calling us, but it's
10305                          * probably not worth the hassle.
10306                          */
10307                         return false;
10308                 }
10309         case PTR_TO_MAP_KEY:
10310         case PTR_TO_MAP_VALUE:
10311                 /* a PTR_TO_MAP_VALUE could be safe to use as a
10312                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10313                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10314                  * checked, doing so could have affected others with the same
10315                  * id, and we can't check for that because we lost the id when
10316                  * we converted to a PTR_TO_MAP_VALUE.
10317                  */
10318                 if (type_may_be_null(rold->type)) {
10319                         if (!type_may_be_null(rcur->type))
10320                                 return false;
10321                         if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10322                                 return false;
10323                         /* Check our ids match any regs they're supposed to */
10324                         return check_ids(rold->id, rcur->id, idmap);
10325                 }
10326
10327                 /* If the new min/max/var_off satisfy the old ones and
10328                  * everything else matches, we are OK.
10329                  * 'id' is not compared, since it's only used for maps with
10330                  * bpf_spin_lock inside map element and in such cases if
10331                  * the rest of the prog is valid for one map element then
10332                  * it's valid for all map elements regardless of the key
10333                  * used in bpf_map_lookup()
10334                  */
10335                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10336                        range_within(rold, rcur) &&
10337                        tnum_in(rold->var_off, rcur->var_off);
10338         case PTR_TO_PACKET_META:
10339         case PTR_TO_PACKET:
10340                 if (rcur->type != rold->type)
10341                         return false;
10342                 /* We must have at least as much range as the old ptr
10343                  * did, so that any accesses which were safe before are
10344                  * still safe.  This is true even if old range < old off,
10345                  * since someone could have accessed through (ptr - k), or
10346                  * even done ptr -= k in a register, to get a safe access.
10347                  */
10348                 if (rold->range > rcur->range)
10349                         return false;
10350                 /* If the offsets don't match, we can't trust our alignment;
10351                  * nor can we be sure that we won't fall out of range.
10352                  */
10353                 if (rold->off != rcur->off)
10354                         return false;
10355                 /* id relations must be preserved */
10356                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10357                         return false;
10358                 /* new val must satisfy old val knowledge */
10359                 return range_within(rold, rcur) &&
10360                        tnum_in(rold->var_off, rcur->var_off);
10361         case PTR_TO_CTX:
10362         case CONST_PTR_TO_MAP:
10363         case PTR_TO_PACKET_END:
10364         case PTR_TO_FLOW_KEYS:
10365         case PTR_TO_SOCKET:
10366         case PTR_TO_SOCK_COMMON:
10367         case PTR_TO_TCP_SOCK:
10368         case PTR_TO_XDP_SOCK:
10369                 /* Only valid matches are exact, which memcmp() above
10370                  * would have accepted
10371                  */
10372         default:
10373                 /* Don't know what's going on, just say it's not safe */
10374                 return false;
10375         }
10376
10377         /* Shouldn't get here; if we do, say it's not safe */
10378         WARN_ON_ONCE(1);
10379         return false;
10380 }
10381
10382 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10383                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10384 {
10385         int i, spi;
10386
10387         /* walk slots of the explored stack and ignore any additional
10388          * slots in the current stack, since explored(safe) state
10389          * didn't use them
10390          */
10391         for (i = 0; i < old->allocated_stack; i++) {
10392                 spi = i / BPF_REG_SIZE;
10393
10394                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10395                         i += BPF_REG_SIZE - 1;
10396                         /* explored state didn't use this */
10397                         continue;
10398                 }
10399
10400                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10401                         continue;
10402
10403                 /* explored stack has more populated slots than current stack
10404                  * and these slots were used
10405                  */
10406                 if (i >= cur->allocated_stack)
10407                         return false;
10408
10409                 /* if old state was safe with misc data in the stack
10410                  * it will be safe with zero-initialized stack.
10411                  * The opposite is not true
10412                  */
10413                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10414                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10415                         continue;
10416                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10417                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10418                         /* Ex: old explored (safe) state has STACK_SPILL in
10419                          * this stack slot, but current has STACK_MISC ->
10420                          * this verifier states are not equivalent,
10421                          * return false to continue verification of this path
10422                          */
10423                         return false;
10424                 if (i % BPF_REG_SIZE)
10425                         continue;
10426                 if (old->stack[spi].slot_type[0] != STACK_SPILL)
10427                         continue;
10428                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
10429                              &cur->stack[spi].spilled_ptr, idmap))
10430                         /* when explored and current stack slot are both storing
10431                          * spilled registers, check that stored pointers types
10432                          * are the same as well.
10433                          * Ex: explored safe path could have stored
10434                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10435                          * but current path has stored:
10436                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10437                          * such verifier states are not equivalent.
10438                          * return false to continue verification of this path
10439                          */
10440                         return false;
10441         }
10442         return true;
10443 }
10444
10445 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10446 {
10447         if (old->acquired_refs != cur->acquired_refs)
10448                 return false;
10449         return !memcmp(old->refs, cur->refs,
10450                        sizeof(*old->refs) * old->acquired_refs);
10451 }
10452
10453 /* compare two verifier states
10454  *
10455  * all states stored in state_list are known to be valid, since
10456  * verifier reached 'bpf_exit' instruction through them
10457  *
10458  * this function is called when verifier exploring different branches of
10459  * execution popped from the state stack. If it sees an old state that has
10460  * more strict register state and more strict stack state then this execution
10461  * branch doesn't need to be explored further, since verifier already
10462  * concluded that more strict state leads to valid finish.
10463  *
10464  * Therefore two states are equivalent if register state is more conservative
10465  * and explored stack state is more conservative than the current one.
10466  * Example:
10467  *       explored                   current
10468  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10469  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10470  *
10471  * In other words if current stack state (one being explored) has more
10472  * valid slots than old one that already passed validation, it means
10473  * the verifier can stop exploring and conclude that current state is valid too
10474  *
10475  * Similarly with registers. If explored state has register type as invalid
10476  * whereas register type in current state is meaningful, it means that
10477  * the current state will reach 'bpf_exit' instruction safely
10478  */
10479 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10480                               struct bpf_func_state *cur)
10481 {
10482         int i;
10483
10484         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10485         for (i = 0; i < MAX_BPF_REG; i++)
10486                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
10487                              env->idmap_scratch))
10488                         return false;
10489
10490         if (!stacksafe(env, old, cur, env->idmap_scratch))
10491                 return false;
10492
10493         if (!refsafe(old, cur))
10494                 return false;
10495
10496         return true;
10497 }
10498
10499 static bool states_equal(struct bpf_verifier_env *env,
10500                          struct bpf_verifier_state *old,
10501                          struct bpf_verifier_state *cur)
10502 {
10503         int i;
10504
10505         if (old->curframe != cur->curframe)
10506                 return false;
10507
10508         /* Verification state from speculative execution simulation
10509          * must never prune a non-speculative execution one.
10510          */
10511         if (old->speculative && !cur->speculative)
10512                 return false;
10513
10514         if (old->active_spin_lock != cur->active_spin_lock)
10515                 return false;
10516
10517         /* for states to be equal callsites have to be the same
10518          * and all frame states need to be equivalent
10519          */
10520         for (i = 0; i <= old->curframe; i++) {
10521                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10522                         return false;
10523                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10524                         return false;
10525         }
10526         return true;
10527 }
10528
10529 /* Return 0 if no propagation happened. Return negative error code if error
10530  * happened. Otherwise, return the propagated bit.
10531  */
10532 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10533                                   struct bpf_reg_state *reg,
10534                                   struct bpf_reg_state *parent_reg)
10535 {
10536         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10537         u8 flag = reg->live & REG_LIVE_READ;
10538         int err;
10539
10540         /* When comes here, read flags of PARENT_REG or REG could be any of
10541          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10542          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10543          */
10544         if (parent_flag == REG_LIVE_READ64 ||
10545             /* Or if there is no read flag from REG. */
10546             !flag ||
10547             /* Or if the read flag from REG is the same as PARENT_REG. */
10548             parent_flag == flag)
10549                 return 0;
10550
10551         err = mark_reg_read(env, reg, parent_reg, flag);
10552         if (err)
10553                 return err;
10554
10555         return flag;
10556 }
10557
10558 /* A write screens off any subsequent reads; but write marks come from the
10559  * straight-line code between a state and its parent.  When we arrive at an
10560  * equivalent state (jump target or such) we didn't arrive by the straight-line
10561  * code, so read marks in the state must propagate to the parent regardless
10562  * of the state's write marks. That's what 'parent == state->parent' comparison
10563  * in mark_reg_read() is for.
10564  */
10565 static int propagate_liveness(struct bpf_verifier_env *env,
10566                               const struct bpf_verifier_state *vstate,
10567                               struct bpf_verifier_state *vparent)
10568 {
10569         struct bpf_reg_state *state_reg, *parent_reg;
10570         struct bpf_func_state *state, *parent;
10571         int i, frame, err = 0;
10572
10573         if (vparent->curframe != vstate->curframe) {
10574                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10575                      vparent->curframe, vstate->curframe);
10576                 return -EFAULT;
10577         }
10578         /* Propagate read liveness of registers... */
10579         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10580         for (frame = 0; frame <= vstate->curframe; frame++) {
10581                 parent = vparent->frame[frame];
10582                 state = vstate->frame[frame];
10583                 parent_reg = parent->regs;
10584                 state_reg = state->regs;
10585                 /* We don't need to worry about FP liveness, it's read-only */
10586                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10587                         err = propagate_liveness_reg(env, &state_reg[i],
10588                                                      &parent_reg[i]);
10589                         if (err < 0)
10590                                 return err;
10591                         if (err == REG_LIVE_READ64)
10592                                 mark_insn_zext(env, &parent_reg[i]);
10593                 }
10594
10595                 /* Propagate stack slots. */
10596                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10597                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10598                         parent_reg = &parent->stack[i].spilled_ptr;
10599                         state_reg = &state->stack[i].spilled_ptr;
10600                         err = propagate_liveness_reg(env, state_reg,
10601                                                      parent_reg);
10602                         if (err < 0)
10603                                 return err;
10604                 }
10605         }
10606         return 0;
10607 }
10608
10609 /* find precise scalars in the previous equivalent state and
10610  * propagate them into the current state
10611  */
10612 static int propagate_precision(struct bpf_verifier_env *env,
10613                                const struct bpf_verifier_state *old)
10614 {
10615         struct bpf_reg_state *state_reg;
10616         struct bpf_func_state *state;
10617         int i, err = 0;
10618
10619         state = old->frame[old->curframe];
10620         state_reg = state->regs;
10621         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10622                 if (state_reg->type != SCALAR_VALUE ||
10623                     !state_reg->precise)
10624                         continue;
10625                 if (env->log.level & BPF_LOG_LEVEL2)
10626                         verbose(env, "propagating r%d\n", i);
10627                 err = mark_chain_precision(env, i);
10628                 if (err < 0)
10629                         return err;
10630         }
10631
10632         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10633                 if (state->stack[i].slot_type[0] != STACK_SPILL)
10634                         continue;
10635                 state_reg = &state->stack[i].spilled_ptr;
10636                 if (state_reg->type != SCALAR_VALUE ||
10637                     !state_reg->precise)
10638                         continue;
10639                 if (env->log.level & BPF_LOG_LEVEL2)
10640                         verbose(env, "propagating fp%d\n",
10641                                 (-i - 1) * BPF_REG_SIZE);
10642                 err = mark_chain_precision_stack(env, i);
10643                 if (err < 0)
10644                         return err;
10645         }
10646         return 0;
10647 }
10648
10649 static bool states_maybe_looping(struct bpf_verifier_state *old,
10650                                  struct bpf_verifier_state *cur)
10651 {
10652         struct bpf_func_state *fold, *fcur;
10653         int i, fr = cur->curframe;
10654
10655         if (old->curframe != fr)
10656                 return false;
10657
10658         fold = old->frame[fr];
10659         fcur = cur->frame[fr];
10660         for (i = 0; i < MAX_BPF_REG; i++)
10661                 if (memcmp(&fold->regs[i], &fcur->regs[i],
10662                            offsetof(struct bpf_reg_state, parent)))
10663                         return false;
10664         return true;
10665 }
10666
10667
10668 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10669 {
10670         struct bpf_verifier_state_list *new_sl;
10671         struct bpf_verifier_state_list *sl, **pprev;
10672         struct bpf_verifier_state *cur = env->cur_state, *new;
10673         int i, j, err, states_cnt = 0;
10674         bool add_new_state = env->test_state_freq ? true : false;
10675
10676         cur->last_insn_idx = env->prev_insn_idx;
10677         if (!env->insn_aux_data[insn_idx].prune_point)
10678                 /* this 'insn_idx' instruction wasn't marked, so we will not
10679                  * be doing state search here
10680                  */
10681                 return 0;
10682
10683         /* bpf progs typically have pruning point every 4 instructions
10684          * http://vger.kernel.org/bpfconf2019.html#session-1
10685          * Do not add new state for future pruning if the verifier hasn't seen
10686          * at least 2 jumps and at least 8 instructions.
10687          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10688          * In tests that amounts to up to 50% reduction into total verifier
10689          * memory consumption and 20% verifier time speedup.
10690          */
10691         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10692             env->insn_processed - env->prev_insn_processed >= 8)
10693                 add_new_state = true;
10694
10695         pprev = explored_state(env, insn_idx);
10696         sl = *pprev;
10697
10698         clean_live_states(env, insn_idx, cur);
10699
10700         while (sl) {
10701                 states_cnt++;
10702                 if (sl->state.insn_idx != insn_idx)
10703                         goto next;
10704
10705                 if (sl->state.branches) {
10706                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
10707
10708                         if (frame->in_async_callback_fn &&
10709                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
10710                                 /* Different async_entry_cnt means that the verifier is
10711                                  * processing another entry into async callback.
10712                                  * Seeing the same state is not an indication of infinite
10713                                  * loop or infinite recursion.
10714                                  * But finding the same state doesn't mean that it's safe
10715                                  * to stop processing the current state. The previous state
10716                                  * hasn't yet reached bpf_exit, since state.branches > 0.
10717                                  * Checking in_async_callback_fn alone is not enough either.
10718                                  * Since the verifier still needs to catch infinite loops
10719                                  * inside async callbacks.
10720                                  */
10721                         } else if (states_maybe_looping(&sl->state, cur) &&
10722                                    states_equal(env, &sl->state, cur)) {
10723                                 verbose_linfo(env, insn_idx, "; ");
10724                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10725                                 return -EINVAL;
10726                         }
10727                         /* if the verifier is processing a loop, avoid adding new state
10728                          * too often, since different loop iterations have distinct
10729                          * states and may not help future pruning.
10730                          * This threshold shouldn't be too low to make sure that
10731                          * a loop with large bound will be rejected quickly.
10732                          * The most abusive loop will be:
10733                          * r1 += 1
10734                          * if r1 < 1000000 goto pc-2
10735                          * 1M insn_procssed limit / 100 == 10k peak states.
10736                          * This threshold shouldn't be too high either, since states
10737                          * at the end of the loop are likely to be useful in pruning.
10738                          */
10739                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10740                             env->insn_processed - env->prev_insn_processed < 100)
10741                                 add_new_state = false;
10742                         goto miss;
10743                 }
10744                 if (states_equal(env, &sl->state, cur)) {
10745                         sl->hit_cnt++;
10746                         /* reached equivalent register/stack state,
10747                          * prune the search.
10748                          * Registers read by the continuation are read by us.
10749                          * If we have any write marks in env->cur_state, they
10750                          * will prevent corresponding reads in the continuation
10751                          * from reaching our parent (an explored_state).  Our
10752                          * own state will get the read marks recorded, but
10753                          * they'll be immediately forgotten as we're pruning
10754                          * this state and will pop a new one.
10755                          */
10756                         err = propagate_liveness(env, &sl->state, cur);
10757
10758                         /* if previous state reached the exit with precision and
10759                          * current state is equivalent to it (except precsion marks)
10760                          * the precision needs to be propagated back in
10761                          * the current state.
10762                          */
10763                         err = err ? : push_jmp_history(env, cur);
10764                         err = err ? : propagate_precision(env, &sl->state);
10765                         if (err)
10766                                 return err;
10767                         return 1;
10768                 }
10769 miss:
10770                 /* when new state is not going to be added do not increase miss count.
10771                  * Otherwise several loop iterations will remove the state
10772                  * recorded earlier. The goal of these heuristics is to have
10773                  * states from some iterations of the loop (some in the beginning
10774                  * and some at the end) to help pruning.
10775                  */
10776                 if (add_new_state)
10777                         sl->miss_cnt++;
10778                 /* heuristic to determine whether this state is beneficial
10779                  * to keep checking from state equivalence point of view.
10780                  * Higher numbers increase max_states_per_insn and verification time,
10781                  * but do not meaningfully decrease insn_processed.
10782                  */
10783                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10784                         /* the state is unlikely to be useful. Remove it to
10785                          * speed up verification
10786                          */
10787                         *pprev = sl->next;
10788                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10789                                 u32 br = sl->state.branches;
10790
10791                                 WARN_ONCE(br,
10792                                           "BUG live_done but branches_to_explore %d\n",
10793                                           br);
10794                                 free_verifier_state(&sl->state, false);
10795                                 kfree(sl);
10796                                 env->peak_states--;
10797                         } else {
10798                                 /* cannot free this state, since parentage chain may
10799                                  * walk it later. Add it for free_list instead to
10800                                  * be freed at the end of verification
10801                                  */
10802                                 sl->next = env->free_list;
10803                                 env->free_list = sl;
10804                         }
10805                         sl = *pprev;
10806                         continue;
10807                 }
10808 next:
10809                 pprev = &sl->next;
10810                 sl = *pprev;
10811         }
10812
10813         if (env->max_states_per_insn < states_cnt)
10814                 env->max_states_per_insn = states_cnt;
10815
10816         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10817                 return push_jmp_history(env, cur);
10818
10819         if (!add_new_state)
10820                 return push_jmp_history(env, cur);
10821
10822         /* There were no equivalent states, remember the current one.
10823          * Technically the current state is not proven to be safe yet,
10824          * but it will either reach outer most bpf_exit (which means it's safe)
10825          * or it will be rejected. When there are no loops the verifier won't be
10826          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
10827          * again on the way to bpf_exit.
10828          * When looping the sl->state.branches will be > 0 and this state
10829          * will not be considered for equivalence until branches == 0.
10830          */
10831         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10832         if (!new_sl)
10833                 return -ENOMEM;
10834         env->total_states++;
10835         env->peak_states++;
10836         env->prev_jmps_processed = env->jmps_processed;
10837         env->prev_insn_processed = env->insn_processed;
10838
10839         /* add new state to the head of linked list */
10840         new = &new_sl->state;
10841         err = copy_verifier_state(new, cur);
10842         if (err) {
10843                 free_verifier_state(new, false);
10844                 kfree(new_sl);
10845                 return err;
10846         }
10847         new->insn_idx = insn_idx;
10848         WARN_ONCE(new->branches != 1,
10849                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10850
10851         cur->parent = new;
10852         cur->first_insn_idx = insn_idx;
10853         clear_jmp_history(cur);
10854         new_sl->next = *explored_state(env, insn_idx);
10855         *explored_state(env, insn_idx) = new_sl;
10856         /* connect new state to parentage chain. Current frame needs all
10857          * registers connected. Only r6 - r9 of the callers are alive (pushed
10858          * to the stack implicitly by JITs) so in callers' frames connect just
10859          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10860          * the state of the call instruction (with WRITTEN set), and r0 comes
10861          * from callee with its full parentage chain, anyway.
10862          */
10863         /* clear write marks in current state: the writes we did are not writes
10864          * our child did, so they don't screen off its reads from us.
10865          * (There are no read marks in current state, because reads always mark
10866          * their parent and current state never has children yet.  Only
10867          * explored_states can get read marks.)
10868          */
10869         for (j = 0; j <= cur->curframe; j++) {
10870                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10871                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10872                 for (i = 0; i < BPF_REG_FP; i++)
10873                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10874         }
10875
10876         /* all stack frames are accessible from callee, clear them all */
10877         for (j = 0; j <= cur->curframe; j++) {
10878                 struct bpf_func_state *frame = cur->frame[j];
10879                 struct bpf_func_state *newframe = new->frame[j];
10880
10881                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10882                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10883                         frame->stack[i].spilled_ptr.parent =
10884                                                 &newframe->stack[i].spilled_ptr;
10885                 }
10886         }
10887         return 0;
10888 }
10889
10890 /* Return true if it's OK to have the same insn return a different type. */
10891 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10892 {
10893         switch (base_type(type)) {
10894         case PTR_TO_CTX:
10895         case PTR_TO_SOCKET:
10896         case PTR_TO_SOCK_COMMON:
10897         case PTR_TO_TCP_SOCK:
10898         case PTR_TO_XDP_SOCK:
10899         case PTR_TO_BTF_ID:
10900                 return false;
10901         default:
10902                 return true;
10903         }
10904 }
10905
10906 /* If an instruction was previously used with particular pointer types, then we
10907  * need to be careful to avoid cases such as the below, where it may be ok
10908  * for one branch accessing the pointer, but not ok for the other branch:
10909  *
10910  * R1 = sock_ptr
10911  * goto X;
10912  * ...
10913  * R1 = some_other_valid_ptr;
10914  * goto X;
10915  * ...
10916  * R2 = *(u32 *)(R1 + 0);
10917  */
10918 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10919 {
10920         return src != prev && (!reg_type_mismatch_ok(src) ||
10921                                !reg_type_mismatch_ok(prev));
10922 }
10923
10924 static int do_check(struct bpf_verifier_env *env)
10925 {
10926         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10927         struct bpf_verifier_state *state = env->cur_state;
10928         struct bpf_insn *insns = env->prog->insnsi;
10929         struct bpf_reg_state *regs;
10930         int insn_cnt = env->prog->len;
10931         bool do_print_state = false;
10932         int prev_insn_idx = -1;
10933
10934         for (;;) {
10935                 struct bpf_insn *insn;
10936                 u8 class;
10937                 int err;
10938
10939                 env->prev_insn_idx = prev_insn_idx;
10940                 if (env->insn_idx >= insn_cnt) {
10941                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
10942                                 env->insn_idx, insn_cnt);
10943                         return -EFAULT;
10944                 }
10945
10946                 insn = &insns[env->insn_idx];
10947                 class = BPF_CLASS(insn->code);
10948
10949                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10950                         verbose(env,
10951                                 "BPF program is too large. Processed %d insn\n",
10952                                 env->insn_processed);
10953                         return -E2BIG;
10954                 }
10955
10956                 err = is_state_visited(env, env->insn_idx);
10957                 if (err < 0)
10958                         return err;
10959                 if (err == 1) {
10960                         /* found equivalent state, can prune the search */
10961                         if (env->log.level & BPF_LOG_LEVEL) {
10962                                 if (do_print_state)
10963                                         verbose(env, "\nfrom %d to %d%s: safe\n",
10964                                                 env->prev_insn_idx, env->insn_idx,
10965                                                 env->cur_state->speculative ?
10966                                                 " (speculative execution)" : "");
10967                                 else
10968                                         verbose(env, "%d: safe\n", env->insn_idx);
10969                         }
10970                         goto process_bpf_exit;
10971                 }
10972
10973                 if (signal_pending(current))
10974                         return -EAGAIN;
10975
10976                 if (need_resched())
10977                         cond_resched();
10978
10979                 if (env->log.level & BPF_LOG_LEVEL2 ||
10980                     (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10981                         if (env->log.level & BPF_LOG_LEVEL2)
10982                                 verbose(env, "%d:", env->insn_idx);
10983                         else
10984                                 verbose(env, "\nfrom %d to %d%s:",
10985                                         env->prev_insn_idx, env->insn_idx,
10986                                         env->cur_state->speculative ?
10987                                         " (speculative execution)" : "");
10988                         print_verifier_state(env, state->frame[state->curframe]);
10989                         do_print_state = false;
10990                 }
10991
10992                 if (env->log.level & BPF_LOG_LEVEL) {
10993                         const struct bpf_insn_cbs cbs = {
10994                                 .cb_call        = disasm_kfunc_name,
10995                                 .cb_print       = verbose,
10996                                 .private_data   = env,
10997                         };
10998
10999                         verbose_linfo(env, env->insn_idx, "; ");
11000                         verbose(env, "%d: ", env->insn_idx);
11001                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
11002                 }
11003
11004                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
11005                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
11006                                                            env->prev_insn_idx);
11007                         if (err)
11008                                 return err;
11009                 }
11010
11011                 regs = cur_regs(env);
11012                 sanitize_mark_insn_seen(env);
11013                 prev_insn_idx = env->insn_idx;
11014
11015                 if (class == BPF_ALU || class == BPF_ALU64) {
11016                         err = check_alu_op(env, insn);
11017                         if (err)
11018                                 return err;
11019
11020                 } else if (class == BPF_LDX) {
11021                         enum bpf_reg_type *prev_src_type, src_reg_type;
11022
11023                         /* check for reserved fields is already done */
11024
11025                         /* check src operand */
11026                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
11027                         if (err)
11028                                 return err;
11029
11030                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11031                         if (err)
11032                                 return err;
11033
11034                         src_reg_type = regs[insn->src_reg].type;
11035
11036                         /* check that memory (src_reg + off) is readable,
11037                          * the state of dst_reg will be updated by this func
11038                          */
11039                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
11040                                                insn->off, BPF_SIZE(insn->code),
11041                                                BPF_READ, insn->dst_reg, false);
11042                         if (err)
11043                                 return err;
11044
11045                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11046
11047                         if (*prev_src_type == NOT_INIT) {
11048                                 /* saw a valid insn
11049                                  * dst_reg = *(u32 *)(src_reg + off)
11050                                  * save type to validate intersecting paths
11051                                  */
11052                                 *prev_src_type = src_reg_type;
11053
11054                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11055                                 /* ABuser program is trying to use the same insn
11056                                  * dst_reg = *(u32*) (src_reg + off)
11057                                  * with different pointer types:
11058                                  * src_reg == ctx in one branch and
11059                                  * src_reg == stack|map in some other branch.
11060                                  * Reject it.
11061                                  */
11062                                 verbose(env, "same insn cannot be used with different pointers\n");
11063                                 return -EINVAL;
11064                         }
11065
11066                 } else if (class == BPF_STX) {
11067                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
11068
11069                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11070                                 err = check_atomic(env, env->insn_idx, insn);
11071                                 if (err)
11072                                         return err;
11073                                 env->insn_idx++;
11074                                 continue;
11075                         }
11076
11077                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11078                                 verbose(env, "BPF_STX uses reserved fields\n");
11079                                 return -EINVAL;
11080                         }
11081
11082                         /* check src1 operand */
11083                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
11084                         if (err)
11085                                 return err;
11086                         /* check src2 operand */
11087                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11088                         if (err)
11089                                 return err;
11090
11091                         dst_reg_type = regs[insn->dst_reg].type;
11092
11093                         /* check that memory (dst_reg + off) is writeable */
11094                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11095                                                insn->off, BPF_SIZE(insn->code),
11096                                                BPF_WRITE, insn->src_reg, false);
11097                         if (err)
11098                                 return err;
11099
11100                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11101
11102                         if (*prev_dst_type == NOT_INIT) {
11103                                 *prev_dst_type = dst_reg_type;
11104                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11105                                 verbose(env, "same insn cannot be used with different pointers\n");
11106                                 return -EINVAL;
11107                         }
11108
11109                 } else if (class == BPF_ST) {
11110                         if (BPF_MODE(insn->code) != BPF_MEM ||
11111                             insn->src_reg != BPF_REG_0) {
11112                                 verbose(env, "BPF_ST uses reserved fields\n");
11113                                 return -EINVAL;
11114                         }
11115                         /* check src operand */
11116                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11117                         if (err)
11118                                 return err;
11119
11120                         if (is_ctx_reg(env, insn->dst_reg)) {
11121                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11122                                         insn->dst_reg,
11123                                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
11124                                 return -EACCES;
11125                         }
11126
11127                         /* check that memory (dst_reg + off) is writeable */
11128                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11129                                                insn->off, BPF_SIZE(insn->code),
11130                                                BPF_WRITE, -1, false);
11131                         if (err)
11132                                 return err;
11133
11134                 } else if (class == BPF_JMP || class == BPF_JMP32) {
11135                         u8 opcode = BPF_OP(insn->code);
11136
11137                         env->jmps_processed++;
11138                         if (opcode == BPF_CALL) {
11139                                 if (BPF_SRC(insn->code) != BPF_K ||
11140                                     insn->off != 0 ||
11141                                     (insn->src_reg != BPF_REG_0 &&
11142                                      insn->src_reg != BPF_PSEUDO_CALL &&
11143                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11144                                     insn->dst_reg != BPF_REG_0 ||
11145                                     class == BPF_JMP32) {
11146                                         verbose(env, "BPF_CALL uses reserved fields\n");
11147                                         return -EINVAL;
11148                                 }
11149
11150                                 if (env->cur_state->active_spin_lock &&
11151                                     (insn->src_reg == BPF_PSEUDO_CALL ||
11152                                      insn->imm != BPF_FUNC_spin_unlock)) {
11153                                         verbose(env, "function calls are not allowed while holding a lock\n");
11154                                         return -EINVAL;
11155                                 }
11156                                 if (insn->src_reg == BPF_PSEUDO_CALL)
11157                                         err = check_func_call(env, insn, &env->insn_idx);
11158                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11159                                         err = check_kfunc_call(env, insn);
11160                                 else
11161                                         err = check_helper_call(env, insn, &env->insn_idx);
11162                                 if (err)
11163                                         return err;
11164                         } else if (opcode == BPF_JA) {
11165                                 if (BPF_SRC(insn->code) != BPF_K ||
11166                                     insn->imm != 0 ||
11167                                     insn->src_reg != BPF_REG_0 ||
11168                                     insn->dst_reg != BPF_REG_0 ||
11169                                     class == BPF_JMP32) {
11170                                         verbose(env, "BPF_JA uses reserved fields\n");
11171                                         return -EINVAL;
11172                                 }
11173
11174                                 env->insn_idx += insn->off + 1;
11175                                 continue;
11176
11177                         } else if (opcode == BPF_EXIT) {
11178                                 if (BPF_SRC(insn->code) != BPF_K ||
11179                                     insn->imm != 0 ||
11180                                     insn->src_reg != BPF_REG_0 ||
11181                                     insn->dst_reg != BPF_REG_0 ||
11182                                     class == BPF_JMP32) {
11183                                         verbose(env, "BPF_EXIT uses reserved fields\n");
11184                                         return -EINVAL;
11185                                 }
11186
11187                                 if (env->cur_state->active_spin_lock) {
11188                                         verbose(env, "bpf_spin_unlock is missing\n");
11189                                         return -EINVAL;
11190                                 }
11191
11192                                 if (state->curframe) {
11193                                         /* exit from nested function */
11194                                         err = prepare_func_exit(env, &env->insn_idx);
11195                                         if (err)
11196                                                 return err;
11197                                         do_print_state = true;
11198                                         continue;
11199                                 }
11200
11201                                 err = check_reference_leak(env);
11202                                 if (err)
11203                                         return err;
11204
11205                                 err = check_return_code(env);
11206                                 if (err)
11207                                         return err;
11208 process_bpf_exit:
11209                                 update_branch_counts(env, env->cur_state);
11210                                 err = pop_stack(env, &prev_insn_idx,
11211                                                 &env->insn_idx, pop_log);
11212                                 if (err < 0) {
11213                                         if (err != -ENOENT)
11214                                                 return err;
11215                                         break;
11216                                 } else {
11217                                         do_print_state = true;
11218                                         continue;
11219                                 }
11220                         } else {
11221                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
11222                                 if (err)
11223                                         return err;
11224                         }
11225                 } else if (class == BPF_LD) {
11226                         u8 mode = BPF_MODE(insn->code);
11227
11228                         if (mode == BPF_ABS || mode == BPF_IND) {
11229                                 err = check_ld_abs(env, insn);
11230                                 if (err)
11231                                         return err;
11232
11233                         } else if (mode == BPF_IMM) {
11234                                 err = check_ld_imm(env, insn);
11235                                 if (err)
11236                                         return err;
11237
11238                                 env->insn_idx++;
11239                                 sanitize_mark_insn_seen(env);
11240                         } else {
11241                                 verbose(env, "invalid BPF_LD mode\n");
11242                                 return -EINVAL;
11243                         }
11244                 } else {
11245                         verbose(env, "unknown insn class %d\n", class);
11246                         return -EINVAL;
11247                 }
11248
11249                 env->insn_idx++;
11250         }
11251
11252         return 0;
11253 }
11254
11255 static int find_btf_percpu_datasec(struct btf *btf)
11256 {
11257         const struct btf_type *t;
11258         const char *tname;
11259         int i, n;
11260
11261         /*
11262          * Both vmlinux and module each have their own ".data..percpu"
11263          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11264          * types to look at only module's own BTF types.
11265          */
11266         n = btf_nr_types(btf);
11267         if (btf_is_module(btf))
11268                 i = btf_nr_types(btf_vmlinux);
11269         else
11270                 i = 1;
11271
11272         for(; i < n; i++) {
11273                 t = btf_type_by_id(btf, i);
11274                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11275                         continue;
11276
11277                 tname = btf_name_by_offset(btf, t->name_off);
11278                 if (!strcmp(tname, ".data..percpu"))
11279                         return i;
11280         }
11281
11282         return -ENOENT;
11283 }
11284
11285 /* replace pseudo btf_id with kernel symbol address */
11286 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11287                                struct bpf_insn *insn,
11288                                struct bpf_insn_aux_data *aux)
11289 {
11290         const struct btf_var_secinfo *vsi;
11291         const struct btf_type *datasec;
11292         struct btf_mod_pair *btf_mod;
11293         const struct btf_type *t;
11294         const char *sym_name;
11295         bool percpu = false;
11296         u32 type, id = insn->imm;
11297         struct btf *btf;
11298         s32 datasec_id;
11299         u64 addr;
11300         int i, btf_fd, err;
11301
11302         btf_fd = insn[1].imm;
11303         if (btf_fd) {
11304                 btf = btf_get_by_fd(btf_fd);
11305                 if (IS_ERR(btf)) {
11306                         verbose(env, "invalid module BTF object FD specified.\n");
11307                         return -EINVAL;
11308                 }
11309         } else {
11310                 if (!btf_vmlinux) {
11311                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11312                         return -EINVAL;
11313                 }
11314                 btf = btf_vmlinux;
11315                 btf_get(btf);
11316         }
11317
11318         t = btf_type_by_id(btf, id);
11319         if (!t) {
11320                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11321                 err = -ENOENT;
11322                 goto err_put;
11323         }
11324
11325         if (!btf_type_is_var(t)) {
11326                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11327                 err = -EINVAL;
11328                 goto err_put;
11329         }
11330
11331         sym_name = btf_name_by_offset(btf, t->name_off);
11332         addr = kallsyms_lookup_name(sym_name);
11333         if (!addr) {
11334                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11335                         sym_name);
11336                 err = -ENOENT;
11337                 goto err_put;
11338         }
11339
11340         datasec_id = find_btf_percpu_datasec(btf);
11341         if (datasec_id > 0) {
11342                 datasec = btf_type_by_id(btf, datasec_id);
11343                 for_each_vsi(i, datasec, vsi) {
11344                         if (vsi->type == id) {
11345                                 percpu = true;
11346                                 break;
11347                         }
11348                 }
11349         }
11350
11351         insn[0].imm = (u32)addr;
11352         insn[1].imm = addr >> 32;
11353
11354         type = t->type;
11355         t = btf_type_skip_modifiers(btf, type, NULL);
11356         if (percpu) {
11357                 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11358                 aux->btf_var.btf = btf;
11359                 aux->btf_var.btf_id = type;
11360         } else if (!btf_type_is_struct(t)) {
11361                 const struct btf_type *ret;
11362                 const char *tname;
11363                 u32 tsize;
11364
11365                 /* resolve the type size of ksym. */
11366                 ret = btf_resolve_size(btf, t, &tsize);
11367                 if (IS_ERR(ret)) {
11368                         tname = btf_name_by_offset(btf, t->name_off);
11369                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11370                                 tname, PTR_ERR(ret));
11371                         err = -EINVAL;
11372                         goto err_put;
11373                 }
11374                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
11375                 aux->btf_var.mem_size = tsize;
11376         } else {
11377                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
11378                 aux->btf_var.btf = btf;
11379                 aux->btf_var.btf_id = type;
11380         }
11381
11382         /* check whether we recorded this BTF (and maybe module) already */
11383         for (i = 0; i < env->used_btf_cnt; i++) {
11384                 if (env->used_btfs[i].btf == btf) {
11385                         btf_put(btf);
11386                         return 0;
11387                 }
11388         }
11389
11390         if (env->used_btf_cnt >= MAX_USED_BTFS) {
11391                 err = -E2BIG;
11392                 goto err_put;
11393         }
11394
11395         btf_mod = &env->used_btfs[env->used_btf_cnt];
11396         btf_mod->btf = btf;
11397         btf_mod->module = NULL;
11398
11399         /* if we reference variables from kernel module, bump its refcount */
11400         if (btf_is_module(btf)) {
11401                 btf_mod->module = btf_try_get_module(btf);
11402                 if (!btf_mod->module) {
11403                         err = -ENXIO;
11404                         goto err_put;
11405                 }
11406         }
11407
11408         env->used_btf_cnt++;
11409
11410         return 0;
11411 err_put:
11412         btf_put(btf);
11413         return err;
11414 }
11415
11416 static int check_map_prealloc(struct bpf_map *map)
11417 {
11418         return (map->map_type != BPF_MAP_TYPE_HASH &&
11419                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11420                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11421                 !(map->map_flags & BPF_F_NO_PREALLOC);
11422 }
11423
11424 static bool is_tracing_prog_type(enum bpf_prog_type type)
11425 {
11426         switch (type) {
11427         case BPF_PROG_TYPE_KPROBE:
11428         case BPF_PROG_TYPE_TRACEPOINT:
11429         case BPF_PROG_TYPE_PERF_EVENT:
11430         case BPF_PROG_TYPE_RAW_TRACEPOINT:
11431                 return true;
11432         default:
11433                 return false;
11434         }
11435 }
11436
11437 static bool is_preallocated_map(struct bpf_map *map)
11438 {
11439         if (!check_map_prealloc(map))
11440                 return false;
11441         if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11442                 return false;
11443         return true;
11444 }
11445
11446 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11447                                         struct bpf_map *map,
11448                                         struct bpf_prog *prog)
11449
11450 {
11451         enum bpf_prog_type prog_type = resolve_prog_type(prog);
11452         /*
11453          * Validate that trace type programs use preallocated hash maps.
11454          *
11455          * For programs attached to PERF events this is mandatory as the
11456          * perf NMI can hit any arbitrary code sequence.
11457          *
11458          * All other trace types using preallocated hash maps are unsafe as
11459          * well because tracepoint or kprobes can be inside locked regions
11460          * of the memory allocator or at a place where a recursion into the
11461          * memory allocator would see inconsistent state.
11462          *
11463          * On RT enabled kernels run-time allocation of all trace type
11464          * programs is strictly prohibited due to lock type constraints. On
11465          * !RT kernels it is allowed for backwards compatibility reasons for
11466          * now, but warnings are emitted so developers are made aware of
11467          * the unsafety and can fix their programs before this is enforced.
11468          */
11469         if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11470                 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11471                         verbose(env, "perf_event programs can only use preallocated hash map\n");
11472                         return -EINVAL;
11473                 }
11474                 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11475                         verbose(env, "trace type programs can only use preallocated hash map\n");
11476                         return -EINVAL;
11477                 }
11478                 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11479                 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11480         }
11481
11482         if (map_value_has_spin_lock(map)) {
11483                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11484                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11485                         return -EINVAL;
11486                 }
11487
11488                 if (is_tracing_prog_type(prog_type)) {
11489                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11490                         return -EINVAL;
11491                 }
11492
11493                 if (prog->aux->sleepable) {
11494                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11495                         return -EINVAL;
11496                 }
11497         }
11498
11499         if (map_value_has_timer(map)) {
11500                 if (is_tracing_prog_type(prog_type)) {
11501                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
11502                         return -EINVAL;
11503                 }
11504         }
11505
11506         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11507             !bpf_offload_prog_map_match(prog, map)) {
11508                 verbose(env, "offload device mismatch between prog and map\n");
11509                 return -EINVAL;
11510         }
11511
11512         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11513                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11514                 return -EINVAL;
11515         }
11516
11517         if (prog->aux->sleepable)
11518                 switch (map->map_type) {
11519                 case BPF_MAP_TYPE_HASH:
11520                 case BPF_MAP_TYPE_LRU_HASH:
11521                 case BPF_MAP_TYPE_ARRAY:
11522                 case BPF_MAP_TYPE_PERCPU_HASH:
11523                 case BPF_MAP_TYPE_PERCPU_ARRAY:
11524                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11525                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11526                 case BPF_MAP_TYPE_HASH_OF_MAPS:
11527                         if (!is_preallocated_map(map)) {
11528                                 verbose(env,
11529                                         "Sleepable programs can only use preallocated maps\n");
11530                                 return -EINVAL;
11531                         }
11532                         break;
11533                 case BPF_MAP_TYPE_RINGBUF:
11534                         break;
11535                 default:
11536                         verbose(env,
11537                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
11538                         return -EINVAL;
11539                 }
11540
11541         return 0;
11542 }
11543
11544 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11545 {
11546         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11547                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11548 }
11549
11550 /* find and rewrite pseudo imm in ld_imm64 instructions:
11551  *
11552  * 1. if it accesses map FD, replace it with actual map pointer.
11553  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11554  *
11555  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11556  */
11557 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11558 {
11559         struct bpf_insn *insn = env->prog->insnsi;
11560         int insn_cnt = env->prog->len;
11561         int i, j, err;
11562
11563         err = bpf_prog_calc_tag(env->prog);
11564         if (err)
11565                 return err;
11566
11567         for (i = 0; i < insn_cnt; i++, insn++) {
11568                 if (BPF_CLASS(insn->code) == BPF_LDX &&
11569                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11570                         verbose(env, "BPF_LDX uses reserved fields\n");
11571                         return -EINVAL;
11572                 }
11573
11574                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11575                         struct bpf_insn_aux_data *aux;
11576                         struct bpf_map *map;
11577                         struct fd f;
11578                         u64 addr;
11579                         u32 fd;
11580
11581                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
11582                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11583                             insn[1].off != 0) {
11584                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
11585                                 return -EINVAL;
11586                         }
11587
11588                         if (insn[0].src_reg == 0)
11589                                 /* valid generic load 64-bit imm */
11590                                 goto next_insn;
11591
11592                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11593                                 aux = &env->insn_aux_data[i];
11594                                 err = check_pseudo_btf_id(env, insn, aux);
11595                                 if (err)
11596                                         return err;
11597                                 goto next_insn;
11598                         }
11599
11600                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11601                                 aux = &env->insn_aux_data[i];
11602                                 aux->ptr_type = PTR_TO_FUNC;
11603                                 goto next_insn;
11604                         }
11605
11606                         /* In final convert_pseudo_ld_imm64() step, this is
11607                          * converted into regular 64-bit imm load insn.
11608                          */
11609                         switch (insn[0].src_reg) {
11610                         case BPF_PSEUDO_MAP_VALUE:
11611                         case BPF_PSEUDO_MAP_IDX_VALUE:
11612                                 break;
11613                         case BPF_PSEUDO_MAP_FD:
11614                         case BPF_PSEUDO_MAP_IDX:
11615                                 if (insn[1].imm == 0)
11616                                         break;
11617                                 fallthrough;
11618                         default:
11619                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11620                                 return -EINVAL;
11621                         }
11622
11623                         switch (insn[0].src_reg) {
11624                         case BPF_PSEUDO_MAP_IDX_VALUE:
11625                         case BPF_PSEUDO_MAP_IDX:
11626                                 if (bpfptr_is_null(env->fd_array)) {
11627                                         verbose(env, "fd_idx without fd_array is invalid\n");
11628                                         return -EPROTO;
11629                                 }
11630                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
11631                                                             insn[0].imm * sizeof(fd),
11632                                                             sizeof(fd)))
11633                                         return -EFAULT;
11634                                 break;
11635                         default:
11636                                 fd = insn[0].imm;
11637                                 break;
11638                         }
11639
11640                         f = fdget(fd);
11641                         map = __bpf_map_get(f);
11642                         if (IS_ERR(map)) {
11643                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
11644                                         insn[0].imm);
11645                                 return PTR_ERR(map);
11646                         }
11647
11648                         err = check_map_prog_compatibility(env, map, env->prog);
11649                         if (err) {
11650                                 fdput(f);
11651                                 return err;
11652                         }
11653
11654                         aux = &env->insn_aux_data[i];
11655                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11656                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11657                                 addr = (unsigned long)map;
11658                         } else {
11659                                 u32 off = insn[1].imm;
11660
11661                                 if (off >= BPF_MAX_VAR_OFF) {
11662                                         verbose(env, "direct value offset of %u is not allowed\n", off);
11663                                         fdput(f);
11664                                         return -EINVAL;
11665                                 }
11666
11667                                 if (!map->ops->map_direct_value_addr) {
11668                                         verbose(env, "no direct value access support for this map type\n");
11669                                         fdput(f);
11670                                         return -EINVAL;
11671                                 }
11672
11673                                 err = map->ops->map_direct_value_addr(map, &addr, off);
11674                                 if (err) {
11675                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11676                                                 map->value_size, off);
11677                                         fdput(f);
11678                                         return err;
11679                                 }
11680
11681                                 aux->map_off = off;
11682                                 addr += off;
11683                         }
11684
11685                         insn[0].imm = (u32)addr;
11686                         insn[1].imm = addr >> 32;
11687
11688                         /* check whether we recorded this map already */
11689                         for (j = 0; j < env->used_map_cnt; j++) {
11690                                 if (env->used_maps[j] == map) {
11691                                         aux->map_index = j;
11692                                         fdput(f);
11693                                         goto next_insn;
11694                                 }
11695                         }
11696
11697                         if (env->used_map_cnt >= MAX_USED_MAPS) {
11698                                 fdput(f);
11699                                 return -E2BIG;
11700                         }
11701
11702                         /* hold the map. If the program is rejected by verifier,
11703                          * the map will be released by release_maps() or it
11704                          * will be used by the valid program until it's unloaded
11705                          * and all maps are released in free_used_maps()
11706                          */
11707                         bpf_map_inc(map);
11708
11709                         aux->map_index = env->used_map_cnt;
11710                         env->used_maps[env->used_map_cnt++] = map;
11711
11712                         if (bpf_map_is_cgroup_storage(map) &&
11713                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
11714                                 verbose(env, "only one cgroup storage of each type is allowed\n");
11715                                 fdput(f);
11716                                 return -EBUSY;
11717                         }
11718
11719                         fdput(f);
11720 next_insn:
11721                         insn++;
11722                         i++;
11723                         continue;
11724                 }
11725
11726                 /* Basic sanity check before we invest more work here. */
11727                 if (!bpf_opcode_in_insntable(insn->code)) {
11728                         verbose(env, "unknown opcode %02x\n", insn->code);
11729                         return -EINVAL;
11730                 }
11731         }
11732
11733         /* now all pseudo BPF_LD_IMM64 instructions load valid
11734          * 'struct bpf_map *' into a register instead of user map_fd.
11735          * These pointers will be used later by verifier to validate map access.
11736          */
11737         return 0;
11738 }
11739
11740 /* drop refcnt of maps used by the rejected program */
11741 static void release_maps(struct bpf_verifier_env *env)
11742 {
11743         __bpf_free_used_maps(env->prog->aux, env->used_maps,
11744                              env->used_map_cnt);
11745 }
11746
11747 /* drop refcnt of maps used by the rejected program */
11748 static void release_btfs(struct bpf_verifier_env *env)
11749 {
11750         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11751                              env->used_btf_cnt);
11752 }
11753
11754 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11755 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11756 {
11757         struct bpf_insn *insn = env->prog->insnsi;
11758         int insn_cnt = env->prog->len;
11759         int i;
11760
11761         for (i = 0; i < insn_cnt; i++, insn++) {
11762                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11763                         continue;
11764                 if (insn->src_reg == BPF_PSEUDO_FUNC)
11765                         continue;
11766                 insn->src_reg = 0;
11767         }
11768 }
11769
11770 /* single env->prog->insni[off] instruction was replaced with the range
11771  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11772  * [0, off) and [off, end) to new locations, so the patched range stays zero
11773  */
11774 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
11775                                  struct bpf_insn_aux_data *new_data,
11776                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
11777 {
11778         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
11779         struct bpf_insn *insn = new_prog->insnsi;
11780         u32 old_seen = old_data[off].seen;
11781         u32 prog_len;
11782         int i;
11783
11784         /* aux info at OFF always needs adjustment, no matter fast path
11785          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11786          * original insn at old prog.
11787          */
11788         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11789
11790         if (cnt == 1)
11791                 return;
11792         prog_len = new_prog->len;
11793
11794         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11795         memcpy(new_data + off + cnt - 1, old_data + off,
11796                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11797         for (i = off; i < off + cnt - 1; i++) {
11798                 /* Expand insni[off]'s seen count to the patched range. */
11799                 new_data[i].seen = old_seen;
11800                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11801         }
11802         env->insn_aux_data = new_data;
11803         vfree(old_data);
11804 }
11805
11806 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11807 {
11808         int i;
11809
11810         if (len == 1)
11811                 return;
11812         /* NOTE: fake 'exit' subprog should be updated as well. */
11813         for (i = 0; i <= env->subprog_cnt; i++) {
11814                 if (env->subprog_info[i].start <= off)
11815                         continue;
11816                 env->subprog_info[i].start += len - 1;
11817         }
11818 }
11819
11820 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
11821 {
11822         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11823         int i, sz = prog->aux->size_poke_tab;
11824         struct bpf_jit_poke_descriptor *desc;
11825
11826         for (i = 0; i < sz; i++) {
11827                 desc = &tab[i];
11828                 if (desc->insn_idx <= off)
11829                         continue;
11830                 desc->insn_idx += len - 1;
11831         }
11832 }
11833
11834 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11835                                             const struct bpf_insn *patch, u32 len)
11836 {
11837         struct bpf_prog *new_prog;
11838         struct bpf_insn_aux_data *new_data = NULL;
11839
11840         if (len > 1) {
11841                 new_data = vzalloc(array_size(env->prog->len + len - 1,
11842                                               sizeof(struct bpf_insn_aux_data)));
11843                 if (!new_data)
11844                         return NULL;
11845         }
11846
11847         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
11848         if (IS_ERR(new_prog)) {
11849                 if (PTR_ERR(new_prog) == -ERANGE)
11850                         verbose(env,
11851                                 "insn %d cannot be patched due to 16-bit range\n",
11852                                 env->insn_aux_data[off].orig_idx);
11853                 vfree(new_data);
11854                 return NULL;
11855         }
11856         adjust_insn_aux_data(env, new_data, new_prog, off, len);
11857         adjust_subprog_starts(env, off, len);
11858         adjust_poke_descs(new_prog, off, len);
11859         return new_prog;
11860 }
11861
11862 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11863                                               u32 off, u32 cnt)
11864 {
11865         int i, j;
11866
11867         /* find first prog starting at or after off (first to remove) */
11868         for (i = 0; i < env->subprog_cnt; i++)
11869                 if (env->subprog_info[i].start >= off)
11870                         break;
11871         /* find first prog starting at or after off + cnt (first to stay) */
11872         for (j = i; j < env->subprog_cnt; j++)
11873                 if (env->subprog_info[j].start >= off + cnt)
11874                         break;
11875         /* if j doesn't start exactly at off + cnt, we are just removing
11876          * the front of previous prog
11877          */
11878         if (env->subprog_info[j].start != off + cnt)
11879                 j--;
11880
11881         if (j > i) {
11882                 struct bpf_prog_aux *aux = env->prog->aux;
11883                 int move;
11884
11885                 /* move fake 'exit' subprog as well */
11886                 move = env->subprog_cnt + 1 - j;
11887
11888                 memmove(env->subprog_info + i,
11889                         env->subprog_info + j,
11890                         sizeof(*env->subprog_info) * move);
11891                 env->subprog_cnt -= j - i;
11892
11893                 /* remove func_info */
11894                 if (aux->func_info) {
11895                         move = aux->func_info_cnt - j;
11896
11897                         memmove(aux->func_info + i,
11898                                 aux->func_info + j,
11899                                 sizeof(*aux->func_info) * move);
11900                         aux->func_info_cnt -= j - i;
11901                         /* func_info->insn_off is set after all code rewrites,
11902                          * in adjust_btf_func() - no need to adjust
11903                          */
11904                 }
11905         } else {
11906                 /* convert i from "first prog to remove" to "first to adjust" */
11907                 if (env->subprog_info[i].start == off)
11908                         i++;
11909         }
11910
11911         /* update fake 'exit' subprog as well */
11912         for (; i <= env->subprog_cnt; i++)
11913                 env->subprog_info[i].start -= cnt;
11914
11915         return 0;
11916 }
11917
11918 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11919                                       u32 cnt)
11920 {
11921         struct bpf_prog *prog = env->prog;
11922         u32 i, l_off, l_cnt, nr_linfo;
11923         struct bpf_line_info *linfo;
11924
11925         nr_linfo = prog->aux->nr_linfo;
11926         if (!nr_linfo)
11927                 return 0;
11928
11929         linfo = prog->aux->linfo;
11930
11931         /* find first line info to remove, count lines to be removed */
11932         for (i = 0; i < nr_linfo; i++)
11933                 if (linfo[i].insn_off >= off)
11934                         break;
11935
11936         l_off = i;
11937         l_cnt = 0;
11938         for (; i < nr_linfo; i++)
11939                 if (linfo[i].insn_off < off + cnt)
11940                         l_cnt++;
11941                 else
11942                         break;
11943
11944         /* First live insn doesn't match first live linfo, it needs to "inherit"
11945          * last removed linfo.  prog is already modified, so prog->len == off
11946          * means no live instructions after (tail of the program was removed).
11947          */
11948         if (prog->len != off && l_cnt &&
11949             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11950                 l_cnt--;
11951                 linfo[--i].insn_off = off + cnt;
11952         }
11953
11954         /* remove the line info which refer to the removed instructions */
11955         if (l_cnt) {
11956                 memmove(linfo + l_off, linfo + i,
11957                         sizeof(*linfo) * (nr_linfo - i));
11958
11959                 prog->aux->nr_linfo -= l_cnt;
11960                 nr_linfo = prog->aux->nr_linfo;
11961         }
11962
11963         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11964         for (i = l_off; i < nr_linfo; i++)
11965                 linfo[i].insn_off -= cnt;
11966
11967         /* fix up all subprogs (incl. 'exit') which start >= off */
11968         for (i = 0; i <= env->subprog_cnt; i++)
11969                 if (env->subprog_info[i].linfo_idx > l_off) {
11970                         /* program may have started in the removed region but
11971                          * may not be fully removed
11972                          */
11973                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11974                                 env->subprog_info[i].linfo_idx -= l_cnt;
11975                         else
11976                                 env->subprog_info[i].linfo_idx = l_off;
11977                 }
11978
11979         return 0;
11980 }
11981
11982 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11983 {
11984         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11985         unsigned int orig_prog_len = env->prog->len;
11986         int err;
11987
11988         if (bpf_prog_is_dev_bound(env->prog->aux))
11989                 bpf_prog_offload_remove_insns(env, off, cnt);
11990
11991         err = bpf_remove_insns(env->prog, off, cnt);
11992         if (err)
11993                 return err;
11994
11995         err = adjust_subprog_starts_after_remove(env, off, cnt);
11996         if (err)
11997                 return err;
11998
11999         err = bpf_adj_linfo_after_remove(env, off, cnt);
12000         if (err)
12001                 return err;
12002
12003         memmove(aux_data + off, aux_data + off + cnt,
12004                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
12005
12006         return 0;
12007 }
12008
12009 /* The verifier does more data flow analysis than llvm and will not
12010  * explore branches that are dead at run time. Malicious programs can
12011  * have dead code too. Therefore replace all dead at-run-time code
12012  * with 'ja -1'.
12013  *
12014  * Just nops are not optimal, e.g. if they would sit at the end of the
12015  * program and through another bug we would manage to jump there, then
12016  * we'd execute beyond program memory otherwise. Returning exception
12017  * code also wouldn't work since we can have subprogs where the dead
12018  * code could be located.
12019  */
12020 static void sanitize_dead_code(struct bpf_verifier_env *env)
12021 {
12022         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12023         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
12024         struct bpf_insn *insn = env->prog->insnsi;
12025         const int insn_cnt = env->prog->len;
12026         int i;
12027
12028         for (i = 0; i < insn_cnt; i++) {
12029                 if (aux_data[i].seen)
12030                         continue;
12031                 memcpy(insn + i, &trap, sizeof(trap));
12032                 aux_data[i].zext_dst = false;
12033         }
12034 }
12035
12036 static bool insn_is_cond_jump(u8 code)
12037 {
12038         u8 op;
12039
12040         if (BPF_CLASS(code) == BPF_JMP32)
12041                 return true;
12042
12043         if (BPF_CLASS(code) != BPF_JMP)
12044                 return false;
12045
12046         op = BPF_OP(code);
12047         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12048 }
12049
12050 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12051 {
12052         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12053         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12054         struct bpf_insn *insn = env->prog->insnsi;
12055         const int insn_cnt = env->prog->len;
12056         int i;
12057
12058         for (i = 0; i < insn_cnt; i++, insn++) {
12059                 if (!insn_is_cond_jump(insn->code))
12060                         continue;
12061
12062                 if (!aux_data[i + 1].seen)
12063                         ja.off = insn->off;
12064                 else if (!aux_data[i + 1 + insn->off].seen)
12065                         ja.off = 0;
12066                 else
12067                         continue;
12068
12069                 if (bpf_prog_is_dev_bound(env->prog->aux))
12070                         bpf_prog_offload_replace_insn(env, i, &ja);
12071
12072                 memcpy(insn, &ja, sizeof(ja));
12073         }
12074 }
12075
12076 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12077 {
12078         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12079         int insn_cnt = env->prog->len;
12080         int i, err;
12081
12082         for (i = 0; i < insn_cnt; i++) {
12083                 int j;
12084
12085                 j = 0;
12086                 while (i + j < insn_cnt && !aux_data[i + j].seen)
12087                         j++;
12088                 if (!j)
12089                         continue;
12090
12091                 err = verifier_remove_insns(env, i, j);
12092                 if (err)
12093                         return err;
12094                 insn_cnt = env->prog->len;
12095         }
12096
12097         return 0;
12098 }
12099
12100 static int opt_remove_nops(struct bpf_verifier_env *env)
12101 {
12102         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12103         struct bpf_insn *insn = env->prog->insnsi;
12104         int insn_cnt = env->prog->len;
12105         int i, err;
12106
12107         for (i = 0; i < insn_cnt; i++) {
12108                 if (memcmp(&insn[i], &ja, sizeof(ja)))
12109                         continue;
12110
12111                 err = verifier_remove_insns(env, i, 1);
12112                 if (err)
12113                         return err;
12114                 insn_cnt--;
12115                 i--;
12116         }
12117
12118         return 0;
12119 }
12120
12121 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12122                                          const union bpf_attr *attr)
12123 {
12124         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12125         struct bpf_insn_aux_data *aux = env->insn_aux_data;
12126         int i, patch_len, delta = 0, len = env->prog->len;
12127         struct bpf_insn *insns = env->prog->insnsi;
12128         struct bpf_prog *new_prog;
12129         bool rnd_hi32;
12130
12131         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12132         zext_patch[1] = BPF_ZEXT_REG(0);
12133         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12134         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12135         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12136         for (i = 0; i < len; i++) {
12137                 int adj_idx = i + delta;
12138                 struct bpf_insn insn;
12139                 int load_reg;
12140
12141                 insn = insns[adj_idx];
12142                 load_reg = insn_def_regno(&insn);
12143                 if (!aux[adj_idx].zext_dst) {
12144                         u8 code, class;
12145                         u32 imm_rnd;
12146
12147                         if (!rnd_hi32)
12148                                 continue;
12149
12150                         code = insn.code;
12151                         class = BPF_CLASS(code);
12152                         if (load_reg == -1)
12153                                 continue;
12154
12155                         /* NOTE: arg "reg" (the fourth one) is only used for
12156                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
12157                          *       here.
12158                          */
12159                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12160                                 if (class == BPF_LD &&
12161                                     BPF_MODE(code) == BPF_IMM)
12162                                         i++;
12163                                 continue;
12164                         }
12165
12166                         /* ctx load could be transformed into wider load. */
12167                         if (class == BPF_LDX &&
12168                             aux[adj_idx].ptr_type == PTR_TO_CTX)
12169                                 continue;
12170
12171                         imm_rnd = get_random_int();
12172                         rnd_hi32_patch[0] = insn;
12173                         rnd_hi32_patch[1].imm = imm_rnd;
12174                         rnd_hi32_patch[3].dst_reg = load_reg;
12175                         patch = rnd_hi32_patch;
12176                         patch_len = 4;
12177                         goto apply_patch_buffer;
12178                 }
12179
12180                 /* Add in an zero-extend instruction if a) the JIT has requested
12181                  * it or b) it's a CMPXCHG.
12182                  *
12183                  * The latter is because: BPF_CMPXCHG always loads a value into
12184                  * R0, therefore always zero-extends. However some archs'
12185                  * equivalent instruction only does this load when the
12186                  * comparison is successful. This detail of CMPXCHG is
12187                  * orthogonal to the general zero-extension behaviour of the
12188                  * CPU, so it's treated independently of bpf_jit_needs_zext.
12189                  */
12190                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12191                         continue;
12192
12193                 if (WARN_ON(load_reg == -1)) {
12194                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12195                         return -EFAULT;
12196                 }
12197
12198                 zext_patch[0] = insn;
12199                 zext_patch[1].dst_reg = load_reg;
12200                 zext_patch[1].src_reg = load_reg;
12201                 patch = zext_patch;
12202                 patch_len = 2;
12203 apply_patch_buffer:
12204                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12205                 if (!new_prog)
12206                         return -ENOMEM;
12207                 env->prog = new_prog;
12208                 insns = new_prog->insnsi;
12209                 aux = env->insn_aux_data;
12210                 delta += patch_len - 1;
12211         }
12212
12213         return 0;
12214 }
12215
12216 /* convert load instructions that access fields of a context type into a
12217  * sequence of instructions that access fields of the underlying structure:
12218  *     struct __sk_buff    -> struct sk_buff
12219  *     struct bpf_sock_ops -> struct sock
12220  */
12221 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12222 {
12223         const struct bpf_verifier_ops *ops = env->ops;
12224         int i, cnt, size, ctx_field_size, delta = 0;
12225         const int insn_cnt = env->prog->len;
12226         struct bpf_insn insn_buf[16], *insn;
12227         u32 target_size, size_default, off;
12228         struct bpf_prog *new_prog;
12229         enum bpf_access_type type;
12230         bool is_narrower_load;
12231
12232         if (ops->gen_prologue || env->seen_direct_write) {
12233                 if (!ops->gen_prologue) {
12234                         verbose(env, "bpf verifier is misconfigured\n");
12235                         return -EINVAL;
12236                 }
12237                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12238                                         env->prog);
12239                 if (cnt >= ARRAY_SIZE(insn_buf)) {
12240                         verbose(env, "bpf verifier is misconfigured\n");
12241                         return -EINVAL;
12242                 } else if (cnt) {
12243                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12244                         if (!new_prog)
12245                                 return -ENOMEM;
12246
12247                         env->prog = new_prog;
12248                         delta += cnt - 1;
12249                 }
12250         }
12251
12252         if (bpf_prog_is_dev_bound(env->prog->aux))
12253                 return 0;
12254
12255         insn = env->prog->insnsi + delta;
12256
12257         for (i = 0; i < insn_cnt; i++, insn++) {
12258                 bpf_convert_ctx_access_t convert_ctx_access;
12259                 bool ctx_access;
12260
12261                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12262                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12263                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12264                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12265                         type = BPF_READ;
12266                         ctx_access = true;
12267                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12268                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12269                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12270                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12271                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12272                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12273                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12274                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12275                         type = BPF_WRITE;
12276                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12277                 } else {
12278                         continue;
12279                 }
12280
12281                 if (type == BPF_WRITE &&
12282                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
12283                         struct bpf_insn patch[] = {
12284                                 *insn,
12285                                 BPF_ST_NOSPEC(),
12286                         };
12287
12288                         cnt = ARRAY_SIZE(patch);
12289                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12290                         if (!new_prog)
12291                                 return -ENOMEM;
12292
12293                         delta    += cnt - 1;
12294                         env->prog = new_prog;
12295                         insn      = new_prog->insnsi + i + delta;
12296                         continue;
12297                 }
12298
12299                 if (!ctx_access)
12300                         continue;
12301
12302                 switch (env->insn_aux_data[i + delta].ptr_type) {
12303                 case PTR_TO_CTX:
12304                         if (!ops->convert_ctx_access)
12305                                 continue;
12306                         convert_ctx_access = ops->convert_ctx_access;
12307                         break;
12308                 case PTR_TO_SOCKET:
12309                 case PTR_TO_SOCK_COMMON:
12310                         convert_ctx_access = bpf_sock_convert_ctx_access;
12311                         break;
12312                 case PTR_TO_TCP_SOCK:
12313                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12314                         break;
12315                 case PTR_TO_XDP_SOCK:
12316                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12317                         break;
12318                 case PTR_TO_BTF_ID:
12319                         if (type == BPF_READ) {
12320                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
12321                                         BPF_SIZE((insn)->code);
12322                                 env->prog->aux->num_exentries++;
12323                         } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12324                                 verbose(env, "Writes through BTF pointers are not allowed\n");
12325                                 return -EINVAL;
12326                         }
12327                         continue;
12328                 default:
12329                         continue;
12330                 }
12331
12332                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12333                 size = BPF_LDST_BYTES(insn);
12334
12335                 /* If the read access is a narrower load of the field,
12336                  * convert to a 4/8-byte load, to minimum program type specific
12337                  * convert_ctx_access changes. If conversion is successful,
12338                  * we will apply proper mask to the result.
12339                  */
12340                 is_narrower_load = size < ctx_field_size;
12341                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12342                 off = insn->off;
12343                 if (is_narrower_load) {
12344                         u8 size_code;
12345
12346                         if (type == BPF_WRITE) {
12347                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12348                                 return -EINVAL;
12349                         }
12350
12351                         size_code = BPF_H;
12352                         if (ctx_field_size == 4)
12353                                 size_code = BPF_W;
12354                         else if (ctx_field_size == 8)
12355                                 size_code = BPF_DW;
12356
12357                         insn->off = off & ~(size_default - 1);
12358                         insn->code = BPF_LDX | BPF_MEM | size_code;
12359                 }
12360
12361                 target_size = 0;
12362                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12363                                          &target_size);
12364                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12365                     (ctx_field_size && !target_size)) {
12366                         verbose(env, "bpf verifier is misconfigured\n");
12367                         return -EINVAL;
12368                 }
12369
12370                 if (is_narrower_load && size < target_size) {
12371                         u8 shift = bpf_ctx_narrow_access_offset(
12372                                 off, size, size_default) * 8;
12373                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12374                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12375                                 return -EINVAL;
12376                         }
12377                         if (ctx_field_size <= 4) {
12378                                 if (shift)
12379                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12380                                                                         insn->dst_reg,
12381                                                                         shift);
12382                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12383                                                                 (1 << size * 8) - 1);
12384                         } else {
12385                                 if (shift)
12386                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12387                                                                         insn->dst_reg,
12388                                                                         shift);
12389                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12390                                                                 (1ULL << size * 8) - 1);
12391                         }
12392                 }
12393
12394                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12395                 if (!new_prog)
12396                         return -ENOMEM;
12397
12398                 delta += cnt - 1;
12399
12400                 /* keep walking new program and skip insns we just inserted */
12401                 env->prog = new_prog;
12402                 insn      = new_prog->insnsi + i + delta;
12403         }
12404
12405         return 0;
12406 }
12407
12408 static int jit_subprogs(struct bpf_verifier_env *env)
12409 {
12410         struct bpf_prog *prog = env->prog, **func, *tmp;
12411         int i, j, subprog_start, subprog_end = 0, len, subprog;
12412         struct bpf_map *map_ptr;
12413         struct bpf_insn *insn;
12414         void *old_bpf_func;
12415         int err, num_exentries;
12416
12417         if (env->subprog_cnt <= 1)
12418                 return 0;
12419
12420         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12421                 if (bpf_pseudo_func(insn)) {
12422                         env->insn_aux_data[i].call_imm = insn->imm;
12423                         /* subprog is encoded in insn[1].imm */
12424                         continue;
12425                 }
12426
12427                 if (!bpf_pseudo_call(insn))
12428                         continue;
12429                 /* Upon error here we cannot fall back to interpreter but
12430                  * need a hard reject of the program. Thus -EFAULT is
12431                  * propagated in any case.
12432                  */
12433                 subprog = find_subprog(env, i + insn->imm + 1);
12434                 if (subprog < 0) {
12435                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12436                                   i + insn->imm + 1);
12437                         return -EFAULT;
12438                 }
12439                 /* temporarily remember subprog id inside insn instead of
12440                  * aux_data, since next loop will split up all insns into funcs
12441                  */
12442                 insn->off = subprog;
12443                 /* remember original imm in case JIT fails and fallback
12444                  * to interpreter will be needed
12445                  */
12446                 env->insn_aux_data[i].call_imm = insn->imm;
12447                 /* point imm to __bpf_call_base+1 from JITs point of view */
12448                 insn->imm = 1;
12449         }
12450
12451         err = bpf_prog_alloc_jited_linfo(prog);
12452         if (err)
12453                 goto out_undo_insn;
12454
12455         err = -ENOMEM;
12456         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12457         if (!func)
12458                 goto out_undo_insn;
12459
12460         for (i = 0; i < env->subprog_cnt; i++) {
12461                 subprog_start = subprog_end;
12462                 subprog_end = env->subprog_info[i + 1].start;
12463
12464                 len = subprog_end - subprog_start;
12465                 /* bpf_prog_run() doesn't call subprogs directly,
12466                  * hence main prog stats include the runtime of subprogs.
12467                  * subprogs don't have IDs and not reachable via prog_get_next_id
12468                  * func[i]->stats will never be accessed and stays NULL
12469                  */
12470                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12471                 if (!func[i])
12472                         goto out_free;
12473                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12474                        len * sizeof(struct bpf_insn));
12475                 func[i]->type = prog->type;
12476                 func[i]->len = len;
12477                 if (bpf_prog_calc_tag(func[i]))
12478                         goto out_free;
12479                 func[i]->is_func = 1;
12480                 func[i]->aux->func_idx = i;
12481                 /* Below members will be freed only at prog->aux */
12482                 func[i]->aux->btf = prog->aux->btf;
12483                 func[i]->aux->func_info = prog->aux->func_info;
12484                 func[i]->aux->poke_tab = prog->aux->poke_tab;
12485                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12486
12487                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
12488                         struct bpf_jit_poke_descriptor *poke;
12489
12490                         poke = &prog->aux->poke_tab[j];
12491                         if (poke->insn_idx < subprog_end &&
12492                             poke->insn_idx >= subprog_start)
12493                                 poke->aux = func[i]->aux;
12494                 }
12495
12496                 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12497                  * Long term would need debug info to populate names
12498                  */
12499                 func[i]->aux->name[0] = 'F';
12500                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12501                 func[i]->jit_requested = 1;
12502                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12503                 func[i]->aux->linfo = prog->aux->linfo;
12504                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12505                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12506                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12507                 num_exentries = 0;
12508                 insn = func[i]->insnsi;
12509                 for (j = 0; j < func[i]->len; j++, insn++) {
12510                         if (BPF_CLASS(insn->code) == BPF_LDX &&
12511                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
12512                                 num_exentries++;
12513                 }
12514                 func[i]->aux->num_exentries = num_exentries;
12515                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12516                 func[i] = bpf_int_jit_compile(func[i]);
12517                 if (!func[i]->jited) {
12518                         err = -ENOTSUPP;
12519                         goto out_free;
12520                 }
12521                 cond_resched();
12522         }
12523
12524         /* at this point all bpf functions were successfully JITed
12525          * now populate all bpf_calls with correct addresses and
12526          * run last pass of JIT
12527          */
12528         for (i = 0; i < env->subprog_cnt; i++) {
12529                 insn = func[i]->insnsi;
12530                 for (j = 0; j < func[i]->len; j++, insn++) {
12531                         if (bpf_pseudo_func(insn)) {
12532                                 subprog = insn[1].imm;
12533                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12534                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12535                                 continue;
12536                         }
12537                         if (!bpf_pseudo_call(insn))
12538                                 continue;
12539                         subprog = insn->off;
12540                         insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12541                                     __bpf_call_base;
12542                 }
12543
12544                 /* we use the aux data to keep a list of the start addresses
12545                  * of the JITed images for each function in the program
12546                  *
12547                  * for some architectures, such as powerpc64, the imm field
12548                  * might not be large enough to hold the offset of the start
12549                  * address of the callee's JITed image from __bpf_call_base
12550                  *
12551                  * in such cases, we can lookup the start address of a callee
12552                  * by using its subprog id, available from the off field of
12553                  * the call instruction, as an index for this list
12554                  */
12555                 func[i]->aux->func = func;
12556                 func[i]->aux->func_cnt = env->subprog_cnt;
12557         }
12558         for (i = 0; i < env->subprog_cnt; i++) {
12559                 old_bpf_func = func[i]->bpf_func;
12560                 tmp = bpf_int_jit_compile(func[i]);
12561                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12562                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12563                         err = -ENOTSUPP;
12564                         goto out_free;
12565                 }
12566                 cond_resched();
12567         }
12568
12569         /* finally lock prog and jit images for all functions and
12570          * populate kallsysm
12571          */
12572         for (i = 0; i < env->subprog_cnt; i++) {
12573                 bpf_prog_lock_ro(func[i]);
12574                 bpf_prog_kallsyms_add(func[i]);
12575         }
12576
12577         /* Last step: make now unused interpreter insns from main
12578          * prog consistent for later dump requests, so they can
12579          * later look the same as if they were interpreted only.
12580          */
12581         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12582                 if (bpf_pseudo_func(insn)) {
12583                         insn[0].imm = env->insn_aux_data[i].call_imm;
12584                         insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12585                         continue;
12586                 }
12587                 if (!bpf_pseudo_call(insn))
12588                         continue;
12589                 insn->off = env->insn_aux_data[i].call_imm;
12590                 subprog = find_subprog(env, i + insn->off + 1);
12591                 insn->imm = subprog;
12592         }
12593
12594         prog->jited = 1;
12595         prog->bpf_func = func[0]->bpf_func;
12596         prog->aux->func = func;
12597         prog->aux->func_cnt = env->subprog_cnt;
12598         bpf_prog_jit_attempt_done(prog);
12599         return 0;
12600 out_free:
12601         /* We failed JIT'ing, so at this point we need to unregister poke
12602          * descriptors from subprogs, so that kernel is not attempting to
12603          * patch it anymore as we're freeing the subprog JIT memory.
12604          */
12605         for (i = 0; i < prog->aux->size_poke_tab; i++) {
12606                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12607                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12608         }
12609         /* At this point we're guaranteed that poke descriptors are not
12610          * live anymore. We can just unlink its descriptor table as it's
12611          * released with the main prog.
12612          */
12613         for (i = 0; i < env->subprog_cnt; i++) {
12614                 if (!func[i])
12615                         continue;
12616                 func[i]->aux->poke_tab = NULL;
12617                 bpf_jit_free(func[i]);
12618         }
12619         kfree(func);
12620 out_undo_insn:
12621         /* cleanup main prog to be interpreted */
12622         prog->jit_requested = 0;
12623         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12624                 if (!bpf_pseudo_call(insn))
12625                         continue;
12626                 insn->off = 0;
12627                 insn->imm = env->insn_aux_data[i].call_imm;
12628         }
12629         bpf_prog_jit_attempt_done(prog);
12630         return err;
12631 }
12632
12633 static int fixup_call_args(struct bpf_verifier_env *env)
12634 {
12635 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12636         struct bpf_prog *prog = env->prog;
12637         struct bpf_insn *insn = prog->insnsi;
12638         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12639         int i, depth;
12640 #endif
12641         int err = 0;
12642
12643         if (env->prog->jit_requested &&
12644             !bpf_prog_is_dev_bound(env->prog->aux)) {
12645                 err = jit_subprogs(env);
12646                 if (err == 0)
12647                         return 0;
12648                 if (err == -EFAULT)
12649                         return err;
12650         }
12651 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12652         if (has_kfunc_call) {
12653                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12654                 return -EINVAL;
12655         }
12656         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12657                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12658                  * have to be rejected, since interpreter doesn't support them yet.
12659                  */
12660                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12661                 return -EINVAL;
12662         }
12663         for (i = 0; i < prog->len; i++, insn++) {
12664                 if (bpf_pseudo_func(insn)) {
12665                         /* When JIT fails the progs with callback calls
12666                          * have to be rejected, since interpreter doesn't support them yet.
12667                          */
12668                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
12669                         return -EINVAL;
12670                 }
12671
12672                 if (!bpf_pseudo_call(insn))
12673                         continue;
12674                 depth = get_callee_stack_depth(env, insn, i);
12675                 if (depth < 0)
12676                         return depth;
12677                 bpf_patch_call_args(insn, depth);
12678         }
12679         err = 0;
12680 #endif
12681         return err;
12682 }
12683
12684 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12685                             struct bpf_insn *insn)
12686 {
12687         const struct bpf_kfunc_desc *desc;
12688
12689         /* insn->imm has the btf func_id. Replace it with
12690          * an address (relative to __bpf_base_call).
12691          */
12692         desc = find_kfunc_desc(env->prog, insn->imm);
12693         if (!desc) {
12694                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12695                         insn->imm);
12696                 return -EFAULT;
12697         }
12698
12699         insn->imm = desc->imm;
12700
12701         return 0;
12702 }
12703
12704 /* Do various post-verification rewrites in a single program pass.
12705  * These rewrites simplify JIT and interpreter implementations.
12706  */
12707 static int do_misc_fixups(struct bpf_verifier_env *env)
12708 {
12709         struct bpf_prog *prog = env->prog;
12710         bool expect_blinding = bpf_jit_blinding_enabled(prog);
12711         enum bpf_prog_type prog_type = resolve_prog_type(prog);
12712         struct bpf_insn *insn = prog->insnsi;
12713         const struct bpf_func_proto *fn;
12714         const int insn_cnt = prog->len;
12715         const struct bpf_map_ops *ops;
12716         struct bpf_insn_aux_data *aux;
12717         struct bpf_insn insn_buf[16];
12718         struct bpf_prog *new_prog;
12719         struct bpf_map *map_ptr;
12720         int i, ret, cnt, delta = 0;
12721
12722         for (i = 0; i < insn_cnt; i++, insn++) {
12723                 /* Make divide-by-zero exceptions impossible. */
12724                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12725                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12726                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12727                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12728                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12729                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12730                         struct bpf_insn *patchlet;
12731                         struct bpf_insn chk_and_div[] = {
12732                                 /* [R,W]x div 0 -> 0 */
12733                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12734                                              BPF_JNE | BPF_K, insn->src_reg,
12735                                              0, 2, 0),
12736                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12737                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12738                                 *insn,
12739                         };
12740                         struct bpf_insn chk_and_mod[] = {
12741                                 /* [R,W]x mod 0 -> [R,W]x */
12742                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12743                                              BPF_JEQ | BPF_K, insn->src_reg,
12744                                              0, 1 + (is64 ? 0 : 1), 0),
12745                                 *insn,
12746                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12747                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12748                         };
12749
12750                         patchlet = isdiv ? chk_and_div : chk_and_mod;
12751                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12752                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12753
12754                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12755                         if (!new_prog)
12756                                 return -ENOMEM;
12757
12758                         delta    += cnt - 1;
12759                         env->prog = prog = new_prog;
12760                         insn      = new_prog->insnsi + i + delta;
12761                         continue;
12762                 }
12763
12764                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12765                 if (BPF_CLASS(insn->code) == BPF_LD &&
12766                     (BPF_MODE(insn->code) == BPF_ABS ||
12767                      BPF_MODE(insn->code) == BPF_IND)) {
12768                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
12769                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12770                                 verbose(env, "bpf verifier is misconfigured\n");
12771                                 return -EINVAL;
12772                         }
12773
12774                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12775                         if (!new_prog)
12776                                 return -ENOMEM;
12777
12778                         delta    += cnt - 1;
12779                         env->prog = prog = new_prog;
12780                         insn      = new_prog->insnsi + i + delta;
12781                         continue;
12782                 }
12783
12784                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
12785                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12786                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12787                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12788                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12789                         struct bpf_insn *patch = &insn_buf[0];
12790                         bool issrc, isneg, isimm;
12791                         u32 off_reg;
12792
12793                         aux = &env->insn_aux_data[i + delta];
12794                         if (!aux->alu_state ||
12795                             aux->alu_state == BPF_ALU_NON_POINTER)
12796                                 continue;
12797
12798                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12799                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12800                                 BPF_ALU_SANITIZE_SRC;
12801                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12802
12803                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
12804                         if (isimm) {
12805                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12806                         } else {
12807                                 if (isneg)
12808                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12809                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12810                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12811                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12812                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12813                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12814                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12815                         }
12816                         if (!issrc)
12817                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12818                         insn->src_reg = BPF_REG_AX;
12819                         if (isneg)
12820                                 insn->code = insn->code == code_add ?
12821                                              code_sub : code_add;
12822                         *patch++ = *insn;
12823                         if (issrc && isneg && !isimm)
12824                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12825                         cnt = patch - insn_buf;
12826
12827                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12828                         if (!new_prog)
12829                                 return -ENOMEM;
12830
12831                         delta    += cnt - 1;
12832                         env->prog = prog = new_prog;
12833                         insn      = new_prog->insnsi + i + delta;
12834                         continue;
12835                 }
12836
12837                 if (insn->code != (BPF_JMP | BPF_CALL))
12838                         continue;
12839                 if (insn->src_reg == BPF_PSEUDO_CALL)
12840                         continue;
12841                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12842                         ret = fixup_kfunc_call(env, insn);
12843                         if (ret)
12844                                 return ret;
12845                         continue;
12846                 }
12847
12848                 if (insn->imm == BPF_FUNC_get_route_realm)
12849                         prog->dst_needed = 1;
12850                 if (insn->imm == BPF_FUNC_get_prandom_u32)
12851                         bpf_user_rnd_init_once();
12852                 if (insn->imm == BPF_FUNC_override_return)
12853                         prog->kprobe_override = 1;
12854                 if (insn->imm == BPF_FUNC_tail_call) {
12855                         /* If we tail call into other programs, we
12856                          * cannot make any assumptions since they can
12857                          * be replaced dynamically during runtime in
12858                          * the program array.
12859                          */
12860                         prog->cb_access = 1;
12861                         if (!allow_tail_call_in_subprogs(env))
12862                                 prog->aux->stack_depth = MAX_BPF_STACK;
12863                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
12864
12865                         /* mark bpf_tail_call as different opcode to avoid
12866                          * conditional branch in the interpreter for every normal
12867                          * call and to prevent accidental JITing by JIT compiler
12868                          * that doesn't support bpf_tail_call yet
12869                          */
12870                         insn->imm = 0;
12871                         insn->code = BPF_JMP | BPF_TAIL_CALL;
12872
12873                         aux = &env->insn_aux_data[i + delta];
12874                         if (env->bpf_capable && !expect_blinding &&
12875                             prog->jit_requested &&
12876                             !bpf_map_key_poisoned(aux) &&
12877                             !bpf_map_ptr_poisoned(aux) &&
12878                             !bpf_map_ptr_unpriv(aux)) {
12879                                 struct bpf_jit_poke_descriptor desc = {
12880                                         .reason = BPF_POKE_REASON_TAIL_CALL,
12881                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12882                                         .tail_call.key = bpf_map_key_immediate(aux),
12883                                         .insn_idx = i + delta,
12884                                 };
12885
12886                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12887                                 if (ret < 0) {
12888                                         verbose(env, "adding tail call poke descriptor failed\n");
12889                                         return ret;
12890                                 }
12891
12892                                 insn->imm = ret + 1;
12893                                 continue;
12894                         }
12895
12896                         if (!bpf_map_ptr_unpriv(aux))
12897                                 continue;
12898
12899                         /* instead of changing every JIT dealing with tail_call
12900                          * emit two extra insns:
12901                          * if (index >= max_entries) goto out;
12902                          * index &= array->index_mask;
12903                          * to avoid out-of-bounds cpu speculation
12904                          */
12905                         if (bpf_map_ptr_poisoned(aux)) {
12906                                 verbose(env, "tail_call abusing map_ptr\n");
12907                                 return -EINVAL;
12908                         }
12909
12910                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12911                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12912                                                   map_ptr->max_entries, 2);
12913                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12914                                                     container_of(map_ptr,
12915                                                                  struct bpf_array,
12916                                                                  map)->index_mask);
12917                         insn_buf[2] = *insn;
12918                         cnt = 3;
12919                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12920                         if (!new_prog)
12921                                 return -ENOMEM;
12922
12923                         delta    += cnt - 1;
12924                         env->prog = prog = new_prog;
12925                         insn      = new_prog->insnsi + i + delta;
12926                         continue;
12927                 }
12928
12929                 if (insn->imm == BPF_FUNC_timer_set_callback) {
12930                         /* The verifier will process callback_fn as many times as necessary
12931                          * with different maps and the register states prepared by
12932                          * set_timer_callback_state will be accurate.
12933                          *
12934                          * The following use case is valid:
12935                          *   map1 is shared by prog1, prog2, prog3.
12936                          *   prog1 calls bpf_timer_init for some map1 elements
12937                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
12938                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
12939                          *   prog3 calls bpf_timer_start for some map1 elements.
12940                          *     Those that were not both bpf_timer_init-ed and
12941                          *     bpf_timer_set_callback-ed will return -EINVAL.
12942                          */
12943                         struct bpf_insn ld_addrs[2] = {
12944                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
12945                         };
12946
12947                         insn_buf[0] = ld_addrs[0];
12948                         insn_buf[1] = ld_addrs[1];
12949                         insn_buf[2] = *insn;
12950                         cnt = 3;
12951
12952                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12953                         if (!new_prog)
12954                                 return -ENOMEM;
12955
12956                         delta    += cnt - 1;
12957                         env->prog = prog = new_prog;
12958                         insn      = new_prog->insnsi + i + delta;
12959                         goto patch_call_imm;
12960                 }
12961
12962                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
12963                  * and other inlining handlers are currently limited to 64 bit
12964                  * only.
12965                  */
12966                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12967                     (insn->imm == BPF_FUNC_map_lookup_elem ||
12968                      insn->imm == BPF_FUNC_map_update_elem ||
12969                      insn->imm == BPF_FUNC_map_delete_elem ||
12970                      insn->imm == BPF_FUNC_map_push_elem   ||
12971                      insn->imm == BPF_FUNC_map_pop_elem    ||
12972                      insn->imm == BPF_FUNC_map_peek_elem   ||
12973                      insn->imm == BPF_FUNC_redirect_map)) {
12974                         aux = &env->insn_aux_data[i + delta];
12975                         if (bpf_map_ptr_poisoned(aux))
12976                                 goto patch_call_imm;
12977
12978                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12979                         ops = map_ptr->ops;
12980                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
12981                             ops->map_gen_lookup) {
12982                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
12983                                 if (cnt == -EOPNOTSUPP)
12984                                         goto patch_map_ops_generic;
12985                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12986                                         verbose(env, "bpf verifier is misconfigured\n");
12987                                         return -EINVAL;
12988                                 }
12989
12990                                 new_prog = bpf_patch_insn_data(env, i + delta,
12991                                                                insn_buf, cnt);
12992                                 if (!new_prog)
12993                                         return -ENOMEM;
12994
12995                                 delta    += cnt - 1;
12996                                 env->prog = prog = new_prog;
12997                                 insn      = new_prog->insnsi + i + delta;
12998                                 continue;
12999                         }
13000
13001                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
13002                                      (void *(*)(struct bpf_map *map, void *key))NULL));
13003                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
13004                                      (int (*)(struct bpf_map *map, void *key))NULL));
13005                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
13006                                      (int (*)(struct bpf_map *map, void *key, void *value,
13007                                               u64 flags))NULL));
13008                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
13009                                      (int (*)(struct bpf_map *map, void *value,
13010                                               u64 flags))NULL));
13011                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13012                                      (int (*)(struct bpf_map *map, void *value))NULL));
13013                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13014                                      (int (*)(struct bpf_map *map, void *value))NULL));
13015                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
13016                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
13017
13018 patch_map_ops_generic:
13019                         switch (insn->imm) {
13020                         case BPF_FUNC_map_lookup_elem:
13021                                 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
13022                                             __bpf_call_base;
13023                                 continue;
13024                         case BPF_FUNC_map_update_elem:
13025                                 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
13026                                             __bpf_call_base;
13027                                 continue;
13028                         case BPF_FUNC_map_delete_elem:
13029                                 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
13030                                             __bpf_call_base;
13031                                 continue;
13032                         case BPF_FUNC_map_push_elem:
13033                                 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
13034                                             __bpf_call_base;
13035                                 continue;
13036                         case BPF_FUNC_map_pop_elem:
13037                                 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
13038                                             __bpf_call_base;
13039                                 continue;
13040                         case BPF_FUNC_map_peek_elem:
13041                                 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
13042                                             __bpf_call_base;
13043                                 continue;
13044                         case BPF_FUNC_redirect_map:
13045                                 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
13046                                             __bpf_call_base;
13047                                 continue;
13048                         }
13049
13050                         goto patch_call_imm;
13051                 }
13052
13053                 /* Implement bpf_jiffies64 inline. */
13054                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
13055                     insn->imm == BPF_FUNC_jiffies64) {
13056                         struct bpf_insn ld_jiffies_addr[2] = {
13057                                 BPF_LD_IMM64(BPF_REG_0,
13058                                              (unsigned long)&jiffies),
13059                         };
13060
13061                         insn_buf[0] = ld_jiffies_addr[0];
13062                         insn_buf[1] = ld_jiffies_addr[1];
13063                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13064                                                   BPF_REG_0, 0);
13065                         cnt = 3;
13066
13067                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13068                                                        cnt);
13069                         if (!new_prog)
13070                                 return -ENOMEM;
13071
13072                         delta    += cnt - 1;
13073                         env->prog = prog = new_prog;
13074                         insn      = new_prog->insnsi + i + delta;
13075                         continue;
13076                 }
13077
13078                 /* Implement bpf_get_func_ip inline. */
13079                 if (prog_type == BPF_PROG_TYPE_TRACING &&
13080                     insn->imm == BPF_FUNC_get_func_ip) {
13081                         /* Load IP address from ctx - 8 */
13082                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13083
13084                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13085                         if (!new_prog)
13086                                 return -ENOMEM;
13087
13088                         env->prog = prog = new_prog;
13089                         insn      = new_prog->insnsi + i + delta;
13090                         continue;
13091                 }
13092
13093 patch_call_imm:
13094                 fn = env->ops->get_func_proto(insn->imm, env->prog);
13095                 /* all functions that have prototype and verifier allowed
13096                  * programs to call them, must be real in-kernel functions
13097                  */
13098                 if (!fn->func) {
13099                         verbose(env,
13100                                 "kernel subsystem misconfigured func %s#%d\n",
13101                                 func_id_name(insn->imm), insn->imm);
13102                         return -EFAULT;
13103                 }
13104                 insn->imm = fn->func - __bpf_call_base;
13105         }
13106
13107         /* Since poke tab is now finalized, publish aux to tracker. */
13108         for (i = 0; i < prog->aux->size_poke_tab; i++) {
13109                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13110                 if (!map_ptr->ops->map_poke_track ||
13111                     !map_ptr->ops->map_poke_untrack ||
13112                     !map_ptr->ops->map_poke_run) {
13113                         verbose(env, "bpf verifier is misconfigured\n");
13114                         return -EINVAL;
13115                 }
13116
13117                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13118                 if (ret < 0) {
13119                         verbose(env, "tracking tail call prog failed\n");
13120                         return ret;
13121                 }
13122         }
13123
13124         sort_kfunc_descs_by_imm(env->prog);
13125
13126         return 0;
13127 }
13128
13129 static void free_states(struct bpf_verifier_env *env)
13130 {
13131         struct bpf_verifier_state_list *sl, *sln;
13132         int i;
13133
13134         sl = env->free_list;
13135         while (sl) {
13136                 sln = sl->next;
13137                 free_verifier_state(&sl->state, false);
13138                 kfree(sl);
13139                 sl = sln;
13140         }
13141         env->free_list = NULL;
13142
13143         if (!env->explored_states)
13144                 return;
13145
13146         for (i = 0; i < state_htab_size(env); i++) {
13147                 sl = env->explored_states[i];
13148
13149                 while (sl) {
13150                         sln = sl->next;
13151                         free_verifier_state(&sl->state, false);
13152                         kfree(sl);
13153                         sl = sln;
13154                 }
13155                 env->explored_states[i] = NULL;
13156         }
13157 }
13158
13159 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13160 {
13161         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13162         struct bpf_verifier_state *state;
13163         struct bpf_reg_state *regs;
13164         int ret, i;
13165
13166         env->prev_linfo = NULL;
13167         env->pass_cnt++;
13168
13169         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13170         if (!state)
13171                 return -ENOMEM;
13172         state->curframe = 0;
13173         state->speculative = false;
13174         state->branches = 1;
13175         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13176         if (!state->frame[0]) {
13177                 kfree(state);
13178                 return -ENOMEM;
13179         }
13180         env->cur_state = state;
13181         init_func_state(env, state->frame[0],
13182                         BPF_MAIN_FUNC /* callsite */,
13183                         0 /* frameno */,
13184                         subprog);
13185
13186         regs = state->frame[state->curframe]->regs;
13187         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13188                 ret = btf_prepare_func_args(env, subprog, regs);
13189                 if (ret)
13190                         goto out;
13191                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13192                         if (regs[i].type == PTR_TO_CTX)
13193                                 mark_reg_known_zero(env, regs, i);
13194                         else if (regs[i].type == SCALAR_VALUE)
13195                                 mark_reg_unknown(env, regs, i);
13196                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
13197                                 const u32 mem_size = regs[i].mem_size;
13198
13199                                 mark_reg_known_zero(env, regs, i);
13200                                 regs[i].mem_size = mem_size;
13201                                 regs[i].id = ++env->id_gen;
13202                         }
13203                 }
13204         } else {
13205                 /* 1st arg to a function */
13206                 regs[BPF_REG_1].type = PTR_TO_CTX;
13207                 mark_reg_known_zero(env, regs, BPF_REG_1);
13208                 ret = btf_check_subprog_arg_match(env, subprog, regs);
13209                 if (ret == -EFAULT)
13210                         /* unlikely verifier bug. abort.
13211                          * ret == 0 and ret < 0 are sadly acceptable for
13212                          * main() function due to backward compatibility.
13213                          * Like socket filter program may be written as:
13214                          * int bpf_prog(struct pt_regs *ctx)
13215                          * and never dereference that ctx in the program.
13216                          * 'struct pt_regs' is a type mismatch for socket
13217                          * filter that should be using 'struct __sk_buff'.
13218                          */
13219                         goto out;
13220         }
13221
13222         ret = do_check(env);
13223 out:
13224         /* check for NULL is necessary, since cur_state can be freed inside
13225          * do_check() under memory pressure.
13226          */
13227         if (env->cur_state) {
13228                 free_verifier_state(env->cur_state, true);
13229                 env->cur_state = NULL;
13230         }
13231         while (!pop_stack(env, NULL, NULL, false));
13232         if (!ret && pop_log)
13233                 bpf_vlog_reset(&env->log, 0);
13234         free_states(env);
13235         return ret;
13236 }
13237
13238 /* Verify all global functions in a BPF program one by one based on their BTF.
13239  * All global functions must pass verification. Otherwise the whole program is rejected.
13240  * Consider:
13241  * int bar(int);
13242  * int foo(int f)
13243  * {
13244  *    return bar(f);
13245  * }
13246  * int bar(int b)
13247  * {
13248  *    ...
13249  * }
13250  * foo() will be verified first for R1=any_scalar_value. During verification it
13251  * will be assumed that bar() already verified successfully and call to bar()
13252  * from foo() will be checked for type match only. Later bar() will be verified
13253  * independently to check that it's safe for R1=any_scalar_value.
13254  */
13255 static int do_check_subprogs(struct bpf_verifier_env *env)
13256 {
13257         struct bpf_prog_aux *aux = env->prog->aux;
13258         int i, ret;
13259
13260         if (!aux->func_info)
13261                 return 0;
13262
13263         for (i = 1; i < env->subprog_cnt; i++) {
13264                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13265                         continue;
13266                 env->insn_idx = env->subprog_info[i].start;
13267                 WARN_ON_ONCE(env->insn_idx == 0);
13268                 ret = do_check_common(env, i);
13269                 if (ret) {
13270                         return ret;
13271                 } else if (env->log.level & BPF_LOG_LEVEL) {
13272                         verbose(env,
13273                                 "Func#%d is safe for any args that match its prototype\n",
13274                                 i);
13275                 }
13276         }
13277         return 0;
13278 }
13279
13280 static int do_check_main(struct bpf_verifier_env *env)
13281 {
13282         int ret;
13283
13284         env->insn_idx = 0;
13285         ret = do_check_common(env, 0);
13286         if (!ret)
13287                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13288         return ret;
13289 }
13290
13291
13292 static void print_verification_stats(struct bpf_verifier_env *env)
13293 {
13294         int i;
13295
13296         if (env->log.level & BPF_LOG_STATS) {
13297                 verbose(env, "verification time %lld usec\n",
13298                         div_u64(env->verification_time, 1000));
13299                 verbose(env, "stack depth ");
13300                 for (i = 0; i < env->subprog_cnt; i++) {
13301                         u32 depth = env->subprog_info[i].stack_depth;
13302
13303                         verbose(env, "%d", depth);
13304                         if (i + 1 < env->subprog_cnt)
13305                                 verbose(env, "+");
13306                 }
13307                 verbose(env, "\n");
13308         }
13309         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13310                 "total_states %d peak_states %d mark_read %d\n",
13311                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13312                 env->max_states_per_insn, env->total_states,
13313                 env->peak_states, env->longest_mark_read_walk);
13314 }
13315
13316 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13317 {
13318         const struct btf_type *t, *func_proto;
13319         const struct bpf_struct_ops *st_ops;
13320         const struct btf_member *member;
13321         struct bpf_prog *prog = env->prog;
13322         u32 btf_id, member_idx;
13323         const char *mname;
13324
13325         if (!prog->gpl_compatible) {
13326                 verbose(env, "struct ops programs must have a GPL compatible license\n");
13327                 return -EINVAL;
13328         }
13329
13330         btf_id = prog->aux->attach_btf_id;
13331         st_ops = bpf_struct_ops_find(btf_id);
13332         if (!st_ops) {
13333                 verbose(env, "attach_btf_id %u is not a supported struct\n",
13334                         btf_id);
13335                 return -ENOTSUPP;
13336         }
13337
13338         t = st_ops->type;
13339         member_idx = prog->expected_attach_type;
13340         if (member_idx >= btf_type_vlen(t)) {
13341                 verbose(env, "attach to invalid member idx %u of struct %s\n",
13342                         member_idx, st_ops->name);
13343                 return -EINVAL;
13344         }
13345
13346         member = &btf_type_member(t)[member_idx];
13347         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13348         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13349                                                NULL);
13350         if (!func_proto) {
13351                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13352                         mname, member_idx, st_ops->name);
13353                 return -EINVAL;
13354         }
13355
13356         if (st_ops->check_member) {
13357                 int err = st_ops->check_member(t, member);
13358
13359                 if (err) {
13360                         verbose(env, "attach to unsupported member %s of struct %s\n",
13361                                 mname, st_ops->name);
13362                         return err;
13363                 }
13364         }
13365
13366         prog->aux->attach_func_proto = func_proto;
13367         prog->aux->attach_func_name = mname;
13368         env->ops = st_ops->verifier_ops;
13369
13370         return 0;
13371 }
13372 #define SECURITY_PREFIX "security_"
13373
13374 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13375 {
13376         if (within_error_injection_list(addr) ||
13377             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13378                 return 0;
13379
13380         return -EINVAL;
13381 }
13382
13383 /* list of non-sleepable functions that are otherwise on
13384  * ALLOW_ERROR_INJECTION list
13385  */
13386 BTF_SET_START(btf_non_sleepable_error_inject)
13387 /* Three functions below can be called from sleepable and non-sleepable context.
13388  * Assume non-sleepable from bpf safety point of view.
13389  */
13390 BTF_ID(func, __add_to_page_cache_locked)
13391 BTF_ID(func, should_fail_alloc_page)
13392 BTF_ID(func, should_failslab)
13393 BTF_SET_END(btf_non_sleepable_error_inject)
13394
13395 static int check_non_sleepable_error_inject(u32 btf_id)
13396 {
13397         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13398 }
13399
13400 int bpf_check_attach_target(struct bpf_verifier_log *log,
13401                             const struct bpf_prog *prog,
13402                             const struct bpf_prog *tgt_prog,
13403                             u32 btf_id,
13404                             struct bpf_attach_target_info *tgt_info)
13405 {
13406         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13407         const char prefix[] = "btf_trace_";
13408         int ret = 0, subprog = -1, i;
13409         const struct btf_type *t;
13410         bool conservative = true;
13411         const char *tname;
13412         struct btf *btf;
13413         long addr = 0;
13414
13415         if (!btf_id) {
13416                 bpf_log(log, "Tracing programs must provide btf_id\n");
13417                 return -EINVAL;
13418         }
13419         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13420         if (!btf) {
13421                 bpf_log(log,
13422                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13423                 return -EINVAL;
13424         }
13425         t = btf_type_by_id(btf, btf_id);
13426         if (!t) {
13427                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13428                 return -EINVAL;
13429         }
13430         tname = btf_name_by_offset(btf, t->name_off);
13431         if (!tname) {
13432                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13433                 return -EINVAL;
13434         }
13435         if (tgt_prog) {
13436                 struct bpf_prog_aux *aux = tgt_prog->aux;
13437
13438                 for (i = 0; i < aux->func_info_cnt; i++)
13439                         if (aux->func_info[i].type_id == btf_id) {
13440                                 subprog = i;
13441                                 break;
13442                         }
13443                 if (subprog == -1) {
13444                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
13445                         return -EINVAL;
13446                 }
13447                 conservative = aux->func_info_aux[subprog].unreliable;
13448                 if (prog_extension) {
13449                         if (conservative) {
13450                                 bpf_log(log,
13451                                         "Cannot replace static functions\n");
13452                                 return -EINVAL;
13453                         }
13454                         if (!prog->jit_requested) {
13455                                 bpf_log(log,
13456                                         "Extension programs should be JITed\n");
13457                                 return -EINVAL;
13458                         }
13459                 }
13460                 if (!tgt_prog->jited) {
13461                         bpf_log(log, "Can attach to only JITed progs\n");
13462                         return -EINVAL;
13463                 }
13464                 if (tgt_prog->type == prog->type) {
13465                         /* Cannot fentry/fexit another fentry/fexit program.
13466                          * Cannot attach program extension to another extension.
13467                          * It's ok to attach fentry/fexit to extension program.
13468                          */
13469                         bpf_log(log, "Cannot recursively attach\n");
13470                         return -EINVAL;
13471                 }
13472                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13473                     prog_extension &&
13474                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13475                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13476                         /* Program extensions can extend all program types
13477                          * except fentry/fexit. The reason is the following.
13478                          * The fentry/fexit programs are used for performance
13479                          * analysis, stats and can be attached to any program
13480                          * type except themselves. When extension program is
13481                          * replacing XDP function it is necessary to allow
13482                          * performance analysis of all functions. Both original
13483                          * XDP program and its program extension. Hence
13484                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13485                          * allowed. If extending of fentry/fexit was allowed it
13486                          * would be possible to create long call chain
13487                          * fentry->extension->fentry->extension beyond
13488                          * reasonable stack size. Hence extending fentry is not
13489                          * allowed.
13490                          */
13491                         bpf_log(log, "Cannot extend fentry/fexit\n");
13492                         return -EINVAL;
13493                 }
13494         } else {
13495                 if (prog_extension) {
13496                         bpf_log(log, "Cannot replace kernel functions\n");
13497                         return -EINVAL;
13498                 }
13499         }
13500
13501         switch (prog->expected_attach_type) {
13502         case BPF_TRACE_RAW_TP:
13503                 if (tgt_prog) {
13504                         bpf_log(log,
13505                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13506                         return -EINVAL;
13507                 }
13508                 if (!btf_type_is_typedef(t)) {
13509                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
13510                                 btf_id);
13511                         return -EINVAL;
13512                 }
13513                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13514                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13515                                 btf_id, tname);
13516                         return -EINVAL;
13517                 }
13518                 tname += sizeof(prefix) - 1;
13519                 t = btf_type_by_id(btf, t->type);
13520                 if (!btf_type_is_ptr(t))
13521                         /* should never happen in valid vmlinux build */
13522                         return -EINVAL;
13523                 t = btf_type_by_id(btf, t->type);
13524                 if (!btf_type_is_func_proto(t))
13525                         /* should never happen in valid vmlinux build */
13526                         return -EINVAL;
13527
13528                 break;
13529         case BPF_TRACE_ITER:
13530                 if (!btf_type_is_func(t)) {
13531                         bpf_log(log, "attach_btf_id %u is not a function\n",
13532                                 btf_id);
13533                         return -EINVAL;
13534                 }
13535                 t = btf_type_by_id(btf, t->type);
13536                 if (!btf_type_is_func_proto(t))
13537                         return -EINVAL;
13538                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13539                 if (ret)
13540                         return ret;
13541                 break;
13542         default:
13543                 if (!prog_extension)
13544                         return -EINVAL;
13545                 fallthrough;
13546         case BPF_MODIFY_RETURN:
13547         case BPF_LSM_MAC:
13548         case BPF_TRACE_FENTRY:
13549         case BPF_TRACE_FEXIT:
13550                 if (!btf_type_is_func(t)) {
13551                         bpf_log(log, "attach_btf_id %u is not a function\n",
13552                                 btf_id);
13553                         return -EINVAL;
13554                 }
13555                 if (prog_extension &&
13556                     btf_check_type_match(log, prog, btf, t))
13557                         return -EINVAL;
13558                 t = btf_type_by_id(btf, t->type);
13559                 if (!btf_type_is_func_proto(t))
13560                         return -EINVAL;
13561
13562                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13563                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13564                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13565                         return -EINVAL;
13566
13567                 if (tgt_prog && conservative)
13568                         t = NULL;
13569
13570                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13571                 if (ret < 0)
13572                         return ret;
13573
13574                 if (tgt_prog) {
13575                         if (subprog == 0)
13576                                 addr = (long) tgt_prog->bpf_func;
13577                         else
13578                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13579                 } else {
13580                         addr = kallsyms_lookup_name(tname);
13581                         if (!addr) {
13582                                 bpf_log(log,
13583                                         "The address of function %s cannot be found\n",
13584                                         tname);
13585                                 return -ENOENT;
13586                         }
13587                 }
13588
13589                 if (prog->aux->sleepable) {
13590                         ret = -EINVAL;
13591                         switch (prog->type) {
13592                         case BPF_PROG_TYPE_TRACING:
13593                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13594                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13595                                  */
13596                                 if (!check_non_sleepable_error_inject(btf_id) &&
13597                                     within_error_injection_list(addr))
13598                                         ret = 0;
13599                                 break;
13600                         case BPF_PROG_TYPE_LSM:
13601                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13602                                  * Only some of them are sleepable.
13603                                  */
13604                                 if (bpf_lsm_is_sleepable_hook(btf_id))
13605                                         ret = 0;
13606                                 break;
13607                         default:
13608                                 break;
13609                         }
13610                         if (ret) {
13611                                 bpf_log(log, "%s is not sleepable\n", tname);
13612                                 return ret;
13613                         }
13614                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13615                         if (tgt_prog) {
13616                                 bpf_log(log, "can't modify return codes of BPF programs\n");
13617                                 return -EINVAL;
13618                         }
13619                         ret = check_attach_modify_return(addr, tname);
13620                         if (ret) {
13621                                 bpf_log(log, "%s() is not modifiable\n", tname);
13622                                 return ret;
13623                         }
13624                 }
13625
13626                 break;
13627         }
13628         tgt_info->tgt_addr = addr;
13629         tgt_info->tgt_name = tname;
13630         tgt_info->tgt_type = t;
13631         return 0;
13632 }
13633
13634 BTF_SET_START(btf_id_deny)
13635 BTF_ID_UNUSED
13636 #ifdef CONFIG_SMP
13637 BTF_ID(func, migrate_disable)
13638 BTF_ID(func, migrate_enable)
13639 #endif
13640 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13641 BTF_ID(func, rcu_read_unlock_strict)
13642 #endif
13643 BTF_SET_END(btf_id_deny)
13644
13645 static int check_attach_btf_id(struct bpf_verifier_env *env)
13646 {
13647         struct bpf_prog *prog = env->prog;
13648         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13649         struct bpf_attach_target_info tgt_info = {};
13650         u32 btf_id = prog->aux->attach_btf_id;
13651         struct bpf_trampoline *tr;
13652         int ret;
13653         u64 key;
13654
13655         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13656                 if (prog->aux->sleepable)
13657                         /* attach_btf_id checked to be zero already */
13658                         return 0;
13659                 verbose(env, "Syscall programs can only be sleepable\n");
13660                 return -EINVAL;
13661         }
13662
13663         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13664             prog->type != BPF_PROG_TYPE_LSM) {
13665                 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13666                 return -EINVAL;
13667         }
13668
13669         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13670                 return check_struct_ops_btf_id(env);
13671
13672         if (prog->type != BPF_PROG_TYPE_TRACING &&
13673             prog->type != BPF_PROG_TYPE_LSM &&
13674             prog->type != BPF_PROG_TYPE_EXT)
13675                 return 0;
13676
13677         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13678         if (ret)
13679                 return ret;
13680
13681         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13682                 /* to make freplace equivalent to their targets, they need to
13683                  * inherit env->ops and expected_attach_type for the rest of the
13684                  * verification
13685                  */
13686                 env->ops = bpf_verifier_ops[tgt_prog->type];
13687                 prog->expected_attach_type = tgt_prog->expected_attach_type;
13688         }
13689
13690         /* store info about the attachment target that will be used later */
13691         prog->aux->attach_func_proto = tgt_info.tgt_type;
13692         prog->aux->attach_func_name = tgt_info.tgt_name;
13693
13694         if (tgt_prog) {
13695                 prog->aux->saved_dst_prog_type = tgt_prog->type;
13696                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13697         }
13698
13699         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13700                 prog->aux->attach_btf_trace = true;
13701                 return 0;
13702         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13703                 if (!bpf_iter_prog_supported(prog))
13704                         return -EINVAL;
13705                 return 0;
13706         }
13707
13708         if (prog->type == BPF_PROG_TYPE_LSM) {
13709                 ret = bpf_lsm_verify_prog(&env->log, prog);
13710                 if (ret < 0)
13711                         return ret;
13712         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
13713                    btf_id_set_contains(&btf_id_deny, btf_id)) {
13714                 return -EINVAL;
13715         }
13716
13717         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13718         tr = bpf_trampoline_get(key, &tgt_info);
13719         if (!tr)
13720                 return -ENOMEM;
13721
13722         prog->aux->dst_trampoline = tr;
13723         return 0;
13724 }
13725
13726 struct btf *bpf_get_btf_vmlinux(void)
13727 {
13728         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13729                 mutex_lock(&bpf_verifier_lock);
13730                 if (!btf_vmlinux)
13731                         btf_vmlinux = btf_parse_vmlinux();
13732                 mutex_unlock(&bpf_verifier_lock);
13733         }
13734         return btf_vmlinux;
13735 }
13736
13737 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
13738 {
13739         u64 start_time = ktime_get_ns();
13740         struct bpf_verifier_env *env;
13741         struct bpf_verifier_log *log;
13742         int i, len, ret = -EINVAL;
13743         bool is_priv;
13744
13745         /* no program is valid */
13746         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13747                 return -EINVAL;
13748
13749         /* 'struct bpf_verifier_env' can be global, but since it's not small,
13750          * allocate/free it every time bpf_check() is called
13751          */
13752         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13753         if (!env)
13754                 return -ENOMEM;
13755         log = &env->log;
13756
13757         len = (*prog)->len;
13758         env->insn_aux_data =
13759                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13760         ret = -ENOMEM;
13761         if (!env->insn_aux_data)
13762                 goto err_free_env;
13763         for (i = 0; i < len; i++)
13764                 env->insn_aux_data[i].orig_idx = i;
13765         env->prog = *prog;
13766         env->ops = bpf_verifier_ops[env->prog->type];
13767         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
13768         is_priv = bpf_capable();
13769
13770         bpf_get_btf_vmlinux();
13771
13772         /* grab the mutex to protect few globals used by verifier */
13773         if (!is_priv)
13774                 mutex_lock(&bpf_verifier_lock);
13775
13776         if (attr->log_level || attr->log_buf || attr->log_size) {
13777                 /* user requested verbose verifier output
13778                  * and supplied buffer to store the verification trace
13779                  */
13780                 log->level = attr->log_level;
13781                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13782                 log->len_total = attr->log_size;
13783
13784                 /* log attributes have to be sane */
13785                 if (!bpf_verifier_log_attr_valid(log)) {
13786                         ret = -EINVAL;
13787                         goto err_unlock;
13788                 }
13789         }
13790
13791         if (IS_ERR(btf_vmlinux)) {
13792                 /* Either gcc or pahole or kernel are broken. */
13793                 verbose(env, "in-kernel BTF is malformed\n");
13794                 ret = PTR_ERR(btf_vmlinux);
13795                 goto skip_full_check;
13796         }
13797
13798         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13799         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13800                 env->strict_alignment = true;
13801         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13802                 env->strict_alignment = false;
13803
13804         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13805         env->allow_uninit_stack = bpf_allow_uninit_stack();
13806         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13807         env->bypass_spec_v1 = bpf_bypass_spec_v1();
13808         env->bypass_spec_v4 = bpf_bypass_spec_v4();
13809         env->bpf_capable = bpf_capable();
13810
13811         if (is_priv)
13812                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13813
13814         env->explored_states = kvcalloc(state_htab_size(env),
13815                                        sizeof(struct bpf_verifier_state_list *),
13816                                        GFP_USER);
13817         ret = -ENOMEM;
13818         if (!env->explored_states)
13819                 goto skip_full_check;
13820
13821         ret = add_subprog_and_kfunc(env);
13822         if (ret < 0)
13823                 goto skip_full_check;
13824
13825         ret = check_subprogs(env);
13826         if (ret < 0)
13827                 goto skip_full_check;
13828
13829         ret = check_btf_info(env, attr, uattr);
13830         if (ret < 0)
13831                 goto skip_full_check;
13832
13833         ret = check_attach_btf_id(env);
13834         if (ret)
13835                 goto skip_full_check;
13836
13837         ret = resolve_pseudo_ldimm64(env);
13838         if (ret < 0)
13839                 goto skip_full_check;
13840
13841         if (bpf_prog_is_dev_bound(env->prog->aux)) {
13842                 ret = bpf_prog_offload_verifier_prep(env->prog);
13843                 if (ret)
13844                         goto skip_full_check;
13845         }
13846
13847         ret = check_cfg(env);
13848         if (ret < 0)
13849                 goto skip_full_check;
13850
13851         ret = do_check_subprogs(env);
13852         ret = ret ?: do_check_main(env);
13853
13854         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13855                 ret = bpf_prog_offload_finalize(env);
13856
13857 skip_full_check:
13858         kvfree(env->explored_states);
13859
13860         if (ret == 0)
13861                 ret = check_max_stack_depth(env);
13862
13863         /* instruction rewrites happen after this point */
13864         if (is_priv) {
13865                 if (ret == 0)
13866                         opt_hard_wire_dead_code_branches(env);
13867                 if (ret == 0)
13868                         ret = opt_remove_dead_code(env);
13869                 if (ret == 0)
13870                         ret = opt_remove_nops(env);
13871         } else {
13872                 if (ret == 0)
13873                         sanitize_dead_code(env);
13874         }
13875
13876         if (ret == 0)
13877                 /* program is valid, convert *(u32*)(ctx + off) accesses */
13878                 ret = convert_ctx_accesses(env);
13879
13880         if (ret == 0)
13881                 ret = do_misc_fixups(env);
13882
13883         /* do 32-bit optimization after insn patching has done so those patched
13884          * insns could be handled correctly.
13885          */
13886         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13887                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13888                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13889                                                                      : false;
13890         }
13891
13892         if (ret == 0)
13893                 ret = fixup_call_args(env);
13894
13895         env->verification_time = ktime_get_ns() - start_time;
13896         print_verification_stats(env);
13897
13898         if (log->level && bpf_verifier_log_full(log))
13899                 ret = -ENOSPC;
13900         if (log->level && !log->ubuf) {
13901                 ret = -EFAULT;
13902                 goto err_release_maps;
13903         }
13904
13905         if (ret)
13906                 goto err_release_maps;
13907
13908         if (env->used_map_cnt) {
13909                 /* if program passed verifier, update used_maps in bpf_prog_info */
13910                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13911                                                           sizeof(env->used_maps[0]),
13912                                                           GFP_KERNEL);
13913
13914                 if (!env->prog->aux->used_maps) {
13915                         ret = -ENOMEM;
13916                         goto err_release_maps;
13917                 }
13918
13919                 memcpy(env->prog->aux->used_maps, env->used_maps,
13920                        sizeof(env->used_maps[0]) * env->used_map_cnt);
13921                 env->prog->aux->used_map_cnt = env->used_map_cnt;
13922         }
13923         if (env->used_btf_cnt) {
13924                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13925                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13926                                                           sizeof(env->used_btfs[0]),
13927                                                           GFP_KERNEL);
13928                 if (!env->prog->aux->used_btfs) {
13929                         ret = -ENOMEM;
13930                         goto err_release_maps;
13931                 }
13932
13933                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13934                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13935                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13936         }
13937         if (env->used_map_cnt || env->used_btf_cnt) {
13938                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13939                  * bpf_ld_imm64 instructions
13940                  */
13941                 convert_pseudo_ld_imm64(env);
13942         }
13943
13944         adjust_btf_func(env);
13945
13946 err_release_maps:
13947         if (!env->prog->aux->used_maps)
13948                 /* if we didn't copy map pointers into bpf_prog_info, release
13949                  * them now. Otherwise free_used_maps() will release them.
13950                  */
13951                 release_maps(env);
13952         if (!env->prog->aux->used_btfs)
13953                 release_btfs(env);
13954
13955         /* extension progs temporarily inherit the attach_type of their targets
13956            for verification purposes, so set it back to zero before returning
13957          */
13958         if (env->prog->type == BPF_PROG_TYPE_EXT)
13959                 env->prog->expected_attach_type = 0;
13960
13961         *prog = env->prog;
13962 err_unlock:
13963         if (!is_priv)
13964                 mutex_unlock(&bpf_verifier_lock);
13965         vfree(env->insn_aux_data);
13966 err_free_env:
13967         kfree(env);
13968         return ret;
13969 }