drm/vc4: hdmi: Fix hotplug extcon uevent to works
[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 struct bpf_call_arg_meta {
244         struct bpf_map *map_ptr;
245         bool raw_mode;
246         bool pkt_access;
247         int regno;
248         int access_size;
249         int mem_size;
250         u64 msize_max_value;
251         int ref_obj_id;
252         int map_uid;
253         int func_id;
254         struct btf *btf;
255         u32 btf_id;
256         struct btf *ret_btf;
257         u32 ret_btf_id;
258         u32 subprogno;
259 };
260
261 struct btf *btf_vmlinux;
262
263 static DEFINE_MUTEX(bpf_verifier_lock);
264
265 static const struct bpf_line_info *
266 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
267 {
268         const struct bpf_line_info *linfo;
269         const struct bpf_prog *prog;
270         u32 i, nr_linfo;
271
272         prog = env->prog;
273         nr_linfo = prog->aux->nr_linfo;
274
275         if (!nr_linfo || insn_off >= prog->len)
276                 return NULL;
277
278         linfo = prog->aux->linfo;
279         for (i = 1; i < nr_linfo; i++)
280                 if (insn_off < linfo[i].insn_off)
281                         break;
282
283         return &linfo[i - 1];
284 }
285
286 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
287                        va_list args)
288 {
289         unsigned int n;
290
291         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
292
293         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
294                   "verifier log line truncated - local buffer too short\n");
295
296         n = min(log->len_total - log->len_used - 1, n);
297         log->kbuf[n] = '\0';
298
299         if (log->level == BPF_LOG_KERNEL) {
300                 pr_err("BPF:%s\n", log->kbuf);
301                 return;
302         }
303         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
304                 log->len_used += n;
305         else
306                 log->ubuf = NULL;
307 }
308
309 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
310 {
311         char zero = 0;
312
313         if (!bpf_verifier_log_needed(log))
314                 return;
315
316         log->len_used = new_pos;
317         if (put_user(zero, log->ubuf + new_pos))
318                 log->ubuf = NULL;
319 }
320
321 /* log_level controls verbosity level of eBPF verifier.
322  * bpf_verifier_log_write() is used to dump the verification trace to the log,
323  * so the user can figure out what's wrong with the program
324  */
325 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
326                                            const char *fmt, ...)
327 {
328         va_list args;
329
330         if (!bpf_verifier_log_needed(&env->log))
331                 return;
332
333         va_start(args, fmt);
334         bpf_verifier_vlog(&env->log, fmt, args);
335         va_end(args);
336 }
337 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
338
339 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
340 {
341         struct bpf_verifier_env *env = private_data;
342         va_list args;
343
344         if (!bpf_verifier_log_needed(&env->log))
345                 return;
346
347         va_start(args, fmt);
348         bpf_verifier_vlog(&env->log, fmt, args);
349         va_end(args);
350 }
351
352 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
353                             const char *fmt, ...)
354 {
355         va_list args;
356
357         if (!bpf_verifier_log_needed(log))
358                 return;
359
360         va_start(args, fmt);
361         bpf_verifier_vlog(log, fmt, args);
362         va_end(args);
363 }
364
365 static const char *ltrim(const char *s)
366 {
367         while (isspace(*s))
368                 s++;
369
370         return s;
371 }
372
373 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
374                                          u32 insn_off,
375                                          const char *prefix_fmt, ...)
376 {
377         const struct bpf_line_info *linfo;
378
379         if (!bpf_verifier_log_needed(&env->log))
380                 return;
381
382         linfo = find_linfo(env, insn_off);
383         if (!linfo || linfo == env->prev_linfo)
384                 return;
385
386         if (prefix_fmt) {
387                 va_list args;
388
389                 va_start(args, prefix_fmt);
390                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
391                 va_end(args);
392         }
393
394         verbose(env, "%s\n",
395                 ltrim(btf_name_by_offset(env->prog->aux->btf,
396                                          linfo->line_off)));
397
398         env->prev_linfo = linfo;
399 }
400
401 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
402                                    struct bpf_reg_state *reg,
403                                    struct tnum *range, const char *ctx,
404                                    const char *reg_name)
405 {
406         char tn_buf[48];
407
408         verbose(env, "At %s the register %s ", ctx, reg_name);
409         if (!tnum_is_unknown(reg->var_off)) {
410                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
411                 verbose(env, "has value %s", tn_buf);
412         } else {
413                 verbose(env, "has unknown scalar value");
414         }
415         tnum_strn(tn_buf, sizeof(tn_buf), *range);
416         verbose(env, " should have been in %s\n", tn_buf);
417 }
418
419 static bool type_is_pkt_pointer(enum bpf_reg_type type)
420 {
421         return type == PTR_TO_PACKET ||
422                type == PTR_TO_PACKET_META;
423 }
424
425 static bool type_is_sk_pointer(enum bpf_reg_type type)
426 {
427         return type == PTR_TO_SOCKET ||
428                 type == PTR_TO_SOCK_COMMON ||
429                 type == PTR_TO_TCP_SOCK ||
430                 type == PTR_TO_XDP_SOCK;
431 }
432
433 static bool reg_type_not_null(enum bpf_reg_type type)
434 {
435         return type == PTR_TO_SOCKET ||
436                 type == PTR_TO_TCP_SOCK ||
437                 type == PTR_TO_MAP_VALUE ||
438                 type == PTR_TO_MAP_KEY ||
439                 type == PTR_TO_SOCK_COMMON;
440 }
441
442 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
443 {
444         return reg->type == PTR_TO_MAP_VALUE &&
445                 map_value_has_spin_lock(reg->map_ptr);
446 }
447
448 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
449 {
450         return base_type(type) == PTR_TO_SOCKET ||
451                 base_type(type) == PTR_TO_TCP_SOCK ||
452                 base_type(type) == PTR_TO_MEM;
453 }
454
455 static bool type_is_rdonly_mem(u32 type)
456 {
457         return type & MEM_RDONLY;
458 }
459
460 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
461 {
462         return type == ARG_PTR_TO_SOCK_COMMON;
463 }
464
465 static bool type_may_be_null(u32 type)
466 {
467         return type & PTR_MAYBE_NULL;
468 }
469
470 /* Determine whether the function releases some resources allocated by another
471  * function call. The first reference type argument will be assumed to be
472  * released by release_reference().
473  */
474 static bool is_release_function(enum bpf_func_id func_id)
475 {
476         return func_id == BPF_FUNC_sk_release ||
477                func_id == BPF_FUNC_ringbuf_submit ||
478                func_id == BPF_FUNC_ringbuf_discard;
479 }
480
481 static bool may_be_acquire_function(enum bpf_func_id func_id)
482 {
483         return func_id == BPF_FUNC_sk_lookup_tcp ||
484                 func_id == BPF_FUNC_sk_lookup_udp ||
485                 func_id == BPF_FUNC_skc_lookup_tcp ||
486                 func_id == BPF_FUNC_map_lookup_elem ||
487                 func_id == BPF_FUNC_ringbuf_reserve;
488 }
489
490 static bool is_acquire_function(enum bpf_func_id func_id,
491                                 const struct bpf_map *map)
492 {
493         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
494
495         if (func_id == BPF_FUNC_sk_lookup_tcp ||
496             func_id == BPF_FUNC_sk_lookup_udp ||
497             func_id == BPF_FUNC_skc_lookup_tcp ||
498             func_id == BPF_FUNC_ringbuf_reserve)
499                 return true;
500
501         if (func_id == BPF_FUNC_map_lookup_elem &&
502             (map_type == BPF_MAP_TYPE_SOCKMAP ||
503              map_type == BPF_MAP_TYPE_SOCKHASH))
504                 return true;
505
506         return false;
507 }
508
509 static bool is_ptr_cast_function(enum bpf_func_id func_id)
510 {
511         return func_id == BPF_FUNC_tcp_sock ||
512                 func_id == BPF_FUNC_sk_fullsock ||
513                 func_id == BPF_FUNC_skc_to_tcp_sock ||
514                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
515                 func_id == BPF_FUNC_skc_to_udp6_sock ||
516                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
517                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
518 }
519
520 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
521 {
522         return BPF_CLASS(insn->code) == BPF_STX &&
523                BPF_MODE(insn->code) == BPF_ATOMIC &&
524                insn->imm == BPF_CMPXCHG;
525 }
526
527 /* string representation of 'enum bpf_reg_type'
528  *
529  * Note that reg_type_str() can not appear more than once in a single verbose()
530  * statement.
531  */
532 static const char *reg_type_str(struct bpf_verifier_env *env,
533                                 enum bpf_reg_type type)
534 {
535         char postfix[16] = {0}, prefix[16] = {0};
536         static const char * const str[] = {
537                 [NOT_INIT]              = "?",
538                 [SCALAR_VALUE]          = "inv",
539                 [PTR_TO_CTX]            = "ctx",
540                 [CONST_PTR_TO_MAP]      = "map_ptr",
541                 [PTR_TO_MAP_VALUE]      = "map_value",
542                 [PTR_TO_STACK]          = "fp",
543                 [PTR_TO_PACKET]         = "pkt",
544                 [PTR_TO_PACKET_META]    = "pkt_meta",
545                 [PTR_TO_PACKET_END]     = "pkt_end",
546                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
547                 [PTR_TO_SOCKET]         = "sock",
548                 [PTR_TO_SOCK_COMMON]    = "sock_common",
549                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
550                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
551                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
552                 [PTR_TO_BTF_ID]         = "ptr_",
553                 [PTR_TO_PERCPU_BTF_ID]  = "percpu_ptr_",
554                 [PTR_TO_MEM]            = "mem",
555                 [PTR_TO_BUF]            = "buf",
556                 [PTR_TO_FUNC]           = "func",
557                 [PTR_TO_MAP_KEY]        = "map_key",
558         };
559
560         if (type & PTR_MAYBE_NULL) {
561                 if (base_type(type) == PTR_TO_BTF_ID ||
562                     base_type(type) == PTR_TO_PERCPU_BTF_ID)
563                         strncpy(postfix, "or_null_", 16);
564                 else
565                         strncpy(postfix, "_or_null", 16);
566         }
567
568         if (type & MEM_RDONLY)
569                 strncpy(prefix, "rdonly_", 16);
570
571         snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
572                  prefix, str[base_type(type)], postfix);
573         return env->type_str_buf;
574 }
575
576 static char slot_type_char[] = {
577         [STACK_INVALID] = '?',
578         [STACK_SPILL]   = 'r',
579         [STACK_MISC]    = 'm',
580         [STACK_ZERO]    = '0',
581 };
582
583 static void print_liveness(struct bpf_verifier_env *env,
584                            enum bpf_reg_liveness live)
585 {
586         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
587             verbose(env, "_");
588         if (live & REG_LIVE_READ)
589                 verbose(env, "r");
590         if (live & REG_LIVE_WRITTEN)
591                 verbose(env, "w");
592         if (live & REG_LIVE_DONE)
593                 verbose(env, "D");
594 }
595
596 static struct bpf_func_state *func(struct bpf_verifier_env *env,
597                                    const struct bpf_reg_state *reg)
598 {
599         struct bpf_verifier_state *cur = env->cur_state;
600
601         return cur->frame[reg->frameno];
602 }
603
604 static const char *kernel_type_name(const struct btf* btf, u32 id)
605 {
606         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
607 }
608
609 static void print_verifier_state(struct bpf_verifier_env *env,
610                                  const struct bpf_func_state *state)
611 {
612         const struct bpf_reg_state *reg;
613         enum bpf_reg_type t;
614         int i;
615
616         if (state->frameno)
617                 verbose(env, " frame%d:", state->frameno);
618         for (i = 0; i < MAX_BPF_REG; i++) {
619                 reg = &state->regs[i];
620                 t = reg->type;
621                 if (t == NOT_INIT)
622                         continue;
623                 verbose(env, " R%d", i);
624                 print_liveness(env, reg->live);
625                 verbose(env, "=%s", reg_type_str(env, t));
626                 if (t == SCALAR_VALUE && reg->precise)
627                         verbose(env, "P");
628                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
629                     tnum_is_const(reg->var_off)) {
630                         /* reg->off should be 0 for SCALAR_VALUE */
631                         verbose(env, "%lld", reg->var_off.value + reg->off);
632                 } else {
633                         if (base_type(t) == PTR_TO_BTF_ID ||
634                             base_type(t) == PTR_TO_PERCPU_BTF_ID)
635                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
636                         verbose(env, "(id=%d", reg->id);
637                         if (reg_type_may_be_refcounted_or_null(t))
638                                 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
639                         if (t != SCALAR_VALUE)
640                                 verbose(env, ",off=%d", reg->off);
641                         if (type_is_pkt_pointer(t))
642                                 verbose(env, ",r=%d", reg->range);
643                         else if (base_type(t) == CONST_PTR_TO_MAP ||
644                                  base_type(t) == PTR_TO_MAP_KEY ||
645                                  base_type(t) == PTR_TO_MAP_VALUE)
646                                 verbose(env, ",ks=%d,vs=%d",
647                                         reg->map_ptr->key_size,
648                                         reg->map_ptr->value_size);
649                         if (tnum_is_const(reg->var_off)) {
650                                 /* Typically an immediate SCALAR_VALUE, but
651                                  * could be a pointer whose offset is too big
652                                  * for reg->off
653                                  */
654                                 verbose(env, ",imm=%llx", reg->var_off.value);
655                         } else {
656                                 if (reg->smin_value != reg->umin_value &&
657                                     reg->smin_value != S64_MIN)
658                                         verbose(env, ",smin_value=%lld",
659                                                 (long long)reg->smin_value);
660                                 if (reg->smax_value != reg->umax_value &&
661                                     reg->smax_value != S64_MAX)
662                                         verbose(env, ",smax_value=%lld",
663                                                 (long long)reg->smax_value);
664                                 if (reg->umin_value != 0)
665                                         verbose(env, ",umin_value=%llu",
666                                                 (unsigned long long)reg->umin_value);
667                                 if (reg->umax_value != U64_MAX)
668                                         verbose(env, ",umax_value=%llu",
669                                                 (unsigned long long)reg->umax_value);
670                                 if (!tnum_is_unknown(reg->var_off)) {
671                                         char tn_buf[48];
672
673                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
674                                         verbose(env, ",var_off=%s", tn_buf);
675                                 }
676                                 if (reg->s32_min_value != reg->smin_value &&
677                                     reg->s32_min_value != S32_MIN)
678                                         verbose(env, ",s32_min_value=%d",
679                                                 (int)(reg->s32_min_value));
680                                 if (reg->s32_max_value != reg->smax_value &&
681                                     reg->s32_max_value != S32_MAX)
682                                         verbose(env, ",s32_max_value=%d",
683                                                 (int)(reg->s32_max_value));
684                                 if (reg->u32_min_value != reg->umin_value &&
685                                     reg->u32_min_value != U32_MIN)
686                                         verbose(env, ",u32_min_value=%d",
687                                                 (int)(reg->u32_min_value));
688                                 if (reg->u32_max_value != reg->umax_value &&
689                                     reg->u32_max_value != U32_MAX)
690                                         verbose(env, ",u32_max_value=%d",
691                                                 (int)(reg->u32_max_value));
692                         }
693                         verbose(env, ")");
694                 }
695         }
696         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
697                 char types_buf[BPF_REG_SIZE + 1];
698                 bool valid = false;
699                 int j;
700
701                 for (j = 0; j < BPF_REG_SIZE; j++) {
702                         if (state->stack[i].slot_type[j] != STACK_INVALID)
703                                 valid = true;
704                         types_buf[j] = slot_type_char[
705                                         state->stack[i].slot_type[j]];
706                 }
707                 types_buf[BPF_REG_SIZE] = 0;
708                 if (!valid)
709                         continue;
710                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
711                 print_liveness(env, state->stack[i].spilled_ptr.live);
712                 if (state->stack[i].slot_type[0] == STACK_SPILL) {
713                         reg = &state->stack[i].spilled_ptr;
714                         t = reg->type;
715                         verbose(env, "=%s", reg_type_str(env, t));
716                         if (t == SCALAR_VALUE && reg->precise)
717                                 verbose(env, "P");
718                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
719                                 verbose(env, "%lld", reg->var_off.value + reg->off);
720                 } else {
721                         verbose(env, "=%s", types_buf);
722                 }
723         }
724         if (state->acquired_refs && state->refs[0].id) {
725                 verbose(env, " refs=%d", state->refs[0].id);
726                 for (i = 1; i < state->acquired_refs; i++)
727                         if (state->refs[i].id)
728                                 verbose(env, ",%d", state->refs[i].id);
729         }
730         if (state->in_callback_fn)
731                 verbose(env, " cb");
732         if (state->in_async_callback_fn)
733                 verbose(env, " async_cb");
734         verbose(env, "\n");
735 }
736
737 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
738  * small to hold src. This is different from krealloc since we don't want to preserve
739  * the contents of dst.
740  *
741  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
742  * not be allocated.
743  */
744 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
745 {
746         size_t bytes;
747
748         if (ZERO_OR_NULL_PTR(src))
749                 goto out;
750
751         if (unlikely(check_mul_overflow(n, size, &bytes)))
752                 return NULL;
753
754         if (ksize(dst) < bytes) {
755                 kfree(dst);
756                 dst = kmalloc_track_caller(bytes, flags);
757                 if (!dst)
758                         return NULL;
759         }
760
761         memcpy(dst, src, bytes);
762 out:
763         return dst ? dst : ZERO_SIZE_PTR;
764 }
765
766 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
767  * small to hold new_n items. new items are zeroed out if the array grows.
768  *
769  * Contrary to krealloc_array, does not free arr if new_n is zero.
770  */
771 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
772 {
773         void *new_arr;
774
775         if (!new_n || old_n == new_n)
776                 goto out;
777
778         new_arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
779         if (!new_arr) {
780                 kfree(arr);
781                 return NULL;
782         }
783         arr = new_arr;
784
785         if (new_n > old_n)
786                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
787
788 out:
789         return arr ? arr : ZERO_SIZE_PTR;
790 }
791
792 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
793 {
794         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
795                                sizeof(struct bpf_reference_state), GFP_KERNEL);
796         if (!dst->refs)
797                 return -ENOMEM;
798
799         dst->acquired_refs = src->acquired_refs;
800         return 0;
801 }
802
803 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
804 {
805         size_t n = src->allocated_stack / BPF_REG_SIZE;
806
807         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
808                                 GFP_KERNEL);
809         if (!dst->stack)
810                 return -ENOMEM;
811
812         dst->allocated_stack = src->allocated_stack;
813         return 0;
814 }
815
816 static int resize_reference_state(struct bpf_func_state *state, size_t n)
817 {
818         state->refs = realloc_array(state->refs, state->acquired_refs, n,
819                                     sizeof(struct bpf_reference_state));
820         if (!state->refs)
821                 return -ENOMEM;
822
823         state->acquired_refs = n;
824         return 0;
825 }
826
827 static int grow_stack_state(struct bpf_func_state *state, int size)
828 {
829         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
830
831         if (old_n >= n)
832                 return 0;
833
834         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
835         if (!state->stack)
836                 return -ENOMEM;
837
838         state->allocated_stack = size;
839         return 0;
840 }
841
842 /* Acquire a pointer id from the env and update the state->refs to include
843  * this new pointer reference.
844  * On success, returns a valid pointer id to associate with the register
845  * On failure, returns a negative errno.
846  */
847 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
848 {
849         struct bpf_func_state *state = cur_func(env);
850         int new_ofs = state->acquired_refs;
851         int id, err;
852
853         err = resize_reference_state(state, state->acquired_refs + 1);
854         if (err)
855                 return err;
856         id = ++env->id_gen;
857         state->refs[new_ofs].id = id;
858         state->refs[new_ofs].insn_idx = insn_idx;
859         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
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                         /* Cannot release caller references in callbacks */
873                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
874                                 return -EINVAL;
875                         if (last_idx && i != last_idx)
876                                 memcpy(&state->refs[i], &state->refs[last_idx],
877                                        sizeof(*state->refs));
878                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
879                         state->acquired_refs--;
880                         return 0;
881                 }
882         }
883         return -EINVAL;
884 }
885
886 static void free_func_state(struct bpf_func_state *state)
887 {
888         if (!state)
889                 return;
890         kfree(state->refs);
891         kfree(state->stack);
892         kfree(state);
893 }
894
895 static void clear_jmp_history(struct bpf_verifier_state *state)
896 {
897         kfree(state->jmp_history);
898         state->jmp_history = NULL;
899         state->jmp_history_cnt = 0;
900 }
901
902 static void free_verifier_state(struct bpf_verifier_state *state,
903                                 bool free_self)
904 {
905         int i;
906
907         for (i = 0; i <= state->curframe; i++) {
908                 free_func_state(state->frame[i]);
909                 state->frame[i] = NULL;
910         }
911         clear_jmp_history(state);
912         if (free_self)
913                 kfree(state);
914 }
915
916 /* copy verifier state from src to dst growing dst stack space
917  * when necessary to accommodate larger src stack
918  */
919 static int copy_func_state(struct bpf_func_state *dst,
920                            const struct bpf_func_state *src)
921 {
922         int err;
923
924         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
925         err = copy_reference_state(dst, src);
926         if (err)
927                 return err;
928         return copy_stack_state(dst, src);
929 }
930
931 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
932                                const struct bpf_verifier_state *src)
933 {
934         struct bpf_func_state *dst;
935         int i, err;
936
937         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
938                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
939                                             GFP_USER);
940         if (!dst_state->jmp_history)
941                 return -ENOMEM;
942         dst_state->jmp_history_cnt = src->jmp_history_cnt;
943
944         /* if dst has more stack frames then src frame, free them */
945         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
946                 free_func_state(dst_state->frame[i]);
947                 dst_state->frame[i] = NULL;
948         }
949         dst_state->speculative = src->speculative;
950         dst_state->curframe = src->curframe;
951         dst_state->active_spin_lock = src->active_spin_lock;
952         dst_state->branches = src->branches;
953         dst_state->parent = src->parent;
954         dst_state->first_insn_idx = src->first_insn_idx;
955         dst_state->last_insn_idx = src->last_insn_idx;
956         for (i = 0; i <= src->curframe; i++) {
957                 dst = dst_state->frame[i];
958                 if (!dst) {
959                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
960                         if (!dst)
961                                 return -ENOMEM;
962                         dst_state->frame[i] = dst;
963                 }
964                 err = copy_func_state(dst, src->frame[i]);
965                 if (err)
966                         return err;
967         }
968         return 0;
969 }
970
971 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
972 {
973         while (st) {
974                 u32 br = --st->branches;
975
976                 /* WARN_ON(br > 1) technically makes sense here,
977                  * but see comment in push_stack(), hence:
978                  */
979                 WARN_ONCE((int)br < 0,
980                           "BUG update_branch_counts:branches_to_explore=%d\n",
981                           br);
982                 if (br)
983                         break;
984                 st = st->parent;
985         }
986 }
987
988 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
989                      int *insn_idx, bool pop_log)
990 {
991         struct bpf_verifier_state *cur = env->cur_state;
992         struct bpf_verifier_stack_elem *elem, *head = env->head;
993         int err;
994
995         if (env->head == NULL)
996                 return -ENOENT;
997
998         if (cur) {
999                 err = copy_verifier_state(cur, &head->st);
1000                 if (err)
1001                         return err;
1002         }
1003         if (pop_log)
1004                 bpf_vlog_reset(&env->log, head->log_pos);
1005         if (insn_idx)
1006                 *insn_idx = head->insn_idx;
1007         if (prev_insn_idx)
1008                 *prev_insn_idx = head->prev_insn_idx;
1009         elem = head->next;
1010         free_verifier_state(&head->st, false);
1011         kfree(head);
1012         env->head = elem;
1013         env->stack_size--;
1014         return 0;
1015 }
1016
1017 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1018                                              int insn_idx, int prev_insn_idx,
1019                                              bool speculative)
1020 {
1021         struct bpf_verifier_state *cur = env->cur_state;
1022         struct bpf_verifier_stack_elem *elem;
1023         int err;
1024
1025         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1026         if (!elem)
1027                 goto err;
1028
1029         elem->insn_idx = insn_idx;
1030         elem->prev_insn_idx = prev_insn_idx;
1031         elem->next = env->head;
1032         elem->log_pos = env->log.len_used;
1033         env->head = elem;
1034         env->stack_size++;
1035         err = copy_verifier_state(&elem->st, cur);
1036         if (err)
1037                 goto err;
1038         elem->st.speculative |= speculative;
1039         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1040                 verbose(env, "The sequence of %d jumps is too complex.\n",
1041                         env->stack_size);
1042                 goto err;
1043         }
1044         if (elem->st.parent) {
1045                 ++elem->st.parent->branches;
1046                 /* WARN_ON(branches > 2) technically makes sense here,
1047                  * but
1048                  * 1. speculative states will bump 'branches' for non-branch
1049                  * instructions
1050                  * 2. is_state_visited() heuristics may decide not to create
1051                  * a new state for a sequence of branches and all such current
1052                  * and cloned states will be pointing to a single parent state
1053                  * which might have large 'branches' count.
1054                  */
1055         }
1056         return &elem->st;
1057 err:
1058         free_verifier_state(env->cur_state, true);
1059         env->cur_state = NULL;
1060         /* pop all elements and return */
1061         while (!pop_stack(env, NULL, NULL, false));
1062         return NULL;
1063 }
1064
1065 #define CALLER_SAVED_REGS 6
1066 static const int caller_saved[CALLER_SAVED_REGS] = {
1067         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1068 };
1069
1070 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1071                                 struct bpf_reg_state *reg);
1072
1073 /* This helper doesn't clear reg->id */
1074 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1075 {
1076         reg->var_off = tnum_const(imm);
1077         reg->smin_value = (s64)imm;
1078         reg->smax_value = (s64)imm;
1079         reg->umin_value = imm;
1080         reg->umax_value = imm;
1081
1082         reg->s32_min_value = (s32)imm;
1083         reg->s32_max_value = (s32)imm;
1084         reg->u32_min_value = (u32)imm;
1085         reg->u32_max_value = (u32)imm;
1086 }
1087
1088 /* Mark the unknown part of a register (variable offset or scalar value) as
1089  * known to have the value @imm.
1090  */
1091 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1092 {
1093         /* Clear id, off, and union(map_ptr, range) */
1094         memset(((u8 *)reg) + sizeof(reg->type), 0,
1095                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1096         ___mark_reg_known(reg, imm);
1097 }
1098
1099 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1100 {
1101         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1102         reg->s32_min_value = (s32)imm;
1103         reg->s32_max_value = (s32)imm;
1104         reg->u32_min_value = (u32)imm;
1105         reg->u32_max_value = (u32)imm;
1106 }
1107
1108 /* Mark the 'variable offset' part of a register as zero.  This should be
1109  * used only on registers holding a pointer type.
1110  */
1111 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1112 {
1113         __mark_reg_known(reg, 0);
1114 }
1115
1116 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1117 {
1118         __mark_reg_known(reg, 0);
1119         reg->type = SCALAR_VALUE;
1120 }
1121
1122 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1123                                 struct bpf_reg_state *regs, u32 regno)
1124 {
1125         if (WARN_ON(regno >= MAX_BPF_REG)) {
1126                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1127                 /* Something bad happened, let's kill all regs */
1128                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1129                         __mark_reg_not_init(env, regs + regno);
1130                 return;
1131         }
1132         __mark_reg_known_zero(regs + regno);
1133 }
1134
1135 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1136 {
1137         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1138                 const struct bpf_map *map = reg->map_ptr;
1139
1140                 if (map->inner_map_meta) {
1141                         reg->type = CONST_PTR_TO_MAP;
1142                         reg->map_ptr = map->inner_map_meta;
1143                         /* transfer reg's id which is unique for every map_lookup_elem
1144                          * as UID of the inner map.
1145                          */
1146                         if (map_value_has_timer(map->inner_map_meta))
1147                                 reg->map_uid = reg->id;
1148                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1149                         reg->type = PTR_TO_XDP_SOCK;
1150                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1151                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1152                         reg->type = PTR_TO_SOCKET;
1153                 } else {
1154                         reg->type = PTR_TO_MAP_VALUE;
1155                 }
1156                 return;
1157         }
1158
1159         reg->type &= ~PTR_MAYBE_NULL;
1160 }
1161
1162 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1163 {
1164         return type_is_pkt_pointer(reg->type);
1165 }
1166
1167 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1168 {
1169         return reg_is_pkt_pointer(reg) ||
1170                reg->type == PTR_TO_PACKET_END;
1171 }
1172
1173 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1174 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1175                                     enum bpf_reg_type which)
1176 {
1177         /* The register can already have a range from prior markings.
1178          * This is fine as long as it hasn't been advanced from its
1179          * origin.
1180          */
1181         return reg->type == which &&
1182                reg->id == 0 &&
1183                reg->off == 0 &&
1184                tnum_equals_const(reg->var_off, 0);
1185 }
1186
1187 /* Reset the min/max bounds of a register */
1188 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1189 {
1190         reg->smin_value = S64_MIN;
1191         reg->smax_value = S64_MAX;
1192         reg->umin_value = 0;
1193         reg->umax_value = U64_MAX;
1194
1195         reg->s32_min_value = S32_MIN;
1196         reg->s32_max_value = S32_MAX;
1197         reg->u32_min_value = 0;
1198         reg->u32_max_value = U32_MAX;
1199 }
1200
1201 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1202 {
1203         reg->smin_value = S64_MIN;
1204         reg->smax_value = S64_MAX;
1205         reg->umin_value = 0;
1206         reg->umax_value = U64_MAX;
1207 }
1208
1209 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1210 {
1211         reg->s32_min_value = S32_MIN;
1212         reg->s32_max_value = S32_MAX;
1213         reg->u32_min_value = 0;
1214         reg->u32_max_value = U32_MAX;
1215 }
1216
1217 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1218 {
1219         struct tnum var32_off = tnum_subreg(reg->var_off);
1220
1221         /* min signed is max(sign bit) | min(other bits) */
1222         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1223                         var32_off.value | (var32_off.mask & S32_MIN));
1224         /* max signed is min(sign bit) | max(other bits) */
1225         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1226                         var32_off.value | (var32_off.mask & S32_MAX));
1227         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1228         reg->u32_max_value = min(reg->u32_max_value,
1229                                  (u32)(var32_off.value | var32_off.mask));
1230 }
1231
1232 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1233 {
1234         /* min signed is max(sign bit) | min(other bits) */
1235         reg->smin_value = max_t(s64, reg->smin_value,
1236                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1237         /* max signed is min(sign bit) | max(other bits) */
1238         reg->smax_value = min_t(s64, reg->smax_value,
1239                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1240         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1241         reg->umax_value = min(reg->umax_value,
1242                               reg->var_off.value | reg->var_off.mask);
1243 }
1244
1245 static void __update_reg_bounds(struct bpf_reg_state *reg)
1246 {
1247         __update_reg32_bounds(reg);
1248         __update_reg64_bounds(reg);
1249 }
1250
1251 /* Uses signed min/max values to inform unsigned, and vice-versa */
1252 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1253 {
1254         /* Learn sign from signed bounds.
1255          * If we cannot cross the sign boundary, then signed and unsigned bounds
1256          * are the same, so combine.  This works even in the negative case, e.g.
1257          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1258          */
1259         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1260                 reg->s32_min_value = reg->u32_min_value =
1261                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1262                 reg->s32_max_value = reg->u32_max_value =
1263                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1264                 return;
1265         }
1266         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1267          * boundary, so we must be careful.
1268          */
1269         if ((s32)reg->u32_max_value >= 0) {
1270                 /* Positive.  We can't learn anything from the smin, but smax
1271                  * is positive, hence safe.
1272                  */
1273                 reg->s32_min_value = reg->u32_min_value;
1274                 reg->s32_max_value = reg->u32_max_value =
1275                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1276         } else if ((s32)reg->u32_min_value < 0) {
1277                 /* Negative.  We can't learn anything from the smax, but smin
1278                  * is negative, hence safe.
1279                  */
1280                 reg->s32_min_value = reg->u32_min_value =
1281                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1282                 reg->s32_max_value = reg->u32_max_value;
1283         }
1284 }
1285
1286 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1287 {
1288         /* Learn sign from signed bounds.
1289          * If we cannot cross the sign boundary, then signed and unsigned bounds
1290          * are the same, so combine.  This works even in the negative case, e.g.
1291          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1292          */
1293         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1294                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1295                                                           reg->umin_value);
1296                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1297                                                           reg->umax_value);
1298                 return;
1299         }
1300         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1301          * boundary, so we must be careful.
1302          */
1303         if ((s64)reg->umax_value >= 0) {
1304                 /* Positive.  We can't learn anything from the smin, but smax
1305                  * is positive, hence safe.
1306                  */
1307                 reg->smin_value = reg->umin_value;
1308                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1309                                                           reg->umax_value);
1310         } else if ((s64)reg->umin_value < 0) {
1311                 /* Negative.  We can't learn anything from the smax, but smin
1312                  * is negative, hence safe.
1313                  */
1314                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1315                                                           reg->umin_value);
1316                 reg->smax_value = reg->umax_value;
1317         }
1318 }
1319
1320 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1321 {
1322         __reg32_deduce_bounds(reg);
1323         __reg64_deduce_bounds(reg);
1324 }
1325
1326 /* Attempts to improve var_off based on unsigned min/max information */
1327 static void __reg_bound_offset(struct bpf_reg_state *reg)
1328 {
1329         struct tnum var64_off = tnum_intersect(reg->var_off,
1330                                                tnum_range(reg->umin_value,
1331                                                           reg->umax_value));
1332         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1333                                                 tnum_range(reg->u32_min_value,
1334                                                            reg->u32_max_value));
1335
1336         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1337 }
1338
1339 static void reg_bounds_sync(struct bpf_reg_state *reg)
1340 {
1341         /* We might have learned new bounds from the var_off. */
1342         __update_reg_bounds(reg);
1343         /* We might have learned something about the sign bit. */
1344         __reg_deduce_bounds(reg);
1345         /* We might have learned some bits from the bounds. */
1346         __reg_bound_offset(reg);
1347         /* Intersecting with the old var_off might have improved our bounds
1348          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1349          * then new var_off is (0; 0x7f...fc) which improves our umax.
1350          */
1351         __update_reg_bounds(reg);
1352 }
1353
1354 static bool __reg32_bound_s64(s32 a)
1355 {
1356         return a >= 0 && a <= S32_MAX;
1357 }
1358
1359 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1360 {
1361         reg->umin_value = reg->u32_min_value;
1362         reg->umax_value = reg->u32_max_value;
1363
1364         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1365          * be positive otherwise set to worse case bounds and refine later
1366          * from tnum.
1367          */
1368         if (__reg32_bound_s64(reg->s32_min_value) &&
1369             __reg32_bound_s64(reg->s32_max_value)) {
1370                 reg->smin_value = reg->s32_min_value;
1371                 reg->smax_value = reg->s32_max_value;
1372         } else {
1373                 reg->smin_value = 0;
1374                 reg->smax_value = U32_MAX;
1375         }
1376 }
1377
1378 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1379 {
1380         /* special case when 64-bit register has upper 32-bit register
1381          * zeroed. Typically happens after zext or <<32, >>32 sequence
1382          * allowing us to use 32-bit bounds directly,
1383          */
1384         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1385                 __reg_assign_32_into_64(reg);
1386         } else {
1387                 /* Otherwise the best we can do is push lower 32bit known and
1388                  * unknown bits into register (var_off set from jmp logic)
1389                  * then learn as much as possible from the 64-bit tnum
1390                  * known and unknown bits. The previous smin/smax bounds are
1391                  * invalid here because of jmp32 compare so mark them unknown
1392                  * so they do not impact tnum bounds calculation.
1393                  */
1394                 __mark_reg64_unbounded(reg);
1395         }
1396         reg_bounds_sync(reg);
1397 }
1398
1399 static bool __reg64_bound_s32(s64 a)
1400 {
1401         return a >= S32_MIN && a <= S32_MAX;
1402 }
1403
1404 static bool __reg64_bound_u32(u64 a)
1405 {
1406         return a >= U32_MIN && a <= U32_MAX;
1407 }
1408
1409 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1410 {
1411         __mark_reg32_unbounded(reg);
1412         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1413                 reg->s32_min_value = (s32)reg->smin_value;
1414                 reg->s32_max_value = (s32)reg->smax_value;
1415         }
1416         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1417                 reg->u32_min_value = (u32)reg->umin_value;
1418                 reg->u32_max_value = (u32)reg->umax_value;
1419         }
1420         reg_bounds_sync(reg);
1421 }
1422
1423 /* Mark a register as having a completely unknown (scalar) value. */
1424 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1425                                struct bpf_reg_state *reg)
1426 {
1427         /*
1428          * Clear type, id, off, and union(map_ptr, range) and
1429          * padding between 'type' and union
1430          */
1431         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1432         reg->type = SCALAR_VALUE;
1433         reg->var_off = tnum_unknown;
1434         reg->frameno = 0;
1435         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1436         __mark_reg_unbounded(reg);
1437 }
1438
1439 static void mark_reg_unknown(struct bpf_verifier_env *env,
1440                              struct bpf_reg_state *regs, u32 regno)
1441 {
1442         if (WARN_ON(regno >= MAX_BPF_REG)) {
1443                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1444                 /* Something bad happened, let's kill all regs except FP */
1445                 for (regno = 0; regno < BPF_REG_FP; regno++)
1446                         __mark_reg_not_init(env, regs + regno);
1447                 return;
1448         }
1449         __mark_reg_unknown(env, regs + regno);
1450 }
1451
1452 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1453                                 struct bpf_reg_state *reg)
1454 {
1455         __mark_reg_unknown(env, reg);
1456         reg->type = NOT_INIT;
1457 }
1458
1459 static void mark_reg_not_init(struct bpf_verifier_env *env,
1460                               struct bpf_reg_state *regs, u32 regno)
1461 {
1462         if (WARN_ON(regno >= MAX_BPF_REG)) {
1463                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1464                 /* Something bad happened, let's kill all regs except FP */
1465                 for (regno = 0; regno < BPF_REG_FP; regno++)
1466                         __mark_reg_not_init(env, regs + regno);
1467                 return;
1468         }
1469         __mark_reg_not_init(env, regs + regno);
1470 }
1471
1472 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1473                             struct bpf_reg_state *regs, u32 regno,
1474                             enum bpf_reg_type reg_type,
1475                             struct btf *btf, u32 btf_id)
1476 {
1477         if (reg_type == SCALAR_VALUE) {
1478                 mark_reg_unknown(env, regs, regno);
1479                 return;
1480         }
1481         mark_reg_known_zero(env, regs, regno);
1482         regs[regno].type = PTR_TO_BTF_ID;
1483         regs[regno].btf = btf;
1484         regs[regno].btf_id = btf_id;
1485 }
1486
1487 #define DEF_NOT_SUBREG  (0)
1488 static void init_reg_state(struct bpf_verifier_env *env,
1489                            struct bpf_func_state *state)
1490 {
1491         struct bpf_reg_state *regs = state->regs;
1492         int i;
1493
1494         for (i = 0; i < MAX_BPF_REG; i++) {
1495                 mark_reg_not_init(env, regs, i);
1496                 regs[i].live = REG_LIVE_NONE;
1497                 regs[i].parent = NULL;
1498                 regs[i].subreg_def = DEF_NOT_SUBREG;
1499         }
1500
1501         /* frame pointer */
1502         regs[BPF_REG_FP].type = PTR_TO_STACK;
1503         mark_reg_known_zero(env, regs, BPF_REG_FP);
1504         regs[BPF_REG_FP].frameno = state->frameno;
1505 }
1506
1507 #define BPF_MAIN_FUNC (-1)
1508 static void init_func_state(struct bpf_verifier_env *env,
1509                             struct bpf_func_state *state,
1510                             int callsite, int frameno, int subprogno)
1511 {
1512         state->callsite = callsite;
1513         state->frameno = frameno;
1514         state->subprogno = subprogno;
1515         init_reg_state(env, state);
1516 }
1517
1518 /* Similar to push_stack(), but for async callbacks */
1519 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1520                                                 int insn_idx, int prev_insn_idx,
1521                                                 int subprog)
1522 {
1523         struct bpf_verifier_stack_elem *elem;
1524         struct bpf_func_state *frame;
1525
1526         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1527         if (!elem)
1528                 goto err;
1529
1530         elem->insn_idx = insn_idx;
1531         elem->prev_insn_idx = prev_insn_idx;
1532         elem->next = env->head;
1533         elem->log_pos = env->log.len_used;
1534         env->head = elem;
1535         env->stack_size++;
1536         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1537                 verbose(env,
1538                         "The sequence of %d jumps is too complex for async cb.\n",
1539                         env->stack_size);
1540                 goto err;
1541         }
1542         /* Unlike push_stack() do not copy_verifier_state().
1543          * The caller state doesn't matter.
1544          * This is async callback. It starts in a fresh stack.
1545          * Initialize it similar to do_check_common().
1546          */
1547         elem->st.branches = 1;
1548         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1549         if (!frame)
1550                 goto err;
1551         init_func_state(env, frame,
1552                         BPF_MAIN_FUNC /* callsite */,
1553                         0 /* frameno within this callchain */,
1554                         subprog /* subprog number within this prog */);
1555         elem->st.frame[0] = frame;
1556         return &elem->st;
1557 err:
1558         free_verifier_state(env->cur_state, true);
1559         env->cur_state = NULL;
1560         /* pop all elements and return */
1561         while (!pop_stack(env, NULL, NULL, false));
1562         return NULL;
1563 }
1564
1565
1566 enum reg_arg_type {
1567         SRC_OP,         /* register is used as source operand */
1568         DST_OP,         /* register is used as destination operand */
1569         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1570 };
1571
1572 static int cmp_subprogs(const void *a, const void *b)
1573 {
1574         return ((struct bpf_subprog_info *)a)->start -
1575                ((struct bpf_subprog_info *)b)->start;
1576 }
1577
1578 static int find_subprog(struct bpf_verifier_env *env, int off)
1579 {
1580         struct bpf_subprog_info *p;
1581
1582         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1583                     sizeof(env->subprog_info[0]), cmp_subprogs);
1584         if (!p)
1585                 return -ENOENT;
1586         return p - env->subprog_info;
1587
1588 }
1589
1590 static int add_subprog(struct bpf_verifier_env *env, int off)
1591 {
1592         int insn_cnt = env->prog->len;
1593         int ret;
1594
1595         if (off >= insn_cnt || off < 0) {
1596                 verbose(env, "call to invalid destination\n");
1597                 return -EINVAL;
1598         }
1599         ret = find_subprog(env, off);
1600         if (ret >= 0)
1601                 return ret;
1602         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1603                 verbose(env, "too many subprograms\n");
1604                 return -E2BIG;
1605         }
1606         /* determine subprog starts. The end is one before the next starts */
1607         env->subprog_info[env->subprog_cnt++].start = off;
1608         sort(env->subprog_info, env->subprog_cnt,
1609              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1610         return env->subprog_cnt - 1;
1611 }
1612
1613 struct bpf_kfunc_desc {
1614         struct btf_func_model func_model;
1615         u32 func_id;
1616         s32 imm;
1617 };
1618
1619 #define MAX_KFUNC_DESCS 256
1620 struct bpf_kfunc_desc_tab {
1621         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1622         u32 nr_descs;
1623 };
1624
1625 static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1626 {
1627         const struct bpf_kfunc_desc *d0 = a;
1628         const struct bpf_kfunc_desc *d1 = b;
1629
1630         /* func_id is not greater than BTF_MAX_TYPE */
1631         return d0->func_id - d1->func_id;
1632 }
1633
1634 static const struct bpf_kfunc_desc *
1635 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1636 {
1637         struct bpf_kfunc_desc desc = {
1638                 .func_id = func_id,
1639         };
1640         struct bpf_kfunc_desc_tab *tab;
1641
1642         tab = prog->aux->kfunc_tab;
1643         return bsearch(&desc, tab->descs, tab->nr_descs,
1644                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1645 }
1646
1647 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1648 {
1649         const struct btf_type *func, *func_proto;
1650         struct bpf_kfunc_desc_tab *tab;
1651         struct bpf_prog_aux *prog_aux;
1652         struct bpf_kfunc_desc *desc;
1653         const char *func_name;
1654         unsigned long addr;
1655         int err;
1656
1657         prog_aux = env->prog->aux;
1658         tab = prog_aux->kfunc_tab;
1659         if (!tab) {
1660                 if (!btf_vmlinux) {
1661                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1662                         return -ENOTSUPP;
1663                 }
1664
1665                 if (!env->prog->jit_requested) {
1666                         verbose(env, "JIT is required for calling kernel function\n");
1667                         return -ENOTSUPP;
1668                 }
1669
1670                 if (!bpf_jit_supports_kfunc_call()) {
1671                         verbose(env, "JIT does not support calling kernel function\n");
1672                         return -ENOTSUPP;
1673                 }
1674
1675                 if (!env->prog->gpl_compatible) {
1676                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1677                         return -EINVAL;
1678                 }
1679
1680                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1681                 if (!tab)
1682                         return -ENOMEM;
1683                 prog_aux->kfunc_tab = tab;
1684         }
1685
1686         if (find_kfunc_desc(env->prog, func_id))
1687                 return 0;
1688
1689         if (tab->nr_descs == MAX_KFUNC_DESCS) {
1690                 verbose(env, "too many different kernel function calls\n");
1691                 return -E2BIG;
1692         }
1693
1694         func = btf_type_by_id(btf_vmlinux, func_id);
1695         if (!func || !btf_type_is_func(func)) {
1696                 verbose(env, "kernel btf_id %u is not a function\n",
1697                         func_id);
1698                 return -EINVAL;
1699         }
1700         func_proto = btf_type_by_id(btf_vmlinux, func->type);
1701         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1702                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1703                         func_id);
1704                 return -EINVAL;
1705         }
1706
1707         func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1708         addr = kallsyms_lookup_name(func_name);
1709         if (!addr) {
1710                 verbose(env, "cannot find address for kernel function %s\n",
1711                         func_name);
1712                 return -EINVAL;
1713         }
1714
1715         desc = &tab->descs[tab->nr_descs++];
1716         desc->func_id = func_id;
1717         desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1718         err = btf_distill_func_proto(&env->log, btf_vmlinux,
1719                                      func_proto, func_name,
1720                                      &desc->func_model);
1721         if (!err)
1722                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1723                      kfunc_desc_cmp_by_id, NULL);
1724         return err;
1725 }
1726
1727 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1728 {
1729         const struct bpf_kfunc_desc *d0 = a;
1730         const struct bpf_kfunc_desc *d1 = b;
1731
1732         if (d0->imm > d1->imm)
1733                 return 1;
1734         else if (d0->imm < d1->imm)
1735                 return -1;
1736         return 0;
1737 }
1738
1739 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1740 {
1741         struct bpf_kfunc_desc_tab *tab;
1742
1743         tab = prog->aux->kfunc_tab;
1744         if (!tab)
1745                 return;
1746
1747         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1748              kfunc_desc_cmp_by_imm, NULL);
1749 }
1750
1751 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1752 {
1753         return !!prog->aux->kfunc_tab;
1754 }
1755
1756 const struct btf_func_model *
1757 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1758                          const struct bpf_insn *insn)
1759 {
1760         const struct bpf_kfunc_desc desc = {
1761                 .imm = insn->imm,
1762         };
1763         const struct bpf_kfunc_desc *res;
1764         struct bpf_kfunc_desc_tab *tab;
1765
1766         tab = prog->aux->kfunc_tab;
1767         res = bsearch(&desc, tab->descs, tab->nr_descs,
1768                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1769
1770         return res ? &res->func_model : NULL;
1771 }
1772
1773 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1774 {
1775         struct bpf_subprog_info *subprog = env->subprog_info;
1776         struct bpf_insn *insn = env->prog->insnsi;
1777         int i, ret, insn_cnt = env->prog->len;
1778
1779         /* Add entry function. */
1780         ret = add_subprog(env, 0);
1781         if (ret)
1782                 return ret;
1783
1784         for (i = 0; i < insn_cnt; i++, insn++) {
1785                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1786                     !bpf_pseudo_kfunc_call(insn))
1787                         continue;
1788
1789                 if (!env->bpf_capable) {
1790                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1791                         return -EPERM;
1792                 }
1793
1794                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
1795                         ret = add_subprog(env, i + insn->imm + 1);
1796                 else
1797                         ret = add_kfunc_call(env, insn->imm);
1798
1799                 if (ret < 0)
1800                         return ret;
1801         }
1802
1803         /* Add a fake 'exit' subprog which could simplify subprog iteration
1804          * logic. 'subprog_cnt' should not be increased.
1805          */
1806         subprog[env->subprog_cnt].start = insn_cnt;
1807
1808         if (env->log.level & BPF_LOG_LEVEL2)
1809                 for (i = 0; i < env->subprog_cnt; i++)
1810                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
1811
1812         return 0;
1813 }
1814
1815 static int check_subprogs(struct bpf_verifier_env *env)
1816 {
1817         int i, subprog_start, subprog_end, off, cur_subprog = 0;
1818         struct bpf_subprog_info *subprog = env->subprog_info;
1819         struct bpf_insn *insn = env->prog->insnsi;
1820         int insn_cnt = env->prog->len;
1821
1822         /* now check that all jumps are within the same subprog */
1823         subprog_start = subprog[cur_subprog].start;
1824         subprog_end = subprog[cur_subprog + 1].start;
1825         for (i = 0; i < insn_cnt; i++) {
1826                 u8 code = insn[i].code;
1827
1828                 if (code == (BPF_JMP | BPF_CALL) &&
1829                     insn[i].imm == BPF_FUNC_tail_call &&
1830                     insn[i].src_reg != BPF_PSEUDO_CALL)
1831                         subprog[cur_subprog].has_tail_call = true;
1832                 if (BPF_CLASS(code) == BPF_LD &&
1833                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1834                         subprog[cur_subprog].has_ld_abs = true;
1835                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1836                         goto next;
1837                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1838                         goto next;
1839                 off = i + insn[i].off + 1;
1840                 if (off < subprog_start || off >= subprog_end) {
1841                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
1842                         return -EINVAL;
1843                 }
1844 next:
1845                 if (i == subprog_end - 1) {
1846                         /* to avoid fall-through from one subprog into another
1847                          * the last insn of the subprog should be either exit
1848                          * or unconditional jump back
1849                          */
1850                         if (code != (BPF_JMP | BPF_EXIT) &&
1851                             code != (BPF_JMP | BPF_JA)) {
1852                                 verbose(env, "last insn is not an exit or jmp\n");
1853                                 return -EINVAL;
1854                         }
1855                         subprog_start = subprog_end;
1856                         cur_subprog++;
1857                         if (cur_subprog < env->subprog_cnt)
1858                                 subprog_end = subprog[cur_subprog + 1].start;
1859                 }
1860         }
1861         return 0;
1862 }
1863
1864 /* Parentage chain of this register (or stack slot) should take care of all
1865  * issues like callee-saved registers, stack slot allocation time, etc.
1866  */
1867 static int mark_reg_read(struct bpf_verifier_env *env,
1868                          const struct bpf_reg_state *state,
1869                          struct bpf_reg_state *parent, u8 flag)
1870 {
1871         bool writes = parent == state->parent; /* Observe write marks */
1872         int cnt = 0;
1873
1874         while (parent) {
1875                 /* if read wasn't screened by an earlier write ... */
1876                 if (writes && state->live & REG_LIVE_WRITTEN)
1877                         break;
1878                 if (parent->live & REG_LIVE_DONE) {
1879                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1880                                 reg_type_str(env, parent->type),
1881                                 parent->var_off.value, parent->off);
1882                         return -EFAULT;
1883                 }
1884                 /* The first condition is more likely to be true than the
1885                  * second, checked it first.
1886                  */
1887                 if ((parent->live & REG_LIVE_READ) == flag ||
1888                     parent->live & REG_LIVE_READ64)
1889                         /* The parentage chain never changes and
1890                          * this parent was already marked as LIVE_READ.
1891                          * There is no need to keep walking the chain again and
1892                          * keep re-marking all parents as LIVE_READ.
1893                          * This case happens when the same register is read
1894                          * multiple times without writes into it in-between.
1895                          * Also, if parent has the stronger REG_LIVE_READ64 set,
1896                          * then no need to set the weak REG_LIVE_READ32.
1897                          */
1898                         break;
1899                 /* ... then we depend on parent's value */
1900                 parent->live |= flag;
1901                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1902                 if (flag == REG_LIVE_READ64)
1903                         parent->live &= ~REG_LIVE_READ32;
1904                 state = parent;
1905                 parent = state->parent;
1906                 writes = true;
1907                 cnt++;
1908         }
1909
1910         if (env->longest_mark_read_walk < cnt)
1911                 env->longest_mark_read_walk = cnt;
1912         return 0;
1913 }
1914
1915 /* This function is supposed to be used by the following 32-bit optimization
1916  * code only. It returns TRUE if the source or destination register operates
1917  * on 64-bit, otherwise return FALSE.
1918  */
1919 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1920                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1921 {
1922         u8 code, class, op;
1923
1924         code = insn->code;
1925         class = BPF_CLASS(code);
1926         op = BPF_OP(code);
1927         if (class == BPF_JMP) {
1928                 /* BPF_EXIT for "main" will reach here. Return TRUE
1929                  * conservatively.
1930                  */
1931                 if (op == BPF_EXIT)
1932                         return true;
1933                 if (op == BPF_CALL) {
1934                         /* BPF to BPF call will reach here because of marking
1935                          * caller saved clobber with DST_OP_NO_MARK for which we
1936                          * don't care the register def because they are anyway
1937                          * marked as NOT_INIT already.
1938                          */
1939                         if (insn->src_reg == BPF_PSEUDO_CALL)
1940                                 return false;
1941                         /* Helper call will reach here because of arg type
1942                          * check, conservatively return TRUE.
1943                          */
1944                         if (t == SRC_OP)
1945                                 return true;
1946
1947                         return false;
1948                 }
1949         }
1950
1951         if (class == BPF_ALU64 || class == BPF_JMP ||
1952             /* BPF_END always use BPF_ALU class. */
1953             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1954                 return true;
1955
1956         if (class == BPF_ALU || class == BPF_JMP32)
1957                 return false;
1958
1959         if (class == BPF_LDX) {
1960                 if (t != SRC_OP)
1961                         return BPF_SIZE(code) == BPF_DW;
1962                 /* LDX source must be ptr. */
1963                 return true;
1964         }
1965
1966         if (class == BPF_STX) {
1967                 /* BPF_STX (including atomic variants) has multiple source
1968                  * operands, one of which is a ptr. Check whether the caller is
1969                  * asking about it.
1970                  */
1971                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
1972                         return true;
1973                 return BPF_SIZE(code) == BPF_DW;
1974         }
1975
1976         if (class == BPF_LD) {
1977                 u8 mode = BPF_MODE(code);
1978
1979                 /* LD_IMM64 */
1980                 if (mode == BPF_IMM)
1981                         return true;
1982
1983                 /* Both LD_IND and LD_ABS return 32-bit data. */
1984                 if (t != SRC_OP)
1985                         return  false;
1986
1987                 /* Implicit ctx ptr. */
1988                 if (regno == BPF_REG_6)
1989                         return true;
1990
1991                 /* Explicit source could be any width. */
1992                 return true;
1993         }
1994
1995         if (class == BPF_ST)
1996                 /* The only source register for BPF_ST is a ptr. */
1997                 return true;
1998
1999         /* Conservatively return true at default. */
2000         return true;
2001 }
2002
2003 /* Return the regno defined by the insn, or -1. */
2004 static int insn_def_regno(const struct bpf_insn *insn)
2005 {
2006         switch (BPF_CLASS(insn->code)) {
2007         case BPF_JMP:
2008         case BPF_JMP32:
2009         case BPF_ST:
2010                 return -1;
2011         case BPF_STX:
2012                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2013                     (insn->imm & BPF_FETCH)) {
2014                         if (insn->imm == BPF_CMPXCHG)
2015                                 return BPF_REG_0;
2016                         else
2017                                 return insn->src_reg;
2018                 } else {
2019                         return -1;
2020                 }
2021         default:
2022                 return insn->dst_reg;
2023         }
2024 }
2025
2026 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2027 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2028 {
2029         int dst_reg = insn_def_regno(insn);
2030
2031         if (dst_reg == -1)
2032                 return false;
2033
2034         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2035 }
2036
2037 static void mark_insn_zext(struct bpf_verifier_env *env,
2038                            struct bpf_reg_state *reg)
2039 {
2040         s32 def_idx = reg->subreg_def;
2041
2042         if (def_idx == DEF_NOT_SUBREG)
2043                 return;
2044
2045         env->insn_aux_data[def_idx - 1].zext_dst = true;
2046         /* The dst will be zero extended, so won't be sub-register anymore. */
2047         reg->subreg_def = DEF_NOT_SUBREG;
2048 }
2049
2050 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2051                          enum reg_arg_type t)
2052 {
2053         struct bpf_verifier_state *vstate = env->cur_state;
2054         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2055         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2056         struct bpf_reg_state *reg, *regs = state->regs;
2057         bool rw64;
2058
2059         if (regno >= MAX_BPF_REG) {
2060                 verbose(env, "R%d is invalid\n", regno);
2061                 return -EINVAL;
2062         }
2063
2064         reg = &regs[regno];
2065         rw64 = is_reg64(env, insn, regno, reg, t);
2066         if (t == SRC_OP) {
2067                 /* check whether register used as source operand can be read */
2068                 if (reg->type == NOT_INIT) {
2069                         verbose(env, "R%d !read_ok\n", regno);
2070                         return -EACCES;
2071                 }
2072                 /* We don't need to worry about FP liveness because it's read-only */
2073                 if (regno == BPF_REG_FP)
2074                         return 0;
2075
2076                 if (rw64)
2077                         mark_insn_zext(env, reg);
2078
2079                 return mark_reg_read(env, reg, reg->parent,
2080                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2081         } else {
2082                 /* check whether register used as dest operand can be written to */
2083                 if (regno == BPF_REG_FP) {
2084                         verbose(env, "frame pointer is read only\n");
2085                         return -EACCES;
2086                 }
2087                 reg->live |= REG_LIVE_WRITTEN;
2088                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2089                 if (t == DST_OP)
2090                         mark_reg_unknown(env, regs, regno);
2091         }
2092         return 0;
2093 }
2094
2095 /* for any branch, call, exit record the history of jmps in the given state */
2096 static int push_jmp_history(struct bpf_verifier_env *env,
2097                             struct bpf_verifier_state *cur)
2098 {
2099         u32 cnt = cur->jmp_history_cnt;
2100         struct bpf_idx_pair *p;
2101
2102         cnt++;
2103         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2104         if (!p)
2105                 return -ENOMEM;
2106         p[cnt - 1].idx = env->insn_idx;
2107         p[cnt - 1].prev_idx = env->prev_insn_idx;
2108         cur->jmp_history = p;
2109         cur->jmp_history_cnt = cnt;
2110         return 0;
2111 }
2112
2113 /* Backtrack one insn at a time. If idx is not at the top of recorded
2114  * history then previous instruction came from straight line execution.
2115  */
2116 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2117                              u32 *history)
2118 {
2119         u32 cnt = *history;
2120
2121         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2122                 i = st->jmp_history[cnt - 1].prev_idx;
2123                 (*history)--;
2124         } else {
2125                 i--;
2126         }
2127         return i;
2128 }
2129
2130 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2131 {
2132         const struct btf_type *func;
2133
2134         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2135                 return NULL;
2136
2137         func = btf_type_by_id(btf_vmlinux, insn->imm);
2138         return btf_name_by_offset(btf_vmlinux, func->name_off);
2139 }
2140
2141 /* For given verifier state backtrack_insn() is called from the last insn to
2142  * the first insn. Its purpose is to compute a bitmask of registers and
2143  * stack slots that needs precision in the parent verifier state.
2144  */
2145 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2146                           u32 *reg_mask, u64 *stack_mask)
2147 {
2148         const struct bpf_insn_cbs cbs = {
2149                 .cb_call        = disasm_kfunc_name,
2150                 .cb_print       = verbose,
2151                 .private_data   = env,
2152         };
2153         struct bpf_insn *insn = env->prog->insnsi + idx;
2154         u8 class = BPF_CLASS(insn->code);
2155         u8 opcode = BPF_OP(insn->code);
2156         u8 mode = BPF_MODE(insn->code);
2157         u32 dreg = 1u << insn->dst_reg;
2158         u32 sreg = 1u << insn->src_reg;
2159         u32 spi;
2160
2161         if (insn->code == 0)
2162                 return 0;
2163         if (env->log.level & BPF_LOG_LEVEL) {
2164                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2165                 verbose(env, "%d: ", idx);
2166                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2167         }
2168
2169         if (class == BPF_ALU || class == BPF_ALU64) {
2170                 if (!(*reg_mask & dreg))
2171                         return 0;
2172                 if (opcode == BPF_MOV) {
2173                         if (BPF_SRC(insn->code) == BPF_X) {
2174                                 /* dreg = sreg
2175                                  * dreg needs precision after this insn
2176                                  * sreg needs precision before this insn
2177                                  */
2178                                 *reg_mask &= ~dreg;
2179                                 *reg_mask |= sreg;
2180                         } else {
2181                                 /* dreg = K
2182                                  * dreg needs precision after this insn.
2183                                  * Corresponding register is already marked
2184                                  * as precise=true in this verifier state.
2185                                  * No further markings in parent are necessary
2186                                  */
2187                                 *reg_mask &= ~dreg;
2188                         }
2189                 } else {
2190                         if (BPF_SRC(insn->code) == BPF_X) {
2191                                 /* dreg += sreg
2192                                  * both dreg and sreg need precision
2193                                  * before this insn
2194                                  */
2195                                 *reg_mask |= sreg;
2196                         } /* else dreg += K
2197                            * dreg still needs precision before this insn
2198                            */
2199                 }
2200         } else if (class == BPF_LDX) {
2201                 if (!(*reg_mask & dreg))
2202                         return 0;
2203                 *reg_mask &= ~dreg;
2204
2205                 /* scalars can only be spilled into stack w/o losing precision.
2206                  * Load from any other memory can be zero extended.
2207                  * The desire to keep that precision is already indicated
2208                  * by 'precise' mark in corresponding register of this state.
2209                  * No further tracking necessary.
2210                  */
2211                 if (insn->src_reg != BPF_REG_FP)
2212                         return 0;
2213                 if (BPF_SIZE(insn->code) != BPF_DW)
2214                         return 0;
2215
2216                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2217                  * that [fp - off] slot contains scalar that needs to be
2218                  * tracked with precision
2219                  */
2220                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2221                 if (spi >= 64) {
2222                         verbose(env, "BUG spi %d\n", spi);
2223                         WARN_ONCE(1, "verifier backtracking bug");
2224                         return -EFAULT;
2225                 }
2226                 *stack_mask |= 1ull << spi;
2227         } else if (class == BPF_STX || class == BPF_ST) {
2228                 if (*reg_mask & dreg)
2229                         /* stx & st shouldn't be using _scalar_ dst_reg
2230                          * to access memory. It means backtracking
2231                          * encountered a case of pointer subtraction.
2232                          */
2233                         return -ENOTSUPP;
2234                 /* scalars can only be spilled into stack */
2235                 if (insn->dst_reg != BPF_REG_FP)
2236                         return 0;
2237                 if (BPF_SIZE(insn->code) != BPF_DW)
2238                         return 0;
2239                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2240                 if (spi >= 64) {
2241                         verbose(env, "BUG spi %d\n", spi);
2242                         WARN_ONCE(1, "verifier backtracking bug");
2243                         return -EFAULT;
2244                 }
2245                 if (!(*stack_mask & (1ull << spi)))
2246                         return 0;
2247                 *stack_mask &= ~(1ull << spi);
2248                 if (class == BPF_STX)
2249                         *reg_mask |= sreg;
2250         } else if (class == BPF_JMP || class == BPF_JMP32) {
2251                 if (opcode == BPF_CALL) {
2252                         if (insn->src_reg == BPF_PSEUDO_CALL)
2253                                 return -ENOTSUPP;
2254                         /* regular helper call sets R0 */
2255                         *reg_mask &= ~1;
2256                         if (*reg_mask & 0x3f) {
2257                                 /* if backtracing was looking for registers R1-R5
2258                                  * they should have been found already.
2259                                  */
2260                                 verbose(env, "BUG regs %x\n", *reg_mask);
2261                                 WARN_ONCE(1, "verifier backtracking bug");
2262                                 return -EFAULT;
2263                         }
2264                 } else if (opcode == BPF_EXIT) {
2265                         return -ENOTSUPP;
2266                 }
2267         } else if (class == BPF_LD) {
2268                 if (!(*reg_mask & dreg))
2269                         return 0;
2270                 *reg_mask &= ~dreg;
2271                 /* It's ld_imm64 or ld_abs or ld_ind.
2272                  * For ld_imm64 no further tracking of precision
2273                  * into parent is necessary
2274                  */
2275                 if (mode == BPF_IND || mode == BPF_ABS)
2276                         /* to be analyzed */
2277                         return -ENOTSUPP;
2278         }
2279         return 0;
2280 }
2281
2282 /* the scalar precision tracking algorithm:
2283  * . at the start all registers have precise=false.
2284  * . scalar ranges are tracked as normal through alu and jmp insns.
2285  * . once precise value of the scalar register is used in:
2286  *   .  ptr + scalar alu
2287  *   . if (scalar cond K|scalar)
2288  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2289  *   backtrack through the verifier states and mark all registers and
2290  *   stack slots with spilled constants that these scalar regisers
2291  *   should be precise.
2292  * . during state pruning two registers (or spilled stack slots)
2293  *   are equivalent if both are not precise.
2294  *
2295  * Note the verifier cannot simply walk register parentage chain,
2296  * since many different registers and stack slots could have been
2297  * used to compute single precise scalar.
2298  *
2299  * The approach of starting with precise=true for all registers and then
2300  * backtrack to mark a register as not precise when the verifier detects
2301  * that program doesn't care about specific value (e.g., when helper
2302  * takes register as ARG_ANYTHING parameter) is not safe.
2303  *
2304  * It's ok to walk single parentage chain of the verifier states.
2305  * It's possible that this backtracking will go all the way till 1st insn.
2306  * All other branches will be explored for needing precision later.
2307  *
2308  * The backtracking needs to deal with cases like:
2309  *   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)
2310  * r9 -= r8
2311  * r5 = r9
2312  * if r5 > 0x79f goto pc+7
2313  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2314  * r5 += 1
2315  * ...
2316  * call bpf_perf_event_output#25
2317  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2318  *
2319  * and this case:
2320  * r6 = 1
2321  * call foo // uses callee's r6 inside to compute r0
2322  * r0 += r6
2323  * if r0 == 0 goto
2324  *
2325  * to track above reg_mask/stack_mask needs to be independent for each frame.
2326  *
2327  * Also if parent's curframe > frame where backtracking started,
2328  * the verifier need to mark registers in both frames, otherwise callees
2329  * may incorrectly prune callers. This is similar to
2330  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2331  *
2332  * For now backtracking falls back into conservative marking.
2333  */
2334 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2335                                      struct bpf_verifier_state *st)
2336 {
2337         struct bpf_func_state *func;
2338         struct bpf_reg_state *reg;
2339         int i, j;
2340
2341         /* big hammer: mark all scalars precise in this path.
2342          * pop_stack may still get !precise scalars.
2343          */
2344         for (; st; st = st->parent)
2345                 for (i = 0; i <= st->curframe; i++) {
2346                         func = st->frame[i];
2347                         for (j = 0; j < BPF_REG_FP; j++) {
2348                                 reg = &func->regs[j];
2349                                 if (reg->type != SCALAR_VALUE)
2350                                         continue;
2351                                 reg->precise = true;
2352                         }
2353                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2354                                 if (func->stack[j].slot_type[0] != STACK_SPILL)
2355                                         continue;
2356                                 reg = &func->stack[j].spilled_ptr;
2357                                 if (reg->type != SCALAR_VALUE)
2358                                         continue;
2359                                 reg->precise = true;
2360                         }
2361                 }
2362 }
2363
2364 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2365                                   int spi)
2366 {
2367         struct bpf_verifier_state *st = env->cur_state;
2368         int first_idx = st->first_insn_idx;
2369         int last_idx = env->insn_idx;
2370         struct bpf_func_state *func;
2371         struct bpf_reg_state *reg;
2372         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2373         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2374         bool skip_first = true;
2375         bool new_marks = false;
2376         int i, err;
2377
2378         if (!env->bpf_capable)
2379                 return 0;
2380
2381         func = st->frame[st->curframe];
2382         if (regno >= 0) {
2383                 reg = &func->regs[regno];
2384                 if (reg->type != SCALAR_VALUE) {
2385                         WARN_ONCE(1, "backtracing misuse");
2386                         return -EFAULT;
2387                 }
2388                 if (!reg->precise)
2389                         new_marks = true;
2390                 else
2391                         reg_mask = 0;
2392                 reg->precise = true;
2393         }
2394
2395         while (spi >= 0) {
2396                 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2397                         stack_mask = 0;
2398                         break;
2399                 }
2400                 reg = &func->stack[spi].spilled_ptr;
2401                 if (reg->type != SCALAR_VALUE) {
2402                         stack_mask = 0;
2403                         break;
2404                 }
2405                 if (!reg->precise)
2406                         new_marks = true;
2407                 else
2408                         stack_mask = 0;
2409                 reg->precise = true;
2410                 break;
2411         }
2412
2413         if (!new_marks)
2414                 return 0;
2415         if (!reg_mask && !stack_mask)
2416                 return 0;
2417         for (;;) {
2418                 DECLARE_BITMAP(mask, 64);
2419                 u32 history = st->jmp_history_cnt;
2420
2421                 if (env->log.level & BPF_LOG_LEVEL)
2422                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2423                 for (i = last_idx;;) {
2424                         if (skip_first) {
2425                                 err = 0;
2426                                 skip_first = false;
2427                         } else {
2428                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2429                         }
2430                         if (err == -ENOTSUPP) {
2431                                 mark_all_scalars_precise(env, st);
2432                                 return 0;
2433                         } else if (err) {
2434                                 return err;
2435                         }
2436                         if (!reg_mask && !stack_mask)
2437                                 /* Found assignment(s) into tracked register in this state.
2438                                  * Since this state is already marked, just return.
2439                                  * Nothing to be tracked further in the parent state.
2440                                  */
2441                                 return 0;
2442                         if (i == first_idx)
2443                                 break;
2444                         i = get_prev_insn_idx(st, i, &history);
2445                         if (i >= env->prog->len) {
2446                                 /* This can happen if backtracking reached insn 0
2447                                  * and there are still reg_mask or stack_mask
2448                                  * to backtrack.
2449                                  * It means the backtracking missed the spot where
2450                                  * particular register was initialized with a constant.
2451                                  */
2452                                 verbose(env, "BUG backtracking idx %d\n", i);
2453                                 WARN_ONCE(1, "verifier backtracking bug");
2454                                 return -EFAULT;
2455                         }
2456                 }
2457                 st = st->parent;
2458                 if (!st)
2459                         break;
2460
2461                 new_marks = false;
2462                 func = st->frame[st->curframe];
2463                 bitmap_from_u64(mask, reg_mask);
2464                 for_each_set_bit(i, mask, 32) {
2465                         reg = &func->regs[i];
2466                         if (reg->type != SCALAR_VALUE) {
2467                                 reg_mask &= ~(1u << i);
2468                                 continue;
2469                         }
2470                         if (!reg->precise)
2471                                 new_marks = true;
2472                         reg->precise = true;
2473                 }
2474
2475                 bitmap_from_u64(mask, stack_mask);
2476                 for_each_set_bit(i, mask, 64) {
2477                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2478                                 /* the sequence of instructions:
2479                                  * 2: (bf) r3 = r10
2480                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2481                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2482                                  * doesn't contain jmps. It's backtracked
2483                                  * as a single block.
2484                                  * During backtracking insn 3 is not recognized as
2485                                  * stack access, so at the end of backtracking
2486                                  * stack slot fp-8 is still marked in stack_mask.
2487                                  * However the parent state may not have accessed
2488                                  * fp-8 and it's "unallocated" stack space.
2489                                  * In such case fallback to conservative.
2490                                  */
2491                                 mark_all_scalars_precise(env, st);
2492                                 return 0;
2493                         }
2494
2495                         if (func->stack[i].slot_type[0] != STACK_SPILL) {
2496                                 stack_mask &= ~(1ull << i);
2497                                 continue;
2498                         }
2499                         reg = &func->stack[i].spilled_ptr;
2500                         if (reg->type != SCALAR_VALUE) {
2501                                 stack_mask &= ~(1ull << i);
2502                                 continue;
2503                         }
2504                         if (!reg->precise)
2505                                 new_marks = true;
2506                         reg->precise = true;
2507                 }
2508                 if (env->log.level & BPF_LOG_LEVEL) {
2509                         print_verifier_state(env, func);
2510                         verbose(env, "parent %s regs=%x stack=%llx marks\n",
2511                                 new_marks ? "didn't have" : "already had",
2512                                 reg_mask, stack_mask);
2513                 }
2514
2515                 if (!reg_mask && !stack_mask)
2516                         break;
2517                 if (!new_marks)
2518                         break;
2519
2520                 last_idx = st->last_insn_idx;
2521                 first_idx = st->first_insn_idx;
2522         }
2523         return 0;
2524 }
2525
2526 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2527 {
2528         return __mark_chain_precision(env, regno, -1);
2529 }
2530
2531 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2532 {
2533         return __mark_chain_precision(env, -1, spi);
2534 }
2535
2536 static bool is_spillable_regtype(enum bpf_reg_type type)
2537 {
2538         switch (base_type(type)) {
2539         case PTR_TO_MAP_VALUE:
2540         case PTR_TO_STACK:
2541         case PTR_TO_CTX:
2542         case PTR_TO_PACKET:
2543         case PTR_TO_PACKET_META:
2544         case PTR_TO_PACKET_END:
2545         case PTR_TO_FLOW_KEYS:
2546         case CONST_PTR_TO_MAP:
2547         case PTR_TO_SOCKET:
2548         case PTR_TO_SOCK_COMMON:
2549         case PTR_TO_TCP_SOCK:
2550         case PTR_TO_XDP_SOCK:
2551         case PTR_TO_BTF_ID:
2552         case PTR_TO_BUF:
2553         case PTR_TO_PERCPU_BTF_ID:
2554         case PTR_TO_MEM:
2555         case PTR_TO_FUNC:
2556         case PTR_TO_MAP_KEY:
2557                 return true;
2558         default:
2559                 return false;
2560         }
2561 }
2562
2563 /* Does this register contain a constant zero? */
2564 static bool register_is_null(struct bpf_reg_state *reg)
2565 {
2566         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2567 }
2568
2569 static bool register_is_const(struct bpf_reg_state *reg)
2570 {
2571         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2572 }
2573
2574 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2575 {
2576         return tnum_is_unknown(reg->var_off) &&
2577                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2578                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2579                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2580                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2581 }
2582
2583 static bool register_is_bounded(struct bpf_reg_state *reg)
2584 {
2585         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2586 }
2587
2588 static bool __is_pointer_value(bool allow_ptr_leaks,
2589                                const struct bpf_reg_state *reg)
2590 {
2591         if (allow_ptr_leaks)
2592                 return false;
2593
2594         return reg->type != SCALAR_VALUE;
2595 }
2596
2597 static void save_register_state(struct bpf_func_state *state,
2598                                 int spi, struct bpf_reg_state *reg)
2599 {
2600         int i;
2601
2602         state->stack[spi].spilled_ptr = *reg;
2603         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2604
2605         for (i = 0; i < BPF_REG_SIZE; i++)
2606                 state->stack[spi].slot_type[i] = STACK_SPILL;
2607 }
2608
2609 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2610  * stack boundary and alignment are checked in check_mem_access()
2611  */
2612 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2613                                        /* stack frame we're writing to */
2614                                        struct bpf_func_state *state,
2615                                        int off, int size, int value_regno,
2616                                        int insn_idx)
2617 {
2618         struct bpf_func_state *cur; /* state of the current function */
2619         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2620         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2621         struct bpf_reg_state *reg = NULL;
2622
2623         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2624         if (err)
2625                 return err;
2626         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2627          * so it's aligned access and [off, off + size) are within stack limits
2628          */
2629         if (!env->allow_ptr_leaks &&
2630             state->stack[spi].slot_type[0] == STACK_SPILL &&
2631             size != BPF_REG_SIZE) {
2632                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2633                 return -EACCES;
2634         }
2635
2636         cur = env->cur_state->frame[env->cur_state->curframe];
2637         if (value_regno >= 0)
2638                 reg = &cur->regs[value_regno];
2639         if (!env->bypass_spec_v4) {
2640                 bool sanitize = reg && is_spillable_regtype(reg->type);
2641
2642                 for (i = 0; i < size; i++) {
2643                         if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2644                                 sanitize = true;
2645                                 break;
2646                         }
2647                 }
2648
2649                 if (sanitize)
2650                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2651         }
2652
2653         if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2654             !register_is_null(reg) && env->bpf_capable) {
2655                 if (dst_reg != BPF_REG_FP) {
2656                         /* The backtracking logic can only recognize explicit
2657                          * stack slot address like [fp - 8]. Other spill of
2658                          * scalar via different register has to be conservative.
2659                          * Backtrack from here and mark all registers as precise
2660                          * that contributed into 'reg' being a constant.
2661                          */
2662                         err = mark_chain_precision(env, value_regno);
2663                         if (err)
2664                                 return err;
2665                 }
2666                 save_register_state(state, spi, reg);
2667         } else if (reg && is_spillable_regtype(reg->type)) {
2668                 /* register containing pointer is being spilled into stack */
2669                 if (size != BPF_REG_SIZE) {
2670                         verbose_linfo(env, insn_idx, "; ");
2671                         verbose(env, "invalid size of register spill\n");
2672                         return -EACCES;
2673                 }
2674                 if (state != cur && reg->type == PTR_TO_STACK) {
2675                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2676                         return -EINVAL;
2677                 }
2678                 save_register_state(state, spi, reg);
2679         } else {
2680                 u8 type = STACK_MISC;
2681
2682                 /* regular write of data into stack destroys any spilled ptr */
2683                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2684                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2685                 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2686                         for (i = 0; i < BPF_REG_SIZE; i++)
2687                                 state->stack[spi].slot_type[i] = STACK_MISC;
2688
2689                 /* only mark the slot as written if all 8 bytes were written
2690                  * otherwise read propagation may incorrectly stop too soon
2691                  * when stack slots are partially written.
2692                  * This heuristic means that read propagation will be
2693                  * conservative, since it will add reg_live_read marks
2694                  * to stack slots all the way to first state when programs
2695                  * writes+reads less than 8 bytes
2696                  */
2697                 if (size == BPF_REG_SIZE)
2698                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2699
2700                 /* when we zero initialize stack slots mark them as such */
2701                 if (reg && register_is_null(reg)) {
2702                         /* backtracking doesn't work for STACK_ZERO yet. */
2703                         err = mark_chain_precision(env, value_regno);
2704                         if (err)
2705                                 return err;
2706                         type = STACK_ZERO;
2707                 }
2708
2709                 /* Mark slots affected by this stack write. */
2710                 for (i = 0; i < size; i++)
2711                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2712                                 type;
2713         }
2714         return 0;
2715 }
2716
2717 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2718  * known to contain a variable offset.
2719  * This function checks whether the write is permitted and conservatively
2720  * tracks the effects of the write, considering that each stack slot in the
2721  * dynamic range is potentially written to.
2722  *
2723  * 'off' includes 'regno->off'.
2724  * 'value_regno' can be -1, meaning that an unknown value is being written to
2725  * the stack.
2726  *
2727  * Spilled pointers in range are not marked as written because we don't know
2728  * what's going to be actually written. This means that read propagation for
2729  * future reads cannot be terminated by this write.
2730  *
2731  * For privileged programs, uninitialized stack slots are considered
2732  * initialized by this write (even though we don't know exactly what offsets
2733  * are going to be written to). The idea is that we don't want the verifier to
2734  * reject future reads that access slots written to through variable offsets.
2735  */
2736 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2737                                      /* func where register points to */
2738                                      struct bpf_func_state *state,
2739                                      int ptr_regno, int off, int size,
2740                                      int value_regno, int insn_idx)
2741 {
2742         struct bpf_func_state *cur; /* state of the current function */
2743         int min_off, max_off;
2744         int i, err;
2745         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2746         bool writing_zero = false;
2747         /* set if the fact that we're writing a zero is used to let any
2748          * stack slots remain STACK_ZERO
2749          */
2750         bool zero_used = false;
2751
2752         cur = env->cur_state->frame[env->cur_state->curframe];
2753         ptr_reg = &cur->regs[ptr_regno];
2754         min_off = ptr_reg->smin_value + off;
2755         max_off = ptr_reg->smax_value + off + size;
2756         if (value_regno >= 0)
2757                 value_reg = &cur->regs[value_regno];
2758         if (value_reg && register_is_null(value_reg))
2759                 writing_zero = true;
2760
2761         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2762         if (err)
2763                 return err;
2764
2765
2766         /* Variable offset writes destroy any spilled pointers in range. */
2767         for (i = min_off; i < max_off; i++) {
2768                 u8 new_type, *stype;
2769                 int slot, spi;
2770
2771                 slot = -i - 1;
2772                 spi = slot / BPF_REG_SIZE;
2773                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2774
2775                 if (!env->allow_ptr_leaks
2776                                 && *stype != NOT_INIT
2777                                 && *stype != SCALAR_VALUE) {
2778                         /* Reject the write if there's are spilled pointers in
2779                          * range. If we didn't reject here, the ptr status
2780                          * would be erased below (even though not all slots are
2781                          * actually overwritten), possibly opening the door to
2782                          * leaks.
2783                          */
2784                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2785                                 insn_idx, i);
2786                         return -EINVAL;
2787                 }
2788
2789                 /* Erase all spilled pointers. */
2790                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2791
2792                 /* Update the slot type. */
2793                 new_type = STACK_MISC;
2794                 if (writing_zero && *stype == STACK_ZERO) {
2795                         new_type = STACK_ZERO;
2796                         zero_used = true;
2797                 }
2798                 /* If the slot is STACK_INVALID, we check whether it's OK to
2799                  * pretend that it will be initialized by this write. The slot
2800                  * might not actually be written to, and so if we mark it as
2801                  * initialized future reads might leak uninitialized memory.
2802                  * For privileged programs, we will accept such reads to slots
2803                  * that may or may not be written because, if we're reject
2804                  * them, the error would be too confusing.
2805                  */
2806                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2807                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2808                                         insn_idx, i);
2809                         return -EINVAL;
2810                 }
2811                 *stype = new_type;
2812         }
2813         if (zero_used) {
2814                 /* backtracking doesn't work for STACK_ZERO yet. */
2815                 err = mark_chain_precision(env, value_regno);
2816                 if (err)
2817                         return err;
2818         }
2819         return 0;
2820 }
2821
2822 /* When register 'dst_regno' is assigned some values from stack[min_off,
2823  * max_off), we set the register's type according to the types of the
2824  * respective stack slots. If all the stack values are known to be zeros, then
2825  * so is the destination reg. Otherwise, the register is considered to be
2826  * SCALAR. This function does not deal with register filling; the caller must
2827  * ensure that all spilled registers in the stack range have been marked as
2828  * read.
2829  */
2830 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2831                                 /* func where src register points to */
2832                                 struct bpf_func_state *ptr_state,
2833                                 int min_off, int max_off, int dst_regno)
2834 {
2835         struct bpf_verifier_state *vstate = env->cur_state;
2836         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2837         int i, slot, spi;
2838         u8 *stype;
2839         int zeros = 0;
2840
2841         for (i = min_off; i < max_off; i++) {
2842                 slot = -i - 1;
2843                 spi = slot / BPF_REG_SIZE;
2844                 stype = ptr_state->stack[spi].slot_type;
2845                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2846                         break;
2847                 zeros++;
2848         }
2849         if (zeros == max_off - min_off) {
2850                 /* any access_size read into register is zero extended,
2851                  * so the whole register == const_zero
2852                  */
2853                 __mark_reg_const_zero(&state->regs[dst_regno]);
2854                 /* backtracking doesn't support STACK_ZERO yet,
2855                  * so mark it precise here, so that later
2856                  * backtracking can stop here.
2857                  * Backtracking may not need this if this register
2858                  * doesn't participate in pointer adjustment.
2859                  * Forward propagation of precise flag is not
2860                  * necessary either. This mark is only to stop
2861                  * backtracking. Any register that contributed
2862                  * to const 0 was marked precise before spill.
2863                  */
2864                 state->regs[dst_regno].precise = true;
2865         } else {
2866                 /* have read misc data from the stack */
2867                 mark_reg_unknown(env, state->regs, dst_regno);
2868         }
2869         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2870 }
2871
2872 /* Read the stack at 'off' and put the results into the register indicated by
2873  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2874  * spilled reg.
2875  *
2876  * 'dst_regno' can be -1, meaning that the read value is not going to a
2877  * register.
2878  *
2879  * The access is assumed to be within the current stack bounds.
2880  */
2881 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2882                                       /* func where src register points to */
2883                                       struct bpf_func_state *reg_state,
2884                                       int off, int size, int dst_regno)
2885 {
2886         struct bpf_verifier_state *vstate = env->cur_state;
2887         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2888         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2889         struct bpf_reg_state *reg;
2890         u8 *stype;
2891
2892         stype = reg_state->stack[spi].slot_type;
2893         reg = &reg_state->stack[spi].spilled_ptr;
2894
2895         if (stype[0] == STACK_SPILL) {
2896                 if (size != BPF_REG_SIZE) {
2897                         if (reg->type != SCALAR_VALUE) {
2898                                 verbose_linfo(env, env->insn_idx, "; ");
2899                                 verbose(env, "invalid size of register fill\n");
2900                                 return -EACCES;
2901                         }
2902                         if (dst_regno >= 0) {
2903                                 mark_reg_unknown(env, state->regs, dst_regno);
2904                                 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2905                         }
2906                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2907                         return 0;
2908                 }
2909                 for (i = 1; i < BPF_REG_SIZE; i++) {
2910                         if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2911                                 verbose(env, "corrupted spill memory\n");
2912                                 return -EACCES;
2913                         }
2914                 }
2915
2916                 if (dst_regno >= 0) {
2917                         /* restore register state from stack */
2918                         state->regs[dst_regno] = *reg;
2919                         /* mark reg as written since spilled pointer state likely
2920                          * has its liveness marks cleared by is_state_visited()
2921                          * which resets stack/reg liveness for state transitions
2922                          */
2923                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2924                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2925                         /* If dst_regno==-1, the caller is asking us whether
2926                          * it is acceptable to use this value as a SCALAR_VALUE
2927                          * (e.g. for XADD).
2928                          * We must not allow unprivileged callers to do that
2929                          * with spilled pointers.
2930                          */
2931                         verbose(env, "leaking pointer from stack off %d\n",
2932                                 off);
2933                         return -EACCES;
2934                 }
2935                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2936         } else {
2937                 u8 type;
2938
2939                 for (i = 0; i < size; i++) {
2940                         type = stype[(slot - i) % BPF_REG_SIZE];
2941                         if (type == STACK_MISC)
2942                                 continue;
2943                         if (type == STACK_ZERO)
2944                                 continue;
2945                         verbose(env, "invalid read from stack off %d+%d size %d\n",
2946                                 off, i, size);
2947                         return -EACCES;
2948                 }
2949                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2950                 if (dst_regno >= 0)
2951                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2952         }
2953         return 0;
2954 }
2955
2956 enum stack_access_src {
2957         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2958         ACCESS_HELPER = 2,  /* the access is performed by a helper */
2959 };
2960
2961 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2962                                          int regno, int off, int access_size,
2963                                          bool zero_size_allowed,
2964                                          enum stack_access_src type,
2965                                          struct bpf_call_arg_meta *meta);
2966
2967 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2968 {
2969         return cur_regs(env) + regno;
2970 }
2971
2972 /* Read the stack at 'ptr_regno + off' and put the result into the register
2973  * 'dst_regno'.
2974  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2975  * but not its variable offset.
2976  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2977  *
2978  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2979  * filling registers (i.e. reads of spilled register cannot be detected when
2980  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2981  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2982  * offset; for a fixed offset check_stack_read_fixed_off should be used
2983  * instead.
2984  */
2985 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2986                                     int ptr_regno, int off, int size, int dst_regno)
2987 {
2988         /* The state of the source register. */
2989         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2990         struct bpf_func_state *ptr_state = func(env, reg);
2991         int err;
2992         int min_off, max_off;
2993
2994         /* Note that we pass a NULL meta, so raw access will not be permitted.
2995          */
2996         err = check_stack_range_initialized(env, ptr_regno, off, size,
2997                                             false, ACCESS_DIRECT, NULL);
2998         if (err)
2999                 return err;
3000
3001         min_off = reg->smin_value + off;
3002         max_off = reg->smax_value + off;
3003         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3004         return 0;
3005 }
3006
3007 /* check_stack_read dispatches to check_stack_read_fixed_off or
3008  * check_stack_read_var_off.
3009  *
3010  * The caller must ensure that the offset falls within the allocated stack
3011  * bounds.
3012  *
3013  * 'dst_regno' is a register which will receive the value from the stack. It
3014  * can be -1, meaning that the read value is not going to a register.
3015  */
3016 static int check_stack_read(struct bpf_verifier_env *env,
3017                             int ptr_regno, int off, int size,
3018                             int dst_regno)
3019 {
3020         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3021         struct bpf_func_state *state = func(env, reg);
3022         int err;
3023         /* Some accesses are only permitted with a static offset. */
3024         bool var_off = !tnum_is_const(reg->var_off);
3025
3026         /* The offset is required to be static when reads don't go to a
3027          * register, in order to not leak pointers (see
3028          * check_stack_read_fixed_off).
3029          */
3030         if (dst_regno < 0 && var_off) {
3031                 char tn_buf[48];
3032
3033                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3034                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3035                         tn_buf, off, size);
3036                 return -EACCES;
3037         }
3038         /* Variable offset is prohibited for unprivileged mode for simplicity
3039          * since it requires corresponding support in Spectre masking for stack
3040          * ALU. See also retrieve_ptr_limit().
3041          */
3042         if (!env->bypass_spec_v1 && var_off) {
3043                 char tn_buf[48];
3044
3045                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3046                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3047                                 ptr_regno, tn_buf);
3048                 return -EACCES;
3049         }
3050
3051         if (!var_off) {
3052                 off += reg->var_off.value;
3053                 err = check_stack_read_fixed_off(env, state, off, size,
3054                                                  dst_regno);
3055         } else {
3056                 /* Variable offset stack reads need more conservative handling
3057                  * than fixed offset ones. Note that dst_regno >= 0 on this
3058                  * branch.
3059                  */
3060                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3061                                                dst_regno);
3062         }
3063         return err;
3064 }
3065
3066
3067 /* check_stack_write dispatches to check_stack_write_fixed_off or
3068  * check_stack_write_var_off.
3069  *
3070  * 'ptr_regno' is the register used as a pointer into the stack.
3071  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3072  * 'value_regno' is the register whose value we're writing to the stack. It can
3073  * be -1, meaning that we're not writing from a register.
3074  *
3075  * The caller must ensure that the offset falls within the maximum stack size.
3076  */
3077 static int check_stack_write(struct bpf_verifier_env *env,
3078                              int ptr_regno, int off, int size,
3079                              int value_regno, int insn_idx)
3080 {
3081         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3082         struct bpf_func_state *state = func(env, reg);
3083         int err;
3084
3085         if (tnum_is_const(reg->var_off)) {
3086                 off += reg->var_off.value;
3087                 err = check_stack_write_fixed_off(env, state, off, size,
3088                                                   value_regno, insn_idx);
3089         } else {
3090                 /* Variable offset stack reads need more conservative handling
3091                  * than fixed offset ones.
3092                  */
3093                 err = check_stack_write_var_off(env, state,
3094                                                 ptr_regno, off, size,
3095                                                 value_regno, insn_idx);
3096         }
3097         return err;
3098 }
3099
3100 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3101                                  int off, int size, enum bpf_access_type type)
3102 {
3103         struct bpf_reg_state *regs = cur_regs(env);
3104         struct bpf_map *map = regs[regno].map_ptr;
3105         u32 cap = bpf_map_flags_to_cap(map);
3106
3107         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3108                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3109                         map->value_size, off, size);
3110                 return -EACCES;
3111         }
3112
3113         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3114                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3115                         map->value_size, off, size);
3116                 return -EACCES;
3117         }
3118
3119         return 0;
3120 }
3121
3122 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3123 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3124                               int off, int size, u32 mem_size,
3125                               bool zero_size_allowed)
3126 {
3127         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3128         struct bpf_reg_state *reg;
3129
3130         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3131                 return 0;
3132
3133         reg = &cur_regs(env)[regno];
3134         switch (reg->type) {
3135         case PTR_TO_MAP_KEY:
3136                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3137                         mem_size, off, size);
3138                 break;
3139         case PTR_TO_MAP_VALUE:
3140                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3141                         mem_size, off, size);
3142                 break;
3143         case PTR_TO_PACKET:
3144         case PTR_TO_PACKET_META:
3145         case PTR_TO_PACKET_END:
3146                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3147                         off, size, regno, reg->id, off, mem_size);
3148                 break;
3149         case PTR_TO_MEM:
3150         default:
3151                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3152                         mem_size, off, size);
3153         }
3154
3155         return -EACCES;
3156 }
3157
3158 /* check read/write into a memory region with possible variable offset */
3159 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3160                                    int off, int size, u32 mem_size,
3161                                    bool zero_size_allowed)
3162 {
3163         struct bpf_verifier_state *vstate = env->cur_state;
3164         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3165         struct bpf_reg_state *reg = &state->regs[regno];
3166         int err;
3167
3168         /* We may have adjusted the register pointing to memory region, so we
3169          * need to try adding each of min_value and max_value to off
3170          * to make sure our theoretical access will be safe.
3171          */
3172         if (env->log.level & BPF_LOG_LEVEL)
3173                 print_verifier_state(env, state);
3174
3175         /* The minimum value is only important with signed
3176          * comparisons where we can't assume the floor of a
3177          * value is 0.  If we are using signed variables for our
3178          * index'es we need to make sure that whatever we use
3179          * will have a set floor within our range.
3180          */
3181         if (reg->smin_value < 0 &&
3182             (reg->smin_value == S64_MIN ||
3183              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3184               reg->smin_value + off < 0)) {
3185                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3186                         regno);
3187                 return -EACCES;
3188         }
3189         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3190                                  mem_size, zero_size_allowed);
3191         if (err) {
3192                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3193                         regno);
3194                 return err;
3195         }
3196
3197         /* If we haven't set a max value then we need to bail since we can't be
3198          * sure we won't do bad things.
3199          * If reg->umax_value + off could overflow, treat that as unbounded too.
3200          */
3201         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3202                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3203                         regno);
3204                 return -EACCES;
3205         }
3206         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3207                                  mem_size, zero_size_allowed);
3208         if (err) {
3209                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3210                         regno);
3211                 return err;
3212         }
3213
3214         return 0;
3215 }
3216
3217 /* check read/write into a map element with possible variable offset */
3218 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3219                             int off, int size, bool zero_size_allowed)
3220 {
3221         struct bpf_verifier_state *vstate = env->cur_state;
3222         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3223         struct bpf_reg_state *reg = &state->regs[regno];
3224         struct bpf_map *map = reg->map_ptr;
3225         int err;
3226
3227         err = check_mem_region_access(env, regno, off, size, map->value_size,
3228                                       zero_size_allowed);
3229         if (err)
3230                 return err;
3231
3232         if (map_value_has_spin_lock(map)) {
3233                 u32 lock = map->spin_lock_off;
3234
3235                 /* if any part of struct bpf_spin_lock can be touched by
3236                  * load/store reject this program.
3237                  * To check that [x1, x2) overlaps with [y1, y2)
3238                  * it is sufficient to check x1 < y2 && y1 < x2.
3239                  */
3240                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3241                      lock < reg->umax_value + off + size) {
3242                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3243                         return -EACCES;
3244                 }
3245         }
3246         if (map_value_has_timer(map)) {
3247                 u32 t = map->timer_off;
3248
3249                 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3250                      t < reg->umax_value + off + size) {
3251                         verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3252                         return -EACCES;
3253                 }
3254         }
3255         return err;
3256 }
3257
3258 #define MAX_PACKET_OFF 0xffff
3259
3260 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3261 {
3262         return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3263 }
3264
3265 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3266                                        const struct bpf_call_arg_meta *meta,
3267                                        enum bpf_access_type t)
3268 {
3269         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3270
3271         switch (prog_type) {
3272         /* Program types only with direct read access go here! */
3273         case BPF_PROG_TYPE_LWT_IN:
3274         case BPF_PROG_TYPE_LWT_OUT:
3275         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3276         case BPF_PROG_TYPE_SK_REUSEPORT:
3277         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3278         case BPF_PROG_TYPE_CGROUP_SKB:
3279                 if (t == BPF_WRITE)
3280                         return false;
3281                 fallthrough;
3282
3283         /* Program types with direct read + write access go here! */
3284         case BPF_PROG_TYPE_SCHED_CLS:
3285         case BPF_PROG_TYPE_SCHED_ACT:
3286         case BPF_PROG_TYPE_XDP:
3287         case BPF_PROG_TYPE_LWT_XMIT:
3288         case BPF_PROG_TYPE_SK_SKB:
3289         case BPF_PROG_TYPE_SK_MSG:
3290                 if (meta)
3291                         return meta->pkt_access;
3292
3293                 env->seen_direct_write = true;
3294                 return true;
3295
3296         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3297                 if (t == BPF_WRITE)
3298                         env->seen_direct_write = true;
3299
3300                 return true;
3301
3302         default:
3303                 return false;
3304         }
3305 }
3306
3307 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3308                                int size, bool zero_size_allowed)
3309 {
3310         struct bpf_reg_state *regs = cur_regs(env);
3311         struct bpf_reg_state *reg = &regs[regno];
3312         int err;
3313
3314         /* We may have added a variable offset to the packet pointer; but any
3315          * reg->range we have comes after that.  We are only checking the fixed
3316          * offset.
3317          */
3318
3319         /* We don't allow negative numbers, because we aren't tracking enough
3320          * detail to prove they're safe.
3321          */
3322         if (reg->smin_value < 0) {
3323                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3324                         regno);
3325                 return -EACCES;
3326         }
3327
3328         err = reg->range < 0 ? -EINVAL :
3329               __check_mem_access(env, regno, off, size, reg->range,
3330                                  zero_size_allowed);
3331         if (err) {
3332                 verbose(env, "R%d offset is outside of the packet\n", regno);
3333                 return err;
3334         }
3335
3336         /* __check_mem_access has made sure "off + size - 1" is within u16.
3337          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3338          * otherwise find_good_pkt_pointers would have refused to set range info
3339          * that __check_mem_access would have rejected this pkt access.
3340          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3341          */
3342         env->prog->aux->max_pkt_offset =
3343                 max_t(u32, env->prog->aux->max_pkt_offset,
3344                       off + reg->umax_value + size - 1);
3345
3346         return err;
3347 }
3348
3349 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3350 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3351                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
3352                             struct btf **btf, u32 *btf_id)
3353 {
3354         struct bpf_insn_access_aux info = {
3355                 .reg_type = *reg_type,
3356                 .log = &env->log,
3357         };
3358
3359         if (env->ops->is_valid_access &&
3360             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3361                 /* A non zero info.ctx_field_size indicates that this field is a
3362                  * candidate for later verifier transformation to load the whole
3363                  * field and then apply a mask when accessed with a narrower
3364                  * access than actual ctx access size. A zero info.ctx_field_size
3365                  * will only allow for whole field access and rejects any other
3366                  * type of narrower access.
3367                  */
3368                 *reg_type = info.reg_type;
3369
3370                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3371                         *btf = info.btf;
3372                         *btf_id = info.btf_id;
3373                 } else {
3374                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3375                 }
3376                 /* remember the offset of last byte accessed in ctx */
3377                 if (env->prog->aux->max_ctx_offset < off + size)
3378                         env->prog->aux->max_ctx_offset = off + size;
3379                 return 0;
3380         }
3381
3382         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3383         return -EACCES;
3384 }
3385
3386 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3387                                   int size)
3388 {
3389         if (size < 0 || off < 0 ||
3390             (u64)off + size > sizeof(struct bpf_flow_keys)) {
3391                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3392                         off, size);
3393                 return -EACCES;
3394         }
3395         return 0;
3396 }
3397
3398 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3399                              u32 regno, int off, int size,
3400                              enum bpf_access_type t)
3401 {
3402         struct bpf_reg_state *regs = cur_regs(env);
3403         struct bpf_reg_state *reg = &regs[regno];
3404         struct bpf_insn_access_aux info = {};
3405         bool valid;
3406
3407         if (reg->smin_value < 0) {
3408                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3409                         regno);
3410                 return -EACCES;
3411         }
3412
3413         switch (reg->type) {
3414         case PTR_TO_SOCK_COMMON:
3415                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3416                 break;
3417         case PTR_TO_SOCKET:
3418                 valid = bpf_sock_is_valid_access(off, size, t, &info);
3419                 break;
3420         case PTR_TO_TCP_SOCK:
3421                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3422                 break;
3423         case PTR_TO_XDP_SOCK:
3424                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3425                 break;
3426         default:
3427                 valid = false;
3428         }
3429
3430
3431         if (valid) {
3432                 env->insn_aux_data[insn_idx].ctx_field_size =
3433                         info.ctx_field_size;
3434                 return 0;
3435         }
3436
3437         verbose(env, "R%d invalid %s access off=%d size=%d\n",
3438                 regno, reg_type_str(env, reg->type), off, size);
3439
3440         return -EACCES;
3441 }
3442
3443 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3444 {
3445         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3446 }
3447
3448 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3449 {
3450         const struct bpf_reg_state *reg = reg_state(env, regno);
3451
3452         return reg->type == PTR_TO_CTX;
3453 }
3454
3455 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3456 {
3457         const struct bpf_reg_state *reg = reg_state(env, regno);
3458
3459         return type_is_sk_pointer(reg->type);
3460 }
3461
3462 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3463 {
3464         const struct bpf_reg_state *reg = reg_state(env, regno);
3465
3466         return type_is_pkt_pointer(reg->type);
3467 }
3468
3469 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3470 {
3471         const struct bpf_reg_state *reg = reg_state(env, regno);
3472
3473         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3474         return reg->type == PTR_TO_FLOW_KEYS;
3475 }
3476
3477 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3478                                    const struct bpf_reg_state *reg,
3479                                    int off, int size, bool strict)
3480 {
3481         struct tnum reg_off;
3482         int ip_align;
3483
3484         /* Byte size accesses are always allowed. */
3485         if (!strict || size == 1)
3486                 return 0;
3487
3488         /* For platforms that do not have a Kconfig enabling
3489          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3490          * NET_IP_ALIGN is universally set to '2'.  And on platforms
3491          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3492          * to this code only in strict mode where we want to emulate
3493          * the NET_IP_ALIGN==2 checking.  Therefore use an
3494          * unconditional IP align value of '2'.
3495          */
3496         ip_align = 2;
3497
3498         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3499         if (!tnum_is_aligned(reg_off, size)) {
3500                 char tn_buf[48];
3501
3502                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3503                 verbose(env,
3504                         "misaligned packet access off %d+%s+%d+%d size %d\n",
3505                         ip_align, tn_buf, reg->off, off, size);
3506                 return -EACCES;
3507         }
3508
3509         return 0;
3510 }
3511
3512 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3513                                        const struct bpf_reg_state *reg,
3514                                        const char *pointer_desc,
3515                                        int off, int size, bool strict)
3516 {
3517         struct tnum reg_off;
3518
3519         /* Byte size accesses are always allowed. */
3520         if (!strict || size == 1)
3521                 return 0;
3522
3523         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3524         if (!tnum_is_aligned(reg_off, size)) {
3525                 char tn_buf[48];
3526
3527                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3528                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3529                         pointer_desc, tn_buf, reg->off, off, size);
3530                 return -EACCES;
3531         }
3532
3533         return 0;
3534 }
3535
3536 static int check_ptr_alignment(struct bpf_verifier_env *env,
3537                                const struct bpf_reg_state *reg, int off,
3538                                int size, bool strict_alignment_once)
3539 {
3540         bool strict = env->strict_alignment || strict_alignment_once;
3541         const char *pointer_desc = "";
3542
3543         switch (reg->type) {
3544         case PTR_TO_PACKET:
3545         case PTR_TO_PACKET_META:
3546                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3547                  * right in front, treat it the very same way.
3548                  */
3549                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3550         case PTR_TO_FLOW_KEYS:
3551                 pointer_desc = "flow keys ";
3552                 break;
3553         case PTR_TO_MAP_KEY:
3554                 pointer_desc = "key ";
3555                 break;
3556         case PTR_TO_MAP_VALUE:
3557                 pointer_desc = "value ";
3558                 break;
3559         case PTR_TO_CTX:
3560                 pointer_desc = "context ";
3561                 break;
3562         case PTR_TO_STACK:
3563                 pointer_desc = "stack ";
3564                 /* The stack spill tracking logic in check_stack_write_fixed_off()
3565                  * and check_stack_read_fixed_off() relies on stack accesses being
3566                  * aligned.
3567                  */
3568                 strict = true;
3569                 break;
3570         case PTR_TO_SOCKET:
3571                 pointer_desc = "sock ";
3572                 break;
3573         case PTR_TO_SOCK_COMMON:
3574                 pointer_desc = "sock_common ";
3575                 break;
3576         case PTR_TO_TCP_SOCK:
3577                 pointer_desc = "tcp_sock ";
3578                 break;
3579         case PTR_TO_XDP_SOCK:
3580                 pointer_desc = "xdp_sock ";
3581                 break;
3582         default:
3583                 break;
3584         }
3585         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3586                                            strict);
3587 }
3588
3589 static int update_stack_depth(struct bpf_verifier_env *env,
3590                               const struct bpf_func_state *func,
3591                               int off)
3592 {
3593         u16 stack = env->subprog_info[func->subprogno].stack_depth;
3594
3595         if (stack >= -off)
3596                 return 0;
3597
3598         /* update known max for given subprogram */
3599         env->subprog_info[func->subprogno].stack_depth = -off;
3600         return 0;
3601 }
3602
3603 /* starting from main bpf function walk all instructions of the function
3604  * and recursively walk all callees that given function can call.
3605  * Ignore jump and exit insns.
3606  * Since recursion is prevented by check_cfg() this algorithm
3607  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3608  */
3609 static int check_max_stack_depth(struct bpf_verifier_env *env)
3610 {
3611         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3612         struct bpf_subprog_info *subprog = env->subprog_info;
3613         struct bpf_insn *insn = env->prog->insnsi;
3614         bool tail_call_reachable = false;
3615         int ret_insn[MAX_CALL_FRAMES];
3616         int ret_prog[MAX_CALL_FRAMES];
3617         int j;
3618
3619 process_func:
3620         /* protect against potential stack overflow that might happen when
3621          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3622          * depth for such case down to 256 so that the worst case scenario
3623          * would result in 8k stack size (32 which is tailcall limit * 256 =
3624          * 8k).
3625          *
3626          * To get the idea what might happen, see an example:
3627          * func1 -> sub rsp, 128
3628          *  subfunc1 -> sub rsp, 256
3629          *  tailcall1 -> add rsp, 256
3630          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3631          *   subfunc2 -> sub rsp, 64
3632          *   subfunc22 -> sub rsp, 128
3633          *   tailcall2 -> add rsp, 128
3634          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3635          *
3636          * tailcall will unwind the current stack frame but it will not get rid
3637          * of caller's stack as shown on the example above.
3638          */
3639         if (idx && subprog[idx].has_tail_call && depth >= 256) {
3640                 verbose(env,
3641                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3642                         depth);
3643                 return -EACCES;
3644         }
3645         /* round up to 32-bytes, since this is granularity
3646          * of interpreter stack size
3647          */
3648         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3649         if (depth > MAX_BPF_STACK) {
3650                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3651                         frame + 1, depth);
3652                 return -EACCES;
3653         }
3654 continue_func:
3655         subprog_end = subprog[idx + 1].start;
3656         for (; i < subprog_end; i++) {
3657                 int next_insn;
3658
3659                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3660                         continue;
3661                 /* remember insn and function to return to */
3662                 ret_insn[frame] = i + 1;
3663                 ret_prog[frame] = idx;
3664
3665                 /* find the callee */
3666                 next_insn = i + insn[i].imm + 1;
3667                 idx = find_subprog(env, next_insn);
3668                 if (idx < 0) {
3669                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3670                                   next_insn);
3671                         return -EFAULT;
3672                 }
3673                 if (subprog[idx].is_async_cb) {
3674                         if (subprog[idx].has_tail_call) {
3675                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3676                                 return -EFAULT;
3677                         }
3678                          /* async callbacks don't increase bpf prog stack size */
3679                         continue;
3680                 }
3681                 i = next_insn;
3682
3683                 if (subprog[idx].has_tail_call)
3684                         tail_call_reachable = true;
3685
3686                 frame++;
3687                 if (frame >= MAX_CALL_FRAMES) {
3688                         verbose(env, "the call stack of %d frames is too deep !\n",
3689                                 frame);
3690                         return -E2BIG;
3691                 }
3692                 goto process_func;
3693         }
3694         /* if tail call got detected across bpf2bpf calls then mark each of the
3695          * currently present subprog frames as tail call reachable subprogs;
3696          * this info will be utilized by JIT so that we will be preserving the
3697          * tail call counter throughout bpf2bpf calls combined with tailcalls
3698          */
3699         if (tail_call_reachable)
3700                 for (j = 0; j < frame; j++)
3701                         subprog[ret_prog[j]].tail_call_reachable = true;
3702         if (subprog[0].tail_call_reachable)
3703                 env->prog->aux->tail_call_reachable = true;
3704
3705         /* end of for() loop means the last insn of the 'subprog'
3706          * was reached. Doesn't matter whether it was JA or EXIT
3707          */
3708         if (frame == 0)
3709                 return 0;
3710         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3711         frame--;
3712         i = ret_insn[frame];
3713         idx = ret_prog[frame];
3714         goto continue_func;
3715 }
3716
3717 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3718 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3719                                   const struct bpf_insn *insn, int idx)
3720 {
3721         int start = idx + insn->imm + 1, subprog;
3722
3723         subprog = find_subprog(env, start);
3724         if (subprog < 0) {
3725                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3726                           start);
3727                 return -EFAULT;
3728         }
3729         return env->subprog_info[subprog].stack_depth;
3730 }
3731 #endif
3732
3733 int check_ctx_reg(struct bpf_verifier_env *env,
3734                   const struct bpf_reg_state *reg, int regno)
3735 {
3736         /* Access to ctx or passing it to a helper is only allowed in
3737          * its original, unmodified form.
3738          */
3739
3740         if (reg->off) {
3741                 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3742                         regno, reg->off);
3743                 return -EACCES;
3744         }
3745
3746         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3747                 char tn_buf[48];
3748
3749                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3750                 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3751                 return -EACCES;
3752         }
3753
3754         return 0;
3755 }
3756
3757 static int __check_buffer_access(struct bpf_verifier_env *env,
3758                                  const char *buf_info,
3759                                  const struct bpf_reg_state *reg,
3760                                  int regno, int off, int size)
3761 {
3762         if (off < 0) {
3763                 verbose(env,
3764                         "R%d invalid %s buffer access: off=%d, size=%d\n",
3765                         regno, buf_info, off, size);
3766                 return -EACCES;
3767         }
3768         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3769                 char tn_buf[48];
3770
3771                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3772                 verbose(env,
3773                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3774                         regno, off, tn_buf);
3775                 return -EACCES;
3776         }
3777
3778         return 0;
3779 }
3780
3781 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3782                                   const struct bpf_reg_state *reg,
3783                                   int regno, int off, int size)
3784 {
3785         int err;
3786
3787         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3788         if (err)
3789                 return err;
3790
3791         if (off + size > env->prog->aux->max_tp_access)
3792                 env->prog->aux->max_tp_access = off + size;
3793
3794         return 0;
3795 }
3796
3797 static int check_buffer_access(struct bpf_verifier_env *env,
3798                                const struct bpf_reg_state *reg,
3799                                int regno, int off, int size,
3800                                bool zero_size_allowed,
3801                                const char *buf_info,
3802                                u32 *max_access)
3803 {
3804         int err;
3805
3806         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3807         if (err)
3808                 return err;
3809
3810         if (off + size > *max_access)
3811                 *max_access = off + size;
3812
3813         return 0;
3814 }
3815
3816 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3817 static void zext_32_to_64(struct bpf_reg_state *reg)
3818 {
3819         reg->var_off = tnum_subreg(reg->var_off);
3820         __reg_assign_32_into_64(reg);
3821 }
3822
3823 /* truncate register to smaller size (in bytes)
3824  * must be called with size < BPF_REG_SIZE
3825  */
3826 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3827 {
3828         u64 mask;
3829
3830         /* clear high bits in bit representation */
3831         reg->var_off = tnum_cast(reg->var_off, size);
3832
3833         /* fix arithmetic bounds */
3834         mask = ((u64)1 << (size * 8)) - 1;
3835         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3836                 reg->umin_value &= mask;
3837                 reg->umax_value &= mask;
3838         } else {
3839                 reg->umin_value = 0;
3840                 reg->umax_value = mask;
3841         }
3842         reg->smin_value = reg->umin_value;
3843         reg->smax_value = reg->umax_value;
3844
3845         /* If size is smaller than 32bit register the 32bit register
3846          * values are also truncated so we push 64-bit bounds into
3847          * 32-bit bounds. Above were truncated < 32-bits already.
3848          */
3849         if (size >= 4)
3850                 return;
3851         __reg_combine_64_into_32(reg);
3852 }
3853
3854 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3855 {
3856         /* A map is considered read-only if the following condition are true:
3857          *
3858          * 1) BPF program side cannot change any of the map content. The
3859          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
3860          *    and was set at map creation time.
3861          * 2) The map value(s) have been initialized from user space by a
3862          *    loader and then "frozen", such that no new map update/delete
3863          *    operations from syscall side are possible for the rest of
3864          *    the map's lifetime from that point onwards.
3865          * 3) Any parallel/pending map update/delete operations from syscall
3866          *    side have been completed. Only after that point, it's safe to
3867          *    assume that map value(s) are immutable.
3868          */
3869         return (map->map_flags & BPF_F_RDONLY_PROG) &&
3870                READ_ONCE(map->frozen) &&
3871                !bpf_map_write_active(map);
3872 }
3873
3874 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3875 {
3876         void *ptr;
3877         u64 addr;
3878         int err;
3879
3880         err = map->ops->map_direct_value_addr(map, &addr, off);
3881         if (err)
3882                 return err;
3883         ptr = (void *)(long)addr + off;
3884
3885         switch (size) {
3886         case sizeof(u8):
3887                 *val = (u64)*(u8 *)ptr;
3888                 break;
3889         case sizeof(u16):
3890                 *val = (u64)*(u16 *)ptr;
3891                 break;
3892         case sizeof(u32):
3893                 *val = (u64)*(u32 *)ptr;
3894                 break;
3895         case sizeof(u64):
3896                 *val = *(u64 *)ptr;
3897                 break;
3898         default:
3899                 return -EINVAL;
3900         }
3901         return 0;
3902 }
3903
3904 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3905                                    struct bpf_reg_state *regs,
3906                                    int regno, int off, int size,
3907                                    enum bpf_access_type atype,
3908                                    int value_regno)
3909 {
3910         struct bpf_reg_state *reg = regs + regno;
3911         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3912         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3913         u32 btf_id;
3914         int ret;
3915
3916         if (off < 0) {
3917                 verbose(env,
3918                         "R%d is ptr_%s invalid negative access: off=%d\n",
3919                         regno, tname, off);
3920                 return -EACCES;
3921         }
3922         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3923                 char tn_buf[48];
3924
3925                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3926                 verbose(env,
3927                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3928                         regno, tname, off, tn_buf);
3929                 return -EACCES;
3930         }
3931
3932         if (env->ops->btf_struct_access) {
3933                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3934                                                   off, size, atype, &btf_id);
3935         } else {
3936                 if (atype != BPF_READ) {
3937                         verbose(env, "only read is supported\n");
3938                         return -EACCES;
3939                 }
3940
3941                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3942                                         atype, &btf_id);
3943         }
3944
3945         if (ret < 0)
3946                 return ret;
3947
3948         if (atype == BPF_READ && value_regno >= 0)
3949                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3950
3951         return 0;
3952 }
3953
3954 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3955                                    struct bpf_reg_state *regs,
3956                                    int regno, int off, int size,
3957                                    enum bpf_access_type atype,
3958                                    int value_regno)
3959 {
3960         struct bpf_reg_state *reg = regs + regno;
3961         struct bpf_map *map = reg->map_ptr;
3962         const struct btf_type *t;
3963         const char *tname;
3964         u32 btf_id;
3965         int ret;
3966
3967         if (!btf_vmlinux) {
3968                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3969                 return -ENOTSUPP;
3970         }
3971
3972         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3973                 verbose(env, "map_ptr access not supported for map type %d\n",
3974                         map->map_type);
3975                 return -ENOTSUPP;
3976         }
3977
3978         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3979         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3980
3981         if (!env->allow_ptr_to_map_access) {
3982                 verbose(env,
3983                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3984                         tname);
3985                 return -EPERM;
3986         }
3987
3988         if (off < 0) {
3989                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3990                         regno, tname, off);
3991                 return -EACCES;
3992         }
3993
3994         if (atype != BPF_READ) {
3995                 verbose(env, "only read from %s is supported\n", tname);
3996                 return -EACCES;
3997         }
3998
3999         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
4000         if (ret < 0)
4001                 return ret;
4002
4003         if (value_regno >= 0)
4004                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
4005
4006         return 0;
4007 }
4008
4009 /* Check that the stack access at the given offset is within bounds. The
4010  * maximum valid offset is -1.
4011  *
4012  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4013  * -state->allocated_stack for reads.
4014  */
4015 static int check_stack_slot_within_bounds(int off,
4016                                           struct bpf_func_state *state,
4017                                           enum bpf_access_type t)
4018 {
4019         int min_valid_off;
4020
4021         if (t == BPF_WRITE)
4022                 min_valid_off = -MAX_BPF_STACK;
4023         else
4024                 min_valid_off = -state->allocated_stack;
4025
4026         if (off < min_valid_off || off > -1)
4027                 return -EACCES;
4028         return 0;
4029 }
4030
4031 /* Check that the stack access at 'regno + off' falls within the maximum stack
4032  * bounds.
4033  *
4034  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4035  */
4036 static int check_stack_access_within_bounds(
4037                 struct bpf_verifier_env *env,
4038                 int regno, int off, int access_size,
4039                 enum stack_access_src src, enum bpf_access_type type)
4040 {
4041         struct bpf_reg_state *regs = cur_regs(env);
4042         struct bpf_reg_state *reg = regs + regno;
4043         struct bpf_func_state *state = func(env, reg);
4044         int min_off, max_off;
4045         int err;
4046         char *err_extra;
4047
4048         if (src == ACCESS_HELPER)
4049                 /* We don't know if helpers are reading or writing (or both). */
4050                 err_extra = " indirect access to";
4051         else if (type == BPF_READ)
4052                 err_extra = " read from";
4053         else
4054                 err_extra = " write to";
4055
4056         if (tnum_is_const(reg->var_off)) {
4057                 min_off = reg->var_off.value + off;
4058                 if (access_size > 0)
4059                         max_off = min_off + access_size - 1;
4060                 else
4061                         max_off = min_off;
4062         } else {
4063                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4064                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4065                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4066                                 err_extra, regno);
4067                         return -EACCES;
4068                 }
4069                 min_off = reg->smin_value + off;
4070                 if (access_size > 0)
4071                         max_off = reg->smax_value + off + access_size - 1;
4072                 else
4073                         max_off = min_off;
4074         }
4075
4076         err = check_stack_slot_within_bounds(min_off, state, type);
4077         if (!err)
4078                 err = check_stack_slot_within_bounds(max_off, state, type);
4079
4080         if (err) {
4081                 if (tnum_is_const(reg->var_off)) {
4082                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4083                                 err_extra, regno, off, access_size);
4084                 } else {
4085                         char tn_buf[48];
4086
4087                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4088                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4089                                 err_extra, regno, tn_buf, access_size);
4090                 }
4091         }
4092         return err;
4093 }
4094
4095 /* check whether memory at (regno + off) is accessible for t = (read | write)
4096  * if t==write, value_regno is a register which value is stored into memory
4097  * if t==read, value_regno is a register which will receive the value from memory
4098  * if t==write && value_regno==-1, some unknown value is stored into memory
4099  * if t==read && value_regno==-1, don't care what we read from memory
4100  */
4101 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4102                             int off, int bpf_size, enum bpf_access_type t,
4103                             int value_regno, bool strict_alignment_once)
4104 {
4105         struct bpf_reg_state *regs = cur_regs(env);
4106         struct bpf_reg_state *reg = regs + regno;
4107         struct bpf_func_state *state;
4108         int size, err = 0;
4109
4110         size = bpf_size_to_bytes(bpf_size);
4111         if (size < 0)
4112                 return size;
4113
4114         /* alignment checks will add in reg->off themselves */
4115         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4116         if (err)
4117                 return err;
4118
4119         /* for access checks, reg->off is just part of off */
4120         off += reg->off;
4121
4122         if (reg->type == PTR_TO_MAP_KEY) {
4123                 if (t == BPF_WRITE) {
4124                         verbose(env, "write to change key R%d not allowed\n", regno);
4125                         return -EACCES;
4126                 }
4127
4128                 err = check_mem_region_access(env, regno, off, size,
4129                                               reg->map_ptr->key_size, false);
4130                 if (err)
4131                         return err;
4132                 if (value_regno >= 0)
4133                         mark_reg_unknown(env, regs, value_regno);
4134         } else if (reg->type == PTR_TO_MAP_VALUE) {
4135                 if (t == BPF_WRITE && value_regno >= 0 &&
4136                     is_pointer_value(env, value_regno)) {
4137                         verbose(env, "R%d leaks addr into map\n", value_regno);
4138                         return -EACCES;
4139                 }
4140                 err = check_map_access_type(env, regno, off, size, t);
4141                 if (err)
4142                         return err;
4143                 err = check_map_access(env, regno, off, size, false);
4144                 if (!err && t == BPF_READ && value_regno >= 0) {
4145                         struct bpf_map *map = reg->map_ptr;
4146
4147                         /* if map is read-only, track its contents as scalars */
4148                         if (tnum_is_const(reg->var_off) &&
4149                             bpf_map_is_rdonly(map) &&
4150                             map->ops->map_direct_value_addr) {
4151                                 int map_off = off + reg->var_off.value;
4152                                 u64 val = 0;
4153
4154                                 err = bpf_map_direct_read(map, map_off, size,
4155                                                           &val);
4156                                 if (err)
4157                                         return err;
4158
4159                                 regs[value_regno].type = SCALAR_VALUE;
4160                                 __mark_reg_known(&regs[value_regno], val);
4161                         } else {
4162                                 mark_reg_unknown(env, regs, value_regno);
4163                         }
4164                 }
4165         } else if (base_type(reg->type) == PTR_TO_MEM) {
4166                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4167
4168                 if (type_may_be_null(reg->type)) {
4169                         verbose(env, "R%d invalid mem access '%s'\n", regno,
4170                                 reg_type_str(env, reg->type));
4171                         return -EACCES;
4172                 }
4173
4174                 if (t == BPF_WRITE && rdonly_mem) {
4175                         verbose(env, "R%d cannot write into %s\n",
4176                                 regno, reg_type_str(env, reg->type));
4177                         return -EACCES;
4178                 }
4179
4180                 if (t == BPF_WRITE && value_regno >= 0 &&
4181                     is_pointer_value(env, value_regno)) {
4182                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4183                         return -EACCES;
4184                 }
4185
4186                 err = check_mem_region_access(env, regno, off, size,
4187                                               reg->mem_size, false);
4188                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4189                         mark_reg_unknown(env, regs, value_regno);
4190         } else if (reg->type == PTR_TO_CTX) {
4191                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4192                 struct btf *btf = NULL;
4193                 u32 btf_id = 0;
4194
4195                 if (t == BPF_WRITE && value_regno >= 0 &&
4196                     is_pointer_value(env, value_regno)) {
4197                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4198                         return -EACCES;
4199                 }
4200
4201                 err = check_ctx_reg(env, reg, regno);
4202                 if (err < 0)
4203                         return err;
4204
4205                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4206                 if (err)
4207                         verbose_linfo(env, insn_idx, "; ");
4208                 if (!err && t == BPF_READ && value_regno >= 0) {
4209                         /* ctx access returns either a scalar, or a
4210                          * PTR_TO_PACKET[_META,_END]. In the latter
4211                          * case, we know the offset is zero.
4212                          */
4213                         if (reg_type == SCALAR_VALUE) {
4214                                 mark_reg_unknown(env, regs, value_regno);
4215                         } else {
4216                                 mark_reg_known_zero(env, regs,
4217                                                     value_regno);
4218                                 if (type_may_be_null(reg_type))
4219                                         regs[value_regno].id = ++env->id_gen;
4220                                 /* A load of ctx field could have different
4221                                  * actual load size with the one encoded in the
4222                                  * insn. When the dst is PTR, it is for sure not
4223                                  * a sub-register.
4224                                  */
4225                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4226                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4227                                         regs[value_regno].btf = btf;
4228                                         regs[value_regno].btf_id = btf_id;
4229                                 }
4230                         }
4231                         regs[value_regno].type = reg_type;
4232                 }
4233
4234         } else if (reg->type == PTR_TO_STACK) {
4235                 /* Basic bounds checks. */
4236                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4237                 if (err)
4238                         return err;
4239
4240                 state = func(env, reg);
4241                 err = update_stack_depth(env, state, off);
4242                 if (err)
4243                         return err;
4244
4245                 if (t == BPF_READ)
4246                         err = check_stack_read(env, regno, off, size,
4247                                                value_regno);
4248                 else
4249                         err = check_stack_write(env, regno, off, size,
4250                                                 value_regno, insn_idx);
4251         } else if (reg_is_pkt_pointer(reg)) {
4252                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4253                         verbose(env, "cannot write into packet\n");
4254                         return -EACCES;
4255                 }
4256                 if (t == BPF_WRITE && value_regno >= 0 &&
4257                     is_pointer_value(env, value_regno)) {
4258                         verbose(env, "R%d leaks addr into packet\n",
4259                                 value_regno);
4260                         return -EACCES;
4261                 }
4262                 err = check_packet_access(env, regno, off, size, false);
4263                 if (!err && t == BPF_READ && value_regno >= 0)
4264                         mark_reg_unknown(env, regs, value_regno);
4265         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4266                 if (t == BPF_WRITE && value_regno >= 0 &&
4267                     is_pointer_value(env, value_regno)) {
4268                         verbose(env, "R%d leaks addr into flow keys\n",
4269                                 value_regno);
4270                         return -EACCES;
4271                 }
4272
4273                 err = check_flow_keys_access(env, off, size);
4274                 if (!err && t == BPF_READ && value_regno >= 0)
4275                         mark_reg_unknown(env, regs, value_regno);
4276         } else if (type_is_sk_pointer(reg->type)) {
4277                 if (t == BPF_WRITE) {
4278                         verbose(env, "R%d cannot write into %s\n",
4279                                 regno, reg_type_str(env, reg->type));
4280                         return -EACCES;
4281                 }
4282                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4283                 if (!err && value_regno >= 0)
4284                         mark_reg_unknown(env, regs, value_regno);
4285         } else if (reg->type == PTR_TO_TP_BUFFER) {
4286                 err = check_tp_buffer_access(env, reg, regno, off, size);
4287                 if (!err && t == BPF_READ && value_regno >= 0)
4288                         mark_reg_unknown(env, regs, value_regno);
4289         } else if (reg->type == PTR_TO_BTF_ID) {
4290                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4291                                               value_regno);
4292         } else if (reg->type == CONST_PTR_TO_MAP) {
4293                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4294                                               value_regno);
4295         } else if (base_type(reg->type) == PTR_TO_BUF) {
4296                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4297                 const char *buf_info;
4298                 u32 *max_access;
4299
4300                 if (rdonly_mem) {
4301                         if (t == BPF_WRITE) {
4302                                 verbose(env, "R%d cannot write into %s\n",
4303                                         regno, reg_type_str(env, reg->type));
4304                                 return -EACCES;
4305                         }
4306                         buf_info = "rdonly";
4307                         max_access = &env->prog->aux->max_rdonly_access;
4308                 } else {
4309                         buf_info = "rdwr";
4310                         max_access = &env->prog->aux->max_rdwr_access;
4311                 }
4312
4313                 err = check_buffer_access(env, reg, regno, off, size, false,
4314                                           buf_info, max_access);
4315
4316                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4317                         mark_reg_unknown(env, regs, value_regno);
4318         } else {
4319                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4320                         reg_type_str(env, reg->type));
4321                 return -EACCES;
4322         }
4323
4324         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4325             regs[value_regno].type == SCALAR_VALUE) {
4326                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4327                 coerce_reg_to_size(&regs[value_regno], size);
4328         }
4329         return err;
4330 }
4331
4332 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4333 {
4334         int load_reg;
4335         int err;
4336
4337         switch (insn->imm) {
4338         case BPF_ADD:
4339         case BPF_ADD | BPF_FETCH:
4340         case BPF_AND:
4341         case BPF_AND | BPF_FETCH:
4342         case BPF_OR:
4343         case BPF_OR | BPF_FETCH:
4344         case BPF_XOR:
4345         case BPF_XOR | BPF_FETCH:
4346         case BPF_XCHG:
4347         case BPF_CMPXCHG:
4348                 break;
4349         default:
4350                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4351                 return -EINVAL;
4352         }
4353
4354         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4355                 verbose(env, "invalid atomic operand size\n");
4356                 return -EINVAL;
4357         }
4358
4359         /* check src1 operand */
4360         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4361         if (err)
4362                 return err;
4363
4364         /* check src2 operand */
4365         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4366         if (err)
4367                 return err;
4368
4369         if (insn->imm == BPF_CMPXCHG) {
4370                 /* Check comparison of R0 with memory location */
4371                 const u32 aux_reg = BPF_REG_0;
4372
4373                 err = check_reg_arg(env, aux_reg, SRC_OP);
4374                 if (err)
4375                         return err;
4376
4377                 if (is_pointer_value(env, aux_reg)) {
4378                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
4379                         return -EACCES;
4380                 }
4381         }
4382
4383         if (is_pointer_value(env, insn->src_reg)) {
4384                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4385                 return -EACCES;
4386         }
4387
4388         if (is_ctx_reg(env, insn->dst_reg) ||
4389             is_pkt_reg(env, insn->dst_reg) ||
4390             is_flow_key_reg(env, insn->dst_reg) ||
4391             is_sk_reg(env, insn->dst_reg)) {
4392                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4393                         insn->dst_reg,
4394                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4395                 return -EACCES;
4396         }
4397
4398         if (insn->imm & BPF_FETCH) {
4399                 if (insn->imm == BPF_CMPXCHG)
4400                         load_reg = BPF_REG_0;
4401                 else
4402                         load_reg = insn->src_reg;
4403
4404                 /* check and record load of old value */
4405                 err = check_reg_arg(env, load_reg, DST_OP);
4406                 if (err)
4407                         return err;
4408         } else {
4409                 /* This instruction accesses a memory location but doesn't
4410                  * actually load it into a register.
4411                  */
4412                 load_reg = -1;
4413         }
4414
4415         /* Check whether we can read the memory, with second call for fetch
4416          * case to simulate the register fill.
4417          */
4418         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4419                                BPF_SIZE(insn->code), BPF_READ, -1, true);
4420         if (!err && load_reg >= 0)
4421                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4422                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
4423                                        true);
4424         if (err)
4425                 return err;
4426
4427         /* Check whether we can write into the same memory. */
4428         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4429                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4430         if (err)
4431                 return err;
4432
4433         return 0;
4434 }
4435
4436 /* When register 'regno' is used to read the stack (either directly or through
4437  * a helper function) make sure that it's within stack boundary and, depending
4438  * on the access type, that all elements of the stack are initialized.
4439  *
4440  * 'off' includes 'regno->off', but not its dynamic part (if any).
4441  *
4442  * All registers that have been spilled on the stack in the slots within the
4443  * read offsets are marked as read.
4444  */
4445 static int check_stack_range_initialized(
4446                 struct bpf_verifier_env *env, int regno, int off,
4447                 int access_size, bool zero_size_allowed,
4448                 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4449 {
4450         struct bpf_reg_state *reg = reg_state(env, regno);
4451         struct bpf_func_state *state = func(env, reg);
4452         int err, min_off, max_off, i, j, slot, spi;
4453         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4454         enum bpf_access_type bounds_check_type;
4455         /* Some accesses can write anything into the stack, others are
4456          * read-only.
4457          */
4458         bool clobber = false;
4459
4460         if (access_size == 0 && !zero_size_allowed) {
4461                 verbose(env, "invalid zero-sized read\n");
4462                 return -EACCES;
4463         }
4464
4465         if (type == ACCESS_HELPER) {
4466                 /* The bounds checks for writes are more permissive than for
4467                  * reads. However, if raw_mode is not set, we'll do extra
4468                  * checks below.
4469                  */
4470                 bounds_check_type = BPF_WRITE;
4471                 clobber = true;
4472         } else {
4473                 bounds_check_type = BPF_READ;
4474         }
4475         err = check_stack_access_within_bounds(env, regno, off, access_size,
4476                                                type, bounds_check_type);
4477         if (err)
4478                 return err;
4479
4480
4481         if (tnum_is_const(reg->var_off)) {
4482                 min_off = max_off = reg->var_off.value + off;
4483         } else {
4484                 /* Variable offset is prohibited for unprivileged mode for
4485                  * simplicity since it requires corresponding support in
4486                  * Spectre masking for stack ALU.
4487                  * See also retrieve_ptr_limit().
4488                  */
4489                 if (!env->bypass_spec_v1) {
4490                         char tn_buf[48];
4491
4492                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4493                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4494                                 regno, err_extra, tn_buf);
4495                         return -EACCES;
4496                 }
4497                 /* Only initialized buffer on stack is allowed to be accessed
4498                  * with variable offset. With uninitialized buffer it's hard to
4499                  * guarantee that whole memory is marked as initialized on
4500                  * helper return since specific bounds are unknown what may
4501                  * cause uninitialized stack leaking.
4502                  */
4503                 if (meta && meta->raw_mode)
4504                         meta = NULL;
4505
4506                 min_off = reg->smin_value + off;
4507                 max_off = reg->smax_value + off;
4508         }
4509
4510         if (meta && meta->raw_mode) {
4511                 meta->access_size = access_size;
4512                 meta->regno = regno;
4513                 return 0;
4514         }
4515
4516         for (i = min_off; i < max_off + access_size; i++) {
4517                 u8 *stype;
4518
4519                 slot = -i - 1;
4520                 spi = slot / BPF_REG_SIZE;
4521                 if (state->allocated_stack <= slot)
4522                         goto err;
4523                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4524                 if (*stype == STACK_MISC)
4525                         goto mark;
4526                 if (*stype == STACK_ZERO) {
4527                         if (clobber) {
4528                                 /* helper can write anything into the stack */
4529                                 *stype = STACK_MISC;
4530                         }
4531                         goto mark;
4532                 }
4533
4534                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4535                     state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4536                         goto mark;
4537
4538                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4539                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4540                      env->allow_ptr_leaks)) {
4541                         if (clobber) {
4542                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4543                                 for (j = 0; j < BPF_REG_SIZE; j++)
4544                                         state->stack[spi].slot_type[j] = STACK_MISC;
4545                         }
4546                         goto mark;
4547                 }
4548
4549 err:
4550                 if (tnum_is_const(reg->var_off)) {
4551                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4552                                 err_extra, regno, min_off, i - min_off, access_size);
4553                 } else {
4554                         char tn_buf[48];
4555
4556                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4557                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4558                                 err_extra, regno, tn_buf, i - min_off, access_size);
4559                 }
4560                 return -EACCES;
4561 mark:
4562                 /* reading any byte out of 8-byte 'spill_slot' will cause
4563                  * the whole slot to be marked as 'read'
4564                  */
4565                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4566                               state->stack[spi].spilled_ptr.parent,
4567                               REG_LIVE_READ64);
4568         }
4569         return update_stack_depth(env, state, min_off);
4570 }
4571
4572 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4573                                    int access_size, bool zero_size_allowed,
4574                                    struct bpf_call_arg_meta *meta)
4575 {
4576         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4577         const char *buf_info;
4578         u32 *max_access;
4579
4580         switch (base_type(reg->type)) {
4581         case PTR_TO_PACKET:
4582         case PTR_TO_PACKET_META:
4583                 return check_packet_access(env, regno, reg->off, access_size,
4584                                            zero_size_allowed);
4585         case PTR_TO_MAP_KEY:
4586                 if (meta && meta->raw_mode) {
4587                         verbose(env, "R%d cannot write into %s\n", regno,
4588                                 reg_type_str(env, reg->type));
4589                         return -EACCES;
4590                 }
4591                 return check_mem_region_access(env, regno, reg->off, access_size,
4592                                                reg->map_ptr->key_size, false);
4593         case PTR_TO_MAP_VALUE:
4594                 if (check_map_access_type(env, regno, reg->off, access_size,
4595                                           meta && meta->raw_mode ? BPF_WRITE :
4596                                           BPF_READ))
4597                         return -EACCES;
4598                 return check_map_access(env, regno, reg->off, access_size,
4599                                         zero_size_allowed);
4600         case PTR_TO_MEM:
4601                 if (type_is_rdonly_mem(reg->type)) {
4602                         if (meta && meta->raw_mode) {
4603                                 verbose(env, "R%d cannot write into %s\n", regno,
4604                                         reg_type_str(env, reg->type));
4605                                 return -EACCES;
4606                         }
4607                 }
4608                 return check_mem_region_access(env, regno, reg->off,
4609                                                access_size, reg->mem_size,
4610                                                zero_size_allowed);
4611         case PTR_TO_BUF:
4612                 if (type_is_rdonly_mem(reg->type)) {
4613                         if (meta && meta->raw_mode) {
4614                                 verbose(env, "R%d cannot write into %s\n", regno,
4615                                         reg_type_str(env, reg->type));
4616                                 return -EACCES;
4617                         }
4618
4619                         buf_info = "rdonly";
4620                         max_access = &env->prog->aux->max_rdonly_access;
4621                 } else {
4622                         buf_info = "rdwr";
4623                         max_access = &env->prog->aux->max_rdwr_access;
4624                 }
4625                 return check_buffer_access(env, reg, regno, reg->off,
4626                                            access_size, zero_size_allowed,
4627                                            buf_info, max_access);
4628         case PTR_TO_STACK:
4629                 return check_stack_range_initialized(
4630                                 env,
4631                                 regno, reg->off, access_size,
4632                                 zero_size_allowed, ACCESS_HELPER, meta);
4633         default: /* scalar_value or invalid ptr */
4634                 /* Allow zero-byte read from NULL, regardless of pointer type */
4635                 if (zero_size_allowed && access_size == 0 &&
4636                     register_is_null(reg))
4637                         return 0;
4638
4639                 verbose(env, "R%d type=%s ", regno,
4640                         reg_type_str(env, reg->type));
4641                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
4642                 return -EACCES;
4643         }
4644 }
4645
4646 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4647                    u32 regno, u32 mem_size)
4648 {
4649         if (register_is_null(reg))
4650                 return 0;
4651
4652         if (type_may_be_null(reg->type)) {
4653                 /* Assuming that the register contains a value check if the memory
4654                  * access is safe. Temporarily save and restore the register's state as
4655                  * the conversion shouldn't be visible to a caller.
4656                  */
4657                 const struct bpf_reg_state saved_reg = *reg;
4658                 int rv;
4659
4660                 mark_ptr_not_null_reg(reg);
4661                 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4662                 *reg = saved_reg;
4663                 return rv;
4664         }
4665
4666         return check_helper_mem_access(env, regno, mem_size, true, NULL);
4667 }
4668
4669 /* Implementation details:
4670  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4671  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4672  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4673  * value_or_null->value transition, since the verifier only cares about
4674  * the range of access to valid map value pointer and doesn't care about actual
4675  * address of the map element.
4676  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4677  * reg->id > 0 after value_or_null->value transition. By doing so
4678  * two bpf_map_lookups will be considered two different pointers that
4679  * point to different bpf_spin_locks.
4680  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4681  * dead-locks.
4682  * Since only one bpf_spin_lock is allowed the checks are simpler than
4683  * reg_is_refcounted() logic. The verifier needs to remember only
4684  * one spin_lock instead of array of acquired_refs.
4685  * cur_state->active_spin_lock remembers which map value element got locked
4686  * and clears it after bpf_spin_unlock.
4687  */
4688 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4689                              bool is_lock)
4690 {
4691         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4692         struct bpf_verifier_state *cur = env->cur_state;
4693         bool is_const = tnum_is_const(reg->var_off);
4694         struct bpf_map *map = reg->map_ptr;
4695         u64 val = reg->var_off.value;
4696
4697         if (!is_const) {
4698                 verbose(env,
4699                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4700                         regno);
4701                 return -EINVAL;
4702         }
4703         if (!map->btf) {
4704                 verbose(env,
4705                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4706                         map->name);
4707                 return -EINVAL;
4708         }
4709         if (!map_value_has_spin_lock(map)) {
4710                 if (map->spin_lock_off == -E2BIG)
4711                         verbose(env,
4712                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4713                                 map->name);
4714                 else if (map->spin_lock_off == -ENOENT)
4715                         verbose(env,
4716                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4717                                 map->name);
4718                 else
4719                         verbose(env,
4720                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4721                                 map->name);
4722                 return -EINVAL;
4723         }
4724         if (map->spin_lock_off != val + reg->off) {
4725                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4726                         val + reg->off);
4727                 return -EINVAL;
4728         }
4729         if (is_lock) {
4730                 if (cur->active_spin_lock) {
4731                         verbose(env,
4732                                 "Locking two bpf_spin_locks are not allowed\n");
4733                         return -EINVAL;
4734                 }
4735                 cur->active_spin_lock = reg->id;
4736         } else {
4737                 if (!cur->active_spin_lock) {
4738                         verbose(env, "bpf_spin_unlock without taking a lock\n");
4739                         return -EINVAL;
4740                 }
4741                 if (cur->active_spin_lock != reg->id) {
4742                         verbose(env, "bpf_spin_unlock of different lock\n");
4743                         return -EINVAL;
4744                 }
4745                 cur->active_spin_lock = 0;
4746         }
4747         return 0;
4748 }
4749
4750 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4751                               struct bpf_call_arg_meta *meta)
4752 {
4753         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4754         bool is_const = tnum_is_const(reg->var_off);
4755         struct bpf_map *map = reg->map_ptr;
4756         u64 val = reg->var_off.value;
4757
4758         if (!is_const) {
4759                 verbose(env,
4760                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
4761                         regno);
4762                 return -EINVAL;
4763         }
4764         if (!map->btf) {
4765                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
4766                         map->name);
4767                 return -EINVAL;
4768         }
4769         if (!map_value_has_timer(map)) {
4770                 if (map->timer_off == -E2BIG)
4771                         verbose(env,
4772                                 "map '%s' has more than one 'struct bpf_timer'\n",
4773                                 map->name);
4774                 else if (map->timer_off == -ENOENT)
4775                         verbose(env,
4776                                 "map '%s' doesn't have 'struct bpf_timer'\n",
4777                                 map->name);
4778                 else
4779                         verbose(env,
4780                                 "map '%s' is not a struct type or bpf_timer is mangled\n",
4781                                 map->name);
4782                 return -EINVAL;
4783         }
4784         if (map->timer_off != val + reg->off) {
4785                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
4786                         val + reg->off, map->timer_off);
4787                 return -EINVAL;
4788         }
4789         if (meta->map_ptr) {
4790                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
4791                 return -EFAULT;
4792         }
4793         meta->map_uid = reg->map_uid;
4794         meta->map_ptr = map;
4795         return 0;
4796 }
4797
4798 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4799 {
4800         return base_type(type) == ARG_PTR_TO_MEM ||
4801                base_type(type) == ARG_PTR_TO_UNINIT_MEM;
4802 }
4803
4804 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4805 {
4806         return type == ARG_CONST_SIZE ||
4807                type == ARG_CONST_SIZE_OR_ZERO;
4808 }
4809
4810 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4811 {
4812         return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4813 }
4814
4815 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4816 {
4817         return type == ARG_PTR_TO_INT ||
4818                type == ARG_PTR_TO_LONG;
4819 }
4820
4821 static int int_ptr_type_to_size(enum bpf_arg_type type)
4822 {
4823         if (type == ARG_PTR_TO_INT)
4824                 return sizeof(u32);
4825         else if (type == ARG_PTR_TO_LONG)
4826                 return sizeof(u64);
4827
4828         return -EINVAL;
4829 }
4830
4831 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4832                                  const struct bpf_call_arg_meta *meta,
4833                                  enum bpf_arg_type *arg_type)
4834 {
4835         if (!meta->map_ptr) {
4836                 /* kernel subsystem misconfigured verifier */
4837                 verbose(env, "invalid map_ptr to access map->type\n");
4838                 return -EACCES;
4839         }
4840
4841         switch (meta->map_ptr->map_type) {
4842         case BPF_MAP_TYPE_SOCKMAP:
4843         case BPF_MAP_TYPE_SOCKHASH:
4844                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4845                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4846                 } else {
4847                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
4848                         return -EINVAL;
4849                 }
4850                 break;
4851
4852         default:
4853                 break;
4854         }
4855         return 0;
4856 }
4857
4858 struct bpf_reg_types {
4859         const enum bpf_reg_type types[10];
4860         u32 *btf_id;
4861 };
4862
4863 static const struct bpf_reg_types map_key_value_types = {
4864         .types = {
4865                 PTR_TO_STACK,
4866                 PTR_TO_PACKET,
4867                 PTR_TO_PACKET_META,
4868                 PTR_TO_MAP_KEY,
4869                 PTR_TO_MAP_VALUE,
4870         },
4871 };
4872
4873 static const struct bpf_reg_types sock_types = {
4874         .types = {
4875                 PTR_TO_SOCK_COMMON,
4876                 PTR_TO_SOCKET,
4877                 PTR_TO_TCP_SOCK,
4878                 PTR_TO_XDP_SOCK,
4879         },
4880 };
4881
4882 #ifdef CONFIG_NET
4883 static const struct bpf_reg_types btf_id_sock_common_types = {
4884         .types = {
4885                 PTR_TO_SOCK_COMMON,
4886                 PTR_TO_SOCKET,
4887                 PTR_TO_TCP_SOCK,
4888                 PTR_TO_XDP_SOCK,
4889                 PTR_TO_BTF_ID,
4890         },
4891         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4892 };
4893 #endif
4894
4895 static const struct bpf_reg_types mem_types = {
4896         .types = {
4897                 PTR_TO_STACK,
4898                 PTR_TO_PACKET,
4899                 PTR_TO_PACKET_META,
4900                 PTR_TO_MAP_KEY,
4901                 PTR_TO_MAP_VALUE,
4902                 PTR_TO_MEM,
4903                 PTR_TO_BUF,
4904         },
4905 };
4906
4907 static const struct bpf_reg_types int_ptr_types = {
4908         .types = {
4909                 PTR_TO_STACK,
4910                 PTR_TO_PACKET,
4911                 PTR_TO_PACKET_META,
4912                 PTR_TO_MAP_KEY,
4913                 PTR_TO_MAP_VALUE,
4914         },
4915 };
4916
4917 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4918 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4919 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4920 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4921 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4922 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4923 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4924 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4925 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4926 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
4927 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
4928 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
4929
4930 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4931         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
4932         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
4933         [ARG_PTR_TO_UNINIT_MAP_VALUE]   = &map_key_value_types,
4934         [ARG_CONST_SIZE]                = &scalar_types,
4935         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
4936         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
4937         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
4938         [ARG_PTR_TO_CTX]                = &context_types,
4939         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
4940 #ifdef CONFIG_NET
4941         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4942 #endif
4943         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
4944         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
4945         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
4946         [ARG_PTR_TO_MEM]                = &mem_types,
4947         [ARG_PTR_TO_UNINIT_MEM]         = &mem_types,
4948         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
4949         [ARG_PTR_TO_INT]                = &int_ptr_types,
4950         [ARG_PTR_TO_LONG]               = &int_ptr_types,
4951         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
4952         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
4953         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
4954         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
4955         [ARG_PTR_TO_TIMER]              = &timer_types,
4956 };
4957
4958 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4959                           enum bpf_arg_type arg_type,
4960                           const u32 *arg_btf_id)
4961 {
4962         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4963         enum bpf_reg_type expected, type = reg->type;
4964         const struct bpf_reg_types *compatible;
4965         int i, j;
4966
4967         compatible = compatible_reg_types[base_type(arg_type)];
4968         if (!compatible) {
4969                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4970                 return -EFAULT;
4971         }
4972
4973         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
4974          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
4975          *
4976          * Same for MAYBE_NULL:
4977          *
4978          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
4979          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
4980          *
4981          * Therefore we fold these flags depending on the arg_type before comparison.
4982          */
4983         if (arg_type & MEM_RDONLY)
4984                 type &= ~MEM_RDONLY;
4985         if (arg_type & PTR_MAYBE_NULL)
4986                 type &= ~PTR_MAYBE_NULL;
4987
4988         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4989                 expected = compatible->types[i];
4990                 if (expected == NOT_INIT)
4991                         break;
4992
4993                 if (type == expected)
4994                         goto found;
4995         }
4996
4997         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
4998         for (j = 0; j + 1 < i; j++)
4999                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5000         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5001         return -EACCES;
5002
5003 found:
5004         if (reg->type == PTR_TO_BTF_ID) {
5005                 if (!arg_btf_id) {
5006                         if (!compatible->btf_id) {
5007                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5008                                 return -EFAULT;
5009                         }
5010                         arg_btf_id = compatible->btf_id;
5011                 }
5012
5013                 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5014                                           btf_vmlinux, *arg_btf_id)) {
5015                         verbose(env, "R%d is of type %s but %s is expected\n",
5016                                 regno, kernel_type_name(reg->btf, reg->btf_id),
5017                                 kernel_type_name(btf_vmlinux, *arg_btf_id));
5018                         return -EACCES;
5019                 }
5020
5021                 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5022                         verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
5023                                 regno);
5024                         return -EACCES;
5025                 }
5026         }
5027
5028         return 0;
5029 }
5030
5031 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5032                           struct bpf_call_arg_meta *meta,
5033                           const struct bpf_func_proto *fn)
5034 {
5035         u32 regno = BPF_REG_1 + arg;
5036         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5037         enum bpf_arg_type arg_type = fn->arg_type[arg];
5038         enum bpf_reg_type type = reg->type;
5039         int err = 0;
5040
5041         if (arg_type == ARG_DONTCARE)
5042                 return 0;
5043
5044         err = check_reg_arg(env, regno, SRC_OP);
5045         if (err)
5046                 return err;
5047
5048         if (arg_type == ARG_ANYTHING) {
5049                 if (is_pointer_value(env, regno)) {
5050                         verbose(env, "R%d leaks addr into helper function\n",
5051                                 regno);
5052                         return -EACCES;
5053                 }
5054                 return 0;
5055         }
5056
5057         if (type_is_pkt_pointer(type) &&
5058             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5059                 verbose(env, "helper access to the packet is not allowed\n");
5060                 return -EACCES;
5061         }
5062
5063         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5064             base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5065                 err = resolve_map_arg_type(env, meta, &arg_type);
5066                 if (err)
5067                         return err;
5068         }
5069
5070         if (register_is_null(reg) && type_may_be_null(arg_type))
5071                 /* A NULL register has a SCALAR_VALUE type, so skip
5072                  * type checking.
5073                  */
5074                 goto skip_type_check;
5075
5076         err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5077         if (err)
5078                 return err;
5079
5080         if (type == PTR_TO_CTX) {
5081                 err = check_ctx_reg(env, reg, regno);
5082                 if (err < 0)
5083                         return err;
5084         }
5085
5086 skip_type_check:
5087         if (reg->ref_obj_id) {
5088                 if (meta->ref_obj_id) {
5089                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5090                                 regno, reg->ref_obj_id,
5091                                 meta->ref_obj_id);
5092                         return -EFAULT;
5093                 }
5094                 meta->ref_obj_id = reg->ref_obj_id;
5095         }
5096
5097         if (arg_type == ARG_CONST_MAP_PTR) {
5098                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5099                 if (meta->map_ptr) {
5100                         /* Use map_uid (which is unique id of inner map) to reject:
5101                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5102                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5103                          * if (inner_map1 && inner_map2) {
5104                          *     timer = bpf_map_lookup_elem(inner_map1);
5105                          *     if (timer)
5106                          *         // mismatch would have been allowed
5107                          *         bpf_timer_init(timer, inner_map2);
5108                          * }
5109                          *
5110                          * Comparing map_ptr is enough to distinguish normal and outer maps.
5111                          */
5112                         if (meta->map_ptr != reg->map_ptr ||
5113                             meta->map_uid != reg->map_uid) {
5114                                 verbose(env,
5115                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5116                                         meta->map_uid, reg->map_uid);
5117                                 return -EINVAL;
5118                         }
5119                 }
5120                 meta->map_ptr = reg->map_ptr;
5121                 meta->map_uid = reg->map_uid;
5122         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5123                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
5124                  * check that [key, key + map->key_size) are within
5125                  * stack limits and initialized
5126                  */
5127                 if (!meta->map_ptr) {
5128                         /* in function declaration map_ptr must come before
5129                          * map_key, so that it's verified and known before
5130                          * we have to check map_key here. Otherwise it means
5131                          * that kernel subsystem misconfigured verifier
5132                          */
5133                         verbose(env, "invalid map_ptr to access map->key\n");
5134                         return -EACCES;
5135                 }
5136                 err = check_helper_mem_access(env, regno,
5137                                               meta->map_ptr->key_size, false,
5138                                               NULL);
5139         } else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5140                    base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5141                 if (type_may_be_null(arg_type) && register_is_null(reg))
5142                         return 0;
5143
5144                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
5145                  * check [value, value + map->value_size) validity
5146                  */
5147                 if (!meta->map_ptr) {
5148                         /* kernel subsystem misconfigured verifier */
5149                         verbose(env, "invalid map_ptr to access map->value\n");
5150                         return -EACCES;
5151                 }
5152                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5153                 err = check_helper_mem_access(env, regno,
5154                                               meta->map_ptr->value_size, false,
5155                                               meta);
5156         } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5157                 if (!reg->btf_id) {
5158                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5159                         return -EACCES;
5160                 }
5161                 meta->ret_btf = reg->btf;
5162                 meta->ret_btf_id = reg->btf_id;
5163         } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5164                 if (meta->func_id == BPF_FUNC_spin_lock) {
5165                         if (process_spin_lock(env, regno, true))
5166                                 return -EACCES;
5167                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
5168                         if (process_spin_lock(env, regno, false))
5169                                 return -EACCES;
5170                 } else {
5171                         verbose(env, "verifier internal error\n");
5172                         return -EFAULT;
5173                 }
5174         } else if (arg_type == ARG_PTR_TO_TIMER) {
5175                 if (process_timer_func(env, regno, meta))
5176                         return -EACCES;
5177         } else if (arg_type == ARG_PTR_TO_FUNC) {
5178                 meta->subprogno = reg->subprogno;
5179         } else if (arg_type_is_mem_ptr(arg_type)) {
5180                 /* The access to this pointer is only checked when we hit the
5181                  * next is_mem_size argument below.
5182                  */
5183                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5184         } else if (arg_type_is_mem_size(arg_type)) {
5185                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5186
5187                 /* This is used to refine r0 return value bounds for helpers
5188                  * that enforce this value as an upper bound on return values.
5189                  * See do_refine_retval_range() for helpers that can refine
5190                  * the return value. C type of helper is u32 so we pull register
5191                  * bound from umax_value however, if negative verifier errors
5192                  * out. Only upper bounds can be learned because retval is an
5193                  * int type and negative retvals are allowed.
5194                  */
5195                 meta->msize_max_value = reg->umax_value;
5196
5197                 /* The register is SCALAR_VALUE; the access check
5198                  * happens using its boundaries.
5199                  */
5200                 if (!tnum_is_const(reg->var_off))
5201                         /* For unprivileged variable accesses, disable raw
5202                          * mode so that the program is required to
5203                          * initialize all the memory that the helper could
5204                          * just partially fill up.
5205                          */
5206                         meta = NULL;
5207
5208                 if (reg->smin_value < 0) {
5209                         verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5210                                 regno);
5211                         return -EACCES;
5212                 }
5213
5214                 if (reg->umin_value == 0) {
5215                         err = check_helper_mem_access(env, regno - 1, 0,
5216                                                       zero_size_allowed,
5217                                                       meta);
5218                         if (err)
5219                                 return err;
5220                 }
5221
5222                 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5223                         verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5224                                 regno);
5225                         return -EACCES;
5226                 }
5227                 err = check_helper_mem_access(env, regno - 1,
5228                                               reg->umax_value,
5229                                               zero_size_allowed, meta);
5230                 if (!err)
5231                         err = mark_chain_precision(env, regno);
5232         } else if (arg_type_is_alloc_size(arg_type)) {
5233                 if (!tnum_is_const(reg->var_off)) {
5234                         verbose(env, "R%d is not a known constant'\n",
5235                                 regno);
5236                         return -EACCES;
5237                 }
5238                 meta->mem_size = reg->var_off.value;
5239         } else if (arg_type_is_int_ptr(arg_type)) {
5240                 int size = int_ptr_type_to_size(arg_type);
5241
5242                 err = check_helper_mem_access(env, regno, size, false, meta);
5243                 if (err)
5244                         return err;
5245                 err = check_ptr_alignment(env, reg, 0, size, true);
5246         } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5247                 struct bpf_map *map = reg->map_ptr;
5248                 int map_off;
5249                 u64 map_addr;
5250                 char *str_ptr;
5251
5252                 if (!bpf_map_is_rdonly(map)) {
5253                         verbose(env, "R%d does not point to a readonly map'\n", regno);
5254                         return -EACCES;
5255                 }
5256
5257                 if (!tnum_is_const(reg->var_off)) {
5258                         verbose(env, "R%d is not a constant address'\n", regno);
5259                         return -EACCES;
5260                 }
5261
5262                 if (!map->ops->map_direct_value_addr) {
5263                         verbose(env, "no direct value access support for this map type\n");
5264                         return -EACCES;
5265                 }
5266
5267                 err = check_map_access(env, regno, reg->off,
5268                                        map->value_size - reg->off, false);
5269                 if (err)
5270                         return err;
5271
5272                 map_off = reg->off + reg->var_off.value;
5273                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5274                 if (err) {
5275                         verbose(env, "direct value access on string failed\n");
5276                         return err;
5277                 }
5278
5279                 str_ptr = (char *)(long)(map_addr);
5280                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5281                         verbose(env, "string is not zero-terminated\n");
5282                         return -EINVAL;
5283                 }
5284         }
5285
5286         return err;
5287 }
5288
5289 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5290 {
5291         enum bpf_attach_type eatype = env->prog->expected_attach_type;
5292         enum bpf_prog_type type = resolve_prog_type(env->prog);
5293
5294         if (func_id != BPF_FUNC_map_update_elem)
5295                 return false;
5296
5297         /* It's not possible to get access to a locked struct sock in these
5298          * contexts, so updating is safe.
5299          */
5300         switch (type) {
5301         case BPF_PROG_TYPE_TRACING:
5302                 if (eatype == BPF_TRACE_ITER)
5303                         return true;
5304                 break;
5305         case BPF_PROG_TYPE_SOCKET_FILTER:
5306         case BPF_PROG_TYPE_SCHED_CLS:
5307         case BPF_PROG_TYPE_SCHED_ACT:
5308         case BPF_PROG_TYPE_XDP:
5309         case BPF_PROG_TYPE_SK_REUSEPORT:
5310         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5311         case BPF_PROG_TYPE_SK_LOOKUP:
5312                 return true;
5313         default:
5314                 break;
5315         }
5316
5317         verbose(env, "cannot update sockmap in this context\n");
5318         return false;
5319 }
5320
5321 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5322 {
5323         return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5324 }
5325
5326 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5327                                         struct bpf_map *map, int func_id)
5328 {
5329         if (!map)
5330                 return 0;
5331
5332         /* We need a two way check, first is from map perspective ... */
5333         switch (map->map_type) {
5334         case BPF_MAP_TYPE_PROG_ARRAY:
5335                 if (func_id != BPF_FUNC_tail_call)
5336                         goto error;
5337                 break;
5338         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5339                 if (func_id != BPF_FUNC_perf_event_read &&
5340                     func_id != BPF_FUNC_perf_event_output &&
5341                     func_id != BPF_FUNC_skb_output &&
5342                     func_id != BPF_FUNC_perf_event_read_value &&
5343                     func_id != BPF_FUNC_xdp_output)
5344                         goto error;
5345                 break;
5346         case BPF_MAP_TYPE_RINGBUF:
5347                 if (func_id != BPF_FUNC_ringbuf_output &&
5348                     func_id != BPF_FUNC_ringbuf_reserve &&
5349                     func_id != BPF_FUNC_ringbuf_query)
5350                         goto error;
5351                 break;
5352         case BPF_MAP_TYPE_STACK_TRACE:
5353                 if (func_id != BPF_FUNC_get_stackid)
5354                         goto error;
5355                 break;
5356         case BPF_MAP_TYPE_CGROUP_ARRAY:
5357                 if (func_id != BPF_FUNC_skb_under_cgroup &&
5358                     func_id != BPF_FUNC_current_task_under_cgroup)
5359                         goto error;
5360                 break;
5361         case BPF_MAP_TYPE_CGROUP_STORAGE:
5362         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5363                 if (func_id != BPF_FUNC_get_local_storage)
5364                         goto error;
5365                 break;
5366         case BPF_MAP_TYPE_DEVMAP:
5367         case BPF_MAP_TYPE_DEVMAP_HASH:
5368                 if (func_id != BPF_FUNC_redirect_map &&
5369                     func_id != BPF_FUNC_map_lookup_elem)
5370                         goto error;
5371                 break;
5372         /* Restrict bpf side of cpumap and xskmap, open when use-cases
5373          * appear.
5374          */
5375         case BPF_MAP_TYPE_CPUMAP:
5376                 if (func_id != BPF_FUNC_redirect_map)
5377                         goto error;
5378                 break;
5379         case BPF_MAP_TYPE_XSKMAP:
5380                 if (func_id != BPF_FUNC_redirect_map &&
5381                     func_id != BPF_FUNC_map_lookup_elem)
5382                         goto error;
5383                 break;
5384         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5385         case BPF_MAP_TYPE_HASH_OF_MAPS:
5386                 if (func_id != BPF_FUNC_map_lookup_elem)
5387                         goto error;
5388                 break;
5389         case BPF_MAP_TYPE_SOCKMAP:
5390                 if (func_id != BPF_FUNC_sk_redirect_map &&
5391                     func_id != BPF_FUNC_sock_map_update &&
5392                     func_id != BPF_FUNC_map_delete_elem &&
5393                     func_id != BPF_FUNC_msg_redirect_map &&
5394                     func_id != BPF_FUNC_sk_select_reuseport &&
5395                     func_id != BPF_FUNC_map_lookup_elem &&
5396                     !may_update_sockmap(env, func_id))
5397                         goto error;
5398                 break;
5399         case BPF_MAP_TYPE_SOCKHASH:
5400                 if (func_id != BPF_FUNC_sk_redirect_hash &&
5401                     func_id != BPF_FUNC_sock_hash_update &&
5402                     func_id != BPF_FUNC_map_delete_elem &&
5403                     func_id != BPF_FUNC_msg_redirect_hash &&
5404                     func_id != BPF_FUNC_sk_select_reuseport &&
5405                     func_id != BPF_FUNC_map_lookup_elem &&
5406                     !may_update_sockmap(env, func_id))
5407                         goto error;
5408                 break;
5409         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5410                 if (func_id != BPF_FUNC_sk_select_reuseport)
5411                         goto error;
5412                 break;
5413         case BPF_MAP_TYPE_QUEUE:
5414         case BPF_MAP_TYPE_STACK:
5415                 if (func_id != BPF_FUNC_map_peek_elem &&
5416                     func_id != BPF_FUNC_map_pop_elem &&
5417                     func_id != BPF_FUNC_map_push_elem)
5418                         goto error;
5419                 break;
5420         case BPF_MAP_TYPE_SK_STORAGE:
5421                 if (func_id != BPF_FUNC_sk_storage_get &&
5422                     func_id != BPF_FUNC_sk_storage_delete)
5423                         goto error;
5424                 break;
5425         case BPF_MAP_TYPE_INODE_STORAGE:
5426                 if (func_id != BPF_FUNC_inode_storage_get &&
5427                     func_id != BPF_FUNC_inode_storage_delete)
5428                         goto error;
5429                 break;
5430         case BPF_MAP_TYPE_TASK_STORAGE:
5431                 if (func_id != BPF_FUNC_task_storage_get &&
5432                     func_id != BPF_FUNC_task_storage_delete)
5433                         goto error;
5434                 break;
5435         default:
5436                 break;
5437         }
5438
5439         /* ... and second from the function itself. */
5440         switch (func_id) {
5441         case BPF_FUNC_tail_call:
5442                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5443                         goto error;
5444                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5445                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5446                         return -EINVAL;
5447                 }
5448                 break;
5449         case BPF_FUNC_perf_event_read:
5450         case BPF_FUNC_perf_event_output:
5451         case BPF_FUNC_perf_event_read_value:
5452         case BPF_FUNC_skb_output:
5453         case BPF_FUNC_xdp_output:
5454                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5455                         goto error;
5456                 break;
5457         case BPF_FUNC_ringbuf_output:
5458         case BPF_FUNC_ringbuf_reserve:
5459         case BPF_FUNC_ringbuf_query:
5460                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5461                         goto error;
5462                 break;
5463         case BPF_FUNC_get_stackid:
5464                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5465                         goto error;
5466                 break;
5467         case BPF_FUNC_current_task_under_cgroup:
5468         case BPF_FUNC_skb_under_cgroup:
5469                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5470                         goto error;
5471                 break;
5472         case BPF_FUNC_redirect_map:
5473                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5474                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5475                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
5476                     map->map_type != BPF_MAP_TYPE_XSKMAP)
5477                         goto error;
5478                 break;
5479         case BPF_FUNC_sk_redirect_map:
5480         case BPF_FUNC_msg_redirect_map:
5481         case BPF_FUNC_sock_map_update:
5482                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5483                         goto error;
5484                 break;
5485         case BPF_FUNC_sk_redirect_hash:
5486         case BPF_FUNC_msg_redirect_hash:
5487         case BPF_FUNC_sock_hash_update:
5488                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5489                         goto error;
5490                 break;
5491         case BPF_FUNC_get_local_storage:
5492                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5493                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5494                         goto error;
5495                 break;
5496         case BPF_FUNC_sk_select_reuseport:
5497                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5498                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5499                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
5500                         goto error;
5501                 break;
5502         case BPF_FUNC_map_peek_elem:
5503         case BPF_FUNC_map_pop_elem:
5504         case BPF_FUNC_map_push_elem:
5505                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5506                     map->map_type != BPF_MAP_TYPE_STACK)
5507                         goto error;
5508                 break;
5509         case BPF_FUNC_sk_storage_get:
5510         case BPF_FUNC_sk_storage_delete:
5511                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5512                         goto error;
5513                 break;
5514         case BPF_FUNC_inode_storage_get:
5515         case BPF_FUNC_inode_storage_delete:
5516                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5517                         goto error;
5518                 break;
5519         case BPF_FUNC_task_storage_get:
5520         case BPF_FUNC_task_storage_delete:
5521                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5522                         goto error;
5523                 break;
5524         default:
5525                 break;
5526         }
5527
5528         return 0;
5529 error:
5530         verbose(env, "cannot pass map_type %d into func %s#%d\n",
5531                 map->map_type, func_id_name(func_id), func_id);
5532         return -EINVAL;
5533 }
5534
5535 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5536 {
5537         int count = 0;
5538
5539         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5540                 count++;
5541         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5542                 count++;
5543         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5544                 count++;
5545         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5546                 count++;
5547         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5548                 count++;
5549
5550         /* We only support one arg being in raw mode at the moment,
5551          * which is sufficient for the helper functions we have
5552          * right now.
5553          */
5554         return count <= 1;
5555 }
5556
5557 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5558                                     enum bpf_arg_type arg_next)
5559 {
5560         return (arg_type_is_mem_ptr(arg_curr) &&
5561                 !arg_type_is_mem_size(arg_next)) ||
5562                (!arg_type_is_mem_ptr(arg_curr) &&
5563                 arg_type_is_mem_size(arg_next));
5564 }
5565
5566 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5567 {
5568         /* bpf_xxx(..., buf, len) call will access 'len'
5569          * bytes from memory 'buf'. Both arg types need
5570          * to be paired, so make sure there's no buggy
5571          * helper function specification.
5572          */
5573         if (arg_type_is_mem_size(fn->arg1_type) ||
5574             arg_type_is_mem_ptr(fn->arg5_type)  ||
5575             check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5576             check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5577             check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5578             check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5579                 return false;
5580
5581         return true;
5582 }
5583
5584 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5585 {
5586         int count = 0;
5587
5588         if (arg_type_may_be_refcounted(fn->arg1_type))
5589                 count++;
5590         if (arg_type_may_be_refcounted(fn->arg2_type))
5591                 count++;
5592         if (arg_type_may_be_refcounted(fn->arg3_type))
5593                 count++;
5594         if (arg_type_may_be_refcounted(fn->arg4_type))
5595                 count++;
5596         if (arg_type_may_be_refcounted(fn->arg5_type))
5597                 count++;
5598
5599         /* A reference acquiring function cannot acquire
5600          * another refcounted ptr.
5601          */
5602         if (may_be_acquire_function(func_id) && count)
5603                 return false;
5604
5605         /* We only support one arg being unreferenced at the moment,
5606          * which is sufficient for the helper functions we have right now.
5607          */
5608         return count <= 1;
5609 }
5610
5611 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5612 {
5613         int i;
5614
5615         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5616                 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5617                         return false;
5618
5619                 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5620                         return false;
5621         }
5622
5623         return true;
5624 }
5625
5626 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5627 {
5628         return check_raw_mode_ok(fn) &&
5629                check_arg_pair_ok(fn) &&
5630                check_btf_id_ok(fn) &&
5631                check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5632 }
5633
5634 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5635  * are now invalid, so turn them into unknown SCALAR_VALUE.
5636  */
5637 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5638 {
5639         struct bpf_func_state *state;
5640         struct bpf_reg_state *reg;
5641
5642         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5643                 if (reg_is_pkt_pointer_any(reg))
5644                         __mark_reg_unknown(env, reg);
5645         }));
5646 }
5647
5648 enum {
5649         AT_PKT_END = -1,
5650         BEYOND_PKT_END = -2,
5651 };
5652
5653 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5654 {
5655         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5656         struct bpf_reg_state *reg = &state->regs[regn];
5657
5658         if (reg->type != PTR_TO_PACKET)
5659                 /* PTR_TO_PACKET_META is not supported yet */
5660                 return;
5661
5662         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5663          * How far beyond pkt_end it goes is unknown.
5664          * if (!range_open) it's the case of pkt >= pkt_end
5665          * if (range_open) it's the case of pkt > pkt_end
5666          * hence this pointer is at least 1 byte bigger than pkt_end
5667          */
5668         if (range_open)
5669                 reg->range = BEYOND_PKT_END;
5670         else
5671                 reg->range = AT_PKT_END;
5672 }
5673
5674 /* The pointer with the specified id has released its reference to kernel
5675  * resources. Identify all copies of the same pointer and clear the reference.
5676  */
5677 static int release_reference(struct bpf_verifier_env *env,
5678                              int ref_obj_id)
5679 {
5680         struct bpf_func_state *state;
5681         struct bpf_reg_state *reg;
5682         int err;
5683
5684         err = release_reference_state(cur_func(env), ref_obj_id);
5685         if (err)
5686                 return err;
5687
5688         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5689                 if (reg->ref_obj_id == ref_obj_id) {
5690                         if (!env->allow_ptr_leaks)
5691                                 __mark_reg_not_init(env, reg);
5692                         else
5693                                 __mark_reg_unknown(env, reg);
5694                 }
5695         }));
5696
5697         return 0;
5698 }
5699
5700 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5701                                     struct bpf_reg_state *regs)
5702 {
5703         int i;
5704
5705         /* after the call registers r0 - r5 were scratched */
5706         for (i = 0; i < CALLER_SAVED_REGS; i++) {
5707                 mark_reg_not_init(env, regs, caller_saved[i]);
5708                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5709         }
5710 }
5711
5712 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5713                                    struct bpf_func_state *caller,
5714                                    struct bpf_func_state *callee,
5715                                    int insn_idx);
5716
5717 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5718                              int *insn_idx, int subprog,
5719                              set_callee_state_fn set_callee_state_cb)
5720 {
5721         struct bpf_verifier_state *state = env->cur_state;
5722         struct bpf_func_info_aux *func_info_aux;
5723         struct bpf_func_state *caller, *callee;
5724         int err;
5725         bool is_global = false;
5726
5727         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5728                 verbose(env, "the call stack of %d frames is too deep\n",
5729                         state->curframe + 2);
5730                 return -E2BIG;
5731         }
5732
5733         caller = state->frame[state->curframe];
5734         if (state->frame[state->curframe + 1]) {
5735                 verbose(env, "verifier bug. Frame %d already allocated\n",
5736                         state->curframe + 1);
5737                 return -EFAULT;
5738         }
5739
5740         func_info_aux = env->prog->aux->func_info_aux;
5741         if (func_info_aux)
5742                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5743         err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5744         if (err == -EFAULT)
5745                 return err;
5746         if (is_global) {
5747                 if (err) {
5748                         verbose(env, "Caller passes invalid args into func#%d\n",
5749                                 subprog);
5750                         return err;
5751                 } else {
5752                         if (env->log.level & BPF_LOG_LEVEL)
5753                                 verbose(env,
5754                                         "Func#%d is global and valid. Skipping.\n",
5755                                         subprog);
5756                         clear_caller_saved_regs(env, caller->regs);
5757
5758                         /* All global functions return a 64-bit SCALAR_VALUE */
5759                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
5760                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5761
5762                         /* continue with next insn after call */
5763                         return 0;
5764                 }
5765         }
5766
5767         if (insn->code == (BPF_JMP | BPF_CALL) &&
5768             insn->src_reg == 0 &&
5769             insn->imm == BPF_FUNC_timer_set_callback) {
5770                 struct bpf_verifier_state *async_cb;
5771
5772                 /* there is no real recursion here. timer callbacks are async */
5773                 env->subprog_info[subprog].is_async_cb = true;
5774                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
5775                                          *insn_idx, subprog);
5776                 if (!async_cb)
5777                         return -EFAULT;
5778                 callee = async_cb->frame[0];
5779                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
5780
5781                 /* Convert bpf_timer_set_callback() args into timer callback args */
5782                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5783                 if (err)
5784                         return err;
5785
5786                 clear_caller_saved_regs(env, caller->regs);
5787                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5788                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5789                 /* continue with next insn after call */
5790                 return 0;
5791         }
5792
5793         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5794         if (!callee)
5795                 return -ENOMEM;
5796         state->frame[state->curframe + 1] = callee;
5797
5798         /* callee cannot access r0, r6 - r9 for reading and has to write
5799          * into its own stack before reading from it.
5800          * callee can read/write into caller's stack
5801          */
5802         init_func_state(env, callee,
5803                         /* remember the callsite, it will be used by bpf_exit */
5804                         *insn_idx /* callsite */,
5805                         state->curframe + 1 /* frameno within this callchain */,
5806                         subprog /* subprog number within this prog */);
5807
5808         /* Transfer references to the callee */
5809         err = copy_reference_state(callee, caller);
5810         if (err)
5811                 return err;
5812
5813         err = set_callee_state_cb(env, caller, callee, *insn_idx);
5814         if (err)
5815                 return err;
5816
5817         clear_caller_saved_regs(env, caller->regs);
5818
5819         /* only increment it after check_reg_arg() finished */
5820         state->curframe++;
5821
5822         /* and go analyze first insn of the callee */
5823         *insn_idx = env->subprog_info[subprog].start - 1;
5824
5825         if (env->log.level & BPF_LOG_LEVEL) {
5826                 verbose(env, "caller:\n");
5827                 print_verifier_state(env, caller);
5828                 verbose(env, "callee:\n");
5829                 print_verifier_state(env, callee);
5830         }
5831         return 0;
5832 }
5833
5834 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5835                                    struct bpf_func_state *caller,
5836                                    struct bpf_func_state *callee)
5837 {
5838         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5839          *      void *callback_ctx, u64 flags);
5840          * callback_fn(struct bpf_map *map, void *key, void *value,
5841          *      void *callback_ctx);
5842          */
5843         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5844
5845         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5846         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5847         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5848
5849         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5850         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5851         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5852
5853         /* pointer to stack or null */
5854         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5855
5856         /* unused */
5857         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5858         return 0;
5859 }
5860
5861 static int set_callee_state(struct bpf_verifier_env *env,
5862                             struct bpf_func_state *caller,
5863                             struct bpf_func_state *callee, int insn_idx)
5864 {
5865         int i;
5866
5867         /* copy r1 - r5 args that callee can access.  The copy includes parent
5868          * pointers, which connects us up to the liveness chain
5869          */
5870         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5871                 callee->regs[i] = caller->regs[i];
5872         return 0;
5873 }
5874
5875 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5876                            int *insn_idx)
5877 {
5878         int subprog, target_insn;
5879
5880         target_insn = *insn_idx + insn->imm + 1;
5881         subprog = find_subprog(env, target_insn);
5882         if (subprog < 0) {
5883                 verbose(env, "verifier bug. No program starts at insn %d\n",
5884                         target_insn);
5885                 return -EFAULT;
5886         }
5887
5888         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5889 }
5890
5891 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5892                                        struct bpf_func_state *caller,
5893                                        struct bpf_func_state *callee,
5894                                        int insn_idx)
5895 {
5896         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5897         struct bpf_map *map;
5898         int err;
5899
5900         if (bpf_map_ptr_poisoned(insn_aux)) {
5901                 verbose(env, "tail_call abusing map_ptr\n");
5902                 return -EINVAL;
5903         }
5904
5905         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5906         if (!map->ops->map_set_for_each_callback_args ||
5907             !map->ops->map_for_each_callback) {
5908                 verbose(env, "callback function not allowed for map\n");
5909                 return -ENOTSUPP;
5910         }
5911
5912         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5913         if (err)
5914                 return err;
5915
5916         callee->in_callback_fn = true;
5917         return 0;
5918 }
5919
5920 static int set_timer_callback_state(struct bpf_verifier_env *env,
5921                                     struct bpf_func_state *caller,
5922                                     struct bpf_func_state *callee,
5923                                     int insn_idx)
5924 {
5925         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
5926
5927         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
5928          * callback_fn(struct bpf_map *map, void *key, void *value);
5929          */
5930         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
5931         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
5932         callee->regs[BPF_REG_1].map_ptr = map_ptr;
5933
5934         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5935         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5936         callee->regs[BPF_REG_2].map_ptr = map_ptr;
5937
5938         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5939         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5940         callee->regs[BPF_REG_3].map_ptr = map_ptr;
5941
5942         /* unused */
5943         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
5944         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5945         callee->in_async_callback_fn = true;
5946         return 0;
5947 }
5948
5949 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5950 {
5951         struct bpf_verifier_state *state = env->cur_state;
5952         struct bpf_func_state *caller, *callee;
5953         struct bpf_reg_state *r0;
5954         int err;
5955
5956         callee = state->frame[state->curframe];
5957         r0 = &callee->regs[BPF_REG_0];
5958         if (r0->type == PTR_TO_STACK) {
5959                 /* technically it's ok to return caller's stack pointer
5960                  * (or caller's caller's pointer) back to the caller,
5961                  * since these pointers are valid. Only current stack
5962                  * pointer will be invalid as soon as function exits,
5963                  * but let's be conservative
5964                  */
5965                 verbose(env, "cannot return stack pointer to the caller\n");
5966                 return -EINVAL;
5967         }
5968
5969         state->curframe--;
5970         caller = state->frame[state->curframe];
5971         if (callee->in_callback_fn) {
5972                 /* enforce R0 return value range [0, 1]. */
5973                 struct tnum range = tnum_range(0, 1);
5974
5975                 if (r0->type != SCALAR_VALUE) {
5976                         verbose(env, "R0 not a scalar value\n");
5977                         return -EACCES;
5978                 }
5979                 if (!tnum_in(range, r0->var_off)) {
5980                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5981                         return -EINVAL;
5982                 }
5983         } else {
5984                 /* return to the caller whatever r0 had in the callee */
5985                 caller->regs[BPF_REG_0] = *r0;
5986         }
5987
5988         /* callback_fn frame should have released its own additions to parent's
5989          * reference state at this point, or check_reference_leak would
5990          * complain, hence it must be the same as the caller. There is no need
5991          * to copy it back.
5992          */
5993         if (!callee->in_callback_fn) {
5994                 /* Transfer references to the caller */
5995                 err = copy_reference_state(caller, callee);
5996                 if (err)
5997                         return err;
5998         }
5999
6000         *insn_idx = callee->callsite + 1;
6001         if (env->log.level & BPF_LOG_LEVEL) {
6002                 verbose(env, "returning from callee:\n");
6003                 print_verifier_state(env, callee);
6004                 verbose(env, "to caller at %d:\n", *insn_idx);
6005                 print_verifier_state(env, caller);
6006         }
6007         /* clear everything in the callee */
6008         free_func_state(callee);
6009         state->frame[state->curframe + 1] = NULL;
6010         return 0;
6011 }
6012
6013 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6014                                    int func_id,
6015                                    struct bpf_call_arg_meta *meta)
6016 {
6017         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6018
6019         if (ret_type != RET_INTEGER ||
6020             (func_id != BPF_FUNC_get_stack &&
6021              func_id != BPF_FUNC_get_task_stack &&
6022              func_id != BPF_FUNC_probe_read_str &&
6023              func_id != BPF_FUNC_probe_read_kernel_str &&
6024              func_id != BPF_FUNC_probe_read_user_str))
6025                 return;
6026
6027         ret_reg->smax_value = meta->msize_max_value;
6028         ret_reg->s32_max_value = meta->msize_max_value;
6029         ret_reg->smin_value = -MAX_ERRNO;
6030         ret_reg->s32_min_value = -MAX_ERRNO;
6031         reg_bounds_sync(ret_reg);
6032 }
6033
6034 static int
6035 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6036                 int func_id, int insn_idx)
6037 {
6038         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6039         struct bpf_map *map = meta->map_ptr;
6040
6041         if (func_id != BPF_FUNC_tail_call &&
6042             func_id != BPF_FUNC_map_lookup_elem &&
6043             func_id != BPF_FUNC_map_update_elem &&
6044             func_id != BPF_FUNC_map_delete_elem &&
6045             func_id != BPF_FUNC_map_push_elem &&
6046             func_id != BPF_FUNC_map_pop_elem &&
6047             func_id != BPF_FUNC_map_peek_elem &&
6048             func_id != BPF_FUNC_for_each_map_elem &&
6049             func_id != BPF_FUNC_redirect_map)
6050                 return 0;
6051
6052         if (map == NULL) {
6053                 verbose(env, "kernel subsystem misconfigured verifier\n");
6054                 return -EINVAL;
6055         }
6056
6057         /* In case of read-only, some additional restrictions
6058          * need to be applied in order to prevent altering the
6059          * state of the map from program side.
6060          */
6061         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6062             (func_id == BPF_FUNC_map_delete_elem ||
6063              func_id == BPF_FUNC_map_update_elem ||
6064              func_id == BPF_FUNC_map_push_elem ||
6065              func_id == BPF_FUNC_map_pop_elem)) {
6066                 verbose(env, "write into map forbidden\n");
6067                 return -EACCES;
6068         }
6069
6070         if (!BPF_MAP_PTR(aux->map_ptr_state))
6071                 bpf_map_ptr_store(aux, meta->map_ptr,
6072                                   !meta->map_ptr->bypass_spec_v1);
6073         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6074                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6075                                   !meta->map_ptr->bypass_spec_v1);
6076         return 0;
6077 }
6078
6079 static int
6080 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6081                 int func_id, int insn_idx)
6082 {
6083         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6084         struct bpf_reg_state *regs = cur_regs(env), *reg;
6085         struct bpf_map *map = meta->map_ptr;
6086         u64 val, max;
6087         int err;
6088
6089         if (func_id != BPF_FUNC_tail_call)
6090                 return 0;
6091         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6092                 verbose(env, "kernel subsystem misconfigured verifier\n");
6093                 return -EINVAL;
6094         }
6095
6096         reg = &regs[BPF_REG_3];
6097         val = reg->var_off.value;
6098         max = map->max_entries;
6099
6100         if (!(register_is_const(reg) && val < max)) {
6101                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6102                 return 0;
6103         }
6104
6105         err = mark_chain_precision(env, BPF_REG_3);
6106         if (err)
6107                 return err;
6108         if (bpf_map_key_unseen(aux))
6109                 bpf_map_key_store(aux, val);
6110         else if (!bpf_map_key_poisoned(aux) &&
6111                   bpf_map_key_immediate(aux) != val)
6112                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6113         return 0;
6114 }
6115
6116 static int check_reference_leak(struct bpf_verifier_env *env)
6117 {
6118         struct bpf_func_state *state = cur_func(env);
6119         bool refs_lingering = false;
6120         int i;
6121
6122         if (state->frameno && !state->in_callback_fn)
6123                 return 0;
6124
6125         for (i = 0; i < state->acquired_refs; i++) {
6126                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
6127                         continue;
6128                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6129                         state->refs[i].id, state->refs[i].insn_idx);
6130                 refs_lingering = true;
6131         }
6132         return refs_lingering ? -EINVAL : 0;
6133 }
6134
6135 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6136                                    struct bpf_reg_state *regs)
6137 {
6138         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6139         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6140         struct bpf_map *fmt_map = fmt_reg->map_ptr;
6141         int err, fmt_map_off, num_args;
6142         u64 fmt_addr;
6143         char *fmt;
6144
6145         /* data must be an array of u64 */
6146         if (data_len_reg->var_off.value % 8)
6147                 return -EINVAL;
6148         num_args = data_len_reg->var_off.value / 8;
6149
6150         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6151          * and map_direct_value_addr is set.
6152          */
6153         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6154         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6155                                                   fmt_map_off);
6156         if (err) {
6157                 verbose(env, "verifier bug\n");
6158                 return -EFAULT;
6159         }
6160         fmt = (char *)(long)fmt_addr + fmt_map_off;
6161
6162         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6163          * can focus on validating the format specifiers.
6164          */
6165         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6166         if (err < 0)
6167                 verbose(env, "Invalid format string\n");
6168
6169         return err;
6170 }
6171
6172 static int check_get_func_ip(struct bpf_verifier_env *env)
6173 {
6174         enum bpf_attach_type eatype = env->prog->expected_attach_type;
6175         enum bpf_prog_type type = resolve_prog_type(env->prog);
6176         int func_id = BPF_FUNC_get_func_ip;
6177
6178         if (type == BPF_PROG_TYPE_TRACING) {
6179                 if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT &&
6180                     eatype != BPF_MODIFY_RETURN) {
6181                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6182                                 func_id_name(func_id), func_id);
6183                         return -ENOTSUPP;
6184                 }
6185                 return 0;
6186         } else if (type == BPF_PROG_TYPE_KPROBE) {
6187                 return 0;
6188         }
6189
6190         verbose(env, "func %s#%d not supported for program type %d\n",
6191                 func_id_name(func_id), func_id, type);
6192         return -ENOTSUPP;
6193 }
6194
6195 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6196                              int *insn_idx_p)
6197 {
6198         const struct bpf_func_proto *fn = NULL;
6199         enum bpf_return_type ret_type;
6200         enum bpf_type_flag ret_flag;
6201         struct bpf_reg_state *regs;
6202         struct bpf_call_arg_meta meta;
6203         int insn_idx = *insn_idx_p;
6204         bool changes_data;
6205         int i, err, func_id;
6206
6207         /* find function prototype */
6208         func_id = insn->imm;
6209         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6210                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6211                         func_id);
6212                 return -EINVAL;
6213         }
6214
6215         if (env->ops->get_func_proto)
6216                 fn = env->ops->get_func_proto(func_id, env->prog);
6217         if (!fn) {
6218                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6219                         func_id);
6220                 return -EINVAL;
6221         }
6222
6223         /* eBPF programs must be GPL compatible to use GPL-ed functions */
6224         if (!env->prog->gpl_compatible && fn->gpl_only) {
6225                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6226                 return -EINVAL;
6227         }
6228
6229         if (fn->allowed && !fn->allowed(env->prog)) {
6230                 verbose(env, "helper call is not allowed in probe\n");
6231                 return -EINVAL;
6232         }
6233
6234         /* With LD_ABS/IND some JITs save/restore skb from r1. */
6235         changes_data = bpf_helper_changes_pkt_data(fn->func);
6236         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6237                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6238                         func_id_name(func_id), func_id);
6239                 return -EINVAL;
6240         }
6241
6242         memset(&meta, 0, sizeof(meta));
6243         meta.pkt_access = fn->pkt_access;
6244
6245         err = check_func_proto(fn, func_id);
6246         if (err) {
6247                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6248                         func_id_name(func_id), func_id);
6249                 return err;
6250         }
6251
6252         meta.func_id = func_id;
6253         /* check args */
6254         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6255                 err = check_func_arg(env, i, &meta, fn);
6256                 if (err)
6257                         return err;
6258         }
6259
6260         err = record_func_map(env, &meta, func_id, insn_idx);
6261         if (err)
6262                 return err;
6263
6264         err = record_func_key(env, &meta, func_id, insn_idx);
6265         if (err)
6266                 return err;
6267
6268         /* Mark slots with STACK_MISC in case of raw mode, stack offset
6269          * is inferred from register state.
6270          */
6271         for (i = 0; i < meta.access_size; i++) {
6272                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6273                                        BPF_WRITE, -1, false);
6274                 if (err)
6275                         return err;
6276         }
6277
6278         if (func_id == BPF_FUNC_tail_call) {
6279                 err = check_reference_leak(env);
6280                 if (err) {
6281                         verbose(env, "tail_call would lead to reference leak\n");
6282                         return err;
6283                 }
6284         } else if (is_release_function(func_id)) {
6285                 err = release_reference(env, meta.ref_obj_id);
6286                 if (err) {
6287                         verbose(env, "func %s#%d reference has not been acquired before\n",
6288                                 func_id_name(func_id), func_id);
6289                         return err;
6290                 }
6291         }
6292
6293         regs = cur_regs(env);
6294
6295         /* check that flags argument in get_local_storage(map, flags) is 0,
6296          * this is required because get_local_storage() can't return an error.
6297          */
6298         if (func_id == BPF_FUNC_get_local_storage &&
6299             !register_is_null(&regs[BPF_REG_2])) {
6300                 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6301                 return -EINVAL;
6302         }
6303
6304         if (func_id == BPF_FUNC_for_each_map_elem) {
6305                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6306                                         set_map_elem_callback_state);
6307                 if (err < 0)
6308                         return -EINVAL;
6309         }
6310
6311         if (func_id == BPF_FUNC_timer_set_callback) {
6312                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6313                                         set_timer_callback_state);
6314                 if (err < 0)
6315                         return -EINVAL;
6316         }
6317
6318         if (func_id == BPF_FUNC_snprintf) {
6319                 err = check_bpf_snprintf_call(env, regs);
6320                 if (err < 0)
6321                         return err;
6322         }
6323
6324         /* reset caller saved regs */
6325         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6326                 mark_reg_not_init(env, regs, caller_saved[i]);
6327                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6328         }
6329
6330         /* helper call returns 64-bit value. */
6331         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6332
6333         /* update return register (already marked as written above) */
6334         ret_type = fn->ret_type;
6335         ret_flag = type_flag(fn->ret_type);
6336         if (ret_type == RET_INTEGER) {
6337                 /* sets type to SCALAR_VALUE */
6338                 mark_reg_unknown(env, regs, BPF_REG_0);
6339         } else if (ret_type == RET_VOID) {
6340                 regs[BPF_REG_0].type = NOT_INIT;
6341         } else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
6342                 /* There is no offset yet applied, variable or fixed */
6343                 mark_reg_known_zero(env, regs, BPF_REG_0);
6344                 /* remember map_ptr, so that check_map_access()
6345                  * can check 'value_size' boundary of memory access
6346                  * to map element returned from bpf_map_lookup_elem()
6347                  */
6348                 if (meta.map_ptr == NULL) {
6349                         verbose(env,
6350                                 "kernel subsystem misconfigured verifier\n");
6351                         return -EINVAL;
6352                 }
6353                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
6354                 regs[BPF_REG_0].map_uid = meta.map_uid;
6355                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
6356                 if (!type_may_be_null(ret_type) &&
6357                     map_value_has_spin_lock(meta.map_ptr)) {
6358                         regs[BPF_REG_0].id = ++env->id_gen;
6359                 }
6360         } else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
6361                 mark_reg_known_zero(env, regs, BPF_REG_0);
6362                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
6363         } else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
6364                 mark_reg_known_zero(env, regs, BPF_REG_0);
6365                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
6366         } else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
6367                 mark_reg_known_zero(env, regs, BPF_REG_0);
6368                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
6369         } else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
6370                 mark_reg_known_zero(env, regs, BPF_REG_0);
6371                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6372                 regs[BPF_REG_0].mem_size = meta.mem_size;
6373         } else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
6374                 const struct btf_type *t;
6375
6376                 mark_reg_known_zero(env, regs, BPF_REG_0);
6377                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6378                 if (!btf_type_is_struct(t)) {
6379                         u32 tsize;
6380                         const struct btf_type *ret;
6381                         const char *tname;
6382
6383                         /* resolve the type size of ksym. */
6384                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6385                         if (IS_ERR(ret)) {
6386                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6387                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6388                                         tname, PTR_ERR(ret));
6389                                 return -EINVAL;
6390                         }
6391                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6392                         regs[BPF_REG_0].mem_size = tsize;
6393                 } else {
6394                         /* MEM_RDONLY may be carried from ret_flag, but it
6395                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
6396                          * it will confuse the check of PTR_TO_BTF_ID in
6397                          * check_mem_access().
6398                          */
6399                         ret_flag &= ~MEM_RDONLY;
6400
6401                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6402                         regs[BPF_REG_0].btf = meta.ret_btf;
6403                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6404                 }
6405         } else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
6406                 int ret_btf_id;
6407
6408                 mark_reg_known_zero(env, regs, BPF_REG_0);
6409                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6410                 ret_btf_id = *fn->ret_btf_id;
6411                 if (ret_btf_id == 0) {
6412                         verbose(env, "invalid return type %u of func %s#%d\n",
6413                                 base_type(ret_type), func_id_name(func_id),
6414                                 func_id);
6415                         return -EINVAL;
6416                 }
6417                 /* current BPF helper definitions are only coming from
6418                  * built-in code with type IDs from  vmlinux BTF
6419                  */
6420                 regs[BPF_REG_0].btf = btf_vmlinux;
6421                 regs[BPF_REG_0].btf_id = ret_btf_id;
6422         } else {
6423                 verbose(env, "unknown return type %u of func %s#%d\n",
6424                         base_type(ret_type), func_id_name(func_id), func_id);
6425                 return -EINVAL;
6426         }
6427
6428         if (type_may_be_null(regs[BPF_REG_0].type))
6429                 regs[BPF_REG_0].id = ++env->id_gen;
6430
6431         if (is_ptr_cast_function(func_id)) {
6432                 /* For release_reference() */
6433                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6434         } else if (is_acquire_function(func_id, meta.map_ptr)) {
6435                 int id = acquire_reference_state(env, insn_idx);
6436
6437                 if (id < 0)
6438                         return id;
6439                 /* For mark_ptr_or_null_reg() */
6440                 regs[BPF_REG_0].id = id;
6441                 /* For release_reference() */
6442                 regs[BPF_REG_0].ref_obj_id = id;
6443         }
6444
6445         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6446
6447         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6448         if (err)
6449                 return err;
6450
6451         if ((func_id == BPF_FUNC_get_stack ||
6452              func_id == BPF_FUNC_get_task_stack) &&
6453             !env->prog->has_callchain_buf) {
6454                 const char *err_str;
6455
6456 #ifdef CONFIG_PERF_EVENTS
6457                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6458                 err_str = "cannot get callchain buffer for func %s#%d\n";
6459 #else
6460                 err = -ENOTSUPP;
6461                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6462 #endif
6463                 if (err) {
6464                         verbose(env, err_str, func_id_name(func_id), func_id);
6465                         return err;
6466                 }
6467
6468                 env->prog->has_callchain_buf = true;
6469         }
6470
6471         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6472                 env->prog->call_get_stack = true;
6473
6474         if (func_id == BPF_FUNC_get_func_ip) {
6475                 if (check_get_func_ip(env))
6476                         return -ENOTSUPP;
6477                 env->prog->call_get_func_ip = true;
6478         }
6479
6480         if (changes_data)
6481                 clear_all_pkt_pointers(env);
6482         return 0;
6483 }
6484
6485 /* mark_btf_func_reg_size() is used when the reg size is determined by
6486  * the BTF func_proto's return value size and argument.
6487  */
6488 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6489                                    size_t reg_size)
6490 {
6491         struct bpf_reg_state *reg = &cur_regs(env)[regno];
6492
6493         if (regno == BPF_REG_0) {
6494                 /* Function return value */
6495                 reg->live |= REG_LIVE_WRITTEN;
6496                 reg->subreg_def = reg_size == sizeof(u64) ?
6497                         DEF_NOT_SUBREG : env->insn_idx + 1;
6498         } else {
6499                 /* Function argument */
6500                 if (reg_size == sizeof(u64)) {
6501                         mark_insn_zext(env, reg);
6502                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6503                 } else {
6504                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6505                 }
6506         }
6507 }
6508
6509 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6510 {
6511         const struct btf_type *t, *func, *func_proto, *ptr_type;
6512         struct bpf_reg_state *regs = cur_regs(env);
6513         const char *func_name, *ptr_type_name;
6514         u32 i, nargs, func_id, ptr_type_id;
6515         const struct btf_param *args;
6516         int err;
6517
6518         func_id = insn->imm;
6519         func = btf_type_by_id(btf_vmlinux, func_id);
6520         func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6521         func_proto = btf_type_by_id(btf_vmlinux, func->type);
6522
6523         if (!env->ops->check_kfunc_call ||
6524             !env->ops->check_kfunc_call(func_id)) {
6525                 verbose(env, "calling kernel function %s is not allowed\n",
6526                         func_name);
6527                 return -EACCES;
6528         }
6529
6530         /* Check the arguments */
6531         err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6532         if (err)
6533                 return err;
6534
6535         for (i = 0; i < CALLER_SAVED_REGS; i++)
6536                 mark_reg_not_init(env, regs, caller_saved[i]);
6537
6538         /* Check return type */
6539         t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6540         if (btf_type_is_scalar(t)) {
6541                 mark_reg_unknown(env, regs, BPF_REG_0);
6542                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6543         } else if (btf_type_is_ptr(t)) {
6544                 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6545                                                    &ptr_type_id);
6546                 if (!btf_type_is_struct(ptr_type)) {
6547                         ptr_type_name = btf_name_by_offset(btf_vmlinux,
6548                                                            ptr_type->name_off);
6549                         verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6550                                 func_name, btf_type_str(ptr_type),
6551                                 ptr_type_name);
6552                         return -EINVAL;
6553                 }
6554                 mark_reg_known_zero(env, regs, BPF_REG_0);
6555                 regs[BPF_REG_0].btf = btf_vmlinux;
6556                 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6557                 regs[BPF_REG_0].btf_id = ptr_type_id;
6558                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6559         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6560
6561         nargs = btf_type_vlen(func_proto);
6562         args = (const struct btf_param *)(func_proto + 1);
6563         for (i = 0; i < nargs; i++) {
6564                 u32 regno = i + 1;
6565
6566                 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6567                 if (btf_type_is_ptr(t))
6568                         mark_btf_func_reg_size(env, regno, sizeof(void *));
6569                 else
6570                         /* scalar. ensured by btf_check_kfunc_arg_match() */
6571                         mark_btf_func_reg_size(env, regno, t->size);
6572         }
6573
6574         return 0;
6575 }
6576
6577 static bool signed_add_overflows(s64 a, s64 b)
6578 {
6579         /* Do the add in u64, where overflow is well-defined */
6580         s64 res = (s64)((u64)a + (u64)b);
6581
6582         if (b < 0)
6583                 return res > a;
6584         return res < a;
6585 }
6586
6587 static bool signed_add32_overflows(s32 a, s32 b)
6588 {
6589         /* Do the add in u32, where overflow is well-defined */
6590         s32 res = (s32)((u32)a + (u32)b);
6591
6592         if (b < 0)
6593                 return res > a;
6594         return res < a;
6595 }
6596
6597 static bool signed_sub_overflows(s64 a, s64 b)
6598 {
6599         /* Do the sub in u64, where overflow is well-defined */
6600         s64 res = (s64)((u64)a - (u64)b);
6601
6602         if (b < 0)
6603                 return res < a;
6604         return res > a;
6605 }
6606
6607 static bool signed_sub32_overflows(s32 a, s32 b)
6608 {
6609         /* Do the sub in u32, where overflow is well-defined */
6610         s32 res = (s32)((u32)a - (u32)b);
6611
6612         if (b < 0)
6613                 return res < a;
6614         return res > a;
6615 }
6616
6617 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6618                                   const struct bpf_reg_state *reg,
6619                                   enum bpf_reg_type type)
6620 {
6621         bool known = tnum_is_const(reg->var_off);
6622         s64 val = reg->var_off.value;
6623         s64 smin = reg->smin_value;
6624
6625         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6626                 verbose(env, "math between %s pointer and %lld is not allowed\n",
6627                         reg_type_str(env, type), val);
6628                 return false;
6629         }
6630
6631         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6632                 verbose(env, "%s pointer offset %d is not allowed\n",
6633                         reg_type_str(env, type), reg->off);
6634                 return false;
6635         }
6636
6637         if (smin == S64_MIN) {
6638                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6639                         reg_type_str(env, type));
6640                 return false;
6641         }
6642
6643         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6644                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6645                         smin, reg_type_str(env, type));
6646                 return false;
6647         }
6648
6649         return true;
6650 }
6651
6652 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6653 {
6654         return &env->insn_aux_data[env->insn_idx];
6655 }
6656
6657 enum {
6658         REASON_BOUNDS   = -1,
6659         REASON_TYPE     = -2,
6660         REASON_PATHS    = -3,
6661         REASON_LIMIT    = -4,
6662         REASON_STACK    = -5,
6663 };
6664
6665 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6666                               u32 *alu_limit, bool mask_to_left)
6667 {
6668         u32 max = 0, ptr_limit = 0;
6669
6670         switch (ptr_reg->type) {
6671         case PTR_TO_STACK:
6672                 /* Offset 0 is out-of-bounds, but acceptable start for the
6673                  * left direction, see BPF_REG_FP. Also, unknown scalar
6674                  * offset where we would need to deal with min/max bounds is
6675                  * currently prohibited for unprivileged.
6676                  */
6677                 max = MAX_BPF_STACK + mask_to_left;
6678                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6679                 break;
6680         case PTR_TO_MAP_VALUE:
6681                 max = ptr_reg->map_ptr->value_size;
6682                 ptr_limit = (mask_to_left ?
6683                              ptr_reg->smin_value :
6684                              ptr_reg->umax_value) + ptr_reg->off;
6685                 break;
6686         default:
6687                 return REASON_TYPE;
6688         }
6689
6690         if (ptr_limit >= max)
6691                 return REASON_LIMIT;
6692         *alu_limit = ptr_limit;
6693         return 0;
6694 }
6695
6696 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6697                                     const struct bpf_insn *insn)
6698 {
6699         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6700 }
6701
6702 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6703                                        u32 alu_state, u32 alu_limit)
6704 {
6705         /* If we arrived here from different branches with different
6706          * state or limits to sanitize, then this won't work.
6707          */
6708         if (aux->alu_state &&
6709             (aux->alu_state != alu_state ||
6710              aux->alu_limit != alu_limit))
6711                 return REASON_PATHS;
6712
6713         /* Corresponding fixup done in do_misc_fixups(). */
6714         aux->alu_state = alu_state;
6715         aux->alu_limit = alu_limit;
6716         return 0;
6717 }
6718
6719 static int sanitize_val_alu(struct bpf_verifier_env *env,
6720                             struct bpf_insn *insn)
6721 {
6722         struct bpf_insn_aux_data *aux = cur_aux(env);
6723
6724         if (can_skip_alu_sanitation(env, insn))
6725                 return 0;
6726
6727         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6728 }
6729
6730 static bool sanitize_needed(u8 opcode)
6731 {
6732         return opcode == BPF_ADD || opcode == BPF_SUB;
6733 }
6734
6735 struct bpf_sanitize_info {
6736         struct bpf_insn_aux_data aux;
6737         bool mask_to_left;
6738 };
6739
6740 static struct bpf_verifier_state *
6741 sanitize_speculative_path(struct bpf_verifier_env *env,
6742                           const struct bpf_insn *insn,
6743                           u32 next_idx, u32 curr_idx)
6744 {
6745         struct bpf_verifier_state *branch;
6746         struct bpf_reg_state *regs;
6747
6748         branch = push_stack(env, next_idx, curr_idx, true);
6749         if (branch && insn) {
6750                 regs = branch->frame[branch->curframe]->regs;
6751                 if (BPF_SRC(insn->code) == BPF_K) {
6752                         mark_reg_unknown(env, regs, insn->dst_reg);
6753                 } else if (BPF_SRC(insn->code) == BPF_X) {
6754                         mark_reg_unknown(env, regs, insn->dst_reg);
6755                         mark_reg_unknown(env, regs, insn->src_reg);
6756                 }
6757         }
6758         return branch;
6759 }
6760
6761 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6762                             struct bpf_insn *insn,
6763                             const struct bpf_reg_state *ptr_reg,
6764                             const struct bpf_reg_state *off_reg,
6765                             struct bpf_reg_state *dst_reg,
6766                             struct bpf_sanitize_info *info,
6767                             const bool commit_window)
6768 {
6769         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6770         struct bpf_verifier_state *vstate = env->cur_state;
6771         bool off_is_imm = tnum_is_const(off_reg->var_off);
6772         bool off_is_neg = off_reg->smin_value < 0;
6773         bool ptr_is_dst_reg = ptr_reg == dst_reg;
6774         u8 opcode = BPF_OP(insn->code);
6775         u32 alu_state, alu_limit;
6776         struct bpf_reg_state tmp;
6777         bool ret;
6778         int err;
6779
6780         if (can_skip_alu_sanitation(env, insn))
6781                 return 0;
6782
6783         /* We already marked aux for masking from non-speculative
6784          * paths, thus we got here in the first place. We only care
6785          * to explore bad access from here.
6786          */
6787         if (vstate->speculative)
6788                 goto do_sim;
6789
6790         if (!commit_window) {
6791                 if (!tnum_is_const(off_reg->var_off) &&
6792                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6793                         return REASON_BOUNDS;
6794
6795                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6796                                      (opcode == BPF_SUB && !off_is_neg);
6797         }
6798
6799         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6800         if (err < 0)
6801                 return err;
6802
6803         if (commit_window) {
6804                 /* In commit phase we narrow the masking window based on
6805                  * the observed pointer move after the simulated operation.
6806                  */
6807                 alu_state = info->aux.alu_state;
6808                 alu_limit = abs(info->aux.alu_limit - alu_limit);
6809         } else {
6810                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6811                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6812                 alu_state |= ptr_is_dst_reg ?
6813                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6814
6815                 /* Limit pruning on unknown scalars to enable deep search for
6816                  * potential masking differences from other program paths.
6817                  */
6818                 if (!off_is_imm)
6819                         env->explore_alu_limits = true;
6820         }
6821
6822         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6823         if (err < 0)
6824                 return err;
6825 do_sim:
6826         /* If we're in commit phase, we're done here given we already
6827          * pushed the truncated dst_reg into the speculative verification
6828          * stack.
6829          *
6830          * Also, when register is a known constant, we rewrite register-based
6831          * operation to immediate-based, and thus do not need masking (and as
6832          * a consequence, do not need to simulate the zero-truncation either).
6833          */
6834         if (commit_window || off_is_imm)
6835                 return 0;
6836
6837         /* Simulate and find potential out-of-bounds access under
6838          * speculative execution from truncation as a result of
6839          * masking when off was not within expected range. If off
6840          * sits in dst, then we temporarily need to move ptr there
6841          * to simulate dst (== 0) +/-= ptr. Needed, for example,
6842          * for cases where we use K-based arithmetic in one direction
6843          * and truncated reg-based in the other in order to explore
6844          * bad access.
6845          */
6846         if (!ptr_is_dst_reg) {
6847                 tmp = *dst_reg;
6848                 *dst_reg = *ptr_reg;
6849         }
6850         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6851                                         env->insn_idx);
6852         if (!ptr_is_dst_reg && ret)
6853                 *dst_reg = tmp;
6854         return !ret ? REASON_STACK : 0;
6855 }
6856
6857 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6858 {
6859         struct bpf_verifier_state *vstate = env->cur_state;
6860
6861         /* If we simulate paths under speculation, we don't update the
6862          * insn as 'seen' such that when we verify unreachable paths in
6863          * the non-speculative domain, sanitize_dead_code() can still
6864          * rewrite/sanitize them.
6865          */
6866         if (!vstate->speculative)
6867                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6868 }
6869
6870 static int sanitize_err(struct bpf_verifier_env *env,
6871                         const struct bpf_insn *insn, int reason,
6872                         const struct bpf_reg_state *off_reg,
6873                         const struct bpf_reg_state *dst_reg)
6874 {
6875         static const char *err = "pointer arithmetic with it prohibited for !root";
6876         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6877         u32 dst = insn->dst_reg, src = insn->src_reg;
6878
6879         switch (reason) {
6880         case REASON_BOUNDS:
6881                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6882                         off_reg == dst_reg ? dst : src, err);
6883                 break;
6884         case REASON_TYPE:
6885                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6886                         off_reg == dst_reg ? src : dst, err);
6887                 break;
6888         case REASON_PATHS:
6889                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6890                         dst, op, err);
6891                 break;
6892         case REASON_LIMIT:
6893                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6894                         dst, op, err);
6895                 break;
6896         case REASON_STACK:
6897                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6898                         dst, err);
6899                 break;
6900         default:
6901                 verbose(env, "verifier internal error: unknown reason (%d)\n",
6902                         reason);
6903                 break;
6904         }
6905
6906         return -EACCES;
6907 }
6908
6909 /* check that stack access falls within stack limits and that 'reg' doesn't
6910  * have a variable offset.
6911  *
6912  * Variable offset is prohibited for unprivileged mode for simplicity since it
6913  * requires corresponding support in Spectre masking for stack ALU.  See also
6914  * retrieve_ptr_limit().
6915  *
6916  *
6917  * 'off' includes 'reg->off'.
6918  */
6919 static int check_stack_access_for_ptr_arithmetic(
6920                                 struct bpf_verifier_env *env,
6921                                 int regno,
6922                                 const struct bpf_reg_state *reg,
6923                                 int off)
6924 {
6925         if (!tnum_is_const(reg->var_off)) {
6926                 char tn_buf[48];
6927
6928                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6929                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6930                         regno, tn_buf, off);
6931                 return -EACCES;
6932         }
6933
6934         if (off >= 0 || off < -MAX_BPF_STACK) {
6935                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6936                         "prohibited for !root; off=%d\n", regno, off);
6937                 return -EACCES;
6938         }
6939
6940         return 0;
6941 }
6942
6943 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6944                                  const struct bpf_insn *insn,
6945                                  const struct bpf_reg_state *dst_reg)
6946 {
6947         u32 dst = insn->dst_reg;
6948
6949         /* For unprivileged we require that resulting offset must be in bounds
6950          * in order to be able to sanitize access later on.
6951          */
6952         if (env->bypass_spec_v1)
6953                 return 0;
6954
6955         switch (dst_reg->type) {
6956         case PTR_TO_STACK:
6957                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6958                                         dst_reg->off + dst_reg->var_off.value))
6959                         return -EACCES;
6960                 break;
6961         case PTR_TO_MAP_VALUE:
6962                 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6963                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6964                                 "prohibited for !root\n", dst);
6965                         return -EACCES;
6966                 }
6967                 break;
6968         default:
6969                 break;
6970         }
6971
6972         return 0;
6973 }
6974
6975 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6976  * Caller should also handle BPF_MOV case separately.
6977  * If we return -EACCES, caller may want to try again treating pointer as a
6978  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6979  */
6980 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6981                                    struct bpf_insn *insn,
6982                                    const struct bpf_reg_state *ptr_reg,
6983                                    const struct bpf_reg_state *off_reg)
6984 {
6985         struct bpf_verifier_state *vstate = env->cur_state;
6986         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6987         struct bpf_reg_state *regs = state->regs, *dst_reg;
6988         bool known = tnum_is_const(off_reg->var_off);
6989         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6990             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6991         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6992             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6993         struct bpf_sanitize_info info = {};
6994         u8 opcode = BPF_OP(insn->code);
6995         u32 dst = insn->dst_reg;
6996         int ret;
6997
6998         dst_reg = &regs[dst];
6999
7000         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7001             smin_val > smax_val || umin_val > umax_val) {
7002                 /* Taint dst register if offset had invalid bounds derived from
7003                  * e.g. dead branches.
7004                  */
7005                 __mark_reg_unknown(env, dst_reg);
7006                 return 0;
7007         }
7008
7009         if (BPF_CLASS(insn->code) != BPF_ALU64) {
7010                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
7011                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7012                         __mark_reg_unknown(env, dst_reg);
7013                         return 0;
7014                 }
7015
7016                 verbose(env,
7017                         "R%d 32-bit pointer arithmetic prohibited\n",
7018                         dst);
7019                 return -EACCES;
7020         }
7021
7022         if (ptr_reg->type & PTR_MAYBE_NULL) {
7023                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7024                         dst, reg_type_str(env, ptr_reg->type));
7025                 return -EACCES;
7026         }
7027
7028         switch (base_type(ptr_reg->type)) {
7029         case CONST_PTR_TO_MAP:
7030                 /* smin_val represents the known value */
7031                 if (known && smin_val == 0 && opcode == BPF_ADD)
7032                         break;
7033                 fallthrough;
7034         case PTR_TO_PACKET_END:
7035         case PTR_TO_SOCKET:
7036         case PTR_TO_SOCK_COMMON:
7037         case PTR_TO_TCP_SOCK:
7038         case PTR_TO_XDP_SOCK:
7039 reject:
7040                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7041                         dst, reg_type_str(env, ptr_reg->type));
7042                 return -EACCES;
7043         default:
7044                 if (type_may_be_null(ptr_reg->type))
7045                         goto reject;
7046                 break;
7047         }
7048
7049         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7050          * The id may be overwritten later if we create a new variable offset.
7051          */
7052         dst_reg->type = ptr_reg->type;
7053         dst_reg->id = ptr_reg->id;
7054
7055         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7056             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7057                 return -EINVAL;
7058
7059         /* pointer types do not carry 32-bit bounds at the moment. */
7060         __mark_reg32_unbounded(dst_reg);
7061
7062         if (sanitize_needed(opcode)) {
7063                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7064                                        &info, false);
7065                 if (ret < 0)
7066                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
7067         }
7068
7069         switch (opcode) {
7070         case BPF_ADD:
7071                 /* We can take a fixed offset as long as it doesn't overflow
7072                  * the s32 'off' field
7073                  */
7074                 if (known && (ptr_reg->off + smin_val ==
7075                               (s64)(s32)(ptr_reg->off + smin_val))) {
7076                         /* pointer += K.  Accumulate it into fixed offset */
7077                         dst_reg->smin_value = smin_ptr;
7078                         dst_reg->smax_value = smax_ptr;
7079                         dst_reg->umin_value = umin_ptr;
7080                         dst_reg->umax_value = umax_ptr;
7081                         dst_reg->var_off = ptr_reg->var_off;
7082                         dst_reg->off = ptr_reg->off + smin_val;
7083                         dst_reg->raw = ptr_reg->raw;
7084                         break;
7085                 }
7086                 /* A new variable offset is created.  Note that off_reg->off
7087                  * == 0, since it's a scalar.
7088                  * dst_reg gets the pointer type and since some positive
7089                  * integer value was added to the pointer, give it a new 'id'
7090                  * if it's a PTR_TO_PACKET.
7091                  * this creates a new 'base' pointer, off_reg (variable) gets
7092                  * added into the variable offset, and we copy the fixed offset
7093                  * from ptr_reg.
7094                  */
7095                 if (signed_add_overflows(smin_ptr, smin_val) ||
7096                     signed_add_overflows(smax_ptr, smax_val)) {
7097                         dst_reg->smin_value = S64_MIN;
7098                         dst_reg->smax_value = S64_MAX;
7099                 } else {
7100                         dst_reg->smin_value = smin_ptr + smin_val;
7101                         dst_reg->smax_value = smax_ptr + smax_val;
7102                 }
7103                 if (umin_ptr + umin_val < umin_ptr ||
7104                     umax_ptr + umax_val < umax_ptr) {
7105                         dst_reg->umin_value = 0;
7106                         dst_reg->umax_value = U64_MAX;
7107                 } else {
7108                         dst_reg->umin_value = umin_ptr + umin_val;
7109                         dst_reg->umax_value = umax_ptr + umax_val;
7110                 }
7111                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7112                 dst_reg->off = ptr_reg->off;
7113                 dst_reg->raw = ptr_reg->raw;
7114                 if (reg_is_pkt_pointer(ptr_reg)) {
7115                         dst_reg->id = ++env->id_gen;
7116                         /* something was added to pkt_ptr, set range to zero */
7117                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7118                 }
7119                 break;
7120         case BPF_SUB:
7121                 if (dst_reg == off_reg) {
7122                         /* scalar -= pointer.  Creates an unknown scalar */
7123                         verbose(env, "R%d tried to subtract pointer from scalar\n",
7124                                 dst);
7125                         return -EACCES;
7126                 }
7127                 /* We don't allow subtraction from FP, because (according to
7128                  * test_verifier.c test "invalid fp arithmetic", JITs might not
7129                  * be able to deal with it.
7130                  */
7131                 if (ptr_reg->type == PTR_TO_STACK) {
7132                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
7133                                 dst);
7134                         return -EACCES;
7135                 }
7136                 if (known && (ptr_reg->off - smin_val ==
7137                               (s64)(s32)(ptr_reg->off - smin_val))) {
7138                         /* pointer -= K.  Subtract it from fixed offset */
7139                         dst_reg->smin_value = smin_ptr;
7140                         dst_reg->smax_value = smax_ptr;
7141                         dst_reg->umin_value = umin_ptr;
7142                         dst_reg->umax_value = umax_ptr;
7143                         dst_reg->var_off = ptr_reg->var_off;
7144                         dst_reg->id = ptr_reg->id;
7145                         dst_reg->off = ptr_reg->off - smin_val;
7146                         dst_reg->raw = ptr_reg->raw;
7147                         break;
7148                 }
7149                 /* A new variable offset is created.  If the subtrahend is known
7150                  * nonnegative, then any reg->range we had before is still good.
7151                  */
7152                 if (signed_sub_overflows(smin_ptr, smax_val) ||
7153                     signed_sub_overflows(smax_ptr, smin_val)) {
7154                         /* Overflow possible, we know nothing */
7155                         dst_reg->smin_value = S64_MIN;
7156                         dst_reg->smax_value = S64_MAX;
7157                 } else {
7158                         dst_reg->smin_value = smin_ptr - smax_val;
7159                         dst_reg->smax_value = smax_ptr - smin_val;
7160                 }
7161                 if (umin_ptr < umax_val) {
7162                         /* Overflow possible, we know nothing */
7163                         dst_reg->umin_value = 0;
7164                         dst_reg->umax_value = U64_MAX;
7165                 } else {
7166                         /* Cannot overflow (as long as bounds are consistent) */
7167                         dst_reg->umin_value = umin_ptr - umax_val;
7168                         dst_reg->umax_value = umax_ptr - umin_val;
7169                 }
7170                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7171                 dst_reg->off = ptr_reg->off;
7172                 dst_reg->raw = ptr_reg->raw;
7173                 if (reg_is_pkt_pointer(ptr_reg)) {
7174                         dst_reg->id = ++env->id_gen;
7175                         /* something was added to pkt_ptr, set range to zero */
7176                         if (smin_val < 0)
7177                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7178                 }
7179                 break;
7180         case BPF_AND:
7181         case BPF_OR:
7182         case BPF_XOR:
7183                 /* bitwise ops on pointers are troublesome, prohibit. */
7184                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7185                         dst, bpf_alu_string[opcode >> 4]);
7186                 return -EACCES;
7187         default:
7188                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
7189                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7190                         dst, bpf_alu_string[opcode >> 4]);
7191                 return -EACCES;
7192         }
7193
7194         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7195                 return -EINVAL;
7196         reg_bounds_sync(dst_reg);
7197         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7198                 return -EACCES;
7199         if (sanitize_needed(opcode)) {
7200                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7201                                        &info, true);
7202                 if (ret < 0)
7203                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
7204         }
7205
7206         return 0;
7207 }
7208
7209 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7210                                  struct bpf_reg_state *src_reg)
7211 {
7212         s32 smin_val = src_reg->s32_min_value;
7213         s32 smax_val = src_reg->s32_max_value;
7214         u32 umin_val = src_reg->u32_min_value;
7215         u32 umax_val = src_reg->u32_max_value;
7216
7217         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7218             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7219                 dst_reg->s32_min_value = S32_MIN;
7220                 dst_reg->s32_max_value = S32_MAX;
7221         } else {
7222                 dst_reg->s32_min_value += smin_val;
7223                 dst_reg->s32_max_value += smax_val;
7224         }
7225         if (dst_reg->u32_min_value + umin_val < umin_val ||
7226             dst_reg->u32_max_value + umax_val < umax_val) {
7227                 dst_reg->u32_min_value = 0;
7228                 dst_reg->u32_max_value = U32_MAX;
7229         } else {
7230                 dst_reg->u32_min_value += umin_val;
7231                 dst_reg->u32_max_value += umax_val;
7232         }
7233 }
7234
7235 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7236                                struct bpf_reg_state *src_reg)
7237 {
7238         s64 smin_val = src_reg->smin_value;
7239         s64 smax_val = src_reg->smax_value;
7240         u64 umin_val = src_reg->umin_value;
7241         u64 umax_val = src_reg->umax_value;
7242
7243         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7244             signed_add_overflows(dst_reg->smax_value, smax_val)) {
7245                 dst_reg->smin_value = S64_MIN;
7246                 dst_reg->smax_value = S64_MAX;
7247         } else {
7248                 dst_reg->smin_value += smin_val;
7249                 dst_reg->smax_value += smax_val;
7250         }
7251         if (dst_reg->umin_value + umin_val < umin_val ||
7252             dst_reg->umax_value + umax_val < umax_val) {
7253                 dst_reg->umin_value = 0;
7254                 dst_reg->umax_value = U64_MAX;
7255         } else {
7256                 dst_reg->umin_value += umin_val;
7257                 dst_reg->umax_value += umax_val;
7258         }
7259 }
7260
7261 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7262                                  struct bpf_reg_state *src_reg)
7263 {
7264         s32 smin_val = src_reg->s32_min_value;
7265         s32 smax_val = src_reg->s32_max_value;
7266         u32 umin_val = src_reg->u32_min_value;
7267         u32 umax_val = src_reg->u32_max_value;
7268
7269         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7270             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7271                 /* Overflow possible, we know nothing */
7272                 dst_reg->s32_min_value = S32_MIN;
7273                 dst_reg->s32_max_value = S32_MAX;
7274         } else {
7275                 dst_reg->s32_min_value -= smax_val;
7276                 dst_reg->s32_max_value -= smin_val;
7277         }
7278         if (dst_reg->u32_min_value < umax_val) {
7279                 /* Overflow possible, we know nothing */
7280                 dst_reg->u32_min_value = 0;
7281                 dst_reg->u32_max_value = U32_MAX;
7282         } else {
7283                 /* Cannot overflow (as long as bounds are consistent) */
7284                 dst_reg->u32_min_value -= umax_val;
7285                 dst_reg->u32_max_value -= umin_val;
7286         }
7287 }
7288
7289 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7290                                struct bpf_reg_state *src_reg)
7291 {
7292         s64 smin_val = src_reg->smin_value;
7293         s64 smax_val = src_reg->smax_value;
7294         u64 umin_val = src_reg->umin_value;
7295         u64 umax_val = src_reg->umax_value;
7296
7297         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7298             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7299                 /* Overflow possible, we know nothing */
7300                 dst_reg->smin_value = S64_MIN;
7301                 dst_reg->smax_value = S64_MAX;
7302         } else {
7303                 dst_reg->smin_value -= smax_val;
7304                 dst_reg->smax_value -= smin_val;
7305         }
7306         if (dst_reg->umin_value < umax_val) {
7307                 /* Overflow possible, we know nothing */
7308                 dst_reg->umin_value = 0;
7309                 dst_reg->umax_value = U64_MAX;
7310         } else {
7311                 /* Cannot overflow (as long as bounds are consistent) */
7312                 dst_reg->umin_value -= umax_val;
7313                 dst_reg->umax_value -= umin_val;
7314         }
7315 }
7316
7317 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7318                                  struct bpf_reg_state *src_reg)
7319 {
7320         s32 smin_val = src_reg->s32_min_value;
7321         u32 umin_val = src_reg->u32_min_value;
7322         u32 umax_val = src_reg->u32_max_value;
7323
7324         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7325                 /* Ain't nobody got time to multiply that sign */
7326                 __mark_reg32_unbounded(dst_reg);
7327                 return;
7328         }
7329         /* Both values are positive, so we can work with unsigned and
7330          * copy the result to signed (unless it exceeds S32_MAX).
7331          */
7332         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7333                 /* Potential overflow, we know nothing */
7334                 __mark_reg32_unbounded(dst_reg);
7335                 return;
7336         }
7337         dst_reg->u32_min_value *= umin_val;
7338         dst_reg->u32_max_value *= umax_val;
7339         if (dst_reg->u32_max_value > S32_MAX) {
7340                 /* Overflow possible, we know nothing */
7341                 dst_reg->s32_min_value = S32_MIN;
7342                 dst_reg->s32_max_value = S32_MAX;
7343         } else {
7344                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7345                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7346         }
7347 }
7348
7349 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7350                                struct bpf_reg_state *src_reg)
7351 {
7352         s64 smin_val = src_reg->smin_value;
7353         u64 umin_val = src_reg->umin_value;
7354         u64 umax_val = src_reg->umax_value;
7355
7356         if (smin_val < 0 || dst_reg->smin_value < 0) {
7357                 /* Ain't nobody got time to multiply that sign */
7358                 __mark_reg64_unbounded(dst_reg);
7359                 return;
7360         }
7361         /* Both values are positive, so we can work with unsigned and
7362          * copy the result to signed (unless it exceeds S64_MAX).
7363          */
7364         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7365                 /* Potential overflow, we know nothing */
7366                 __mark_reg64_unbounded(dst_reg);
7367                 return;
7368         }
7369         dst_reg->umin_value *= umin_val;
7370         dst_reg->umax_value *= umax_val;
7371         if (dst_reg->umax_value > S64_MAX) {
7372                 /* Overflow possible, we know nothing */
7373                 dst_reg->smin_value = S64_MIN;
7374                 dst_reg->smax_value = S64_MAX;
7375         } else {
7376                 dst_reg->smin_value = dst_reg->umin_value;
7377                 dst_reg->smax_value = dst_reg->umax_value;
7378         }
7379 }
7380
7381 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7382                                  struct bpf_reg_state *src_reg)
7383 {
7384         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7385         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7386         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7387         s32 smin_val = src_reg->s32_min_value;
7388         u32 umax_val = src_reg->u32_max_value;
7389
7390         if (src_known && dst_known) {
7391                 __mark_reg32_known(dst_reg, var32_off.value);
7392                 return;
7393         }
7394
7395         /* We get our minimum from the var_off, since that's inherently
7396          * bitwise.  Our maximum is the minimum of the operands' maxima.
7397          */
7398         dst_reg->u32_min_value = var32_off.value;
7399         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7400         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7401                 /* Lose signed bounds when ANDing negative numbers,
7402                  * ain't nobody got time for that.
7403                  */
7404                 dst_reg->s32_min_value = S32_MIN;
7405                 dst_reg->s32_max_value = S32_MAX;
7406         } else {
7407                 /* ANDing two positives gives a positive, so safe to
7408                  * cast result into s64.
7409                  */
7410                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7411                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7412         }
7413 }
7414
7415 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7416                                struct bpf_reg_state *src_reg)
7417 {
7418         bool src_known = tnum_is_const(src_reg->var_off);
7419         bool dst_known = tnum_is_const(dst_reg->var_off);
7420         s64 smin_val = src_reg->smin_value;
7421         u64 umax_val = src_reg->umax_value;
7422
7423         if (src_known && dst_known) {
7424                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7425                 return;
7426         }
7427
7428         /* We get our minimum from the var_off, since that's inherently
7429          * bitwise.  Our maximum is the minimum of the operands' maxima.
7430          */
7431         dst_reg->umin_value = dst_reg->var_off.value;
7432         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7433         if (dst_reg->smin_value < 0 || smin_val < 0) {
7434                 /* Lose signed bounds when ANDing negative numbers,
7435                  * ain't nobody got time for that.
7436                  */
7437                 dst_reg->smin_value = S64_MIN;
7438                 dst_reg->smax_value = S64_MAX;
7439         } else {
7440                 /* ANDing two positives gives a positive, so safe to
7441                  * cast result into s64.
7442                  */
7443                 dst_reg->smin_value = dst_reg->umin_value;
7444                 dst_reg->smax_value = dst_reg->umax_value;
7445         }
7446         /* We may learn something more from the var_off */
7447         __update_reg_bounds(dst_reg);
7448 }
7449
7450 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7451                                 struct bpf_reg_state *src_reg)
7452 {
7453         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7454         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7455         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7456         s32 smin_val = src_reg->s32_min_value;
7457         u32 umin_val = src_reg->u32_min_value;
7458
7459         if (src_known && dst_known) {
7460                 __mark_reg32_known(dst_reg, var32_off.value);
7461                 return;
7462         }
7463
7464         /* We get our maximum from the var_off, and our minimum is the
7465          * maximum of the operands' minima
7466          */
7467         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7468         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7469         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7470                 /* Lose signed bounds when ORing negative numbers,
7471                  * ain't nobody got time for that.
7472                  */
7473                 dst_reg->s32_min_value = S32_MIN;
7474                 dst_reg->s32_max_value = S32_MAX;
7475         } else {
7476                 /* ORing two positives gives a positive, so safe to
7477                  * cast result into s64.
7478                  */
7479                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7480                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7481         }
7482 }
7483
7484 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7485                               struct bpf_reg_state *src_reg)
7486 {
7487         bool src_known = tnum_is_const(src_reg->var_off);
7488         bool dst_known = tnum_is_const(dst_reg->var_off);
7489         s64 smin_val = src_reg->smin_value;
7490         u64 umin_val = src_reg->umin_value;
7491
7492         if (src_known && dst_known) {
7493                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7494                 return;
7495         }
7496
7497         /* We get our maximum from the var_off, and our minimum is the
7498          * maximum of the operands' minima
7499          */
7500         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7501         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7502         if (dst_reg->smin_value < 0 || smin_val < 0) {
7503                 /* Lose signed bounds when ORing negative numbers,
7504                  * ain't nobody got time for that.
7505                  */
7506                 dst_reg->smin_value = S64_MIN;
7507                 dst_reg->smax_value = S64_MAX;
7508         } else {
7509                 /* ORing two positives gives a positive, so safe to
7510                  * cast result into s64.
7511                  */
7512                 dst_reg->smin_value = dst_reg->umin_value;
7513                 dst_reg->smax_value = dst_reg->umax_value;
7514         }
7515         /* We may learn something more from the var_off */
7516         __update_reg_bounds(dst_reg);
7517 }
7518
7519 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7520                                  struct bpf_reg_state *src_reg)
7521 {
7522         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7523         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7524         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7525         s32 smin_val = src_reg->s32_min_value;
7526
7527         if (src_known && dst_known) {
7528                 __mark_reg32_known(dst_reg, var32_off.value);
7529                 return;
7530         }
7531
7532         /* We get both minimum and maximum from the var32_off. */
7533         dst_reg->u32_min_value = var32_off.value;
7534         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7535
7536         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7537                 /* XORing two positive sign numbers gives a positive,
7538                  * so safe to cast u32 result into s32.
7539                  */
7540                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7541                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7542         } else {
7543                 dst_reg->s32_min_value = S32_MIN;
7544                 dst_reg->s32_max_value = S32_MAX;
7545         }
7546 }
7547
7548 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7549                                struct bpf_reg_state *src_reg)
7550 {
7551         bool src_known = tnum_is_const(src_reg->var_off);
7552         bool dst_known = tnum_is_const(dst_reg->var_off);
7553         s64 smin_val = src_reg->smin_value;
7554
7555         if (src_known && dst_known) {
7556                 /* dst_reg->var_off.value has been updated earlier */
7557                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7558                 return;
7559         }
7560
7561         /* We get both minimum and maximum from the var_off. */
7562         dst_reg->umin_value = dst_reg->var_off.value;
7563         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7564
7565         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7566                 /* XORing two positive sign numbers gives a positive,
7567                  * so safe to cast u64 result into s64.
7568                  */
7569                 dst_reg->smin_value = dst_reg->umin_value;
7570                 dst_reg->smax_value = dst_reg->umax_value;
7571         } else {
7572                 dst_reg->smin_value = S64_MIN;
7573                 dst_reg->smax_value = S64_MAX;
7574         }
7575
7576         __update_reg_bounds(dst_reg);
7577 }
7578
7579 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7580                                    u64 umin_val, u64 umax_val)
7581 {
7582         /* We lose all sign bit information (except what we can pick
7583          * up from var_off)
7584          */
7585         dst_reg->s32_min_value = S32_MIN;
7586         dst_reg->s32_max_value = S32_MAX;
7587         /* If we might shift our top bit out, then we know nothing */
7588         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7589                 dst_reg->u32_min_value = 0;
7590                 dst_reg->u32_max_value = U32_MAX;
7591         } else {
7592                 dst_reg->u32_min_value <<= umin_val;
7593                 dst_reg->u32_max_value <<= umax_val;
7594         }
7595 }
7596
7597 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7598                                  struct bpf_reg_state *src_reg)
7599 {
7600         u32 umax_val = src_reg->u32_max_value;
7601         u32 umin_val = src_reg->u32_min_value;
7602         /* u32 alu operation will zext upper bits */
7603         struct tnum subreg = tnum_subreg(dst_reg->var_off);
7604
7605         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7606         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7607         /* Not required but being careful mark reg64 bounds as unknown so
7608          * that we are forced to pick them up from tnum and zext later and
7609          * if some path skips this step we are still safe.
7610          */
7611         __mark_reg64_unbounded(dst_reg);
7612         __update_reg32_bounds(dst_reg);
7613 }
7614
7615 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7616                                    u64 umin_val, u64 umax_val)
7617 {
7618         /* Special case <<32 because it is a common compiler pattern to sign
7619          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7620          * positive we know this shift will also be positive so we can track
7621          * bounds correctly. Otherwise we lose all sign bit information except
7622          * what we can pick up from var_off. Perhaps we can generalize this
7623          * later to shifts of any length.
7624          */
7625         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7626                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7627         else
7628                 dst_reg->smax_value = S64_MAX;
7629
7630         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7631                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7632         else
7633                 dst_reg->smin_value = S64_MIN;
7634
7635         /* If we might shift our top bit out, then we know nothing */
7636         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7637                 dst_reg->umin_value = 0;
7638                 dst_reg->umax_value = U64_MAX;
7639         } else {
7640                 dst_reg->umin_value <<= umin_val;
7641                 dst_reg->umax_value <<= umax_val;
7642         }
7643 }
7644
7645 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7646                                struct bpf_reg_state *src_reg)
7647 {
7648         u64 umax_val = src_reg->umax_value;
7649         u64 umin_val = src_reg->umin_value;
7650
7651         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7652         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7653         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7654
7655         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7656         /* We may learn something more from the var_off */
7657         __update_reg_bounds(dst_reg);
7658 }
7659
7660 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7661                                  struct bpf_reg_state *src_reg)
7662 {
7663         struct tnum subreg = tnum_subreg(dst_reg->var_off);
7664         u32 umax_val = src_reg->u32_max_value;
7665         u32 umin_val = src_reg->u32_min_value;
7666
7667         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7668          * be negative, then either:
7669          * 1) src_reg might be zero, so the sign bit of the result is
7670          *    unknown, so we lose our signed bounds
7671          * 2) it's known negative, thus the unsigned bounds capture the
7672          *    signed bounds
7673          * 3) the signed bounds cross zero, so they tell us nothing
7674          *    about the result
7675          * If the value in dst_reg is known nonnegative, then again the
7676          * unsigned bounds capture the signed bounds.
7677          * Thus, in all cases it suffices to blow away our signed bounds
7678          * and rely on inferring new ones from the unsigned bounds and
7679          * var_off of the result.
7680          */
7681         dst_reg->s32_min_value = S32_MIN;
7682         dst_reg->s32_max_value = S32_MAX;
7683
7684         dst_reg->var_off = tnum_rshift(subreg, umin_val);
7685         dst_reg->u32_min_value >>= umax_val;
7686         dst_reg->u32_max_value >>= umin_val;
7687
7688         __mark_reg64_unbounded(dst_reg);
7689         __update_reg32_bounds(dst_reg);
7690 }
7691
7692 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7693                                struct bpf_reg_state *src_reg)
7694 {
7695         u64 umax_val = src_reg->umax_value;
7696         u64 umin_val = src_reg->umin_value;
7697
7698         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7699          * be negative, then either:
7700          * 1) src_reg might be zero, so the sign bit of the result is
7701          *    unknown, so we lose our signed bounds
7702          * 2) it's known negative, thus the unsigned bounds capture the
7703          *    signed bounds
7704          * 3) the signed bounds cross zero, so they tell us nothing
7705          *    about the result
7706          * If the value in dst_reg is known nonnegative, then again the
7707          * unsigned bounds capture the signed bounds.
7708          * Thus, in all cases it suffices to blow away our signed bounds
7709          * and rely on inferring new ones from the unsigned bounds and
7710          * var_off of the result.
7711          */
7712         dst_reg->smin_value = S64_MIN;
7713         dst_reg->smax_value = S64_MAX;
7714         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7715         dst_reg->umin_value >>= umax_val;
7716         dst_reg->umax_value >>= umin_val;
7717
7718         /* Its not easy to operate on alu32 bounds here because it depends
7719          * on bits being shifted in. Take easy way out and mark unbounded
7720          * so we can recalculate later from tnum.
7721          */
7722         __mark_reg32_unbounded(dst_reg);
7723         __update_reg_bounds(dst_reg);
7724 }
7725
7726 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7727                                   struct bpf_reg_state *src_reg)
7728 {
7729         u64 umin_val = src_reg->u32_min_value;
7730
7731         /* Upon reaching here, src_known is true and
7732          * umax_val is equal to umin_val.
7733          */
7734         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7735         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7736
7737         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7738
7739         /* blow away the dst_reg umin_value/umax_value and rely on
7740          * dst_reg var_off to refine the result.
7741          */
7742         dst_reg->u32_min_value = 0;
7743         dst_reg->u32_max_value = U32_MAX;
7744
7745         __mark_reg64_unbounded(dst_reg);
7746         __update_reg32_bounds(dst_reg);
7747 }
7748
7749 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7750                                 struct bpf_reg_state *src_reg)
7751 {
7752         u64 umin_val = src_reg->umin_value;
7753
7754         /* Upon reaching here, src_known is true and umax_val is equal
7755          * to umin_val.
7756          */
7757         dst_reg->smin_value >>= umin_val;
7758         dst_reg->smax_value >>= umin_val;
7759
7760         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7761
7762         /* blow away the dst_reg umin_value/umax_value and rely on
7763          * dst_reg var_off to refine the result.
7764          */
7765         dst_reg->umin_value = 0;
7766         dst_reg->umax_value = U64_MAX;
7767
7768         /* Its not easy to operate on alu32 bounds here because it depends
7769          * on bits being shifted in from upper 32-bits. Take easy way out
7770          * and mark unbounded so we can recalculate later from tnum.
7771          */
7772         __mark_reg32_unbounded(dst_reg);
7773         __update_reg_bounds(dst_reg);
7774 }
7775
7776 /* WARNING: This function does calculations on 64-bit values, but the actual
7777  * execution may occur on 32-bit values. Therefore, things like bitshifts
7778  * need extra checks in the 32-bit case.
7779  */
7780 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7781                                       struct bpf_insn *insn,
7782                                       struct bpf_reg_state *dst_reg,
7783                                       struct bpf_reg_state src_reg)
7784 {
7785         struct bpf_reg_state *regs = cur_regs(env);
7786         u8 opcode = BPF_OP(insn->code);
7787         bool src_known;
7788         s64 smin_val, smax_val;
7789         u64 umin_val, umax_val;
7790         s32 s32_min_val, s32_max_val;
7791         u32 u32_min_val, u32_max_val;
7792         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7793         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7794         int ret;
7795
7796         smin_val = src_reg.smin_value;
7797         smax_val = src_reg.smax_value;
7798         umin_val = src_reg.umin_value;
7799         umax_val = src_reg.umax_value;
7800
7801         s32_min_val = src_reg.s32_min_value;
7802         s32_max_val = src_reg.s32_max_value;
7803         u32_min_val = src_reg.u32_min_value;
7804         u32_max_val = src_reg.u32_max_value;
7805
7806         if (alu32) {
7807                 src_known = tnum_subreg_is_const(src_reg.var_off);
7808                 if ((src_known &&
7809                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7810                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7811                         /* Taint dst register if offset had invalid bounds
7812                          * derived from e.g. dead branches.
7813                          */
7814                         __mark_reg_unknown(env, dst_reg);
7815                         return 0;
7816                 }
7817         } else {
7818                 src_known = tnum_is_const(src_reg.var_off);
7819                 if ((src_known &&
7820                      (smin_val != smax_val || umin_val != umax_val)) ||
7821                     smin_val > smax_val || umin_val > umax_val) {
7822                         /* Taint dst register if offset had invalid bounds
7823                          * derived from e.g. dead branches.
7824                          */
7825                         __mark_reg_unknown(env, dst_reg);
7826                         return 0;
7827                 }
7828         }
7829
7830         if (!src_known &&
7831             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7832                 __mark_reg_unknown(env, dst_reg);
7833                 return 0;
7834         }
7835
7836         if (sanitize_needed(opcode)) {
7837                 ret = sanitize_val_alu(env, insn);
7838                 if (ret < 0)
7839                         return sanitize_err(env, insn, ret, NULL, NULL);
7840         }
7841
7842         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7843          * There are two classes of instructions: The first class we track both
7844          * alu32 and alu64 sign/unsigned bounds independently this provides the
7845          * greatest amount of precision when alu operations are mixed with jmp32
7846          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7847          * and BPF_OR. This is possible because these ops have fairly easy to
7848          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7849          * See alu32 verifier tests for examples. The second class of
7850          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7851          * with regards to tracking sign/unsigned bounds because the bits may
7852          * cross subreg boundaries in the alu64 case. When this happens we mark
7853          * the reg unbounded in the subreg bound space and use the resulting
7854          * tnum to calculate an approximation of the sign/unsigned bounds.
7855          */
7856         switch (opcode) {
7857         case BPF_ADD:
7858                 scalar32_min_max_add(dst_reg, &src_reg);
7859                 scalar_min_max_add(dst_reg, &src_reg);
7860                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7861                 break;
7862         case BPF_SUB:
7863                 scalar32_min_max_sub(dst_reg, &src_reg);
7864                 scalar_min_max_sub(dst_reg, &src_reg);
7865                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7866                 break;
7867         case BPF_MUL:
7868                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7869                 scalar32_min_max_mul(dst_reg, &src_reg);
7870                 scalar_min_max_mul(dst_reg, &src_reg);
7871                 break;
7872         case BPF_AND:
7873                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7874                 scalar32_min_max_and(dst_reg, &src_reg);
7875                 scalar_min_max_and(dst_reg, &src_reg);
7876                 break;
7877         case BPF_OR:
7878                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7879                 scalar32_min_max_or(dst_reg, &src_reg);
7880                 scalar_min_max_or(dst_reg, &src_reg);
7881                 break;
7882         case BPF_XOR:
7883                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7884                 scalar32_min_max_xor(dst_reg, &src_reg);
7885                 scalar_min_max_xor(dst_reg, &src_reg);
7886                 break;
7887         case BPF_LSH:
7888                 if (umax_val >= insn_bitness) {
7889                         /* Shifts greater than 31 or 63 are undefined.
7890                          * This includes shifts by a negative number.
7891                          */
7892                         mark_reg_unknown(env, regs, insn->dst_reg);
7893                         break;
7894                 }
7895                 if (alu32)
7896                         scalar32_min_max_lsh(dst_reg, &src_reg);
7897                 else
7898                         scalar_min_max_lsh(dst_reg, &src_reg);
7899                 break;
7900         case BPF_RSH:
7901                 if (umax_val >= insn_bitness) {
7902                         /* Shifts greater than 31 or 63 are undefined.
7903                          * This includes shifts by a negative number.
7904                          */
7905                         mark_reg_unknown(env, regs, insn->dst_reg);
7906                         break;
7907                 }
7908                 if (alu32)
7909                         scalar32_min_max_rsh(dst_reg, &src_reg);
7910                 else
7911                         scalar_min_max_rsh(dst_reg, &src_reg);
7912                 break;
7913         case BPF_ARSH:
7914                 if (umax_val >= insn_bitness) {
7915                         /* Shifts greater than 31 or 63 are undefined.
7916                          * This includes shifts by a negative number.
7917                          */
7918                         mark_reg_unknown(env, regs, insn->dst_reg);
7919                         break;
7920                 }
7921                 if (alu32)
7922                         scalar32_min_max_arsh(dst_reg, &src_reg);
7923                 else
7924                         scalar_min_max_arsh(dst_reg, &src_reg);
7925                 break;
7926         default:
7927                 mark_reg_unknown(env, regs, insn->dst_reg);
7928                 break;
7929         }
7930
7931         /* ALU32 ops are zero extended into 64bit register */
7932         if (alu32)
7933                 zext_32_to_64(dst_reg);
7934         reg_bounds_sync(dst_reg);
7935         return 0;
7936 }
7937
7938 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7939  * and var_off.
7940  */
7941 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7942                                    struct bpf_insn *insn)
7943 {
7944         struct bpf_verifier_state *vstate = env->cur_state;
7945         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7946         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7947         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7948         u8 opcode = BPF_OP(insn->code);
7949         int err;
7950
7951         dst_reg = &regs[insn->dst_reg];
7952         src_reg = NULL;
7953         if (dst_reg->type != SCALAR_VALUE)
7954                 ptr_reg = dst_reg;
7955         else
7956                 /* Make sure ID is cleared otherwise dst_reg min/max could be
7957                  * incorrectly propagated into other registers by find_equal_scalars()
7958                  */
7959                 dst_reg->id = 0;
7960         if (BPF_SRC(insn->code) == BPF_X) {
7961                 src_reg = &regs[insn->src_reg];
7962                 if (src_reg->type != SCALAR_VALUE) {
7963                         if (dst_reg->type != SCALAR_VALUE) {
7964                                 /* Combining two pointers by any ALU op yields
7965                                  * an arbitrary scalar. Disallow all math except
7966                                  * pointer subtraction
7967                                  */
7968                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7969                                         mark_reg_unknown(env, regs, insn->dst_reg);
7970                                         return 0;
7971                                 }
7972                                 verbose(env, "R%d pointer %s pointer prohibited\n",
7973                                         insn->dst_reg,
7974                                         bpf_alu_string[opcode >> 4]);
7975                                 return -EACCES;
7976                         } else {
7977                                 /* scalar += pointer
7978                                  * This is legal, but we have to reverse our
7979                                  * src/dest handling in computing the range
7980                                  */
7981                                 err = mark_chain_precision(env, insn->dst_reg);
7982                                 if (err)
7983                                         return err;
7984                                 return adjust_ptr_min_max_vals(env, insn,
7985                                                                src_reg, dst_reg);
7986                         }
7987                 } else if (ptr_reg) {
7988                         /* pointer += scalar */
7989                         err = mark_chain_precision(env, insn->src_reg);
7990                         if (err)
7991                                 return err;
7992                         return adjust_ptr_min_max_vals(env, insn,
7993                                                        dst_reg, src_reg);
7994                 }
7995         } else {
7996                 /* Pretend the src is a reg with a known value, since we only
7997                  * need to be able to read from this state.
7998                  */
7999                 off_reg.type = SCALAR_VALUE;
8000                 __mark_reg_known(&off_reg, insn->imm);
8001                 src_reg = &off_reg;
8002                 if (ptr_reg) /* pointer += K */
8003                         return adjust_ptr_min_max_vals(env, insn,
8004                                                        ptr_reg, src_reg);
8005         }
8006
8007         /* Got here implies adding two SCALAR_VALUEs */
8008         if (WARN_ON_ONCE(ptr_reg)) {
8009                 print_verifier_state(env, state);
8010                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
8011                 return -EINVAL;
8012         }
8013         if (WARN_ON(!src_reg)) {
8014                 print_verifier_state(env, state);
8015                 verbose(env, "verifier internal error: no src_reg\n");
8016                 return -EINVAL;
8017         }
8018         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8019 }
8020
8021 /* check validity of 32-bit and 64-bit arithmetic operations */
8022 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8023 {
8024         struct bpf_reg_state *regs = cur_regs(env);
8025         u8 opcode = BPF_OP(insn->code);
8026         int err;
8027
8028         if (opcode == BPF_END || opcode == BPF_NEG) {
8029                 if (opcode == BPF_NEG) {
8030                         if (BPF_SRC(insn->code) != 0 ||
8031                             insn->src_reg != BPF_REG_0 ||
8032                             insn->off != 0 || insn->imm != 0) {
8033                                 verbose(env, "BPF_NEG uses reserved fields\n");
8034                                 return -EINVAL;
8035                         }
8036                 } else {
8037                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8038                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8039                             BPF_CLASS(insn->code) == BPF_ALU64) {
8040                                 verbose(env, "BPF_END uses reserved fields\n");
8041                                 return -EINVAL;
8042                         }
8043                 }
8044
8045                 /* check src operand */
8046                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8047                 if (err)
8048                         return err;
8049
8050                 if (is_pointer_value(env, insn->dst_reg)) {
8051                         verbose(env, "R%d pointer arithmetic prohibited\n",
8052                                 insn->dst_reg);
8053                         return -EACCES;
8054                 }
8055
8056                 /* check dest operand */
8057                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
8058                 if (err)
8059                         return err;
8060
8061         } else if (opcode == BPF_MOV) {
8062
8063                 if (BPF_SRC(insn->code) == BPF_X) {
8064                         if (insn->imm != 0 || insn->off != 0) {
8065                                 verbose(env, "BPF_MOV uses reserved fields\n");
8066                                 return -EINVAL;
8067                         }
8068
8069                         /* check src operand */
8070                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
8071                         if (err)
8072                                 return err;
8073                 } else {
8074                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8075                                 verbose(env, "BPF_MOV uses reserved fields\n");
8076                                 return -EINVAL;
8077                         }
8078                 }
8079
8080                 /* check dest operand, mark as required later */
8081                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8082                 if (err)
8083                         return err;
8084
8085                 if (BPF_SRC(insn->code) == BPF_X) {
8086                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
8087                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8088
8089                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
8090                                 /* case: R1 = R2
8091                                  * copy register state to dest reg
8092                                  */
8093                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8094                                         /* Assign src and dst registers the same ID
8095                                          * that will be used by find_equal_scalars()
8096                                          * to propagate min/max range.
8097                                          */
8098                                         src_reg->id = ++env->id_gen;
8099                                 *dst_reg = *src_reg;
8100                                 dst_reg->live |= REG_LIVE_WRITTEN;
8101                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
8102                         } else {
8103                                 /* R1 = (u32) R2 */
8104                                 if (is_pointer_value(env, insn->src_reg)) {
8105                                         verbose(env,
8106                                                 "R%d partial copy of pointer\n",
8107                                                 insn->src_reg);
8108                                         return -EACCES;
8109                                 } else if (src_reg->type == SCALAR_VALUE) {
8110                                         *dst_reg = *src_reg;
8111                                         /* Make sure ID is cleared otherwise
8112                                          * dst_reg min/max could be incorrectly
8113                                          * propagated into src_reg by find_equal_scalars()
8114                                          */
8115                                         dst_reg->id = 0;
8116                                         dst_reg->live |= REG_LIVE_WRITTEN;
8117                                         dst_reg->subreg_def = env->insn_idx + 1;
8118                                 } else {
8119                                         mark_reg_unknown(env, regs,
8120                                                          insn->dst_reg);
8121                                 }
8122                                 zext_32_to_64(dst_reg);
8123                                 reg_bounds_sync(dst_reg);
8124                         }
8125                 } else {
8126                         /* case: R = imm
8127                          * remember the value we stored into this reg
8128                          */
8129                         /* clear any state __mark_reg_known doesn't set */
8130                         mark_reg_unknown(env, regs, insn->dst_reg);
8131                         regs[insn->dst_reg].type = SCALAR_VALUE;
8132                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
8133                                 __mark_reg_known(regs + insn->dst_reg,
8134                                                  insn->imm);
8135                         } else {
8136                                 __mark_reg_known(regs + insn->dst_reg,
8137                                                  (u32)insn->imm);
8138                         }
8139                 }
8140
8141         } else if (opcode > BPF_END) {
8142                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8143                 return -EINVAL;
8144
8145         } else {        /* all other ALU ops: and, sub, xor, add, ... */
8146
8147                 if (BPF_SRC(insn->code) == BPF_X) {
8148                         if (insn->imm != 0 || insn->off != 0) {
8149                                 verbose(env, "BPF_ALU uses reserved fields\n");
8150                                 return -EINVAL;
8151                         }
8152                         /* check src1 operand */
8153                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
8154                         if (err)
8155                                 return err;
8156                 } else {
8157                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8158                                 verbose(env, "BPF_ALU uses reserved fields\n");
8159                                 return -EINVAL;
8160                         }
8161                 }
8162
8163                 /* check src2 operand */
8164                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8165                 if (err)
8166                         return err;
8167
8168                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8169                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8170                         verbose(env, "div by zero\n");
8171                         return -EINVAL;
8172                 }
8173
8174                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8175                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8176                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8177
8178                         if (insn->imm < 0 || insn->imm >= size) {
8179                                 verbose(env, "invalid shift %d\n", insn->imm);
8180                                 return -EINVAL;
8181                         }
8182                 }
8183
8184                 /* check dest operand */
8185                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8186                 if (err)
8187                         return err;
8188
8189                 return adjust_reg_min_max_vals(env, insn);
8190         }
8191
8192         return 0;
8193 }
8194
8195 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8196                                    struct bpf_reg_state *dst_reg,
8197                                    enum bpf_reg_type type,
8198                                    bool range_right_open)
8199 {
8200         struct bpf_func_state *state;
8201         struct bpf_reg_state *reg;
8202         int new_range;
8203
8204         if (dst_reg->off < 0 ||
8205             (dst_reg->off == 0 && range_right_open))
8206                 /* This doesn't give us any range */
8207                 return;
8208
8209         if (dst_reg->umax_value > MAX_PACKET_OFF ||
8210             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8211                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
8212                  * than pkt_end, but that's because it's also less than pkt.
8213                  */
8214                 return;
8215
8216         new_range = dst_reg->off;
8217         if (range_right_open)
8218                 new_range++;
8219
8220         /* Examples for register markings:
8221          *
8222          * pkt_data in dst register:
8223          *
8224          *   r2 = r3;
8225          *   r2 += 8;
8226          *   if (r2 > pkt_end) goto <handle exception>
8227          *   <access okay>
8228          *
8229          *   r2 = r3;
8230          *   r2 += 8;
8231          *   if (r2 < pkt_end) goto <access okay>
8232          *   <handle exception>
8233          *
8234          *   Where:
8235          *     r2 == dst_reg, pkt_end == src_reg
8236          *     r2=pkt(id=n,off=8,r=0)
8237          *     r3=pkt(id=n,off=0,r=0)
8238          *
8239          * pkt_data in src register:
8240          *
8241          *   r2 = r3;
8242          *   r2 += 8;
8243          *   if (pkt_end >= r2) goto <access okay>
8244          *   <handle exception>
8245          *
8246          *   r2 = r3;
8247          *   r2 += 8;
8248          *   if (pkt_end <= r2) goto <handle exception>
8249          *   <access okay>
8250          *
8251          *   Where:
8252          *     pkt_end == dst_reg, r2 == src_reg
8253          *     r2=pkt(id=n,off=8,r=0)
8254          *     r3=pkt(id=n,off=0,r=0)
8255          *
8256          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8257          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8258          * and [r3, r3 + 8-1) respectively is safe to access depending on
8259          * the check.
8260          */
8261
8262         /* If our ids match, then we must have the same max_value.  And we
8263          * don't care about the other reg's fixed offset, since if it's too big
8264          * the range won't allow anything.
8265          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8266          */
8267         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8268                 if (reg->type == type && reg->id == dst_reg->id)
8269                         /* keep the maximum range already checked */
8270                         reg->range = max(reg->range, new_range);
8271         }));
8272 }
8273
8274 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8275 {
8276         struct tnum subreg = tnum_subreg(reg->var_off);
8277         s32 sval = (s32)val;
8278
8279         switch (opcode) {
8280         case BPF_JEQ:
8281                 if (tnum_is_const(subreg))
8282                         return !!tnum_equals_const(subreg, val);
8283                 break;
8284         case BPF_JNE:
8285                 if (tnum_is_const(subreg))
8286                         return !tnum_equals_const(subreg, val);
8287                 break;
8288         case BPF_JSET:
8289                 if ((~subreg.mask & subreg.value) & val)
8290                         return 1;
8291                 if (!((subreg.mask | subreg.value) & val))
8292                         return 0;
8293                 break;
8294         case BPF_JGT:
8295                 if (reg->u32_min_value > val)
8296                         return 1;
8297                 else if (reg->u32_max_value <= val)
8298                         return 0;
8299                 break;
8300         case BPF_JSGT:
8301                 if (reg->s32_min_value > sval)
8302                         return 1;
8303                 else if (reg->s32_max_value <= sval)
8304                         return 0;
8305                 break;
8306         case BPF_JLT:
8307                 if (reg->u32_max_value < val)
8308                         return 1;
8309                 else if (reg->u32_min_value >= val)
8310                         return 0;
8311                 break;
8312         case BPF_JSLT:
8313                 if (reg->s32_max_value < sval)
8314                         return 1;
8315                 else if (reg->s32_min_value >= sval)
8316                         return 0;
8317                 break;
8318         case BPF_JGE:
8319                 if (reg->u32_min_value >= val)
8320                         return 1;
8321                 else if (reg->u32_max_value < val)
8322                         return 0;
8323                 break;
8324         case BPF_JSGE:
8325                 if (reg->s32_min_value >= sval)
8326                         return 1;
8327                 else if (reg->s32_max_value < sval)
8328                         return 0;
8329                 break;
8330         case BPF_JLE:
8331                 if (reg->u32_max_value <= val)
8332                         return 1;
8333                 else if (reg->u32_min_value > val)
8334                         return 0;
8335                 break;
8336         case BPF_JSLE:
8337                 if (reg->s32_max_value <= sval)
8338                         return 1;
8339                 else if (reg->s32_min_value > sval)
8340                         return 0;
8341                 break;
8342         }
8343
8344         return -1;
8345 }
8346
8347
8348 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8349 {
8350         s64 sval = (s64)val;
8351
8352         switch (opcode) {
8353         case BPF_JEQ:
8354                 if (tnum_is_const(reg->var_off))
8355                         return !!tnum_equals_const(reg->var_off, val);
8356                 break;
8357         case BPF_JNE:
8358                 if (tnum_is_const(reg->var_off))
8359                         return !tnum_equals_const(reg->var_off, val);
8360                 break;
8361         case BPF_JSET:
8362                 if ((~reg->var_off.mask & reg->var_off.value) & val)
8363                         return 1;
8364                 if (!((reg->var_off.mask | reg->var_off.value) & val))
8365                         return 0;
8366                 break;
8367         case BPF_JGT:
8368                 if (reg->umin_value > val)
8369                         return 1;
8370                 else if (reg->umax_value <= val)
8371                         return 0;
8372                 break;
8373         case BPF_JSGT:
8374                 if (reg->smin_value > sval)
8375                         return 1;
8376                 else if (reg->smax_value <= sval)
8377                         return 0;
8378                 break;
8379         case BPF_JLT:
8380                 if (reg->umax_value < val)
8381                         return 1;
8382                 else if (reg->umin_value >= val)
8383                         return 0;
8384                 break;
8385         case BPF_JSLT:
8386                 if (reg->smax_value < sval)
8387                         return 1;
8388                 else if (reg->smin_value >= sval)
8389                         return 0;
8390                 break;
8391         case BPF_JGE:
8392                 if (reg->umin_value >= val)
8393                         return 1;
8394                 else if (reg->umax_value < val)
8395                         return 0;
8396                 break;
8397         case BPF_JSGE:
8398                 if (reg->smin_value >= sval)
8399                         return 1;
8400                 else if (reg->smax_value < sval)
8401                         return 0;
8402                 break;
8403         case BPF_JLE:
8404                 if (reg->umax_value <= val)
8405                         return 1;
8406                 else if (reg->umin_value > val)
8407                         return 0;
8408                 break;
8409         case BPF_JSLE:
8410                 if (reg->smax_value <= sval)
8411                         return 1;
8412                 else if (reg->smin_value > sval)
8413                         return 0;
8414                 break;
8415         }
8416
8417         return -1;
8418 }
8419
8420 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8421  * and return:
8422  *  1 - branch will be taken and "goto target" will be executed
8423  *  0 - branch will not be taken and fall-through to next insn
8424  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8425  *      range [0,10]
8426  */
8427 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8428                            bool is_jmp32)
8429 {
8430         if (__is_pointer_value(false, reg)) {
8431                 if (!reg_type_not_null(reg->type))
8432                         return -1;
8433
8434                 /* If pointer is valid tests against zero will fail so we can
8435                  * use this to direct branch taken.
8436                  */
8437                 if (val != 0)
8438                         return -1;
8439
8440                 switch (opcode) {
8441                 case BPF_JEQ:
8442                         return 0;
8443                 case BPF_JNE:
8444                         return 1;
8445                 default:
8446                         return -1;
8447                 }
8448         }
8449
8450         if (is_jmp32)
8451                 return is_branch32_taken(reg, val, opcode);
8452         return is_branch64_taken(reg, val, opcode);
8453 }
8454
8455 static int flip_opcode(u32 opcode)
8456 {
8457         /* How can we transform "a <op> b" into "b <op> a"? */
8458         static const u8 opcode_flip[16] = {
8459                 /* these stay the same */
8460                 [BPF_JEQ  >> 4] = BPF_JEQ,
8461                 [BPF_JNE  >> 4] = BPF_JNE,
8462                 [BPF_JSET >> 4] = BPF_JSET,
8463                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8464                 [BPF_JGE  >> 4] = BPF_JLE,
8465                 [BPF_JGT  >> 4] = BPF_JLT,
8466                 [BPF_JLE  >> 4] = BPF_JGE,
8467                 [BPF_JLT  >> 4] = BPF_JGT,
8468                 [BPF_JSGE >> 4] = BPF_JSLE,
8469                 [BPF_JSGT >> 4] = BPF_JSLT,
8470                 [BPF_JSLE >> 4] = BPF_JSGE,
8471                 [BPF_JSLT >> 4] = BPF_JSGT
8472         };
8473         return opcode_flip[opcode >> 4];
8474 }
8475
8476 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8477                                    struct bpf_reg_state *src_reg,
8478                                    u8 opcode)
8479 {
8480         struct bpf_reg_state *pkt;
8481
8482         if (src_reg->type == PTR_TO_PACKET_END) {
8483                 pkt = dst_reg;
8484         } else if (dst_reg->type == PTR_TO_PACKET_END) {
8485                 pkt = src_reg;
8486                 opcode = flip_opcode(opcode);
8487         } else {
8488                 return -1;
8489         }
8490
8491         if (pkt->range >= 0)
8492                 return -1;
8493
8494         switch (opcode) {
8495         case BPF_JLE:
8496                 /* pkt <= pkt_end */
8497                 fallthrough;
8498         case BPF_JGT:
8499                 /* pkt > pkt_end */
8500                 if (pkt->range == BEYOND_PKT_END)
8501                         /* pkt has at last one extra byte beyond pkt_end */
8502                         return opcode == BPF_JGT;
8503                 break;
8504         case BPF_JLT:
8505                 /* pkt < pkt_end */
8506                 fallthrough;
8507         case BPF_JGE:
8508                 /* pkt >= pkt_end */
8509                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8510                         return opcode == BPF_JGE;
8511                 break;
8512         }
8513         return -1;
8514 }
8515
8516 /* Adjusts the register min/max values in the case that the dst_reg is the
8517  * variable register that we are working on, and src_reg is a constant or we're
8518  * simply doing a BPF_K check.
8519  * In JEQ/JNE cases we also adjust the var_off values.
8520  */
8521 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8522                             struct bpf_reg_state *false_reg,
8523                             u64 val, u32 val32,
8524                             u8 opcode, bool is_jmp32)
8525 {
8526         struct tnum false_32off = tnum_subreg(false_reg->var_off);
8527         struct tnum false_64off = false_reg->var_off;
8528         struct tnum true_32off = tnum_subreg(true_reg->var_off);
8529         struct tnum true_64off = true_reg->var_off;
8530         s64 sval = (s64)val;
8531         s32 sval32 = (s32)val32;
8532
8533         /* If the dst_reg is a pointer, we can't learn anything about its
8534          * variable offset from the compare (unless src_reg were a pointer into
8535          * the same object, but we don't bother with that.
8536          * Since false_reg and true_reg have the same type by construction, we
8537          * only need to check one of them for pointerness.
8538          */
8539         if (__is_pointer_value(false, false_reg))
8540                 return;
8541
8542         switch (opcode) {
8543         /* JEQ/JNE comparison doesn't change the register equivalence.
8544          *
8545          * r1 = r2;
8546          * if (r1 == 42) goto label;
8547          * ...
8548          * label: // here both r1 and r2 are known to be 42.
8549          *
8550          * Hence when marking register as known preserve it's ID.
8551          */
8552         case BPF_JEQ:
8553                 if (is_jmp32) {
8554                         __mark_reg32_known(true_reg, val32);
8555                         true_32off = tnum_subreg(true_reg->var_off);
8556                 } else {
8557                         ___mark_reg_known(true_reg, val);
8558                         true_64off = true_reg->var_off;
8559                 }
8560                 break;
8561         case BPF_JNE:
8562                 if (is_jmp32) {
8563                         __mark_reg32_known(false_reg, val32);
8564                         false_32off = tnum_subreg(false_reg->var_off);
8565                 } else {
8566                         ___mark_reg_known(false_reg, val);
8567                         false_64off = false_reg->var_off;
8568                 }
8569                 break;
8570         case BPF_JSET:
8571                 if (is_jmp32) {
8572                         false_32off = tnum_and(false_32off, tnum_const(~val32));
8573                         if (is_power_of_2(val32))
8574                                 true_32off = tnum_or(true_32off,
8575                                                      tnum_const(val32));
8576                 } else {
8577                         false_64off = tnum_and(false_64off, tnum_const(~val));
8578                         if (is_power_of_2(val))
8579                                 true_64off = tnum_or(true_64off,
8580                                                      tnum_const(val));
8581                 }
8582                 break;
8583         case BPF_JGE:
8584         case BPF_JGT:
8585         {
8586                 if (is_jmp32) {
8587                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8588                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8589
8590                         false_reg->u32_max_value = min(false_reg->u32_max_value,
8591                                                        false_umax);
8592                         true_reg->u32_min_value = max(true_reg->u32_min_value,
8593                                                       true_umin);
8594                 } else {
8595                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8596                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8597
8598                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
8599                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
8600                 }
8601                 break;
8602         }
8603         case BPF_JSGE:
8604         case BPF_JSGT:
8605         {
8606                 if (is_jmp32) {
8607                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8608                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8609
8610                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8611                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8612                 } else {
8613                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8614                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8615
8616                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
8617                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
8618                 }
8619                 break;
8620         }
8621         case BPF_JLE:
8622         case BPF_JLT:
8623         {
8624                 if (is_jmp32) {
8625                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8626                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8627
8628                         false_reg->u32_min_value = max(false_reg->u32_min_value,
8629                                                        false_umin);
8630                         true_reg->u32_max_value = min(true_reg->u32_max_value,
8631                                                       true_umax);
8632                 } else {
8633                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8634                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8635
8636                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
8637                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
8638                 }
8639                 break;
8640         }
8641         case BPF_JSLE:
8642         case BPF_JSLT:
8643         {
8644                 if (is_jmp32) {
8645                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8646                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8647
8648                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8649                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8650                 } else {
8651                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8652                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8653
8654                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
8655                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
8656                 }
8657                 break;
8658         }
8659         default:
8660                 return;
8661         }
8662
8663         if (is_jmp32) {
8664                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8665                                              tnum_subreg(false_32off));
8666                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8667                                             tnum_subreg(true_32off));
8668                 __reg_combine_32_into_64(false_reg);
8669                 __reg_combine_32_into_64(true_reg);
8670         } else {
8671                 false_reg->var_off = false_64off;
8672                 true_reg->var_off = true_64off;
8673                 __reg_combine_64_into_32(false_reg);
8674                 __reg_combine_64_into_32(true_reg);
8675         }
8676 }
8677
8678 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8679  * the variable reg.
8680  */
8681 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8682                                 struct bpf_reg_state *false_reg,
8683                                 u64 val, u32 val32,
8684                                 u8 opcode, bool is_jmp32)
8685 {
8686         opcode = flip_opcode(opcode);
8687         /* This uses zero as "not present in table"; luckily the zero opcode,
8688          * BPF_JA, can't get here.
8689          */
8690         if (opcode)
8691                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8692 }
8693
8694 /* Regs are known to be equal, so intersect their min/max/var_off */
8695 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8696                                   struct bpf_reg_state *dst_reg)
8697 {
8698         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8699                                                         dst_reg->umin_value);
8700         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8701                                                         dst_reg->umax_value);
8702         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8703                                                         dst_reg->smin_value);
8704         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8705                                                         dst_reg->smax_value);
8706         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8707                                                              dst_reg->var_off);
8708         reg_bounds_sync(src_reg);
8709         reg_bounds_sync(dst_reg);
8710 }
8711
8712 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8713                                 struct bpf_reg_state *true_dst,
8714                                 struct bpf_reg_state *false_src,
8715                                 struct bpf_reg_state *false_dst,
8716                                 u8 opcode)
8717 {
8718         switch (opcode) {
8719         case BPF_JEQ:
8720                 __reg_combine_min_max(true_src, true_dst);
8721                 break;
8722         case BPF_JNE:
8723                 __reg_combine_min_max(false_src, false_dst);
8724                 break;
8725         }
8726 }
8727
8728 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8729                                  struct bpf_reg_state *reg, u32 id,
8730                                  bool is_null)
8731 {
8732         if (type_may_be_null(reg->type) && reg->id == id &&
8733             !WARN_ON_ONCE(!reg->id)) {
8734                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8735                                  !tnum_equals_const(reg->var_off, 0) ||
8736                                  reg->off)) {
8737                         /* Old offset (both fixed and variable parts) should
8738                          * have been known-zero, because we don't allow pointer
8739                          * arithmetic on pointers that might be NULL. If we
8740                          * see this happening, don't convert the register.
8741                          */
8742                         return;
8743                 }
8744                 if (is_null) {
8745                         reg->type = SCALAR_VALUE;
8746                         /* We don't need id and ref_obj_id from this point
8747                          * onwards anymore, thus we should better reset it,
8748                          * so that state pruning has chances to take effect.
8749                          */
8750                         reg->id = 0;
8751                         reg->ref_obj_id = 0;
8752
8753                         return;
8754                 }
8755
8756                 mark_ptr_not_null_reg(reg);
8757
8758                 if (!reg_may_point_to_spin_lock(reg)) {
8759                         /* For not-NULL ptr, reg->ref_obj_id will be reset
8760                          * in release_reference().
8761                          *
8762                          * reg->id is still used by spin_lock ptr. Other
8763                          * than spin_lock ptr type, reg->id can be reset.
8764                          */
8765                         reg->id = 0;
8766                 }
8767         }
8768 }
8769
8770 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8771  * be folded together at some point.
8772  */
8773 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8774                                   bool is_null)
8775 {
8776         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8777         struct bpf_reg_state *regs = state->regs, *reg;
8778         u32 ref_obj_id = regs[regno].ref_obj_id;
8779         u32 id = regs[regno].id;
8780
8781         if (ref_obj_id && ref_obj_id == id && is_null)
8782                 /* regs[regno] is in the " == NULL" branch.
8783                  * No one could have freed the reference state before
8784                  * doing the NULL check.
8785                  */
8786                 WARN_ON_ONCE(release_reference_state(state, id));
8787
8788         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8789                 mark_ptr_or_null_reg(state, reg, id, is_null);
8790         }));
8791 }
8792
8793 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8794                                    struct bpf_reg_state *dst_reg,
8795                                    struct bpf_reg_state *src_reg,
8796                                    struct bpf_verifier_state *this_branch,
8797                                    struct bpf_verifier_state *other_branch)
8798 {
8799         if (BPF_SRC(insn->code) != BPF_X)
8800                 return false;
8801
8802         /* Pointers are always 64-bit. */
8803         if (BPF_CLASS(insn->code) == BPF_JMP32)
8804                 return false;
8805
8806         switch (BPF_OP(insn->code)) {
8807         case BPF_JGT:
8808                 if ((dst_reg->type == PTR_TO_PACKET &&
8809                      src_reg->type == PTR_TO_PACKET_END) ||
8810                     (dst_reg->type == PTR_TO_PACKET_META &&
8811                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8812                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8813                         find_good_pkt_pointers(this_branch, dst_reg,
8814                                                dst_reg->type, false);
8815                         mark_pkt_end(other_branch, insn->dst_reg, true);
8816                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8817                             src_reg->type == PTR_TO_PACKET) ||
8818                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8819                             src_reg->type == PTR_TO_PACKET_META)) {
8820                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8821                         find_good_pkt_pointers(other_branch, src_reg,
8822                                                src_reg->type, true);
8823                         mark_pkt_end(this_branch, insn->src_reg, false);
8824                 } else {
8825                         return false;
8826                 }
8827                 break;
8828         case BPF_JLT:
8829                 if ((dst_reg->type == PTR_TO_PACKET &&
8830                      src_reg->type == PTR_TO_PACKET_END) ||
8831                     (dst_reg->type == PTR_TO_PACKET_META &&
8832                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8833                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8834                         find_good_pkt_pointers(other_branch, dst_reg,
8835                                                dst_reg->type, true);
8836                         mark_pkt_end(this_branch, insn->dst_reg, false);
8837                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8838                             src_reg->type == PTR_TO_PACKET) ||
8839                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8840                             src_reg->type == PTR_TO_PACKET_META)) {
8841                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8842                         find_good_pkt_pointers(this_branch, src_reg,
8843                                                src_reg->type, false);
8844                         mark_pkt_end(other_branch, insn->src_reg, true);
8845                 } else {
8846                         return false;
8847                 }
8848                 break;
8849         case BPF_JGE:
8850                 if ((dst_reg->type == PTR_TO_PACKET &&
8851                      src_reg->type == PTR_TO_PACKET_END) ||
8852                     (dst_reg->type == PTR_TO_PACKET_META &&
8853                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8854                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8855                         find_good_pkt_pointers(this_branch, dst_reg,
8856                                                dst_reg->type, true);
8857                         mark_pkt_end(other_branch, insn->dst_reg, false);
8858                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8859                             src_reg->type == PTR_TO_PACKET) ||
8860                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8861                             src_reg->type == PTR_TO_PACKET_META)) {
8862                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8863                         find_good_pkt_pointers(other_branch, src_reg,
8864                                                src_reg->type, false);
8865                         mark_pkt_end(this_branch, insn->src_reg, true);
8866                 } else {
8867                         return false;
8868                 }
8869                 break;
8870         case BPF_JLE:
8871                 if ((dst_reg->type == PTR_TO_PACKET &&
8872                      src_reg->type == PTR_TO_PACKET_END) ||
8873                     (dst_reg->type == PTR_TO_PACKET_META &&
8874                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8875                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8876                         find_good_pkt_pointers(other_branch, dst_reg,
8877                                                dst_reg->type, false);
8878                         mark_pkt_end(this_branch, insn->dst_reg, true);
8879                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8880                             src_reg->type == PTR_TO_PACKET) ||
8881                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8882                             src_reg->type == PTR_TO_PACKET_META)) {
8883                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8884                         find_good_pkt_pointers(this_branch, src_reg,
8885                                                src_reg->type, true);
8886                         mark_pkt_end(other_branch, insn->src_reg, false);
8887                 } else {
8888                         return false;
8889                 }
8890                 break;
8891         default:
8892                 return false;
8893         }
8894
8895         return true;
8896 }
8897
8898 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8899                                struct bpf_reg_state *known_reg)
8900 {
8901         struct bpf_func_state *state;
8902         struct bpf_reg_state *reg;
8903
8904         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8905                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8906                         *reg = *known_reg;
8907         }));
8908 }
8909
8910 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8911                              struct bpf_insn *insn, int *insn_idx)
8912 {
8913         struct bpf_verifier_state *this_branch = env->cur_state;
8914         struct bpf_verifier_state *other_branch;
8915         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8916         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8917         u8 opcode = BPF_OP(insn->code);
8918         bool is_jmp32;
8919         int pred = -1;
8920         int err;
8921
8922         /* Only conditional jumps are expected to reach here. */
8923         if (opcode == BPF_JA || opcode > BPF_JSLE) {
8924                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8925                 return -EINVAL;
8926         }
8927
8928         if (BPF_SRC(insn->code) == BPF_X) {
8929                 if (insn->imm != 0) {
8930                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8931                         return -EINVAL;
8932                 }
8933
8934                 /* check src1 operand */
8935                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8936                 if (err)
8937                         return err;
8938
8939                 if (is_pointer_value(env, insn->src_reg)) {
8940                         verbose(env, "R%d pointer comparison prohibited\n",
8941                                 insn->src_reg);
8942                         return -EACCES;
8943                 }
8944                 src_reg = &regs[insn->src_reg];
8945         } else {
8946                 if (insn->src_reg != BPF_REG_0) {
8947                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8948                         return -EINVAL;
8949                 }
8950         }
8951
8952         /* check src2 operand */
8953         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8954         if (err)
8955                 return err;
8956
8957         dst_reg = &regs[insn->dst_reg];
8958         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8959
8960         if (BPF_SRC(insn->code) == BPF_K) {
8961                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8962         } else if (src_reg->type == SCALAR_VALUE &&
8963                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8964                 pred = is_branch_taken(dst_reg,
8965                                        tnum_subreg(src_reg->var_off).value,
8966                                        opcode,
8967                                        is_jmp32);
8968         } else if (src_reg->type == SCALAR_VALUE &&
8969                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8970                 pred = is_branch_taken(dst_reg,
8971                                        src_reg->var_off.value,
8972                                        opcode,
8973                                        is_jmp32);
8974         } else if (reg_is_pkt_pointer_any(dst_reg) &&
8975                    reg_is_pkt_pointer_any(src_reg) &&
8976                    !is_jmp32) {
8977                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8978         }
8979
8980         if (pred >= 0) {
8981                 /* If we get here with a dst_reg pointer type it is because
8982                  * above is_branch_taken() special cased the 0 comparison.
8983                  */
8984                 if (!__is_pointer_value(false, dst_reg))
8985                         err = mark_chain_precision(env, insn->dst_reg);
8986                 if (BPF_SRC(insn->code) == BPF_X && !err &&
8987                     !__is_pointer_value(false, src_reg))
8988                         err = mark_chain_precision(env, insn->src_reg);
8989                 if (err)
8990                         return err;
8991         }
8992
8993         if (pred == 1) {
8994                 /* Only follow the goto, ignore fall-through. If needed, push
8995                  * the fall-through branch for simulation under speculative
8996                  * execution.
8997                  */
8998                 if (!env->bypass_spec_v1 &&
8999                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
9000                                                *insn_idx))
9001                         return -EFAULT;
9002                 *insn_idx += insn->off;
9003                 return 0;
9004         } else if (pred == 0) {
9005                 /* Only follow the fall-through branch, since that's where the
9006                  * program will go. If needed, push the goto branch for
9007                  * simulation under speculative execution.
9008                  */
9009                 if (!env->bypass_spec_v1 &&
9010                     !sanitize_speculative_path(env, insn,
9011                                                *insn_idx + insn->off + 1,
9012                                                *insn_idx))
9013                         return -EFAULT;
9014                 return 0;
9015         }
9016
9017         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9018                                   false);
9019         if (!other_branch)
9020                 return -EFAULT;
9021         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9022
9023         /* detect if we are comparing against a constant value so we can adjust
9024          * our min/max values for our dst register.
9025          * this is only legit if both are scalars (or pointers to the same
9026          * object, I suppose, but we don't support that right now), because
9027          * otherwise the different base pointers mean the offsets aren't
9028          * comparable.
9029          */
9030         if (BPF_SRC(insn->code) == BPF_X) {
9031                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9032
9033                 if (dst_reg->type == SCALAR_VALUE &&
9034                     src_reg->type == SCALAR_VALUE) {
9035                         if (tnum_is_const(src_reg->var_off) ||
9036                             (is_jmp32 &&
9037                              tnum_is_const(tnum_subreg(src_reg->var_off))))
9038                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
9039                                                 dst_reg,
9040                                                 src_reg->var_off.value,
9041                                                 tnum_subreg(src_reg->var_off).value,
9042                                                 opcode, is_jmp32);
9043                         else if (tnum_is_const(dst_reg->var_off) ||
9044                                  (is_jmp32 &&
9045                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
9046                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9047                                                     src_reg,
9048                                                     dst_reg->var_off.value,
9049                                                     tnum_subreg(dst_reg->var_off).value,
9050                                                     opcode, is_jmp32);
9051                         else if (!is_jmp32 &&
9052                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
9053                                 /* Comparing for equality, we can combine knowledge */
9054                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
9055                                                     &other_branch_regs[insn->dst_reg],
9056                                                     src_reg, dst_reg, opcode);
9057                         if (src_reg->id &&
9058                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9059                                 find_equal_scalars(this_branch, src_reg);
9060                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9061                         }
9062
9063                 }
9064         } else if (dst_reg->type == SCALAR_VALUE) {
9065                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
9066                                         dst_reg, insn->imm, (u32)insn->imm,
9067                                         opcode, is_jmp32);
9068         }
9069
9070         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9071             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9072                 find_equal_scalars(this_branch, dst_reg);
9073                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9074         }
9075
9076         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9077          * NOTE: these optimizations below are related with pointer comparison
9078          *       which will never be JMP32.
9079          */
9080         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9081             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9082             type_may_be_null(dst_reg->type)) {
9083                 /* Mark all identical registers in each branch as either
9084                  * safe or unknown depending R == 0 or R != 0 conditional.
9085                  */
9086                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9087                                       opcode == BPF_JNE);
9088                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9089                                       opcode == BPF_JEQ);
9090         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9091                                            this_branch, other_branch) &&
9092                    is_pointer_value(env, insn->dst_reg)) {
9093                 verbose(env, "R%d pointer comparison prohibited\n",
9094                         insn->dst_reg);
9095                 return -EACCES;
9096         }
9097         if (env->log.level & BPF_LOG_LEVEL)
9098                 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9099         return 0;
9100 }
9101
9102 /* verify BPF_LD_IMM64 instruction */
9103 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9104 {
9105         struct bpf_insn_aux_data *aux = cur_aux(env);
9106         struct bpf_reg_state *regs = cur_regs(env);
9107         struct bpf_reg_state *dst_reg;
9108         struct bpf_map *map;
9109         int err;
9110
9111         if (BPF_SIZE(insn->code) != BPF_DW) {
9112                 verbose(env, "invalid BPF_LD_IMM insn\n");
9113                 return -EINVAL;
9114         }
9115         if (insn->off != 0) {
9116                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9117                 return -EINVAL;
9118         }
9119
9120         err = check_reg_arg(env, insn->dst_reg, DST_OP);
9121         if (err)
9122                 return err;
9123
9124         dst_reg = &regs[insn->dst_reg];
9125         if (insn->src_reg == 0) {
9126                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9127
9128                 dst_reg->type = SCALAR_VALUE;
9129                 __mark_reg_known(&regs[insn->dst_reg], imm);
9130                 return 0;
9131         }
9132
9133         /* All special src_reg cases are listed below. From this point onwards
9134          * we either succeed and assign a corresponding dst_reg->type after
9135          * zeroing the offset, or fail and reject the program.
9136          */
9137         mark_reg_known_zero(env, regs, insn->dst_reg);
9138
9139         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9140                 dst_reg->type = aux->btf_var.reg_type;
9141                 switch (base_type(dst_reg->type)) {
9142                 case PTR_TO_MEM:
9143                         dst_reg->mem_size = aux->btf_var.mem_size;
9144                         break;
9145                 case PTR_TO_BTF_ID:
9146                 case PTR_TO_PERCPU_BTF_ID:
9147                         dst_reg->btf = aux->btf_var.btf;
9148                         dst_reg->btf_id = aux->btf_var.btf_id;
9149                         break;
9150                 default:
9151                         verbose(env, "bpf verifier is misconfigured\n");
9152                         return -EFAULT;
9153                 }
9154                 return 0;
9155         }
9156
9157         if (insn->src_reg == BPF_PSEUDO_FUNC) {
9158                 struct bpf_prog_aux *aux = env->prog->aux;
9159                 u32 subprogno = find_subprog(env,
9160                                              env->insn_idx + insn->imm + 1);
9161
9162                 if (!aux->func_info) {
9163                         verbose(env, "missing btf func_info\n");
9164                         return -EINVAL;
9165                 }
9166                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9167                         verbose(env, "callback function not static\n");
9168                         return -EINVAL;
9169                 }
9170
9171                 dst_reg->type = PTR_TO_FUNC;
9172                 dst_reg->subprogno = subprogno;
9173                 return 0;
9174         }
9175
9176         map = env->used_maps[aux->map_index];
9177         dst_reg->map_ptr = map;
9178
9179         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9180             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9181                 dst_reg->type = PTR_TO_MAP_VALUE;
9182                 dst_reg->off = aux->map_off;
9183                 if (map_value_has_spin_lock(map))
9184                         dst_reg->id = ++env->id_gen;
9185         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9186                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9187                 dst_reg->type = CONST_PTR_TO_MAP;
9188         } else {
9189                 verbose(env, "bpf verifier is misconfigured\n");
9190                 return -EINVAL;
9191         }
9192
9193         return 0;
9194 }
9195
9196 static bool may_access_skb(enum bpf_prog_type type)
9197 {
9198         switch (type) {
9199         case BPF_PROG_TYPE_SOCKET_FILTER:
9200         case BPF_PROG_TYPE_SCHED_CLS:
9201         case BPF_PROG_TYPE_SCHED_ACT:
9202                 return true;
9203         default:
9204                 return false;
9205         }
9206 }
9207
9208 /* verify safety of LD_ABS|LD_IND instructions:
9209  * - they can only appear in the programs where ctx == skb
9210  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9211  *   preserve R6-R9, and store return value into R0
9212  *
9213  * Implicit input:
9214  *   ctx == skb == R6 == CTX
9215  *
9216  * Explicit input:
9217  *   SRC == any register
9218  *   IMM == 32-bit immediate
9219  *
9220  * Output:
9221  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9222  */
9223 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9224 {
9225         struct bpf_reg_state *regs = cur_regs(env);
9226         static const int ctx_reg = BPF_REG_6;
9227         u8 mode = BPF_MODE(insn->code);
9228         int i, err;
9229
9230         if (!may_access_skb(resolve_prog_type(env->prog))) {
9231                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9232                 return -EINVAL;
9233         }
9234
9235         if (!env->ops->gen_ld_abs) {
9236                 verbose(env, "bpf verifier is misconfigured\n");
9237                 return -EINVAL;
9238         }
9239
9240         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9241             BPF_SIZE(insn->code) == BPF_DW ||
9242             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9243                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9244                 return -EINVAL;
9245         }
9246
9247         /* check whether implicit source operand (register R6) is readable */
9248         err = check_reg_arg(env, ctx_reg, SRC_OP);
9249         if (err)
9250                 return err;
9251
9252         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9253          * gen_ld_abs() may terminate the program at runtime, leading to
9254          * reference leak.
9255          */
9256         err = check_reference_leak(env);
9257         if (err) {
9258                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9259                 return err;
9260         }
9261
9262         if (env->cur_state->active_spin_lock) {
9263                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9264                 return -EINVAL;
9265         }
9266
9267         if (regs[ctx_reg].type != PTR_TO_CTX) {
9268                 verbose(env,
9269                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9270                 return -EINVAL;
9271         }
9272
9273         if (mode == BPF_IND) {
9274                 /* check explicit source operand */
9275                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9276                 if (err)
9277                         return err;
9278         }
9279
9280         err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9281         if (err < 0)
9282                 return err;
9283
9284         /* reset caller saved regs to unreadable */
9285         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9286                 mark_reg_not_init(env, regs, caller_saved[i]);
9287                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9288         }
9289
9290         /* mark destination R0 register as readable, since it contains
9291          * the value fetched from the packet.
9292          * Already marked as written above.
9293          */
9294         mark_reg_unknown(env, regs, BPF_REG_0);
9295         /* ld_abs load up to 32-bit skb data. */
9296         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9297         return 0;
9298 }
9299
9300 static int check_return_code(struct bpf_verifier_env *env)
9301 {
9302         struct tnum enforce_attach_type_range = tnum_unknown;
9303         const struct bpf_prog *prog = env->prog;
9304         struct bpf_reg_state *reg;
9305         struct tnum range = tnum_range(0, 1);
9306         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9307         int err;
9308         struct bpf_func_state *frame = env->cur_state->frame[0];
9309         const bool is_subprog = frame->subprogno;
9310
9311         /* LSM and struct_ops func-ptr's return type could be "void" */
9312         if (!is_subprog &&
9313             (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9314              prog_type == BPF_PROG_TYPE_LSM) &&
9315             !prog->aux->attach_func_proto->type)
9316                 return 0;
9317
9318         /* eBPF calling convention is such that R0 is used
9319          * to return the value from eBPF program.
9320          * Make sure that it's readable at this time
9321          * of bpf_exit, which means that program wrote
9322          * something into it earlier
9323          */
9324         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9325         if (err)
9326                 return err;
9327
9328         if (is_pointer_value(env, BPF_REG_0)) {
9329                 verbose(env, "R0 leaks addr as return value\n");
9330                 return -EACCES;
9331         }
9332
9333         reg = cur_regs(env) + BPF_REG_0;
9334
9335         if (frame->in_async_callback_fn) {
9336                 /* enforce return zero from async callbacks like timer */
9337                 if (reg->type != SCALAR_VALUE) {
9338                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9339                                 reg_type_str(env, reg->type));
9340                         return -EINVAL;
9341                 }
9342
9343                 if (!tnum_in(tnum_const(0), reg->var_off)) {
9344                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9345                         return -EINVAL;
9346                 }
9347                 return 0;
9348         }
9349
9350         if (is_subprog) {
9351                 if (reg->type != SCALAR_VALUE) {
9352                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9353                                 reg_type_str(env, reg->type));
9354                         return -EINVAL;
9355                 }
9356                 return 0;
9357         }
9358
9359         switch (prog_type) {
9360         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9361                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9362                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9363                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9364                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9365                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9366                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9367                         range = tnum_range(1, 1);
9368                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9369                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9370                         range = tnum_range(0, 3);
9371                 break;
9372         case BPF_PROG_TYPE_CGROUP_SKB:
9373                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9374                         range = tnum_range(0, 3);
9375                         enforce_attach_type_range = tnum_range(2, 3);
9376                 }
9377                 break;
9378         case BPF_PROG_TYPE_CGROUP_SOCK:
9379         case BPF_PROG_TYPE_SOCK_OPS:
9380         case BPF_PROG_TYPE_CGROUP_DEVICE:
9381         case BPF_PROG_TYPE_CGROUP_SYSCTL:
9382         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9383                 break;
9384         case BPF_PROG_TYPE_RAW_TRACEPOINT:
9385                 if (!env->prog->aux->attach_btf_id)
9386                         return 0;
9387                 range = tnum_const(0);
9388                 break;
9389         case BPF_PROG_TYPE_TRACING:
9390                 switch (env->prog->expected_attach_type) {
9391                 case BPF_TRACE_FENTRY:
9392                 case BPF_TRACE_FEXIT:
9393                         range = tnum_const(0);
9394                         break;
9395                 case BPF_TRACE_RAW_TP:
9396                 case BPF_MODIFY_RETURN:
9397                         return 0;
9398                 case BPF_TRACE_ITER:
9399                         break;
9400                 default:
9401                         return -ENOTSUPP;
9402                 }
9403                 break;
9404         case BPF_PROG_TYPE_SK_LOOKUP:
9405                 range = tnum_range(SK_DROP, SK_PASS);
9406                 break;
9407         case BPF_PROG_TYPE_EXT:
9408                 /* freplace program can return anything as its return value
9409                  * depends on the to-be-replaced kernel func or bpf program.
9410                  */
9411         default:
9412                 return 0;
9413         }
9414
9415         if (reg->type != SCALAR_VALUE) {
9416                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9417                         reg_type_str(env, reg->type));
9418                 return -EINVAL;
9419         }
9420
9421         if (!tnum_in(range, reg->var_off)) {
9422                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9423                 return -EINVAL;
9424         }
9425
9426         if (!tnum_is_unknown(enforce_attach_type_range) &&
9427             tnum_in(enforce_attach_type_range, reg->var_off))
9428                 env->prog->enforce_expected_attach_type = 1;
9429         return 0;
9430 }
9431
9432 /* non-recursive DFS pseudo code
9433  * 1  procedure DFS-iterative(G,v):
9434  * 2      label v as discovered
9435  * 3      let S be a stack
9436  * 4      S.push(v)
9437  * 5      while S is not empty
9438  * 6            t <- S.pop()
9439  * 7            if t is what we're looking for:
9440  * 8                return t
9441  * 9            for all edges e in G.adjacentEdges(t) do
9442  * 10               if edge e is already labelled
9443  * 11                   continue with the next edge
9444  * 12               w <- G.adjacentVertex(t,e)
9445  * 13               if vertex w is not discovered and not explored
9446  * 14                   label e as tree-edge
9447  * 15                   label w as discovered
9448  * 16                   S.push(w)
9449  * 17                   continue at 5
9450  * 18               else if vertex w is discovered
9451  * 19                   label e as back-edge
9452  * 20               else
9453  * 21                   // vertex w is explored
9454  * 22                   label e as forward- or cross-edge
9455  * 23           label t as explored
9456  * 24           S.pop()
9457  *
9458  * convention:
9459  * 0x10 - discovered
9460  * 0x11 - discovered and fall-through edge labelled
9461  * 0x12 - discovered and fall-through and branch edges labelled
9462  * 0x20 - explored
9463  */
9464
9465 enum {
9466         DISCOVERED = 0x10,
9467         EXPLORED = 0x20,
9468         FALLTHROUGH = 1,
9469         BRANCH = 2,
9470 };
9471
9472 static u32 state_htab_size(struct bpf_verifier_env *env)
9473 {
9474         return env->prog->len;
9475 }
9476
9477 static struct bpf_verifier_state_list **explored_state(
9478                                         struct bpf_verifier_env *env,
9479                                         int idx)
9480 {
9481         struct bpf_verifier_state *cur = env->cur_state;
9482         struct bpf_func_state *state = cur->frame[cur->curframe];
9483
9484         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9485 }
9486
9487 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9488 {
9489         env->insn_aux_data[idx].prune_point = true;
9490 }
9491
9492 enum {
9493         DONE_EXPLORING = 0,
9494         KEEP_EXPLORING = 1,
9495 };
9496
9497 /* t, w, e - match pseudo-code above:
9498  * t - index of current instruction
9499  * w - next instruction
9500  * e - edge
9501  */
9502 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9503                      bool loop_ok)
9504 {
9505         int *insn_stack = env->cfg.insn_stack;
9506         int *insn_state = env->cfg.insn_state;
9507
9508         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9509                 return DONE_EXPLORING;
9510
9511         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9512                 return DONE_EXPLORING;
9513
9514         if (w < 0 || w >= env->prog->len) {
9515                 verbose_linfo(env, t, "%d: ", t);
9516                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
9517                 return -EINVAL;
9518         }
9519
9520         if (e == BRANCH)
9521                 /* mark branch target for state pruning */
9522                 init_explored_state(env, w);
9523
9524         if (insn_state[w] == 0) {
9525                 /* tree-edge */
9526                 insn_state[t] = DISCOVERED | e;
9527                 insn_state[w] = DISCOVERED;
9528                 if (env->cfg.cur_stack >= env->prog->len)
9529                         return -E2BIG;
9530                 insn_stack[env->cfg.cur_stack++] = w;
9531                 return KEEP_EXPLORING;
9532         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9533                 if (loop_ok && env->bpf_capable)
9534                         return DONE_EXPLORING;
9535                 verbose_linfo(env, t, "%d: ", t);
9536                 verbose_linfo(env, w, "%d: ", w);
9537                 verbose(env, "back-edge from insn %d to %d\n", t, w);
9538                 return -EINVAL;
9539         } else if (insn_state[w] == EXPLORED) {
9540                 /* forward- or cross-edge */
9541                 insn_state[t] = DISCOVERED | e;
9542         } else {
9543                 verbose(env, "insn state internal bug\n");
9544                 return -EFAULT;
9545         }
9546         return DONE_EXPLORING;
9547 }
9548
9549 static int visit_func_call_insn(int t, int insn_cnt,
9550                                 struct bpf_insn *insns,
9551                                 struct bpf_verifier_env *env,
9552                                 bool visit_callee)
9553 {
9554         int ret;
9555
9556         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9557         if (ret)
9558                 return ret;
9559
9560         if (t + 1 < insn_cnt)
9561                 init_explored_state(env, t + 1);
9562         if (visit_callee) {
9563                 init_explored_state(env, t);
9564                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9565                                 /* It's ok to allow recursion from CFG point of
9566                                  * view. __check_func_call() will do the actual
9567                                  * check.
9568                                  */
9569                                 bpf_pseudo_func(insns + t));
9570         }
9571         return ret;
9572 }
9573
9574 /* Visits the instruction at index t and returns one of the following:
9575  *  < 0 - an error occurred
9576  *  DONE_EXPLORING - the instruction was fully explored
9577  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9578  */
9579 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9580 {
9581         struct bpf_insn *insns = env->prog->insnsi;
9582         int ret;
9583
9584         if (bpf_pseudo_func(insns + t))
9585                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9586
9587         /* All non-branch instructions have a single fall-through edge. */
9588         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9589             BPF_CLASS(insns[t].code) != BPF_JMP32)
9590                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9591
9592         switch (BPF_OP(insns[t].code)) {
9593         case BPF_EXIT:
9594                 return DONE_EXPLORING;
9595
9596         case BPF_CALL:
9597                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
9598                         /* Mark this call insn to trigger is_state_visited() check
9599                          * before call itself is processed by __check_func_call().
9600                          * Otherwise new async state will be pushed for further
9601                          * exploration.
9602                          */
9603                         init_explored_state(env, t);
9604                 return visit_func_call_insn(t, insn_cnt, insns, env,
9605                                             insns[t].src_reg == BPF_PSEUDO_CALL);
9606
9607         case BPF_JA:
9608                 if (BPF_SRC(insns[t].code) != BPF_K)
9609                         return -EINVAL;
9610
9611                 /* unconditional jump with single edge */
9612                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9613                                 true);
9614                 if (ret)
9615                         return ret;
9616
9617                 /* unconditional jmp is not a good pruning point,
9618                  * but it's marked, since backtracking needs
9619                  * to record jmp history in is_state_visited().
9620                  */
9621                 init_explored_state(env, t + insns[t].off + 1);
9622                 /* tell verifier to check for equivalent states
9623                  * after every call and jump
9624                  */
9625                 if (t + 1 < insn_cnt)
9626                         init_explored_state(env, t + 1);
9627
9628                 return ret;
9629
9630         default:
9631                 /* conditional jump with two edges */
9632                 init_explored_state(env, t);
9633                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9634                 if (ret)
9635                         return ret;
9636
9637                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9638         }
9639 }
9640
9641 /* non-recursive depth-first-search to detect loops in BPF program
9642  * loop == back-edge in directed graph
9643  */
9644 static int check_cfg(struct bpf_verifier_env *env)
9645 {
9646         int insn_cnt = env->prog->len;
9647         int *insn_stack, *insn_state;
9648         int ret = 0;
9649         int i;
9650
9651         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9652         if (!insn_state)
9653                 return -ENOMEM;
9654
9655         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9656         if (!insn_stack) {
9657                 kvfree(insn_state);
9658                 return -ENOMEM;
9659         }
9660
9661         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9662         insn_stack[0] = 0; /* 0 is the first instruction */
9663         env->cfg.cur_stack = 1;
9664
9665         while (env->cfg.cur_stack > 0) {
9666                 int t = insn_stack[env->cfg.cur_stack - 1];
9667
9668                 ret = visit_insn(t, insn_cnt, env);
9669                 switch (ret) {
9670                 case DONE_EXPLORING:
9671                         insn_state[t] = EXPLORED;
9672                         env->cfg.cur_stack--;
9673                         break;
9674                 case KEEP_EXPLORING:
9675                         break;
9676                 default:
9677                         if (ret > 0) {
9678                                 verbose(env, "visit_insn internal bug\n");
9679                                 ret = -EFAULT;
9680                         }
9681                         goto err_free;
9682                 }
9683         }
9684
9685         if (env->cfg.cur_stack < 0) {
9686                 verbose(env, "pop stack internal bug\n");
9687                 ret = -EFAULT;
9688                 goto err_free;
9689         }
9690
9691         for (i = 0; i < insn_cnt; i++) {
9692                 if (insn_state[i] != EXPLORED) {
9693                         verbose(env, "unreachable insn %d\n", i);
9694                         ret = -EINVAL;
9695                         goto err_free;
9696                 }
9697         }
9698         ret = 0; /* cfg looks good */
9699
9700 err_free:
9701         kvfree(insn_state);
9702         kvfree(insn_stack);
9703         env->cfg.insn_state = env->cfg.insn_stack = NULL;
9704         return ret;
9705 }
9706
9707 static int check_abnormal_return(struct bpf_verifier_env *env)
9708 {
9709         int i;
9710
9711         for (i = 1; i < env->subprog_cnt; i++) {
9712                 if (env->subprog_info[i].has_ld_abs) {
9713                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9714                         return -EINVAL;
9715                 }
9716                 if (env->subprog_info[i].has_tail_call) {
9717                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9718                         return -EINVAL;
9719                 }
9720         }
9721         return 0;
9722 }
9723
9724 /* The minimum supported BTF func info size */
9725 #define MIN_BPF_FUNCINFO_SIZE   8
9726 #define MAX_FUNCINFO_REC_SIZE   252
9727
9728 static int check_btf_func(struct bpf_verifier_env *env,
9729                           const union bpf_attr *attr,
9730                           bpfptr_t uattr)
9731 {
9732         const struct btf_type *type, *func_proto, *ret_type;
9733         u32 i, nfuncs, urec_size, min_size;
9734         u32 krec_size = sizeof(struct bpf_func_info);
9735         struct bpf_func_info *krecord;
9736         struct bpf_func_info_aux *info_aux = NULL;
9737         struct bpf_prog *prog;
9738         const struct btf *btf;
9739         bpfptr_t urecord;
9740         u32 prev_offset = 0;
9741         bool scalar_return;
9742         int ret = -ENOMEM;
9743
9744         nfuncs = attr->func_info_cnt;
9745         if (!nfuncs) {
9746                 if (check_abnormal_return(env))
9747                         return -EINVAL;
9748                 return 0;
9749         }
9750
9751         if (nfuncs != env->subprog_cnt) {
9752                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9753                 return -EINVAL;
9754         }
9755
9756         urec_size = attr->func_info_rec_size;
9757         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9758             urec_size > MAX_FUNCINFO_REC_SIZE ||
9759             urec_size % sizeof(u32)) {
9760                 verbose(env, "invalid func info rec size %u\n", urec_size);
9761                 return -EINVAL;
9762         }
9763
9764         prog = env->prog;
9765         btf = prog->aux->btf;
9766
9767         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
9768         min_size = min_t(u32, krec_size, urec_size);
9769
9770         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9771         if (!krecord)
9772                 return -ENOMEM;
9773         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9774         if (!info_aux)
9775                 goto err_free;
9776
9777         for (i = 0; i < nfuncs; i++) {
9778                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9779                 if (ret) {
9780                         if (ret == -E2BIG) {
9781                                 verbose(env, "nonzero tailing record in func info");
9782                                 /* set the size kernel expects so loader can zero
9783                                  * out the rest of the record.
9784                                  */
9785                                 if (copy_to_bpfptr_offset(uattr,
9786                                                           offsetof(union bpf_attr, func_info_rec_size),
9787                                                           &min_size, sizeof(min_size)))
9788                                         ret = -EFAULT;
9789                         }
9790                         goto err_free;
9791                 }
9792
9793                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
9794                         ret = -EFAULT;
9795                         goto err_free;
9796                 }
9797
9798                 /* check insn_off */
9799                 ret = -EINVAL;
9800                 if (i == 0) {
9801                         if (krecord[i].insn_off) {
9802                                 verbose(env,
9803                                         "nonzero insn_off %u for the first func info record",
9804                                         krecord[i].insn_off);
9805                                 goto err_free;
9806                         }
9807                 } else if (krecord[i].insn_off <= prev_offset) {
9808                         verbose(env,
9809                                 "same or smaller insn offset (%u) than previous func info record (%u)",
9810                                 krecord[i].insn_off, prev_offset);
9811                         goto err_free;
9812                 }
9813
9814                 if (env->subprog_info[i].start != krecord[i].insn_off) {
9815                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9816                         goto err_free;
9817                 }
9818
9819                 /* check type_id */
9820                 type = btf_type_by_id(btf, krecord[i].type_id);
9821                 if (!type || !btf_type_is_func(type)) {
9822                         verbose(env, "invalid type id %d in func info",
9823                                 krecord[i].type_id);
9824                         goto err_free;
9825                 }
9826                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9827
9828                 func_proto = btf_type_by_id(btf, type->type);
9829                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9830                         /* btf_func_check() already verified it during BTF load */
9831                         goto err_free;
9832                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9833                 scalar_return =
9834                         btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9835                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9836                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9837                         goto err_free;
9838                 }
9839                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9840                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9841                         goto err_free;
9842                 }
9843
9844                 prev_offset = krecord[i].insn_off;
9845                 bpfptr_add(&urecord, urec_size);
9846         }
9847
9848         prog->aux->func_info = krecord;
9849         prog->aux->func_info_cnt = nfuncs;
9850         prog->aux->func_info_aux = info_aux;
9851         return 0;
9852
9853 err_free:
9854         kvfree(krecord);
9855         kfree(info_aux);
9856         return ret;
9857 }
9858
9859 static void adjust_btf_func(struct bpf_verifier_env *env)
9860 {
9861         struct bpf_prog_aux *aux = env->prog->aux;
9862         int i;
9863
9864         if (!aux->func_info)
9865                 return;
9866
9867         for (i = 0; i < env->subprog_cnt; i++)
9868                 aux->func_info[i].insn_off = env->subprog_info[i].start;
9869 }
9870
9871 #define MIN_BPF_LINEINFO_SIZE   (offsetof(struct bpf_line_info, line_col) + \
9872                 sizeof(((struct bpf_line_info *)(0))->line_col))
9873 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
9874
9875 static int check_btf_line(struct bpf_verifier_env *env,
9876                           const union bpf_attr *attr,
9877                           bpfptr_t uattr)
9878 {
9879         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9880         struct bpf_subprog_info *sub;
9881         struct bpf_line_info *linfo;
9882         struct bpf_prog *prog;
9883         const struct btf *btf;
9884         bpfptr_t ulinfo;
9885         int err;
9886
9887         nr_linfo = attr->line_info_cnt;
9888         if (!nr_linfo)
9889                 return 0;
9890         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
9891                 return -EINVAL;
9892
9893         rec_size = attr->line_info_rec_size;
9894         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9895             rec_size > MAX_LINEINFO_REC_SIZE ||
9896             rec_size & (sizeof(u32) - 1))
9897                 return -EINVAL;
9898
9899         /* Need to zero it in case the userspace may
9900          * pass in a smaller bpf_line_info object.
9901          */
9902         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9903                          GFP_KERNEL | __GFP_NOWARN);
9904         if (!linfo)
9905                 return -ENOMEM;
9906
9907         prog = env->prog;
9908         btf = prog->aux->btf;
9909
9910         s = 0;
9911         sub = env->subprog_info;
9912         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
9913         expected_size = sizeof(struct bpf_line_info);
9914         ncopy = min_t(u32, expected_size, rec_size);
9915         for (i = 0; i < nr_linfo; i++) {
9916                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9917                 if (err) {
9918                         if (err == -E2BIG) {
9919                                 verbose(env, "nonzero tailing record in line_info");
9920                                 if (copy_to_bpfptr_offset(uattr,
9921                                                           offsetof(union bpf_attr, line_info_rec_size),
9922                                                           &expected_size, sizeof(expected_size)))
9923                                         err = -EFAULT;
9924                         }
9925                         goto err_free;
9926                 }
9927
9928                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
9929                         err = -EFAULT;
9930                         goto err_free;
9931                 }
9932
9933                 /*
9934                  * Check insn_off to ensure
9935                  * 1) strictly increasing AND
9936                  * 2) bounded by prog->len
9937                  *
9938                  * The linfo[0].insn_off == 0 check logically falls into
9939                  * the later "missing bpf_line_info for func..." case
9940                  * because the first linfo[0].insn_off must be the
9941                  * first sub also and the first sub must have
9942                  * subprog_info[0].start == 0.
9943                  */
9944                 if ((i && linfo[i].insn_off <= prev_offset) ||
9945                     linfo[i].insn_off >= prog->len) {
9946                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9947                                 i, linfo[i].insn_off, prev_offset,
9948                                 prog->len);
9949                         err = -EINVAL;
9950                         goto err_free;
9951                 }
9952
9953                 if (!prog->insnsi[linfo[i].insn_off].code) {
9954                         verbose(env,
9955                                 "Invalid insn code at line_info[%u].insn_off\n",
9956                                 i);
9957                         err = -EINVAL;
9958                         goto err_free;
9959                 }
9960
9961                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9962                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9963                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9964                         err = -EINVAL;
9965                         goto err_free;
9966                 }
9967
9968                 if (s != env->subprog_cnt) {
9969                         if (linfo[i].insn_off == sub[s].start) {
9970                                 sub[s].linfo_idx = i;
9971                                 s++;
9972                         } else if (sub[s].start < linfo[i].insn_off) {
9973                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
9974                                 err = -EINVAL;
9975                                 goto err_free;
9976                         }
9977                 }
9978
9979                 prev_offset = linfo[i].insn_off;
9980                 bpfptr_add(&ulinfo, rec_size);
9981         }
9982
9983         if (s != env->subprog_cnt) {
9984                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9985                         env->subprog_cnt - s, s);
9986                 err = -EINVAL;
9987                 goto err_free;
9988         }
9989
9990         prog->aux->linfo = linfo;
9991         prog->aux->nr_linfo = nr_linfo;
9992
9993         return 0;
9994
9995 err_free:
9996         kvfree(linfo);
9997         return err;
9998 }
9999
10000 static int check_btf_info(struct bpf_verifier_env *env,
10001                           const union bpf_attr *attr,
10002                           bpfptr_t uattr)
10003 {
10004         struct btf *btf;
10005         int err;
10006
10007         if (!attr->func_info_cnt && !attr->line_info_cnt) {
10008                 if (check_abnormal_return(env))
10009                         return -EINVAL;
10010                 return 0;
10011         }
10012
10013         btf = btf_get_by_fd(attr->prog_btf_fd);
10014         if (IS_ERR(btf))
10015                 return PTR_ERR(btf);
10016         if (btf_is_kernel(btf)) {
10017                 btf_put(btf);
10018                 return -EACCES;
10019         }
10020         env->prog->aux->btf = btf;
10021
10022         err = check_btf_func(env, attr, uattr);
10023         if (err)
10024                 return err;
10025
10026         err = check_btf_line(env, attr, uattr);
10027         if (err)
10028                 return err;
10029
10030         return 0;
10031 }
10032
10033 /* check %cur's range satisfies %old's */
10034 static bool range_within(struct bpf_reg_state *old,
10035                          struct bpf_reg_state *cur)
10036 {
10037         return old->umin_value <= cur->umin_value &&
10038                old->umax_value >= cur->umax_value &&
10039                old->smin_value <= cur->smin_value &&
10040                old->smax_value >= cur->smax_value &&
10041                old->u32_min_value <= cur->u32_min_value &&
10042                old->u32_max_value >= cur->u32_max_value &&
10043                old->s32_min_value <= cur->s32_min_value &&
10044                old->s32_max_value >= cur->s32_max_value;
10045 }
10046
10047 /* If in the old state two registers had the same id, then they need to have
10048  * the same id in the new state as well.  But that id could be different from
10049  * the old state, so we need to track the mapping from old to new ids.
10050  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10051  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10052  * regs with a different old id could still have new id 9, we don't care about
10053  * that.
10054  * So we look through our idmap to see if this old id has been seen before.  If
10055  * so, we require the new id to match; otherwise, we add the id pair to the map.
10056  */
10057 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10058 {
10059         unsigned int i;
10060
10061         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10062                 if (!idmap[i].old) {
10063                         /* Reached an empty slot; haven't seen this id before */
10064                         idmap[i].old = old_id;
10065                         idmap[i].cur = cur_id;
10066                         return true;
10067                 }
10068                 if (idmap[i].old == old_id)
10069                         return idmap[i].cur == cur_id;
10070         }
10071         /* We ran out of idmap slots, which should be impossible */
10072         WARN_ON_ONCE(1);
10073         return false;
10074 }
10075
10076 static void clean_func_state(struct bpf_verifier_env *env,
10077                              struct bpf_func_state *st)
10078 {
10079         enum bpf_reg_liveness live;
10080         int i, j;
10081
10082         for (i = 0; i < BPF_REG_FP; i++) {
10083                 live = st->regs[i].live;
10084                 /* liveness must not touch this register anymore */
10085                 st->regs[i].live |= REG_LIVE_DONE;
10086                 if (!(live & REG_LIVE_READ))
10087                         /* since the register is unused, clear its state
10088                          * to make further comparison simpler
10089                          */
10090                         __mark_reg_not_init(env, &st->regs[i]);
10091         }
10092
10093         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10094                 live = st->stack[i].spilled_ptr.live;
10095                 /* liveness must not touch this stack slot anymore */
10096                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10097                 if (!(live & REG_LIVE_READ)) {
10098                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10099                         for (j = 0; j < BPF_REG_SIZE; j++)
10100                                 st->stack[i].slot_type[j] = STACK_INVALID;
10101                 }
10102         }
10103 }
10104
10105 static void clean_verifier_state(struct bpf_verifier_env *env,
10106                                  struct bpf_verifier_state *st)
10107 {
10108         int i;
10109
10110         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10111                 /* all regs in this state in all frames were already marked */
10112                 return;
10113
10114         for (i = 0; i <= st->curframe; i++)
10115                 clean_func_state(env, st->frame[i]);
10116 }
10117
10118 /* the parentage chains form a tree.
10119  * the verifier states are added to state lists at given insn and
10120  * pushed into state stack for future exploration.
10121  * when the verifier reaches bpf_exit insn some of the verifer states
10122  * stored in the state lists have their final liveness state already,
10123  * but a lot of states will get revised from liveness point of view when
10124  * the verifier explores other branches.
10125  * Example:
10126  * 1: r0 = 1
10127  * 2: if r1 == 100 goto pc+1
10128  * 3: r0 = 2
10129  * 4: exit
10130  * when the verifier reaches exit insn the register r0 in the state list of
10131  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10132  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10133  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10134  *
10135  * Since the verifier pushes the branch states as it sees them while exploring
10136  * the program the condition of walking the branch instruction for the second
10137  * time means that all states below this branch were already explored and
10138  * their final liveness marks are already propagated.
10139  * Hence when the verifier completes the search of state list in is_state_visited()
10140  * we can call this clean_live_states() function to mark all liveness states
10141  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10142  * will not be used.
10143  * This function also clears the registers and stack for states that !READ
10144  * to simplify state merging.
10145  *
10146  * Important note here that walking the same branch instruction in the callee
10147  * doesn't meant that the states are DONE. The verifier has to compare
10148  * the callsites
10149  */
10150 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10151                               struct bpf_verifier_state *cur)
10152 {
10153         struct bpf_verifier_state_list *sl;
10154         int i;
10155
10156         sl = *explored_state(env, insn);
10157         while (sl) {
10158                 if (sl->state.branches)
10159                         goto next;
10160                 if (sl->state.insn_idx != insn ||
10161                     sl->state.curframe != cur->curframe)
10162                         goto next;
10163                 for (i = 0; i <= cur->curframe; i++)
10164                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10165                                 goto next;
10166                 clean_verifier_state(env, &sl->state);
10167 next:
10168                 sl = sl->next;
10169         }
10170 }
10171
10172 /* Returns true if (rold safe implies rcur safe) */
10173 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10174                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10175 {
10176         bool equal;
10177
10178         if (!(rold->live & REG_LIVE_READ))
10179                 /* explored state didn't use this */
10180                 return true;
10181
10182         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10183
10184         if (rold->type == PTR_TO_STACK)
10185                 /* two stack pointers are equal only if they're pointing to
10186                  * the same stack frame, since fp-8 in foo != fp-8 in bar
10187                  */
10188                 return equal && rold->frameno == rcur->frameno;
10189
10190         if (equal)
10191                 return true;
10192
10193         if (rold->type == NOT_INIT)
10194                 /* explored state can't have used this */
10195                 return true;
10196         if (rcur->type == NOT_INIT)
10197                 return false;
10198         switch (base_type(rold->type)) {
10199         case SCALAR_VALUE:
10200                 if (env->explore_alu_limits)
10201                         return false;
10202                 if (rcur->type == SCALAR_VALUE) {
10203                         if (!rold->precise && !rcur->precise)
10204                                 return true;
10205                         /* new val must satisfy old val knowledge */
10206                         return range_within(rold, rcur) &&
10207                                tnum_in(rold->var_off, rcur->var_off);
10208                 } else {
10209                         /* We're trying to use a pointer in place of a scalar.
10210                          * Even if the scalar was unbounded, this could lead to
10211                          * pointer leaks because scalars are allowed to leak
10212                          * while pointers are not. We could make this safe in
10213                          * special cases if root is calling us, but it's
10214                          * probably not worth the hassle.
10215                          */
10216                         return false;
10217                 }
10218         case PTR_TO_MAP_KEY:
10219         case PTR_TO_MAP_VALUE:
10220                 /* a PTR_TO_MAP_VALUE could be safe to use as a
10221                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10222                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10223                  * checked, doing so could have affected others with the same
10224                  * id, and we can't check for that because we lost the id when
10225                  * we converted to a PTR_TO_MAP_VALUE.
10226                  */
10227                 if (type_may_be_null(rold->type)) {
10228                         if (!type_may_be_null(rcur->type))
10229                                 return false;
10230                         if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10231                                 return false;
10232                         /* Check our ids match any regs they're supposed to */
10233                         return check_ids(rold->id, rcur->id, idmap);
10234                 }
10235
10236                 /* If the new min/max/var_off satisfy the old ones and
10237                  * everything else matches, we are OK.
10238                  * 'id' is not compared, since it's only used for maps with
10239                  * bpf_spin_lock inside map element and in such cases if
10240                  * the rest of the prog is valid for one map element then
10241                  * it's valid for all map elements regardless of the key
10242                  * used in bpf_map_lookup()
10243                  */
10244                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10245                        range_within(rold, rcur) &&
10246                        tnum_in(rold->var_off, rcur->var_off);
10247         case PTR_TO_PACKET_META:
10248         case PTR_TO_PACKET:
10249                 if (rcur->type != rold->type)
10250                         return false;
10251                 /* We must have at least as much range as the old ptr
10252                  * did, so that any accesses which were safe before are
10253                  * still safe.  This is true even if old range < old off,
10254                  * since someone could have accessed through (ptr - k), or
10255                  * even done ptr -= k in a register, to get a safe access.
10256                  */
10257                 if (rold->range > rcur->range)
10258                         return false;
10259                 /* If the offsets don't match, we can't trust our alignment;
10260                  * nor can we be sure that we won't fall out of range.
10261                  */
10262                 if (rold->off != rcur->off)
10263                         return false;
10264                 /* id relations must be preserved */
10265                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10266                         return false;
10267                 /* new val must satisfy old val knowledge */
10268                 return range_within(rold, rcur) &&
10269                        tnum_in(rold->var_off, rcur->var_off);
10270         case PTR_TO_CTX:
10271         case CONST_PTR_TO_MAP:
10272         case PTR_TO_PACKET_END:
10273         case PTR_TO_FLOW_KEYS:
10274         case PTR_TO_SOCKET:
10275         case PTR_TO_SOCK_COMMON:
10276         case PTR_TO_TCP_SOCK:
10277         case PTR_TO_XDP_SOCK:
10278                 /* Only valid matches are exact, which memcmp() above
10279                  * would have accepted
10280                  */
10281         default:
10282                 /* Don't know what's going on, just say it's not safe */
10283                 return false;
10284         }
10285
10286         /* Shouldn't get here; if we do, say it's not safe */
10287         WARN_ON_ONCE(1);
10288         return false;
10289 }
10290
10291 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10292                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10293 {
10294         int i, spi;
10295
10296         /* walk slots of the explored stack and ignore any additional
10297          * slots in the current stack, since explored(safe) state
10298          * didn't use them
10299          */
10300         for (i = 0; i < old->allocated_stack; i++) {
10301                 spi = i / BPF_REG_SIZE;
10302
10303                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10304                         i += BPF_REG_SIZE - 1;
10305                         /* explored state didn't use this */
10306                         continue;
10307                 }
10308
10309                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10310                         continue;
10311
10312                 /* explored stack has more populated slots than current stack
10313                  * and these slots were used
10314                  */
10315                 if (i >= cur->allocated_stack)
10316                         return false;
10317
10318                 /* if old state was safe with misc data in the stack
10319                  * it will be safe with zero-initialized stack.
10320                  * The opposite is not true
10321                  */
10322                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10323                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10324                         continue;
10325                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10326                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10327                         /* Ex: old explored (safe) state has STACK_SPILL in
10328                          * this stack slot, but current has STACK_MISC ->
10329                          * this verifier states are not equivalent,
10330                          * return false to continue verification of this path
10331                          */
10332                         return false;
10333                 if (i % BPF_REG_SIZE)
10334                         continue;
10335                 if (old->stack[spi].slot_type[0] != STACK_SPILL)
10336                         continue;
10337                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
10338                              &cur->stack[spi].spilled_ptr, idmap))
10339                         /* when explored and current stack slot are both storing
10340                          * spilled registers, check that stored pointers types
10341                          * are the same as well.
10342                          * Ex: explored safe path could have stored
10343                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10344                          * but current path has stored:
10345                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10346                          * such verifier states are not equivalent.
10347                          * return false to continue verification of this path
10348                          */
10349                         return false;
10350         }
10351         return true;
10352 }
10353
10354 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10355 {
10356         if (old->acquired_refs != cur->acquired_refs)
10357                 return false;
10358         return !memcmp(old->refs, cur->refs,
10359                        sizeof(*old->refs) * old->acquired_refs);
10360 }
10361
10362 /* compare two verifier states
10363  *
10364  * all states stored in state_list are known to be valid, since
10365  * verifier reached 'bpf_exit' instruction through them
10366  *
10367  * this function is called when verifier exploring different branches of
10368  * execution popped from the state stack. If it sees an old state that has
10369  * more strict register state and more strict stack state then this execution
10370  * branch doesn't need to be explored further, since verifier already
10371  * concluded that more strict state leads to valid finish.
10372  *
10373  * Therefore two states are equivalent if register state is more conservative
10374  * and explored stack state is more conservative than the current one.
10375  * Example:
10376  *       explored                   current
10377  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10378  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10379  *
10380  * In other words if current stack state (one being explored) has more
10381  * valid slots than old one that already passed validation, it means
10382  * the verifier can stop exploring and conclude that current state is valid too
10383  *
10384  * Similarly with registers. If explored state has register type as invalid
10385  * whereas register type in current state is meaningful, it means that
10386  * the current state will reach 'bpf_exit' instruction safely
10387  */
10388 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10389                               struct bpf_func_state *cur)
10390 {
10391         int i;
10392
10393         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10394         for (i = 0; i < MAX_BPF_REG; i++)
10395                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
10396                              env->idmap_scratch))
10397                         return false;
10398
10399         if (!stacksafe(env, old, cur, env->idmap_scratch))
10400                 return false;
10401
10402         if (!refsafe(old, cur))
10403                 return false;
10404
10405         return true;
10406 }
10407
10408 static bool states_equal(struct bpf_verifier_env *env,
10409                          struct bpf_verifier_state *old,
10410                          struct bpf_verifier_state *cur)
10411 {
10412         int i;
10413
10414         if (old->curframe != cur->curframe)
10415                 return false;
10416
10417         /* Verification state from speculative execution simulation
10418          * must never prune a non-speculative execution one.
10419          */
10420         if (old->speculative && !cur->speculative)
10421                 return false;
10422
10423         if (old->active_spin_lock != cur->active_spin_lock)
10424                 return false;
10425
10426         /* for states to be equal callsites have to be the same
10427          * and all frame states need to be equivalent
10428          */
10429         for (i = 0; i <= old->curframe; i++) {
10430                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10431                         return false;
10432                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10433                         return false;
10434         }
10435         return true;
10436 }
10437
10438 /* Return 0 if no propagation happened. Return negative error code if error
10439  * happened. Otherwise, return the propagated bit.
10440  */
10441 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10442                                   struct bpf_reg_state *reg,
10443                                   struct bpf_reg_state *parent_reg)
10444 {
10445         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10446         u8 flag = reg->live & REG_LIVE_READ;
10447         int err;
10448
10449         /* When comes here, read flags of PARENT_REG or REG could be any of
10450          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10451          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10452          */
10453         if (parent_flag == REG_LIVE_READ64 ||
10454             /* Or if there is no read flag from REG. */
10455             !flag ||
10456             /* Or if the read flag from REG is the same as PARENT_REG. */
10457             parent_flag == flag)
10458                 return 0;
10459
10460         err = mark_reg_read(env, reg, parent_reg, flag);
10461         if (err)
10462                 return err;
10463
10464         return flag;
10465 }
10466
10467 /* A write screens off any subsequent reads; but write marks come from the
10468  * straight-line code between a state and its parent.  When we arrive at an
10469  * equivalent state (jump target or such) we didn't arrive by the straight-line
10470  * code, so read marks in the state must propagate to the parent regardless
10471  * of the state's write marks. That's what 'parent == state->parent' comparison
10472  * in mark_reg_read() is for.
10473  */
10474 static int propagate_liveness(struct bpf_verifier_env *env,
10475                               const struct bpf_verifier_state *vstate,
10476                               struct bpf_verifier_state *vparent)
10477 {
10478         struct bpf_reg_state *state_reg, *parent_reg;
10479         struct bpf_func_state *state, *parent;
10480         int i, frame, err = 0;
10481
10482         if (vparent->curframe != vstate->curframe) {
10483                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10484                      vparent->curframe, vstate->curframe);
10485                 return -EFAULT;
10486         }
10487         /* Propagate read liveness of registers... */
10488         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10489         for (frame = 0; frame <= vstate->curframe; frame++) {
10490                 parent = vparent->frame[frame];
10491                 state = vstate->frame[frame];
10492                 parent_reg = parent->regs;
10493                 state_reg = state->regs;
10494                 /* We don't need to worry about FP liveness, it's read-only */
10495                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10496                         err = propagate_liveness_reg(env, &state_reg[i],
10497                                                      &parent_reg[i]);
10498                         if (err < 0)
10499                                 return err;
10500                         if (err == REG_LIVE_READ64)
10501                                 mark_insn_zext(env, &parent_reg[i]);
10502                 }
10503
10504                 /* Propagate stack slots. */
10505                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10506                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10507                         parent_reg = &parent->stack[i].spilled_ptr;
10508                         state_reg = &state->stack[i].spilled_ptr;
10509                         err = propagate_liveness_reg(env, state_reg,
10510                                                      parent_reg);
10511                         if (err < 0)
10512                                 return err;
10513                 }
10514         }
10515         return 0;
10516 }
10517
10518 /* find precise scalars in the previous equivalent state and
10519  * propagate them into the current state
10520  */
10521 static int propagate_precision(struct bpf_verifier_env *env,
10522                                const struct bpf_verifier_state *old)
10523 {
10524         struct bpf_reg_state *state_reg;
10525         struct bpf_func_state *state;
10526         int i, err = 0;
10527
10528         state = old->frame[old->curframe];
10529         state_reg = state->regs;
10530         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10531                 if (state_reg->type != SCALAR_VALUE ||
10532                     !state_reg->precise)
10533                         continue;
10534                 if (env->log.level & BPF_LOG_LEVEL2)
10535                         verbose(env, "propagating r%d\n", i);
10536                 err = mark_chain_precision(env, i);
10537                 if (err < 0)
10538                         return err;
10539         }
10540
10541         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10542                 if (state->stack[i].slot_type[0] != STACK_SPILL)
10543                         continue;
10544                 state_reg = &state->stack[i].spilled_ptr;
10545                 if (state_reg->type != SCALAR_VALUE ||
10546                     !state_reg->precise)
10547                         continue;
10548                 if (env->log.level & BPF_LOG_LEVEL2)
10549                         verbose(env, "propagating fp%d\n",
10550                                 (-i - 1) * BPF_REG_SIZE);
10551                 err = mark_chain_precision_stack(env, i);
10552                 if (err < 0)
10553                         return err;
10554         }
10555         return 0;
10556 }
10557
10558 static bool states_maybe_looping(struct bpf_verifier_state *old,
10559                                  struct bpf_verifier_state *cur)
10560 {
10561         struct bpf_func_state *fold, *fcur;
10562         int i, fr = cur->curframe;
10563
10564         if (old->curframe != fr)
10565                 return false;
10566
10567         fold = old->frame[fr];
10568         fcur = cur->frame[fr];
10569         for (i = 0; i < MAX_BPF_REG; i++)
10570                 if (memcmp(&fold->regs[i], &fcur->regs[i],
10571                            offsetof(struct bpf_reg_state, parent)))
10572                         return false;
10573         return true;
10574 }
10575
10576
10577 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10578 {
10579         struct bpf_verifier_state_list *new_sl;
10580         struct bpf_verifier_state_list *sl, **pprev;
10581         struct bpf_verifier_state *cur = env->cur_state, *new;
10582         int i, j, err, states_cnt = 0;
10583         bool add_new_state = env->test_state_freq ? true : false;
10584
10585         cur->last_insn_idx = env->prev_insn_idx;
10586         if (!env->insn_aux_data[insn_idx].prune_point)
10587                 /* this 'insn_idx' instruction wasn't marked, so we will not
10588                  * be doing state search here
10589                  */
10590                 return 0;
10591
10592         /* bpf progs typically have pruning point every 4 instructions
10593          * http://vger.kernel.org/bpfconf2019.html#session-1
10594          * Do not add new state for future pruning if the verifier hasn't seen
10595          * at least 2 jumps and at least 8 instructions.
10596          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10597          * In tests that amounts to up to 50% reduction into total verifier
10598          * memory consumption and 20% verifier time speedup.
10599          */
10600         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10601             env->insn_processed - env->prev_insn_processed >= 8)
10602                 add_new_state = true;
10603
10604         pprev = explored_state(env, insn_idx);
10605         sl = *pprev;
10606
10607         clean_live_states(env, insn_idx, cur);
10608
10609         while (sl) {
10610                 states_cnt++;
10611                 if (sl->state.insn_idx != insn_idx)
10612                         goto next;
10613
10614                 if (sl->state.branches) {
10615                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
10616
10617                         if (frame->in_async_callback_fn &&
10618                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
10619                                 /* Different async_entry_cnt means that the verifier is
10620                                  * processing another entry into async callback.
10621                                  * Seeing the same state is not an indication of infinite
10622                                  * loop or infinite recursion.
10623                                  * But finding the same state doesn't mean that it's safe
10624                                  * to stop processing the current state. The previous state
10625                                  * hasn't yet reached bpf_exit, since state.branches > 0.
10626                                  * Checking in_async_callback_fn alone is not enough either.
10627                                  * Since the verifier still needs to catch infinite loops
10628                                  * inside async callbacks.
10629                                  */
10630                         } else if (states_maybe_looping(&sl->state, cur) &&
10631                                    states_equal(env, &sl->state, cur)) {
10632                                 verbose_linfo(env, insn_idx, "; ");
10633                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10634                                 return -EINVAL;
10635                         }
10636                         /* if the verifier is processing a loop, avoid adding new state
10637                          * too often, since different loop iterations have distinct
10638                          * states and may not help future pruning.
10639                          * This threshold shouldn't be too low to make sure that
10640                          * a loop with large bound will be rejected quickly.
10641                          * The most abusive loop will be:
10642                          * r1 += 1
10643                          * if r1 < 1000000 goto pc-2
10644                          * 1M insn_procssed limit / 100 == 10k peak states.
10645                          * This threshold shouldn't be too high either, since states
10646                          * at the end of the loop are likely to be useful in pruning.
10647                          */
10648                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10649                             env->insn_processed - env->prev_insn_processed < 100)
10650                                 add_new_state = false;
10651                         goto miss;
10652                 }
10653                 if (states_equal(env, &sl->state, cur)) {
10654                         sl->hit_cnt++;
10655                         /* reached equivalent register/stack state,
10656                          * prune the search.
10657                          * Registers read by the continuation are read by us.
10658                          * If we have any write marks in env->cur_state, they
10659                          * will prevent corresponding reads in the continuation
10660                          * from reaching our parent (an explored_state).  Our
10661                          * own state will get the read marks recorded, but
10662                          * they'll be immediately forgotten as we're pruning
10663                          * this state and will pop a new one.
10664                          */
10665                         err = propagate_liveness(env, &sl->state, cur);
10666
10667                         /* if previous state reached the exit with precision and
10668                          * current state is equivalent to it (except precsion marks)
10669                          * the precision needs to be propagated back in
10670                          * the current state.
10671                          */
10672                         err = err ? : push_jmp_history(env, cur);
10673                         err = err ? : propagate_precision(env, &sl->state);
10674                         if (err)
10675                                 return err;
10676                         return 1;
10677                 }
10678 miss:
10679                 /* when new state is not going to be added do not increase miss count.
10680                  * Otherwise several loop iterations will remove the state
10681                  * recorded earlier. The goal of these heuristics is to have
10682                  * states from some iterations of the loop (some in the beginning
10683                  * and some at the end) to help pruning.
10684                  */
10685                 if (add_new_state)
10686                         sl->miss_cnt++;
10687                 /* heuristic to determine whether this state is beneficial
10688                  * to keep checking from state equivalence point of view.
10689                  * Higher numbers increase max_states_per_insn and verification time,
10690                  * but do not meaningfully decrease insn_processed.
10691                  */
10692                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10693                         /* the state is unlikely to be useful. Remove it to
10694                          * speed up verification
10695                          */
10696                         *pprev = sl->next;
10697                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10698                                 u32 br = sl->state.branches;
10699
10700                                 WARN_ONCE(br,
10701                                           "BUG live_done but branches_to_explore %d\n",
10702                                           br);
10703                                 free_verifier_state(&sl->state, false);
10704                                 kfree(sl);
10705                                 env->peak_states--;
10706                         } else {
10707                                 /* cannot free this state, since parentage chain may
10708                                  * walk it later. Add it for free_list instead to
10709                                  * be freed at the end of verification
10710                                  */
10711                                 sl->next = env->free_list;
10712                                 env->free_list = sl;
10713                         }
10714                         sl = *pprev;
10715                         continue;
10716                 }
10717 next:
10718                 pprev = &sl->next;
10719                 sl = *pprev;
10720         }
10721
10722         if (env->max_states_per_insn < states_cnt)
10723                 env->max_states_per_insn = states_cnt;
10724
10725         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10726                 return push_jmp_history(env, cur);
10727
10728         if (!add_new_state)
10729                 return push_jmp_history(env, cur);
10730
10731         /* There were no equivalent states, remember the current one.
10732          * Technically the current state is not proven to be safe yet,
10733          * but it will either reach outer most bpf_exit (which means it's safe)
10734          * or it will be rejected. When there are no loops the verifier won't be
10735          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
10736          * again on the way to bpf_exit.
10737          * When looping the sl->state.branches will be > 0 and this state
10738          * will not be considered for equivalence until branches == 0.
10739          */
10740         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10741         if (!new_sl)
10742                 return -ENOMEM;
10743         env->total_states++;
10744         env->peak_states++;
10745         env->prev_jmps_processed = env->jmps_processed;
10746         env->prev_insn_processed = env->insn_processed;
10747
10748         /* add new state to the head of linked list */
10749         new = &new_sl->state;
10750         err = copy_verifier_state(new, cur);
10751         if (err) {
10752                 free_verifier_state(new, false);
10753                 kfree(new_sl);
10754                 return err;
10755         }
10756         new->insn_idx = insn_idx;
10757         WARN_ONCE(new->branches != 1,
10758                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10759
10760         cur->parent = new;
10761         cur->first_insn_idx = insn_idx;
10762         clear_jmp_history(cur);
10763         new_sl->next = *explored_state(env, insn_idx);
10764         *explored_state(env, insn_idx) = new_sl;
10765         /* connect new state to parentage chain. Current frame needs all
10766          * registers connected. Only r6 - r9 of the callers are alive (pushed
10767          * to the stack implicitly by JITs) so in callers' frames connect just
10768          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10769          * the state of the call instruction (with WRITTEN set), and r0 comes
10770          * from callee with its full parentage chain, anyway.
10771          */
10772         /* clear write marks in current state: the writes we did are not writes
10773          * our child did, so they don't screen off its reads from us.
10774          * (There are no read marks in current state, because reads always mark
10775          * their parent and current state never has children yet.  Only
10776          * explored_states can get read marks.)
10777          */
10778         for (j = 0; j <= cur->curframe; j++) {
10779                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10780                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10781                 for (i = 0; i < BPF_REG_FP; i++)
10782                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10783         }
10784
10785         /* all stack frames are accessible from callee, clear them all */
10786         for (j = 0; j <= cur->curframe; j++) {
10787                 struct bpf_func_state *frame = cur->frame[j];
10788                 struct bpf_func_state *newframe = new->frame[j];
10789
10790                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10791                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10792                         frame->stack[i].spilled_ptr.parent =
10793                                                 &newframe->stack[i].spilled_ptr;
10794                 }
10795         }
10796         return 0;
10797 }
10798
10799 /* Return true if it's OK to have the same insn return a different type. */
10800 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10801 {
10802         switch (base_type(type)) {
10803         case PTR_TO_CTX:
10804         case PTR_TO_SOCKET:
10805         case PTR_TO_SOCK_COMMON:
10806         case PTR_TO_TCP_SOCK:
10807         case PTR_TO_XDP_SOCK:
10808         case PTR_TO_BTF_ID:
10809                 return false;
10810         default:
10811                 return true;
10812         }
10813 }
10814
10815 /* If an instruction was previously used with particular pointer types, then we
10816  * need to be careful to avoid cases such as the below, where it may be ok
10817  * for one branch accessing the pointer, but not ok for the other branch:
10818  *
10819  * R1 = sock_ptr
10820  * goto X;
10821  * ...
10822  * R1 = some_other_valid_ptr;
10823  * goto X;
10824  * ...
10825  * R2 = *(u32 *)(R1 + 0);
10826  */
10827 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10828 {
10829         return src != prev && (!reg_type_mismatch_ok(src) ||
10830                                !reg_type_mismatch_ok(prev));
10831 }
10832
10833 static int do_check(struct bpf_verifier_env *env)
10834 {
10835         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10836         struct bpf_verifier_state *state = env->cur_state;
10837         struct bpf_insn *insns = env->prog->insnsi;
10838         struct bpf_reg_state *regs;
10839         int insn_cnt = env->prog->len;
10840         bool do_print_state = false;
10841         int prev_insn_idx = -1;
10842
10843         for (;;) {
10844                 struct bpf_insn *insn;
10845                 u8 class;
10846                 int err;
10847
10848                 env->prev_insn_idx = prev_insn_idx;
10849                 if (env->insn_idx >= insn_cnt) {
10850                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
10851                                 env->insn_idx, insn_cnt);
10852                         return -EFAULT;
10853                 }
10854
10855                 insn = &insns[env->insn_idx];
10856                 class = BPF_CLASS(insn->code);
10857
10858                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10859                         verbose(env,
10860                                 "BPF program is too large. Processed %d insn\n",
10861                                 env->insn_processed);
10862                         return -E2BIG;
10863                 }
10864
10865                 err = is_state_visited(env, env->insn_idx);
10866                 if (err < 0)
10867                         return err;
10868                 if (err == 1) {
10869                         /* found equivalent state, can prune the search */
10870                         if (env->log.level & BPF_LOG_LEVEL) {
10871                                 if (do_print_state)
10872                                         verbose(env, "\nfrom %d to %d%s: safe\n",
10873                                                 env->prev_insn_idx, env->insn_idx,
10874                                                 env->cur_state->speculative ?
10875                                                 " (speculative execution)" : "");
10876                                 else
10877                                         verbose(env, "%d: safe\n", env->insn_idx);
10878                         }
10879                         goto process_bpf_exit;
10880                 }
10881
10882                 if (signal_pending(current))
10883                         return -EAGAIN;
10884
10885                 if (need_resched())
10886                         cond_resched();
10887
10888                 if (env->log.level & BPF_LOG_LEVEL2 ||
10889                     (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10890                         if (env->log.level & BPF_LOG_LEVEL2)
10891                                 verbose(env, "%d:", env->insn_idx);
10892                         else
10893                                 verbose(env, "\nfrom %d to %d%s:",
10894                                         env->prev_insn_idx, env->insn_idx,
10895                                         env->cur_state->speculative ?
10896                                         " (speculative execution)" : "");
10897                         print_verifier_state(env, state->frame[state->curframe]);
10898                         do_print_state = false;
10899                 }
10900
10901                 if (env->log.level & BPF_LOG_LEVEL) {
10902                         const struct bpf_insn_cbs cbs = {
10903                                 .cb_call        = disasm_kfunc_name,
10904                                 .cb_print       = verbose,
10905                                 .private_data   = env,
10906                         };
10907
10908                         verbose_linfo(env, env->insn_idx, "; ");
10909                         verbose(env, "%d: ", env->insn_idx);
10910                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10911                 }
10912
10913                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10914                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10915                                                            env->prev_insn_idx);
10916                         if (err)
10917                                 return err;
10918                 }
10919
10920                 regs = cur_regs(env);
10921                 sanitize_mark_insn_seen(env);
10922                 prev_insn_idx = env->insn_idx;
10923
10924                 if (class == BPF_ALU || class == BPF_ALU64) {
10925                         err = check_alu_op(env, insn);
10926                         if (err)
10927                                 return err;
10928
10929                 } else if (class == BPF_LDX) {
10930                         enum bpf_reg_type *prev_src_type, src_reg_type;
10931
10932                         /* check for reserved fields is already done */
10933
10934                         /* check src operand */
10935                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10936                         if (err)
10937                                 return err;
10938
10939                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10940                         if (err)
10941                                 return err;
10942
10943                         src_reg_type = regs[insn->src_reg].type;
10944
10945                         /* check that memory (src_reg + off) is readable,
10946                          * the state of dst_reg will be updated by this func
10947                          */
10948                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
10949                                                insn->off, BPF_SIZE(insn->code),
10950                                                BPF_READ, insn->dst_reg, false);
10951                         if (err)
10952                                 return err;
10953
10954                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10955
10956                         if (*prev_src_type == NOT_INIT) {
10957                                 /* saw a valid insn
10958                                  * dst_reg = *(u32 *)(src_reg + off)
10959                                  * save type to validate intersecting paths
10960                                  */
10961                                 *prev_src_type = src_reg_type;
10962
10963                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10964                                 /* ABuser program is trying to use the same insn
10965                                  * dst_reg = *(u32*) (src_reg + off)
10966                                  * with different pointer types:
10967                                  * src_reg == ctx in one branch and
10968                                  * src_reg == stack|map in some other branch.
10969                                  * Reject it.
10970                                  */
10971                                 verbose(env, "same insn cannot be used with different pointers\n");
10972                                 return -EINVAL;
10973                         }
10974
10975                 } else if (class == BPF_STX) {
10976                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
10977
10978                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10979                                 err = check_atomic(env, env->insn_idx, insn);
10980                                 if (err)
10981                                         return err;
10982                                 env->insn_idx++;
10983                                 continue;
10984                         }
10985
10986                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10987                                 verbose(env, "BPF_STX uses reserved fields\n");
10988                                 return -EINVAL;
10989                         }
10990
10991                         /* check src1 operand */
10992                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10993                         if (err)
10994                                 return err;
10995                         /* check src2 operand */
10996                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10997                         if (err)
10998                                 return err;
10999
11000                         dst_reg_type = regs[insn->dst_reg].type;
11001
11002                         /* check that memory (dst_reg + off) is writeable */
11003                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11004                                                insn->off, BPF_SIZE(insn->code),
11005                                                BPF_WRITE, insn->src_reg, false);
11006                         if (err)
11007                                 return err;
11008
11009                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11010
11011                         if (*prev_dst_type == NOT_INIT) {
11012                                 *prev_dst_type = dst_reg_type;
11013                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11014                                 verbose(env, "same insn cannot be used with different pointers\n");
11015                                 return -EINVAL;
11016                         }
11017
11018                 } else if (class == BPF_ST) {
11019                         if (BPF_MODE(insn->code) != BPF_MEM ||
11020                             insn->src_reg != BPF_REG_0) {
11021                                 verbose(env, "BPF_ST uses reserved fields\n");
11022                                 return -EINVAL;
11023                         }
11024                         /* check src operand */
11025                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11026                         if (err)
11027                                 return err;
11028
11029                         if (is_ctx_reg(env, insn->dst_reg)) {
11030                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11031                                         insn->dst_reg,
11032                                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
11033                                 return -EACCES;
11034                         }
11035
11036                         /* check that memory (dst_reg + off) is writeable */
11037                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11038                                                insn->off, BPF_SIZE(insn->code),
11039                                                BPF_WRITE, -1, false);
11040                         if (err)
11041                                 return err;
11042
11043                 } else if (class == BPF_JMP || class == BPF_JMP32) {
11044                         u8 opcode = BPF_OP(insn->code);
11045
11046                         env->jmps_processed++;
11047                         if (opcode == BPF_CALL) {
11048                                 if (BPF_SRC(insn->code) != BPF_K ||
11049                                     insn->off != 0 ||
11050                                     (insn->src_reg != BPF_REG_0 &&
11051                                      insn->src_reg != BPF_PSEUDO_CALL &&
11052                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11053                                     insn->dst_reg != BPF_REG_0 ||
11054                                     class == BPF_JMP32) {
11055                                         verbose(env, "BPF_CALL uses reserved fields\n");
11056                                         return -EINVAL;
11057                                 }
11058
11059                                 if (env->cur_state->active_spin_lock &&
11060                                     (insn->src_reg == BPF_PSEUDO_CALL ||
11061                                      insn->imm != BPF_FUNC_spin_unlock)) {
11062                                         verbose(env, "function calls are not allowed while holding a lock\n");
11063                                         return -EINVAL;
11064                                 }
11065                                 if (insn->src_reg == BPF_PSEUDO_CALL)
11066                                         err = check_func_call(env, insn, &env->insn_idx);
11067                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11068                                         err = check_kfunc_call(env, insn);
11069                                 else
11070                                         err = check_helper_call(env, insn, &env->insn_idx);
11071                                 if (err)
11072                                         return err;
11073                         } else if (opcode == BPF_JA) {
11074                                 if (BPF_SRC(insn->code) != BPF_K ||
11075                                     insn->imm != 0 ||
11076                                     insn->src_reg != BPF_REG_0 ||
11077                                     insn->dst_reg != BPF_REG_0 ||
11078                                     class == BPF_JMP32) {
11079                                         verbose(env, "BPF_JA uses reserved fields\n");
11080                                         return -EINVAL;
11081                                 }
11082
11083                                 env->insn_idx += insn->off + 1;
11084                                 continue;
11085
11086                         } else if (opcode == BPF_EXIT) {
11087                                 if (BPF_SRC(insn->code) != BPF_K ||
11088                                     insn->imm != 0 ||
11089                                     insn->src_reg != BPF_REG_0 ||
11090                                     insn->dst_reg != BPF_REG_0 ||
11091                                     class == BPF_JMP32) {
11092                                         verbose(env, "BPF_EXIT uses reserved fields\n");
11093                                         return -EINVAL;
11094                                 }
11095
11096                                 if (env->cur_state->active_spin_lock) {
11097                                         verbose(env, "bpf_spin_unlock is missing\n");
11098                                         return -EINVAL;
11099                                 }
11100
11101                                 /* We must do check_reference_leak here before
11102                                  * prepare_func_exit to handle the case when
11103                                  * state->curframe > 0, it may be a callback
11104                                  * function, for which reference_state must
11105                                  * match caller reference state when it exits.
11106                                  */
11107                                 err = check_reference_leak(env);
11108                                 if (err)
11109                                         return err;
11110
11111                                 if (state->curframe) {
11112                                         /* exit from nested function */
11113                                         err = prepare_func_exit(env, &env->insn_idx);
11114                                         if (err)
11115                                                 return err;
11116                                         do_print_state = true;
11117                                         continue;
11118                                 }
11119
11120                                 err = check_return_code(env);
11121                                 if (err)
11122                                         return err;
11123 process_bpf_exit:
11124                                 update_branch_counts(env, env->cur_state);
11125                                 err = pop_stack(env, &prev_insn_idx,
11126                                                 &env->insn_idx, pop_log);
11127                                 if (err < 0) {
11128                                         if (err != -ENOENT)
11129                                                 return err;
11130                                         break;
11131                                 } else {
11132                                         do_print_state = true;
11133                                         continue;
11134                                 }
11135                         } else {
11136                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
11137                                 if (err)
11138                                         return err;
11139                         }
11140                 } else if (class == BPF_LD) {
11141                         u8 mode = BPF_MODE(insn->code);
11142
11143                         if (mode == BPF_ABS || mode == BPF_IND) {
11144                                 err = check_ld_abs(env, insn);
11145                                 if (err)
11146                                         return err;
11147
11148                         } else if (mode == BPF_IMM) {
11149                                 err = check_ld_imm(env, insn);
11150                                 if (err)
11151                                         return err;
11152
11153                                 env->insn_idx++;
11154                                 sanitize_mark_insn_seen(env);
11155                         } else {
11156                                 verbose(env, "invalid BPF_LD mode\n");
11157                                 return -EINVAL;
11158                         }
11159                 } else {
11160                         verbose(env, "unknown insn class %d\n", class);
11161                         return -EINVAL;
11162                 }
11163
11164                 env->insn_idx++;
11165         }
11166
11167         return 0;
11168 }
11169
11170 static int find_btf_percpu_datasec(struct btf *btf)
11171 {
11172         const struct btf_type *t;
11173         const char *tname;
11174         int i, n;
11175
11176         /*
11177          * Both vmlinux and module each have their own ".data..percpu"
11178          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11179          * types to look at only module's own BTF types.
11180          */
11181         n = btf_nr_types(btf);
11182         if (btf_is_module(btf))
11183                 i = btf_nr_types(btf_vmlinux);
11184         else
11185                 i = 1;
11186
11187         for(; i < n; i++) {
11188                 t = btf_type_by_id(btf, i);
11189                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11190                         continue;
11191
11192                 tname = btf_name_by_offset(btf, t->name_off);
11193                 if (!strcmp(tname, ".data..percpu"))
11194                         return i;
11195         }
11196
11197         return -ENOENT;
11198 }
11199
11200 /* replace pseudo btf_id with kernel symbol address */
11201 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11202                                struct bpf_insn *insn,
11203                                struct bpf_insn_aux_data *aux)
11204 {
11205         const struct btf_var_secinfo *vsi;
11206         const struct btf_type *datasec;
11207         struct btf_mod_pair *btf_mod;
11208         const struct btf_type *t;
11209         const char *sym_name;
11210         bool percpu = false;
11211         u32 type, id = insn->imm;
11212         struct btf *btf;
11213         s32 datasec_id;
11214         u64 addr;
11215         int i, btf_fd, err;
11216
11217         btf_fd = insn[1].imm;
11218         if (btf_fd) {
11219                 btf = btf_get_by_fd(btf_fd);
11220                 if (IS_ERR(btf)) {
11221                         verbose(env, "invalid module BTF object FD specified.\n");
11222                         return -EINVAL;
11223                 }
11224         } else {
11225                 if (!btf_vmlinux) {
11226                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11227                         return -EINVAL;
11228                 }
11229                 btf = btf_vmlinux;
11230                 btf_get(btf);
11231         }
11232
11233         t = btf_type_by_id(btf, id);
11234         if (!t) {
11235                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11236                 err = -ENOENT;
11237                 goto err_put;
11238         }
11239
11240         if (!btf_type_is_var(t)) {
11241                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11242                 err = -EINVAL;
11243                 goto err_put;
11244         }
11245
11246         sym_name = btf_name_by_offset(btf, t->name_off);
11247         addr = kallsyms_lookup_name(sym_name);
11248         if (!addr) {
11249                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11250                         sym_name);
11251                 err = -ENOENT;
11252                 goto err_put;
11253         }
11254
11255         datasec_id = find_btf_percpu_datasec(btf);
11256         if (datasec_id > 0) {
11257                 datasec = btf_type_by_id(btf, datasec_id);
11258                 for_each_vsi(i, datasec, vsi) {
11259                         if (vsi->type == id) {
11260                                 percpu = true;
11261                                 break;
11262                         }
11263                 }
11264         }
11265
11266         insn[0].imm = (u32)addr;
11267         insn[1].imm = addr >> 32;
11268
11269         type = t->type;
11270         t = btf_type_skip_modifiers(btf, type, NULL);
11271         if (percpu) {
11272                 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11273                 aux->btf_var.btf = btf;
11274                 aux->btf_var.btf_id = type;
11275         } else if (!btf_type_is_struct(t)) {
11276                 const struct btf_type *ret;
11277                 const char *tname;
11278                 u32 tsize;
11279
11280                 /* resolve the type size of ksym. */
11281                 ret = btf_resolve_size(btf, t, &tsize);
11282                 if (IS_ERR(ret)) {
11283                         tname = btf_name_by_offset(btf, t->name_off);
11284                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11285                                 tname, PTR_ERR(ret));
11286                         err = -EINVAL;
11287                         goto err_put;
11288                 }
11289                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
11290                 aux->btf_var.mem_size = tsize;
11291         } else {
11292                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
11293                 aux->btf_var.btf = btf;
11294                 aux->btf_var.btf_id = type;
11295         }
11296
11297         /* check whether we recorded this BTF (and maybe module) already */
11298         for (i = 0; i < env->used_btf_cnt; i++) {
11299                 if (env->used_btfs[i].btf == btf) {
11300                         btf_put(btf);
11301                         return 0;
11302                 }
11303         }
11304
11305         if (env->used_btf_cnt >= MAX_USED_BTFS) {
11306                 err = -E2BIG;
11307                 goto err_put;
11308         }
11309
11310         btf_mod = &env->used_btfs[env->used_btf_cnt];
11311         btf_mod->btf = btf;
11312         btf_mod->module = NULL;
11313
11314         /* if we reference variables from kernel module, bump its refcount */
11315         if (btf_is_module(btf)) {
11316                 btf_mod->module = btf_try_get_module(btf);
11317                 if (!btf_mod->module) {
11318                         err = -ENXIO;
11319                         goto err_put;
11320                 }
11321         }
11322
11323         env->used_btf_cnt++;
11324
11325         return 0;
11326 err_put:
11327         btf_put(btf);
11328         return err;
11329 }
11330
11331 static int check_map_prealloc(struct bpf_map *map)
11332 {
11333         return (map->map_type != BPF_MAP_TYPE_HASH &&
11334                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11335                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11336                 !(map->map_flags & BPF_F_NO_PREALLOC);
11337 }
11338
11339 static bool is_tracing_prog_type(enum bpf_prog_type type)
11340 {
11341         switch (type) {
11342         case BPF_PROG_TYPE_KPROBE:
11343         case BPF_PROG_TYPE_TRACEPOINT:
11344         case BPF_PROG_TYPE_PERF_EVENT:
11345         case BPF_PROG_TYPE_RAW_TRACEPOINT:
11346                 return true;
11347         default:
11348                 return false;
11349         }
11350 }
11351
11352 static bool is_preallocated_map(struct bpf_map *map)
11353 {
11354         if (!check_map_prealloc(map))
11355                 return false;
11356         if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11357                 return false;
11358         return true;
11359 }
11360
11361 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11362                                         struct bpf_map *map,
11363                                         struct bpf_prog *prog)
11364
11365 {
11366         enum bpf_prog_type prog_type = resolve_prog_type(prog);
11367         /*
11368          * Validate that trace type programs use preallocated hash maps.
11369          *
11370          * For programs attached to PERF events this is mandatory as the
11371          * perf NMI can hit any arbitrary code sequence.
11372          *
11373          * All other trace types using preallocated hash maps are unsafe as
11374          * well because tracepoint or kprobes can be inside locked regions
11375          * of the memory allocator or at a place where a recursion into the
11376          * memory allocator would see inconsistent state.
11377          *
11378          * On RT enabled kernels run-time allocation of all trace type
11379          * programs is strictly prohibited due to lock type constraints. On
11380          * !RT kernels it is allowed for backwards compatibility reasons for
11381          * now, but warnings are emitted so developers are made aware of
11382          * the unsafety and can fix their programs before this is enforced.
11383          */
11384         if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11385                 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11386                         verbose(env, "perf_event programs can only use preallocated hash map\n");
11387                         return -EINVAL;
11388                 }
11389                 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11390                         verbose(env, "trace type programs can only use preallocated hash map\n");
11391                         return -EINVAL;
11392                 }
11393                 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11394                 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11395         }
11396
11397         if (map_value_has_spin_lock(map)) {
11398                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11399                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11400                         return -EINVAL;
11401                 }
11402
11403                 if (is_tracing_prog_type(prog_type)) {
11404                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11405                         return -EINVAL;
11406                 }
11407
11408                 if (prog->aux->sleepable) {
11409                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11410                         return -EINVAL;
11411                 }
11412         }
11413
11414         if (map_value_has_timer(map)) {
11415                 if (is_tracing_prog_type(prog_type)) {
11416                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
11417                         return -EINVAL;
11418                 }
11419         }
11420
11421         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11422             !bpf_offload_prog_map_match(prog, map)) {
11423                 verbose(env, "offload device mismatch between prog and map\n");
11424                 return -EINVAL;
11425         }
11426
11427         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11428                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11429                 return -EINVAL;
11430         }
11431
11432         if (prog->aux->sleepable)
11433                 switch (map->map_type) {
11434                 case BPF_MAP_TYPE_HASH:
11435                 case BPF_MAP_TYPE_LRU_HASH:
11436                 case BPF_MAP_TYPE_ARRAY:
11437                 case BPF_MAP_TYPE_PERCPU_HASH:
11438                 case BPF_MAP_TYPE_PERCPU_ARRAY:
11439                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11440                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11441                 case BPF_MAP_TYPE_HASH_OF_MAPS:
11442                         if (!is_preallocated_map(map)) {
11443                                 verbose(env,
11444                                         "Sleepable programs can only use preallocated maps\n");
11445                                 return -EINVAL;
11446                         }
11447                         break;
11448                 case BPF_MAP_TYPE_RINGBUF:
11449                         break;
11450                 default:
11451                         verbose(env,
11452                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
11453                         return -EINVAL;
11454                 }
11455
11456         return 0;
11457 }
11458
11459 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11460 {
11461         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11462                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11463 }
11464
11465 /* find and rewrite pseudo imm in ld_imm64 instructions:
11466  *
11467  * 1. if it accesses map FD, replace it with actual map pointer.
11468  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11469  *
11470  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11471  */
11472 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11473 {
11474         struct bpf_insn *insn = env->prog->insnsi;
11475         int insn_cnt = env->prog->len;
11476         int i, j, err;
11477
11478         err = bpf_prog_calc_tag(env->prog);
11479         if (err)
11480                 return err;
11481
11482         for (i = 0; i < insn_cnt; i++, insn++) {
11483                 if (BPF_CLASS(insn->code) == BPF_LDX &&
11484                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11485                         verbose(env, "BPF_LDX uses reserved fields\n");
11486                         return -EINVAL;
11487                 }
11488
11489                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11490                         struct bpf_insn_aux_data *aux;
11491                         struct bpf_map *map;
11492                         struct fd f;
11493                         u64 addr;
11494                         u32 fd;
11495
11496                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
11497                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11498                             insn[1].off != 0) {
11499                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
11500                                 return -EINVAL;
11501                         }
11502
11503                         if (insn[0].src_reg == 0)
11504                                 /* valid generic load 64-bit imm */
11505                                 goto next_insn;
11506
11507                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11508                                 aux = &env->insn_aux_data[i];
11509                                 err = check_pseudo_btf_id(env, insn, aux);
11510                                 if (err)
11511                                         return err;
11512                                 goto next_insn;
11513                         }
11514
11515                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11516                                 aux = &env->insn_aux_data[i];
11517                                 aux->ptr_type = PTR_TO_FUNC;
11518                                 goto next_insn;
11519                         }
11520
11521                         /* In final convert_pseudo_ld_imm64() step, this is
11522                          * converted into regular 64-bit imm load insn.
11523                          */
11524                         switch (insn[0].src_reg) {
11525                         case BPF_PSEUDO_MAP_VALUE:
11526                         case BPF_PSEUDO_MAP_IDX_VALUE:
11527                                 break;
11528                         case BPF_PSEUDO_MAP_FD:
11529                         case BPF_PSEUDO_MAP_IDX:
11530                                 if (insn[1].imm == 0)
11531                                         break;
11532                                 fallthrough;
11533                         default:
11534                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11535                                 return -EINVAL;
11536                         }
11537
11538                         switch (insn[0].src_reg) {
11539                         case BPF_PSEUDO_MAP_IDX_VALUE:
11540                         case BPF_PSEUDO_MAP_IDX:
11541                                 if (bpfptr_is_null(env->fd_array)) {
11542                                         verbose(env, "fd_idx without fd_array is invalid\n");
11543                                         return -EPROTO;
11544                                 }
11545                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
11546                                                             insn[0].imm * sizeof(fd),
11547                                                             sizeof(fd)))
11548                                         return -EFAULT;
11549                                 break;
11550                         default:
11551                                 fd = insn[0].imm;
11552                                 break;
11553                         }
11554
11555                         f = fdget(fd);
11556                         map = __bpf_map_get(f);
11557                         if (IS_ERR(map)) {
11558                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
11559                                         insn[0].imm);
11560                                 return PTR_ERR(map);
11561                         }
11562
11563                         err = check_map_prog_compatibility(env, map, env->prog);
11564                         if (err) {
11565                                 fdput(f);
11566                                 return err;
11567                         }
11568
11569                         aux = &env->insn_aux_data[i];
11570                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11571                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11572                                 addr = (unsigned long)map;
11573                         } else {
11574                                 u32 off = insn[1].imm;
11575
11576                                 if (off >= BPF_MAX_VAR_OFF) {
11577                                         verbose(env, "direct value offset of %u is not allowed\n", off);
11578                                         fdput(f);
11579                                         return -EINVAL;
11580                                 }
11581
11582                                 if (!map->ops->map_direct_value_addr) {
11583                                         verbose(env, "no direct value access support for this map type\n");
11584                                         fdput(f);
11585                                         return -EINVAL;
11586                                 }
11587
11588                                 err = map->ops->map_direct_value_addr(map, &addr, off);
11589                                 if (err) {
11590                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11591                                                 map->value_size, off);
11592                                         fdput(f);
11593                                         return err;
11594                                 }
11595
11596                                 aux->map_off = off;
11597                                 addr += off;
11598                         }
11599
11600                         insn[0].imm = (u32)addr;
11601                         insn[1].imm = addr >> 32;
11602
11603                         /* check whether we recorded this map already */
11604                         for (j = 0; j < env->used_map_cnt; j++) {
11605                                 if (env->used_maps[j] == map) {
11606                                         aux->map_index = j;
11607                                         fdput(f);
11608                                         goto next_insn;
11609                                 }
11610                         }
11611
11612                         if (env->used_map_cnt >= MAX_USED_MAPS) {
11613                                 fdput(f);
11614                                 return -E2BIG;
11615                         }
11616
11617                         /* hold the map. If the program is rejected by verifier,
11618                          * the map will be released by release_maps() or it
11619                          * will be used by the valid program until it's unloaded
11620                          * and all maps are released in free_used_maps()
11621                          */
11622                         bpf_map_inc(map);
11623
11624                         aux->map_index = env->used_map_cnt;
11625                         env->used_maps[env->used_map_cnt++] = map;
11626
11627                         if (bpf_map_is_cgroup_storage(map) &&
11628                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
11629                                 verbose(env, "only one cgroup storage of each type is allowed\n");
11630                                 fdput(f);
11631                                 return -EBUSY;
11632                         }
11633
11634                         fdput(f);
11635 next_insn:
11636                         insn++;
11637                         i++;
11638                         continue;
11639                 }
11640
11641                 /* Basic sanity check before we invest more work here. */
11642                 if (!bpf_opcode_in_insntable(insn->code)) {
11643                         verbose(env, "unknown opcode %02x\n", insn->code);
11644                         return -EINVAL;
11645                 }
11646         }
11647
11648         /* now all pseudo BPF_LD_IMM64 instructions load valid
11649          * 'struct bpf_map *' into a register instead of user map_fd.
11650          * These pointers will be used later by verifier to validate map access.
11651          */
11652         return 0;
11653 }
11654
11655 /* drop refcnt of maps used by the rejected program */
11656 static void release_maps(struct bpf_verifier_env *env)
11657 {
11658         __bpf_free_used_maps(env->prog->aux, env->used_maps,
11659                              env->used_map_cnt);
11660 }
11661
11662 /* drop refcnt of maps used by the rejected program */
11663 static void release_btfs(struct bpf_verifier_env *env)
11664 {
11665         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11666                              env->used_btf_cnt);
11667 }
11668
11669 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11670 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11671 {
11672         struct bpf_insn *insn = env->prog->insnsi;
11673         int insn_cnt = env->prog->len;
11674         int i;
11675
11676         for (i = 0; i < insn_cnt; i++, insn++) {
11677                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11678                         continue;
11679                 if (insn->src_reg == BPF_PSEUDO_FUNC)
11680                         continue;
11681                 insn->src_reg = 0;
11682         }
11683 }
11684
11685 /* single env->prog->insni[off] instruction was replaced with the range
11686  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11687  * [0, off) and [off, end) to new locations, so the patched range stays zero
11688  */
11689 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
11690                                  struct bpf_insn_aux_data *new_data,
11691                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
11692 {
11693         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
11694         struct bpf_insn *insn = new_prog->insnsi;
11695         u32 old_seen = old_data[off].seen;
11696         u32 prog_len;
11697         int i;
11698
11699         /* aux info at OFF always needs adjustment, no matter fast path
11700          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11701          * original insn at old prog.
11702          */
11703         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11704
11705         if (cnt == 1)
11706                 return;
11707         prog_len = new_prog->len;
11708
11709         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11710         memcpy(new_data + off + cnt - 1, old_data + off,
11711                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11712         for (i = off; i < off + cnt - 1; i++) {
11713                 /* Expand insni[off]'s seen count to the patched range. */
11714                 new_data[i].seen = old_seen;
11715                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11716         }
11717         env->insn_aux_data = new_data;
11718         vfree(old_data);
11719 }
11720
11721 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11722 {
11723         int i;
11724
11725         if (len == 1)
11726                 return;
11727         /* NOTE: fake 'exit' subprog should be updated as well. */
11728         for (i = 0; i <= env->subprog_cnt; i++) {
11729                 if (env->subprog_info[i].start <= off)
11730                         continue;
11731                 env->subprog_info[i].start += len - 1;
11732         }
11733 }
11734
11735 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
11736 {
11737         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11738         int i, sz = prog->aux->size_poke_tab;
11739         struct bpf_jit_poke_descriptor *desc;
11740
11741         for (i = 0; i < sz; i++) {
11742                 desc = &tab[i];
11743                 if (desc->insn_idx <= off)
11744                         continue;
11745                 desc->insn_idx += len - 1;
11746         }
11747 }
11748
11749 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11750                                             const struct bpf_insn *patch, u32 len)
11751 {
11752         struct bpf_prog *new_prog;
11753         struct bpf_insn_aux_data *new_data = NULL;
11754
11755         if (len > 1) {
11756                 new_data = vzalloc(array_size(env->prog->len + len - 1,
11757                                               sizeof(struct bpf_insn_aux_data)));
11758                 if (!new_data)
11759                         return NULL;
11760         }
11761
11762         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
11763         if (IS_ERR(new_prog)) {
11764                 if (PTR_ERR(new_prog) == -ERANGE)
11765                         verbose(env,
11766                                 "insn %d cannot be patched due to 16-bit range\n",
11767                                 env->insn_aux_data[off].orig_idx);
11768                 vfree(new_data);
11769                 return NULL;
11770         }
11771         adjust_insn_aux_data(env, new_data, new_prog, off, len);
11772         adjust_subprog_starts(env, off, len);
11773         adjust_poke_descs(new_prog, off, len);
11774         return new_prog;
11775 }
11776
11777 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11778                                               u32 off, u32 cnt)
11779 {
11780         int i, j;
11781
11782         /* find first prog starting at or after off (first to remove) */
11783         for (i = 0; i < env->subprog_cnt; i++)
11784                 if (env->subprog_info[i].start >= off)
11785                         break;
11786         /* find first prog starting at or after off + cnt (first to stay) */
11787         for (j = i; j < env->subprog_cnt; j++)
11788                 if (env->subprog_info[j].start >= off + cnt)
11789                         break;
11790         /* if j doesn't start exactly at off + cnt, we are just removing
11791          * the front of previous prog
11792          */
11793         if (env->subprog_info[j].start != off + cnt)
11794                 j--;
11795
11796         if (j > i) {
11797                 struct bpf_prog_aux *aux = env->prog->aux;
11798                 int move;
11799
11800                 /* move fake 'exit' subprog as well */
11801                 move = env->subprog_cnt + 1 - j;
11802
11803                 memmove(env->subprog_info + i,
11804                         env->subprog_info + j,
11805                         sizeof(*env->subprog_info) * move);
11806                 env->subprog_cnt -= j - i;
11807
11808                 /* remove func_info */
11809                 if (aux->func_info) {
11810                         move = aux->func_info_cnt - j;
11811
11812                         memmove(aux->func_info + i,
11813                                 aux->func_info + j,
11814                                 sizeof(*aux->func_info) * move);
11815                         aux->func_info_cnt -= j - i;
11816                         /* func_info->insn_off is set after all code rewrites,
11817                          * in adjust_btf_func() - no need to adjust
11818                          */
11819                 }
11820         } else {
11821                 /* convert i from "first prog to remove" to "first to adjust" */
11822                 if (env->subprog_info[i].start == off)
11823                         i++;
11824         }
11825
11826         /* update fake 'exit' subprog as well */
11827         for (; i <= env->subprog_cnt; i++)
11828                 env->subprog_info[i].start -= cnt;
11829
11830         return 0;
11831 }
11832
11833 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11834                                       u32 cnt)
11835 {
11836         struct bpf_prog *prog = env->prog;
11837         u32 i, l_off, l_cnt, nr_linfo;
11838         struct bpf_line_info *linfo;
11839
11840         nr_linfo = prog->aux->nr_linfo;
11841         if (!nr_linfo)
11842                 return 0;
11843
11844         linfo = prog->aux->linfo;
11845
11846         /* find first line info to remove, count lines to be removed */
11847         for (i = 0; i < nr_linfo; i++)
11848                 if (linfo[i].insn_off >= off)
11849                         break;
11850
11851         l_off = i;
11852         l_cnt = 0;
11853         for (; i < nr_linfo; i++)
11854                 if (linfo[i].insn_off < off + cnt)
11855                         l_cnt++;
11856                 else
11857                         break;
11858
11859         /* First live insn doesn't match first live linfo, it needs to "inherit"
11860          * last removed linfo.  prog is already modified, so prog->len == off
11861          * means no live instructions after (tail of the program was removed).
11862          */
11863         if (prog->len != off && l_cnt &&
11864             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11865                 l_cnt--;
11866                 linfo[--i].insn_off = off + cnt;
11867         }
11868
11869         /* remove the line info which refer to the removed instructions */
11870         if (l_cnt) {
11871                 memmove(linfo + l_off, linfo + i,
11872                         sizeof(*linfo) * (nr_linfo - i));
11873
11874                 prog->aux->nr_linfo -= l_cnt;
11875                 nr_linfo = prog->aux->nr_linfo;
11876         }
11877
11878         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11879         for (i = l_off; i < nr_linfo; i++)
11880                 linfo[i].insn_off -= cnt;
11881
11882         /* fix up all subprogs (incl. 'exit') which start >= off */
11883         for (i = 0; i <= env->subprog_cnt; i++)
11884                 if (env->subprog_info[i].linfo_idx > l_off) {
11885                         /* program may have started in the removed region but
11886                          * may not be fully removed
11887                          */
11888                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11889                                 env->subprog_info[i].linfo_idx -= l_cnt;
11890                         else
11891                                 env->subprog_info[i].linfo_idx = l_off;
11892                 }
11893
11894         return 0;
11895 }
11896
11897 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11898 {
11899         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11900         unsigned int orig_prog_len = env->prog->len;
11901         int err;
11902
11903         if (bpf_prog_is_dev_bound(env->prog->aux))
11904                 bpf_prog_offload_remove_insns(env, off, cnt);
11905
11906         err = bpf_remove_insns(env->prog, off, cnt);
11907         if (err)
11908                 return err;
11909
11910         err = adjust_subprog_starts_after_remove(env, off, cnt);
11911         if (err)
11912                 return err;
11913
11914         err = bpf_adj_linfo_after_remove(env, off, cnt);
11915         if (err)
11916                 return err;
11917
11918         memmove(aux_data + off, aux_data + off + cnt,
11919                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11920
11921         return 0;
11922 }
11923
11924 /* The verifier does more data flow analysis than llvm and will not
11925  * explore branches that are dead at run time. Malicious programs can
11926  * have dead code too. Therefore replace all dead at-run-time code
11927  * with 'ja -1'.
11928  *
11929  * Just nops are not optimal, e.g. if they would sit at the end of the
11930  * program and through another bug we would manage to jump there, then
11931  * we'd execute beyond program memory otherwise. Returning exception
11932  * code also wouldn't work since we can have subprogs where the dead
11933  * code could be located.
11934  */
11935 static void sanitize_dead_code(struct bpf_verifier_env *env)
11936 {
11937         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11938         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11939         struct bpf_insn *insn = env->prog->insnsi;
11940         const int insn_cnt = env->prog->len;
11941         int i;
11942
11943         for (i = 0; i < insn_cnt; i++) {
11944                 if (aux_data[i].seen)
11945                         continue;
11946                 memcpy(insn + i, &trap, sizeof(trap));
11947                 aux_data[i].zext_dst = false;
11948         }
11949 }
11950
11951 static bool insn_is_cond_jump(u8 code)
11952 {
11953         u8 op;
11954
11955         if (BPF_CLASS(code) == BPF_JMP32)
11956                 return true;
11957
11958         if (BPF_CLASS(code) != BPF_JMP)
11959                 return false;
11960
11961         op = BPF_OP(code);
11962         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11963 }
11964
11965 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11966 {
11967         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11968         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11969         struct bpf_insn *insn = env->prog->insnsi;
11970         const int insn_cnt = env->prog->len;
11971         int i;
11972
11973         for (i = 0; i < insn_cnt; i++, insn++) {
11974                 if (!insn_is_cond_jump(insn->code))
11975                         continue;
11976
11977                 if (!aux_data[i + 1].seen)
11978                         ja.off = insn->off;
11979                 else if (!aux_data[i + 1 + insn->off].seen)
11980                         ja.off = 0;
11981                 else
11982                         continue;
11983
11984                 if (bpf_prog_is_dev_bound(env->prog->aux))
11985                         bpf_prog_offload_replace_insn(env, i, &ja);
11986
11987                 memcpy(insn, &ja, sizeof(ja));
11988         }
11989 }
11990
11991 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11992 {
11993         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11994         int insn_cnt = env->prog->len;
11995         int i, err;
11996
11997         for (i = 0; i < insn_cnt; i++) {
11998                 int j;
11999
12000                 j = 0;
12001                 while (i + j < insn_cnt && !aux_data[i + j].seen)
12002                         j++;
12003                 if (!j)
12004                         continue;
12005
12006                 err = verifier_remove_insns(env, i, j);
12007                 if (err)
12008                         return err;
12009                 insn_cnt = env->prog->len;
12010         }
12011
12012         return 0;
12013 }
12014
12015 static int opt_remove_nops(struct bpf_verifier_env *env)
12016 {
12017         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12018         struct bpf_insn *insn = env->prog->insnsi;
12019         int insn_cnt = env->prog->len;
12020         int i, err;
12021
12022         for (i = 0; i < insn_cnt; i++) {
12023                 if (memcmp(&insn[i], &ja, sizeof(ja)))
12024                         continue;
12025
12026                 err = verifier_remove_insns(env, i, 1);
12027                 if (err)
12028                         return err;
12029                 insn_cnt--;
12030                 i--;
12031         }
12032
12033         return 0;
12034 }
12035
12036 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12037                                          const union bpf_attr *attr)
12038 {
12039         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12040         struct bpf_insn_aux_data *aux = env->insn_aux_data;
12041         int i, patch_len, delta = 0, len = env->prog->len;
12042         struct bpf_insn *insns = env->prog->insnsi;
12043         struct bpf_prog *new_prog;
12044         bool rnd_hi32;
12045
12046         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12047         zext_patch[1] = BPF_ZEXT_REG(0);
12048         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12049         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12050         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12051         for (i = 0; i < len; i++) {
12052                 int adj_idx = i + delta;
12053                 struct bpf_insn insn;
12054                 int load_reg;
12055
12056                 insn = insns[adj_idx];
12057                 load_reg = insn_def_regno(&insn);
12058                 if (!aux[adj_idx].zext_dst) {
12059                         u8 code, class;
12060                         u32 imm_rnd;
12061
12062                         if (!rnd_hi32)
12063                                 continue;
12064
12065                         code = insn.code;
12066                         class = BPF_CLASS(code);
12067                         if (load_reg == -1)
12068                                 continue;
12069
12070                         /* NOTE: arg "reg" (the fourth one) is only used for
12071                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
12072                          *       here.
12073                          */
12074                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12075                                 if (class == BPF_LD &&
12076                                     BPF_MODE(code) == BPF_IMM)
12077                                         i++;
12078                                 continue;
12079                         }
12080
12081                         /* ctx load could be transformed into wider load. */
12082                         if (class == BPF_LDX &&
12083                             aux[adj_idx].ptr_type == PTR_TO_CTX)
12084                                 continue;
12085
12086                         imm_rnd = get_random_int();
12087                         rnd_hi32_patch[0] = insn;
12088                         rnd_hi32_patch[1].imm = imm_rnd;
12089                         rnd_hi32_patch[3].dst_reg = load_reg;
12090                         patch = rnd_hi32_patch;
12091                         patch_len = 4;
12092                         goto apply_patch_buffer;
12093                 }
12094
12095                 /* Add in an zero-extend instruction if a) the JIT has requested
12096                  * it or b) it's a CMPXCHG.
12097                  *
12098                  * The latter is because: BPF_CMPXCHG always loads a value into
12099                  * R0, therefore always zero-extends. However some archs'
12100                  * equivalent instruction only does this load when the
12101                  * comparison is successful. This detail of CMPXCHG is
12102                  * orthogonal to the general zero-extension behaviour of the
12103                  * CPU, so it's treated independently of bpf_jit_needs_zext.
12104                  */
12105                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12106                         continue;
12107
12108                 if (WARN_ON(load_reg == -1)) {
12109                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12110                         return -EFAULT;
12111                 }
12112
12113                 zext_patch[0] = insn;
12114                 zext_patch[1].dst_reg = load_reg;
12115                 zext_patch[1].src_reg = load_reg;
12116                 patch = zext_patch;
12117                 patch_len = 2;
12118 apply_patch_buffer:
12119                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12120                 if (!new_prog)
12121                         return -ENOMEM;
12122                 env->prog = new_prog;
12123                 insns = new_prog->insnsi;
12124                 aux = env->insn_aux_data;
12125                 delta += patch_len - 1;
12126         }
12127
12128         return 0;
12129 }
12130
12131 /* convert load instructions that access fields of a context type into a
12132  * sequence of instructions that access fields of the underlying structure:
12133  *     struct __sk_buff    -> struct sk_buff
12134  *     struct bpf_sock_ops -> struct sock
12135  */
12136 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12137 {
12138         const struct bpf_verifier_ops *ops = env->ops;
12139         int i, cnt, size, ctx_field_size, delta = 0;
12140         const int insn_cnt = env->prog->len;
12141         struct bpf_insn insn_buf[16], *insn;
12142         u32 target_size, size_default, off;
12143         struct bpf_prog *new_prog;
12144         enum bpf_access_type type;
12145         bool is_narrower_load;
12146
12147         if (ops->gen_prologue || env->seen_direct_write) {
12148                 if (!ops->gen_prologue) {
12149                         verbose(env, "bpf verifier is misconfigured\n");
12150                         return -EINVAL;
12151                 }
12152                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12153                                         env->prog);
12154                 if (cnt >= ARRAY_SIZE(insn_buf)) {
12155                         verbose(env, "bpf verifier is misconfigured\n");
12156                         return -EINVAL;
12157                 } else if (cnt) {
12158                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12159                         if (!new_prog)
12160                                 return -ENOMEM;
12161
12162                         env->prog = new_prog;
12163                         delta += cnt - 1;
12164                 }
12165         }
12166
12167         if (bpf_prog_is_dev_bound(env->prog->aux))
12168                 return 0;
12169
12170         insn = env->prog->insnsi + delta;
12171
12172         for (i = 0; i < insn_cnt; i++, insn++) {
12173                 bpf_convert_ctx_access_t convert_ctx_access;
12174                 bool ctx_access;
12175
12176                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12177                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12178                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12179                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12180                         type = BPF_READ;
12181                         ctx_access = true;
12182                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12183                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12184                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12185                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12186                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12187                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12188                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12189                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12190                         type = BPF_WRITE;
12191                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12192                 } else {
12193                         continue;
12194                 }
12195
12196                 if (type == BPF_WRITE &&
12197                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
12198                         struct bpf_insn patch[] = {
12199                                 *insn,
12200                                 BPF_ST_NOSPEC(),
12201                         };
12202
12203                         cnt = ARRAY_SIZE(patch);
12204                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12205                         if (!new_prog)
12206                                 return -ENOMEM;
12207
12208                         delta    += cnt - 1;
12209                         env->prog = new_prog;
12210                         insn      = new_prog->insnsi + i + delta;
12211                         continue;
12212                 }
12213
12214                 if (!ctx_access)
12215                         continue;
12216
12217                 switch (env->insn_aux_data[i + delta].ptr_type) {
12218                 case PTR_TO_CTX:
12219                         if (!ops->convert_ctx_access)
12220                                 continue;
12221                         convert_ctx_access = ops->convert_ctx_access;
12222                         break;
12223                 case PTR_TO_SOCKET:
12224                 case PTR_TO_SOCK_COMMON:
12225                         convert_ctx_access = bpf_sock_convert_ctx_access;
12226                         break;
12227                 case PTR_TO_TCP_SOCK:
12228                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12229                         break;
12230                 case PTR_TO_XDP_SOCK:
12231                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12232                         break;
12233                 case PTR_TO_BTF_ID:
12234                         if (type == BPF_READ) {
12235                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
12236                                         BPF_SIZE((insn)->code);
12237                                 env->prog->aux->num_exentries++;
12238                         } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12239                                 verbose(env, "Writes through BTF pointers are not allowed\n");
12240                                 return -EINVAL;
12241                         }
12242                         continue;
12243                 default:
12244                         continue;
12245                 }
12246
12247                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12248                 size = BPF_LDST_BYTES(insn);
12249
12250                 /* If the read access is a narrower load of the field,
12251                  * convert to a 4/8-byte load, to minimum program type specific
12252                  * convert_ctx_access changes. If conversion is successful,
12253                  * we will apply proper mask to the result.
12254                  */
12255                 is_narrower_load = size < ctx_field_size;
12256                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12257                 off = insn->off;
12258                 if (is_narrower_load) {
12259                         u8 size_code;
12260
12261                         if (type == BPF_WRITE) {
12262                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12263                                 return -EINVAL;
12264                         }
12265
12266                         size_code = BPF_H;
12267                         if (ctx_field_size == 4)
12268                                 size_code = BPF_W;
12269                         else if (ctx_field_size == 8)
12270                                 size_code = BPF_DW;
12271
12272                         insn->off = off & ~(size_default - 1);
12273                         insn->code = BPF_LDX | BPF_MEM | size_code;
12274                 }
12275
12276                 target_size = 0;
12277                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12278                                          &target_size);
12279                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12280                     (ctx_field_size && !target_size)) {
12281                         verbose(env, "bpf verifier is misconfigured\n");
12282                         return -EINVAL;
12283                 }
12284
12285                 if (is_narrower_load && size < target_size) {
12286                         u8 shift = bpf_ctx_narrow_access_offset(
12287                                 off, size, size_default) * 8;
12288                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12289                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12290                                 return -EINVAL;
12291                         }
12292                         if (ctx_field_size <= 4) {
12293                                 if (shift)
12294                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12295                                                                         insn->dst_reg,
12296                                                                         shift);
12297                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12298                                                                 (1 << size * 8) - 1);
12299                         } else {
12300                                 if (shift)
12301                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12302                                                                         insn->dst_reg,
12303                                                                         shift);
12304                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12305                                                                 (1ULL << size * 8) - 1);
12306                         }
12307                 }
12308
12309                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12310                 if (!new_prog)
12311                         return -ENOMEM;
12312
12313                 delta += cnt - 1;
12314
12315                 /* keep walking new program and skip insns we just inserted */
12316                 env->prog = new_prog;
12317                 insn      = new_prog->insnsi + i + delta;
12318         }
12319
12320         return 0;
12321 }
12322
12323 static int jit_subprogs(struct bpf_verifier_env *env)
12324 {
12325         struct bpf_prog *prog = env->prog, **func, *tmp;
12326         int i, j, subprog_start, subprog_end = 0, len, subprog;
12327         struct bpf_map *map_ptr;
12328         struct bpf_insn *insn;
12329         void *old_bpf_func;
12330         int err, num_exentries;
12331
12332         if (env->subprog_cnt <= 1)
12333                 return 0;
12334
12335         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12336                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
12337                         continue;
12338
12339                 /* Upon error here we cannot fall back to interpreter but
12340                  * need a hard reject of the program. Thus -EFAULT is
12341                  * propagated in any case.
12342                  */
12343                 subprog = find_subprog(env, i + insn->imm + 1);
12344                 if (subprog < 0) {
12345                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12346                                   i + insn->imm + 1);
12347                         return -EFAULT;
12348                 }
12349                 /* temporarily remember subprog id inside insn instead of
12350                  * aux_data, since next loop will split up all insns into funcs
12351                  */
12352                 insn->off = subprog;
12353                 /* remember original imm in case JIT fails and fallback
12354                  * to interpreter will be needed
12355                  */
12356                 env->insn_aux_data[i].call_imm = insn->imm;
12357                 /* point imm to __bpf_call_base+1 from JITs point of view */
12358                 insn->imm = 1;
12359                 if (bpf_pseudo_func(insn))
12360                         /* jit (e.g. x86_64) may emit fewer instructions
12361                          * if it learns a u32 imm is the same as a u64 imm.
12362                          * Force a non zero here.
12363                          */
12364                         insn[1].imm = 1;
12365         }
12366
12367         err = bpf_prog_alloc_jited_linfo(prog);
12368         if (err)
12369                 goto out_undo_insn;
12370
12371         err = -ENOMEM;
12372         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12373         if (!func)
12374                 goto out_undo_insn;
12375
12376         for (i = 0; i < env->subprog_cnt; i++) {
12377                 subprog_start = subprog_end;
12378                 subprog_end = env->subprog_info[i + 1].start;
12379
12380                 len = subprog_end - subprog_start;
12381                 /* bpf_prog_run() doesn't call subprogs directly,
12382                  * hence main prog stats include the runtime of subprogs.
12383                  * subprogs don't have IDs and not reachable via prog_get_next_id
12384                  * func[i]->stats will never be accessed and stays NULL
12385                  */
12386                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12387                 if (!func[i])
12388                         goto out_free;
12389                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12390                        len * sizeof(struct bpf_insn));
12391                 func[i]->type = prog->type;
12392                 func[i]->len = len;
12393                 if (bpf_prog_calc_tag(func[i]))
12394                         goto out_free;
12395                 func[i]->is_func = 1;
12396                 func[i]->aux->func_idx = i;
12397                 /* Below members will be freed only at prog->aux */
12398                 func[i]->aux->btf = prog->aux->btf;
12399                 func[i]->aux->func_info = prog->aux->func_info;
12400                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
12401                 func[i]->aux->poke_tab = prog->aux->poke_tab;
12402                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12403
12404                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
12405                         struct bpf_jit_poke_descriptor *poke;
12406
12407                         poke = &prog->aux->poke_tab[j];
12408                         if (poke->insn_idx < subprog_end &&
12409                             poke->insn_idx >= subprog_start)
12410                                 poke->aux = func[i]->aux;
12411                 }
12412
12413                 func[i]->aux->name[0] = 'F';
12414                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12415                 func[i]->jit_requested = 1;
12416                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12417                 func[i]->aux->linfo = prog->aux->linfo;
12418                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12419                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12420                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12421                 num_exentries = 0;
12422                 insn = func[i]->insnsi;
12423                 for (j = 0; j < func[i]->len; j++, insn++) {
12424                         if (BPF_CLASS(insn->code) == BPF_LDX &&
12425                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
12426                                 num_exentries++;
12427                 }
12428                 func[i]->aux->num_exentries = num_exentries;
12429                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12430                 func[i] = bpf_int_jit_compile(func[i]);
12431                 if (!func[i]->jited) {
12432                         err = -ENOTSUPP;
12433                         goto out_free;
12434                 }
12435                 cond_resched();
12436         }
12437
12438         /* at this point all bpf functions were successfully JITed
12439          * now populate all bpf_calls with correct addresses and
12440          * run last pass of JIT
12441          */
12442         for (i = 0; i < env->subprog_cnt; i++) {
12443                 insn = func[i]->insnsi;
12444                 for (j = 0; j < func[i]->len; j++, insn++) {
12445                         if (bpf_pseudo_func(insn)) {
12446                                 subprog = insn->off;
12447                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12448                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12449                                 continue;
12450                         }
12451                         if (!bpf_pseudo_call(insn))
12452                                 continue;
12453                         subprog = insn->off;
12454                         insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12455                                     __bpf_call_base;
12456                 }
12457
12458                 /* we use the aux data to keep a list of the start addresses
12459                  * of the JITed images for each function in the program
12460                  *
12461                  * for some architectures, such as powerpc64, the imm field
12462                  * might not be large enough to hold the offset of the start
12463                  * address of the callee's JITed image from __bpf_call_base
12464                  *
12465                  * in such cases, we can lookup the start address of a callee
12466                  * by using its subprog id, available from the off field of
12467                  * the call instruction, as an index for this list
12468                  */
12469                 func[i]->aux->func = func;
12470                 func[i]->aux->func_cnt = env->subprog_cnt;
12471         }
12472         for (i = 0; i < env->subprog_cnt; i++) {
12473                 old_bpf_func = func[i]->bpf_func;
12474                 tmp = bpf_int_jit_compile(func[i]);
12475                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12476                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12477                         err = -ENOTSUPP;
12478                         goto out_free;
12479                 }
12480                 cond_resched();
12481         }
12482
12483         /* finally lock prog and jit images for all functions and
12484          * populate kallsysm
12485          */
12486         for (i = 0; i < env->subprog_cnt; i++) {
12487                 bpf_prog_lock_ro(func[i]);
12488                 bpf_prog_kallsyms_add(func[i]);
12489         }
12490
12491         /* Last step: make now unused interpreter insns from main
12492          * prog consistent for later dump requests, so they can
12493          * later look the same as if they were interpreted only.
12494          */
12495         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12496                 if (bpf_pseudo_func(insn)) {
12497                         insn[0].imm = env->insn_aux_data[i].call_imm;
12498                         insn[1].imm = insn->off;
12499                         insn->off = 0;
12500                         continue;
12501                 }
12502                 if (!bpf_pseudo_call(insn))
12503                         continue;
12504                 insn->off = env->insn_aux_data[i].call_imm;
12505                 subprog = find_subprog(env, i + insn->off + 1);
12506                 insn->imm = subprog;
12507         }
12508
12509         prog->jited = 1;
12510         prog->bpf_func = func[0]->bpf_func;
12511         prog->aux->func = func;
12512         prog->aux->func_cnt = env->subprog_cnt;
12513         bpf_prog_jit_attempt_done(prog);
12514         return 0;
12515 out_free:
12516         /* We failed JIT'ing, so at this point we need to unregister poke
12517          * descriptors from subprogs, so that kernel is not attempting to
12518          * patch it anymore as we're freeing the subprog JIT memory.
12519          */
12520         for (i = 0; i < prog->aux->size_poke_tab; i++) {
12521                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12522                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12523         }
12524         /* At this point we're guaranteed that poke descriptors are not
12525          * live anymore. We can just unlink its descriptor table as it's
12526          * released with the main prog.
12527          */
12528         for (i = 0; i < env->subprog_cnt; i++) {
12529                 if (!func[i])
12530                         continue;
12531                 func[i]->aux->poke_tab = NULL;
12532                 bpf_jit_free(func[i]);
12533         }
12534         kfree(func);
12535 out_undo_insn:
12536         /* cleanup main prog to be interpreted */
12537         prog->jit_requested = 0;
12538         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12539                 if (!bpf_pseudo_call(insn))
12540                         continue;
12541                 insn->off = 0;
12542                 insn->imm = env->insn_aux_data[i].call_imm;
12543         }
12544         bpf_prog_jit_attempt_done(prog);
12545         return err;
12546 }
12547
12548 static int fixup_call_args(struct bpf_verifier_env *env)
12549 {
12550 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12551         struct bpf_prog *prog = env->prog;
12552         struct bpf_insn *insn = prog->insnsi;
12553         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12554         int i, depth;
12555 #endif
12556         int err = 0;
12557
12558         if (env->prog->jit_requested &&
12559             !bpf_prog_is_dev_bound(env->prog->aux)) {
12560                 err = jit_subprogs(env);
12561                 if (err == 0)
12562                         return 0;
12563                 if (err == -EFAULT)
12564                         return err;
12565         }
12566 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12567         if (has_kfunc_call) {
12568                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12569                 return -EINVAL;
12570         }
12571         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12572                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12573                  * have to be rejected, since interpreter doesn't support them yet.
12574                  */
12575                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12576                 return -EINVAL;
12577         }
12578         for (i = 0; i < prog->len; i++, insn++) {
12579                 if (bpf_pseudo_func(insn)) {
12580                         /* When JIT fails the progs with callback calls
12581                          * have to be rejected, since interpreter doesn't support them yet.
12582                          */
12583                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
12584                         return -EINVAL;
12585                 }
12586
12587                 if (!bpf_pseudo_call(insn))
12588                         continue;
12589                 depth = get_callee_stack_depth(env, insn, i);
12590                 if (depth < 0)
12591                         return depth;
12592                 bpf_patch_call_args(insn, depth);
12593         }
12594         err = 0;
12595 #endif
12596         return err;
12597 }
12598
12599 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12600                             struct bpf_insn *insn)
12601 {
12602         const struct bpf_kfunc_desc *desc;
12603
12604         /* insn->imm has the btf func_id. Replace it with
12605          * an address (relative to __bpf_base_call).
12606          */
12607         desc = find_kfunc_desc(env->prog, insn->imm);
12608         if (!desc) {
12609                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12610                         insn->imm);
12611                 return -EFAULT;
12612         }
12613
12614         insn->imm = desc->imm;
12615
12616         return 0;
12617 }
12618
12619 /* Do various post-verification rewrites in a single program pass.
12620  * These rewrites simplify JIT and interpreter implementations.
12621  */
12622 static int do_misc_fixups(struct bpf_verifier_env *env)
12623 {
12624         struct bpf_prog *prog = env->prog;
12625         bool expect_blinding = bpf_jit_blinding_enabled(prog);
12626         enum bpf_prog_type prog_type = resolve_prog_type(prog);
12627         struct bpf_insn *insn = prog->insnsi;
12628         const struct bpf_func_proto *fn;
12629         const int insn_cnt = prog->len;
12630         const struct bpf_map_ops *ops;
12631         struct bpf_insn_aux_data *aux;
12632         struct bpf_insn insn_buf[16];
12633         struct bpf_prog *new_prog;
12634         struct bpf_map *map_ptr;
12635         int i, ret, cnt, delta = 0;
12636
12637         for (i = 0; i < insn_cnt; i++, insn++) {
12638                 /* Make divide-by-zero exceptions impossible. */
12639                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12640                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12641                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12642                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12643                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12644                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12645                         struct bpf_insn *patchlet;
12646                         struct bpf_insn chk_and_div[] = {
12647                                 /* [R,W]x div 0 -> 0 */
12648                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12649                                              BPF_JNE | BPF_K, insn->src_reg,
12650                                              0, 2, 0),
12651                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12652                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12653                                 *insn,
12654                         };
12655                         struct bpf_insn chk_and_mod[] = {
12656                                 /* [R,W]x mod 0 -> [R,W]x */
12657                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12658                                              BPF_JEQ | BPF_K, insn->src_reg,
12659                                              0, 1 + (is64 ? 0 : 1), 0),
12660                                 *insn,
12661                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12662                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12663                         };
12664
12665                         patchlet = isdiv ? chk_and_div : chk_and_mod;
12666                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12667                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12668
12669                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12670                         if (!new_prog)
12671                                 return -ENOMEM;
12672
12673                         delta    += cnt - 1;
12674                         env->prog = prog = new_prog;
12675                         insn      = new_prog->insnsi + i + delta;
12676                         continue;
12677                 }
12678
12679                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12680                 if (BPF_CLASS(insn->code) == BPF_LD &&
12681                     (BPF_MODE(insn->code) == BPF_ABS ||
12682                      BPF_MODE(insn->code) == BPF_IND)) {
12683                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
12684                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12685                                 verbose(env, "bpf verifier is misconfigured\n");
12686                                 return -EINVAL;
12687                         }
12688
12689                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12690                         if (!new_prog)
12691                                 return -ENOMEM;
12692
12693                         delta    += cnt - 1;
12694                         env->prog = prog = new_prog;
12695                         insn      = new_prog->insnsi + i + delta;
12696                         continue;
12697                 }
12698
12699                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
12700                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12701                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12702                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12703                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12704                         struct bpf_insn *patch = &insn_buf[0];
12705                         bool issrc, isneg, isimm;
12706                         u32 off_reg;
12707
12708                         aux = &env->insn_aux_data[i + delta];
12709                         if (!aux->alu_state ||
12710                             aux->alu_state == BPF_ALU_NON_POINTER)
12711                                 continue;
12712
12713                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12714                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12715                                 BPF_ALU_SANITIZE_SRC;
12716                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12717
12718                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
12719                         if (isimm) {
12720                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12721                         } else {
12722                                 if (isneg)
12723                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12724                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12725                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12726                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12727                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12728                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12729                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12730                         }
12731                         if (!issrc)
12732                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12733                         insn->src_reg = BPF_REG_AX;
12734                         if (isneg)
12735                                 insn->code = insn->code == code_add ?
12736                                              code_sub : code_add;
12737                         *patch++ = *insn;
12738                         if (issrc && isneg && !isimm)
12739                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12740                         cnt = patch - insn_buf;
12741
12742                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12743                         if (!new_prog)
12744                                 return -ENOMEM;
12745
12746                         delta    += cnt - 1;
12747                         env->prog = prog = new_prog;
12748                         insn      = new_prog->insnsi + i + delta;
12749                         continue;
12750                 }
12751
12752                 if (insn->code != (BPF_JMP | BPF_CALL))
12753                         continue;
12754                 if (insn->src_reg == BPF_PSEUDO_CALL)
12755                         continue;
12756                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12757                         ret = fixup_kfunc_call(env, insn);
12758                         if (ret)
12759                                 return ret;
12760                         continue;
12761                 }
12762
12763                 if (insn->imm == BPF_FUNC_get_route_realm)
12764                         prog->dst_needed = 1;
12765                 if (insn->imm == BPF_FUNC_get_prandom_u32)
12766                         bpf_user_rnd_init_once();
12767                 if (insn->imm == BPF_FUNC_override_return)
12768                         prog->kprobe_override = 1;
12769                 if (insn->imm == BPF_FUNC_tail_call) {
12770                         /* If we tail call into other programs, we
12771                          * cannot make any assumptions since they can
12772                          * be replaced dynamically during runtime in
12773                          * the program array.
12774                          */
12775                         prog->cb_access = 1;
12776                         if (!allow_tail_call_in_subprogs(env))
12777                                 prog->aux->stack_depth = MAX_BPF_STACK;
12778                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
12779
12780                         /* mark bpf_tail_call as different opcode to avoid
12781                          * conditional branch in the interpreter for every normal
12782                          * call and to prevent accidental JITing by JIT compiler
12783                          * that doesn't support bpf_tail_call yet
12784                          */
12785                         insn->imm = 0;
12786                         insn->code = BPF_JMP | BPF_TAIL_CALL;
12787
12788                         aux = &env->insn_aux_data[i + delta];
12789                         if (env->bpf_capable && !expect_blinding &&
12790                             prog->jit_requested &&
12791                             !bpf_map_key_poisoned(aux) &&
12792                             !bpf_map_ptr_poisoned(aux) &&
12793                             !bpf_map_ptr_unpriv(aux)) {
12794                                 struct bpf_jit_poke_descriptor desc = {
12795                                         .reason = BPF_POKE_REASON_TAIL_CALL,
12796                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12797                                         .tail_call.key = bpf_map_key_immediate(aux),
12798                                         .insn_idx = i + delta,
12799                                 };
12800
12801                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12802                                 if (ret < 0) {
12803                                         verbose(env, "adding tail call poke descriptor failed\n");
12804                                         return ret;
12805                                 }
12806
12807                                 insn->imm = ret + 1;
12808                                 continue;
12809                         }
12810
12811                         if (!bpf_map_ptr_unpriv(aux))
12812                                 continue;
12813
12814                         /* instead of changing every JIT dealing with tail_call
12815                          * emit two extra insns:
12816                          * if (index >= max_entries) goto out;
12817                          * index &= array->index_mask;
12818                          * to avoid out-of-bounds cpu speculation
12819                          */
12820                         if (bpf_map_ptr_poisoned(aux)) {
12821                                 verbose(env, "tail_call abusing map_ptr\n");
12822                                 return -EINVAL;
12823                         }
12824
12825                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12826                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12827                                                   map_ptr->max_entries, 2);
12828                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12829                                                     container_of(map_ptr,
12830                                                                  struct bpf_array,
12831                                                                  map)->index_mask);
12832                         insn_buf[2] = *insn;
12833                         cnt = 3;
12834                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12835                         if (!new_prog)
12836                                 return -ENOMEM;
12837
12838                         delta    += cnt - 1;
12839                         env->prog = prog = new_prog;
12840                         insn      = new_prog->insnsi + i + delta;
12841                         continue;
12842                 }
12843
12844                 if (insn->imm == BPF_FUNC_timer_set_callback) {
12845                         /* The verifier will process callback_fn as many times as necessary
12846                          * with different maps and the register states prepared by
12847                          * set_timer_callback_state will be accurate.
12848                          *
12849                          * The following use case is valid:
12850                          *   map1 is shared by prog1, prog2, prog3.
12851                          *   prog1 calls bpf_timer_init for some map1 elements
12852                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
12853                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
12854                          *   prog3 calls bpf_timer_start for some map1 elements.
12855                          *     Those that were not both bpf_timer_init-ed and
12856                          *     bpf_timer_set_callback-ed will return -EINVAL.
12857                          */
12858                         struct bpf_insn ld_addrs[2] = {
12859                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
12860                         };
12861
12862                         insn_buf[0] = ld_addrs[0];
12863                         insn_buf[1] = ld_addrs[1];
12864                         insn_buf[2] = *insn;
12865                         cnt = 3;
12866
12867                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12868                         if (!new_prog)
12869                                 return -ENOMEM;
12870
12871                         delta    += cnt - 1;
12872                         env->prog = prog = new_prog;
12873                         insn      = new_prog->insnsi + i + delta;
12874                         goto patch_call_imm;
12875                 }
12876
12877                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
12878                  * and other inlining handlers are currently limited to 64 bit
12879                  * only.
12880                  */
12881                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12882                     (insn->imm == BPF_FUNC_map_lookup_elem ||
12883                      insn->imm == BPF_FUNC_map_update_elem ||
12884                      insn->imm == BPF_FUNC_map_delete_elem ||
12885                      insn->imm == BPF_FUNC_map_push_elem   ||
12886                      insn->imm == BPF_FUNC_map_pop_elem    ||
12887                      insn->imm == BPF_FUNC_map_peek_elem   ||
12888                      insn->imm == BPF_FUNC_redirect_map)) {
12889                         aux = &env->insn_aux_data[i + delta];
12890                         if (bpf_map_ptr_poisoned(aux))
12891                                 goto patch_call_imm;
12892
12893                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12894                         ops = map_ptr->ops;
12895                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
12896                             ops->map_gen_lookup) {
12897                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
12898                                 if (cnt == -EOPNOTSUPP)
12899                                         goto patch_map_ops_generic;
12900                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12901                                         verbose(env, "bpf verifier is misconfigured\n");
12902                                         return -EINVAL;
12903                                 }
12904
12905                                 new_prog = bpf_patch_insn_data(env, i + delta,
12906                                                                insn_buf, cnt);
12907                                 if (!new_prog)
12908                                         return -ENOMEM;
12909
12910                                 delta    += cnt - 1;
12911                                 env->prog = prog = new_prog;
12912                                 insn      = new_prog->insnsi + i + delta;
12913                                 continue;
12914                         }
12915
12916                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12917                                      (void *(*)(struct bpf_map *map, void *key))NULL));
12918                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12919                                      (int (*)(struct bpf_map *map, void *key))NULL));
12920                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12921                                      (int (*)(struct bpf_map *map, void *key, void *value,
12922                                               u64 flags))NULL));
12923                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12924                                      (int (*)(struct bpf_map *map, void *value,
12925                                               u64 flags))NULL));
12926                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12927                                      (int (*)(struct bpf_map *map, void *value))NULL));
12928                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12929                                      (int (*)(struct bpf_map *map, void *value))NULL));
12930                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
12931                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12932
12933 patch_map_ops_generic:
12934                         switch (insn->imm) {
12935                         case BPF_FUNC_map_lookup_elem:
12936                                 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12937                                             __bpf_call_base;
12938                                 continue;
12939                         case BPF_FUNC_map_update_elem:
12940                                 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12941                                             __bpf_call_base;
12942                                 continue;
12943                         case BPF_FUNC_map_delete_elem:
12944                                 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12945                                             __bpf_call_base;
12946                                 continue;
12947                         case BPF_FUNC_map_push_elem:
12948                                 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12949                                             __bpf_call_base;
12950                                 continue;
12951                         case BPF_FUNC_map_pop_elem:
12952                                 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12953                                             __bpf_call_base;
12954                                 continue;
12955                         case BPF_FUNC_map_peek_elem:
12956                                 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12957                                             __bpf_call_base;
12958                                 continue;
12959                         case BPF_FUNC_redirect_map:
12960                                 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12961                                             __bpf_call_base;
12962                                 continue;
12963                         }
12964
12965                         goto patch_call_imm;
12966                 }
12967
12968                 /* Implement bpf_jiffies64 inline. */
12969                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12970                     insn->imm == BPF_FUNC_jiffies64) {
12971                         struct bpf_insn ld_jiffies_addr[2] = {
12972                                 BPF_LD_IMM64(BPF_REG_0,
12973                                              (unsigned long)&jiffies),
12974                         };
12975
12976                         insn_buf[0] = ld_jiffies_addr[0];
12977                         insn_buf[1] = ld_jiffies_addr[1];
12978                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12979                                                   BPF_REG_0, 0);
12980                         cnt = 3;
12981
12982                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12983                                                        cnt);
12984                         if (!new_prog)
12985                                 return -ENOMEM;
12986
12987                         delta    += cnt - 1;
12988                         env->prog = prog = new_prog;
12989                         insn      = new_prog->insnsi + i + delta;
12990                         continue;
12991                 }
12992
12993                 /* Implement bpf_get_func_ip inline. */
12994                 if (prog_type == BPF_PROG_TYPE_TRACING &&
12995                     insn->imm == BPF_FUNC_get_func_ip) {
12996                         /* Load IP address from ctx - 8 */
12997                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
12998
12999                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13000                         if (!new_prog)
13001                                 return -ENOMEM;
13002
13003                         env->prog = prog = new_prog;
13004                         insn      = new_prog->insnsi + i + delta;
13005                         continue;
13006                 }
13007
13008 patch_call_imm:
13009                 fn = env->ops->get_func_proto(insn->imm, env->prog);
13010                 /* all functions that have prototype and verifier allowed
13011                  * programs to call them, must be real in-kernel functions
13012                  */
13013                 if (!fn->func) {
13014                         verbose(env,
13015                                 "kernel subsystem misconfigured func %s#%d\n",
13016                                 func_id_name(insn->imm), insn->imm);
13017                         return -EFAULT;
13018                 }
13019                 insn->imm = fn->func - __bpf_call_base;
13020         }
13021
13022         /* Since poke tab is now finalized, publish aux to tracker. */
13023         for (i = 0; i < prog->aux->size_poke_tab; i++) {
13024                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13025                 if (!map_ptr->ops->map_poke_track ||
13026                     !map_ptr->ops->map_poke_untrack ||
13027                     !map_ptr->ops->map_poke_run) {
13028                         verbose(env, "bpf verifier is misconfigured\n");
13029                         return -EINVAL;
13030                 }
13031
13032                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13033                 if (ret < 0) {
13034                         verbose(env, "tracking tail call prog failed\n");
13035                         return ret;
13036                 }
13037         }
13038
13039         sort_kfunc_descs_by_imm(env->prog);
13040
13041         return 0;
13042 }
13043
13044 static void free_states(struct bpf_verifier_env *env)
13045 {
13046         struct bpf_verifier_state_list *sl, *sln;
13047         int i;
13048
13049         sl = env->free_list;
13050         while (sl) {
13051                 sln = sl->next;
13052                 free_verifier_state(&sl->state, false);
13053                 kfree(sl);
13054                 sl = sln;
13055         }
13056         env->free_list = NULL;
13057
13058         if (!env->explored_states)
13059                 return;
13060
13061         for (i = 0; i < state_htab_size(env); i++) {
13062                 sl = env->explored_states[i];
13063
13064                 while (sl) {
13065                         sln = sl->next;
13066                         free_verifier_state(&sl->state, false);
13067                         kfree(sl);
13068                         sl = sln;
13069                 }
13070                 env->explored_states[i] = NULL;
13071         }
13072 }
13073
13074 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13075 {
13076         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13077         struct bpf_verifier_state *state;
13078         struct bpf_reg_state *regs;
13079         int ret, i;
13080
13081         env->prev_linfo = NULL;
13082         env->pass_cnt++;
13083
13084         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13085         if (!state)
13086                 return -ENOMEM;
13087         state->curframe = 0;
13088         state->speculative = false;
13089         state->branches = 1;
13090         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13091         if (!state->frame[0]) {
13092                 kfree(state);
13093                 return -ENOMEM;
13094         }
13095         env->cur_state = state;
13096         init_func_state(env, state->frame[0],
13097                         BPF_MAIN_FUNC /* callsite */,
13098                         0 /* frameno */,
13099                         subprog);
13100
13101         regs = state->frame[state->curframe]->regs;
13102         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13103                 ret = btf_prepare_func_args(env, subprog, regs);
13104                 if (ret)
13105                         goto out;
13106                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13107                         if (regs[i].type == PTR_TO_CTX)
13108                                 mark_reg_known_zero(env, regs, i);
13109                         else if (regs[i].type == SCALAR_VALUE)
13110                                 mark_reg_unknown(env, regs, i);
13111                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
13112                                 const u32 mem_size = regs[i].mem_size;
13113
13114                                 mark_reg_known_zero(env, regs, i);
13115                                 regs[i].mem_size = mem_size;
13116                                 regs[i].id = ++env->id_gen;
13117                         }
13118                 }
13119         } else {
13120                 /* 1st arg to a function */
13121                 regs[BPF_REG_1].type = PTR_TO_CTX;
13122                 mark_reg_known_zero(env, regs, BPF_REG_1);
13123                 ret = btf_check_subprog_arg_match(env, subprog, regs);
13124                 if (ret == -EFAULT)
13125                         /* unlikely verifier bug. abort.
13126                          * ret == 0 and ret < 0 are sadly acceptable for
13127                          * main() function due to backward compatibility.
13128                          * Like socket filter program may be written as:
13129                          * int bpf_prog(struct pt_regs *ctx)
13130                          * and never dereference that ctx in the program.
13131                          * 'struct pt_regs' is a type mismatch for socket
13132                          * filter that should be using 'struct __sk_buff'.
13133                          */
13134                         goto out;
13135         }
13136
13137         ret = do_check(env);
13138 out:
13139         /* check for NULL is necessary, since cur_state can be freed inside
13140          * do_check() under memory pressure.
13141          */
13142         if (env->cur_state) {
13143                 free_verifier_state(env->cur_state, true);
13144                 env->cur_state = NULL;
13145         }
13146         while (!pop_stack(env, NULL, NULL, false));
13147         if (!ret && pop_log)
13148                 bpf_vlog_reset(&env->log, 0);
13149         free_states(env);
13150         return ret;
13151 }
13152
13153 /* Verify all global functions in a BPF program one by one based on their BTF.
13154  * All global functions must pass verification. Otherwise the whole program is rejected.
13155  * Consider:
13156  * int bar(int);
13157  * int foo(int f)
13158  * {
13159  *    return bar(f);
13160  * }
13161  * int bar(int b)
13162  * {
13163  *    ...
13164  * }
13165  * foo() will be verified first for R1=any_scalar_value. During verification it
13166  * will be assumed that bar() already verified successfully and call to bar()
13167  * from foo() will be checked for type match only. Later bar() will be verified
13168  * independently to check that it's safe for R1=any_scalar_value.
13169  */
13170 static int do_check_subprogs(struct bpf_verifier_env *env)
13171 {
13172         struct bpf_prog_aux *aux = env->prog->aux;
13173         int i, ret;
13174
13175         if (!aux->func_info)
13176                 return 0;
13177
13178         for (i = 1; i < env->subprog_cnt; i++) {
13179                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13180                         continue;
13181                 env->insn_idx = env->subprog_info[i].start;
13182                 WARN_ON_ONCE(env->insn_idx == 0);
13183                 ret = do_check_common(env, i);
13184                 if (ret) {
13185                         return ret;
13186                 } else if (env->log.level & BPF_LOG_LEVEL) {
13187                         verbose(env,
13188                                 "Func#%d is safe for any args that match its prototype\n",
13189                                 i);
13190                 }
13191         }
13192         return 0;
13193 }
13194
13195 static int do_check_main(struct bpf_verifier_env *env)
13196 {
13197         int ret;
13198
13199         env->insn_idx = 0;
13200         ret = do_check_common(env, 0);
13201         if (!ret)
13202                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13203         return ret;
13204 }
13205
13206
13207 static void print_verification_stats(struct bpf_verifier_env *env)
13208 {
13209         int i;
13210
13211         if (env->log.level & BPF_LOG_STATS) {
13212                 verbose(env, "verification time %lld usec\n",
13213                         div_u64(env->verification_time, 1000));
13214                 verbose(env, "stack depth ");
13215                 for (i = 0; i < env->subprog_cnt; i++) {
13216                         u32 depth = env->subprog_info[i].stack_depth;
13217
13218                         verbose(env, "%d", depth);
13219                         if (i + 1 < env->subprog_cnt)
13220                                 verbose(env, "+");
13221                 }
13222                 verbose(env, "\n");
13223         }
13224         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13225                 "total_states %d peak_states %d mark_read %d\n",
13226                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13227                 env->max_states_per_insn, env->total_states,
13228                 env->peak_states, env->longest_mark_read_walk);
13229 }
13230
13231 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13232 {
13233         const struct btf_type *t, *func_proto;
13234         const struct bpf_struct_ops *st_ops;
13235         const struct btf_member *member;
13236         struct bpf_prog *prog = env->prog;
13237         u32 btf_id, member_idx;
13238         const char *mname;
13239
13240         if (!prog->gpl_compatible) {
13241                 verbose(env, "struct ops programs must have a GPL compatible license\n");
13242                 return -EINVAL;
13243         }
13244
13245         btf_id = prog->aux->attach_btf_id;
13246         st_ops = bpf_struct_ops_find(btf_id);
13247         if (!st_ops) {
13248                 verbose(env, "attach_btf_id %u is not a supported struct\n",
13249                         btf_id);
13250                 return -ENOTSUPP;
13251         }
13252
13253         t = st_ops->type;
13254         member_idx = prog->expected_attach_type;
13255         if (member_idx >= btf_type_vlen(t)) {
13256                 verbose(env, "attach to invalid member idx %u of struct %s\n",
13257                         member_idx, st_ops->name);
13258                 return -EINVAL;
13259         }
13260
13261         member = &btf_type_member(t)[member_idx];
13262         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13263         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13264                                                NULL);
13265         if (!func_proto) {
13266                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13267                         mname, member_idx, st_ops->name);
13268                 return -EINVAL;
13269         }
13270
13271         if (st_ops->check_member) {
13272                 int err = st_ops->check_member(t, member);
13273
13274                 if (err) {
13275                         verbose(env, "attach to unsupported member %s of struct %s\n",
13276                                 mname, st_ops->name);
13277                         return err;
13278                 }
13279         }
13280
13281         prog->aux->attach_func_proto = func_proto;
13282         prog->aux->attach_func_name = mname;
13283         env->ops = st_ops->verifier_ops;
13284
13285         return 0;
13286 }
13287 #define SECURITY_PREFIX "security_"
13288
13289 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13290 {
13291         if (within_error_injection_list(addr) ||
13292             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13293                 return 0;
13294
13295         return -EINVAL;
13296 }
13297
13298 /* list of non-sleepable functions that are otherwise on
13299  * ALLOW_ERROR_INJECTION list
13300  */
13301 BTF_SET_START(btf_non_sleepable_error_inject)
13302 /* Three functions below can be called from sleepable and non-sleepable context.
13303  * Assume non-sleepable from bpf safety point of view.
13304  */
13305 BTF_ID(func, __add_to_page_cache_locked)
13306 BTF_ID(func, should_fail_alloc_page)
13307 BTF_ID(func, should_failslab)
13308 BTF_SET_END(btf_non_sleepable_error_inject)
13309
13310 static int check_non_sleepable_error_inject(u32 btf_id)
13311 {
13312         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13313 }
13314
13315 int bpf_check_attach_target(struct bpf_verifier_log *log,
13316                             const struct bpf_prog *prog,
13317                             const struct bpf_prog *tgt_prog,
13318                             u32 btf_id,
13319                             struct bpf_attach_target_info *tgt_info)
13320 {
13321         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13322         const char prefix[] = "btf_trace_";
13323         int ret = 0, subprog = -1, i;
13324         const struct btf_type *t;
13325         bool conservative = true;
13326         const char *tname;
13327         struct btf *btf;
13328         long addr = 0;
13329
13330         if (!btf_id) {
13331                 bpf_log(log, "Tracing programs must provide btf_id\n");
13332                 return -EINVAL;
13333         }
13334         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13335         if (!btf) {
13336                 bpf_log(log,
13337                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13338                 return -EINVAL;
13339         }
13340         t = btf_type_by_id(btf, btf_id);
13341         if (!t) {
13342                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13343                 return -EINVAL;
13344         }
13345         tname = btf_name_by_offset(btf, t->name_off);
13346         if (!tname) {
13347                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13348                 return -EINVAL;
13349         }
13350         if (tgt_prog) {
13351                 struct bpf_prog_aux *aux = tgt_prog->aux;
13352
13353                 for (i = 0; i < aux->func_info_cnt; i++)
13354                         if (aux->func_info[i].type_id == btf_id) {
13355                                 subprog = i;
13356                                 break;
13357                         }
13358                 if (subprog == -1) {
13359                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
13360                         return -EINVAL;
13361                 }
13362                 conservative = aux->func_info_aux[subprog].unreliable;
13363                 if (prog_extension) {
13364                         if (conservative) {
13365                                 bpf_log(log,
13366                                         "Cannot replace static functions\n");
13367                                 return -EINVAL;
13368                         }
13369                         if (!prog->jit_requested) {
13370                                 bpf_log(log,
13371                                         "Extension programs should be JITed\n");
13372                                 return -EINVAL;
13373                         }
13374                 }
13375                 if (!tgt_prog->jited) {
13376                         bpf_log(log, "Can attach to only JITed progs\n");
13377                         return -EINVAL;
13378                 }
13379                 if (tgt_prog->type == prog->type) {
13380                         /* Cannot fentry/fexit another fentry/fexit program.
13381                          * Cannot attach program extension to another extension.
13382                          * It's ok to attach fentry/fexit to extension program.
13383                          */
13384                         bpf_log(log, "Cannot recursively attach\n");
13385                         return -EINVAL;
13386                 }
13387                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13388                     prog_extension &&
13389                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13390                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13391                         /* Program extensions can extend all program types
13392                          * except fentry/fexit. The reason is the following.
13393                          * The fentry/fexit programs are used for performance
13394                          * analysis, stats and can be attached to any program
13395                          * type except themselves. When extension program is
13396                          * replacing XDP function it is necessary to allow
13397                          * performance analysis of all functions. Both original
13398                          * XDP program and its program extension. Hence
13399                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13400                          * allowed. If extending of fentry/fexit was allowed it
13401                          * would be possible to create long call chain
13402                          * fentry->extension->fentry->extension beyond
13403                          * reasonable stack size. Hence extending fentry is not
13404                          * allowed.
13405                          */
13406                         bpf_log(log, "Cannot extend fentry/fexit\n");
13407                         return -EINVAL;
13408                 }
13409         } else {
13410                 if (prog_extension) {
13411                         bpf_log(log, "Cannot replace kernel functions\n");
13412                         return -EINVAL;
13413                 }
13414         }
13415
13416         switch (prog->expected_attach_type) {
13417         case BPF_TRACE_RAW_TP:
13418                 if (tgt_prog) {
13419                         bpf_log(log,
13420                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13421                         return -EINVAL;
13422                 }
13423                 if (!btf_type_is_typedef(t)) {
13424                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
13425                                 btf_id);
13426                         return -EINVAL;
13427                 }
13428                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13429                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13430                                 btf_id, tname);
13431                         return -EINVAL;
13432                 }
13433                 tname += sizeof(prefix) - 1;
13434                 t = btf_type_by_id(btf, t->type);
13435                 if (!btf_type_is_ptr(t))
13436                         /* should never happen in valid vmlinux build */
13437                         return -EINVAL;
13438                 t = btf_type_by_id(btf, t->type);
13439                 if (!btf_type_is_func_proto(t))
13440                         /* should never happen in valid vmlinux build */
13441                         return -EINVAL;
13442
13443                 break;
13444         case BPF_TRACE_ITER:
13445                 if (!btf_type_is_func(t)) {
13446                         bpf_log(log, "attach_btf_id %u is not a function\n",
13447                                 btf_id);
13448                         return -EINVAL;
13449                 }
13450                 t = btf_type_by_id(btf, t->type);
13451                 if (!btf_type_is_func_proto(t))
13452                         return -EINVAL;
13453                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13454                 if (ret)
13455                         return ret;
13456                 break;
13457         default:
13458                 if (!prog_extension)
13459                         return -EINVAL;
13460                 fallthrough;
13461         case BPF_MODIFY_RETURN:
13462         case BPF_LSM_MAC:
13463         case BPF_TRACE_FENTRY:
13464         case BPF_TRACE_FEXIT:
13465                 if (!btf_type_is_func(t)) {
13466                         bpf_log(log, "attach_btf_id %u is not a function\n",
13467                                 btf_id);
13468                         return -EINVAL;
13469                 }
13470                 if (prog_extension &&
13471                     btf_check_type_match(log, prog, btf, t))
13472                         return -EINVAL;
13473                 t = btf_type_by_id(btf, t->type);
13474                 if (!btf_type_is_func_proto(t))
13475                         return -EINVAL;
13476
13477                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13478                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13479                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13480                         return -EINVAL;
13481
13482                 if (tgt_prog && conservative)
13483                         t = NULL;
13484
13485                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13486                 if (ret < 0)
13487                         return ret;
13488
13489                 if (tgt_prog) {
13490                         if (subprog == 0)
13491                                 addr = (long) tgt_prog->bpf_func;
13492                         else
13493                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13494                 } else {
13495                         addr = kallsyms_lookup_name(tname);
13496                         if (!addr) {
13497                                 bpf_log(log,
13498                                         "The address of function %s cannot be found\n",
13499                                         tname);
13500                                 return -ENOENT;
13501                         }
13502                 }
13503
13504                 if (prog->aux->sleepable) {
13505                         ret = -EINVAL;
13506                         switch (prog->type) {
13507                         case BPF_PROG_TYPE_TRACING:
13508                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13509                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13510                                  */
13511                                 if (!check_non_sleepable_error_inject(btf_id) &&
13512                                     within_error_injection_list(addr))
13513                                         ret = 0;
13514                                 break;
13515                         case BPF_PROG_TYPE_LSM:
13516                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13517                                  * Only some of them are sleepable.
13518                                  */
13519                                 if (bpf_lsm_is_sleepable_hook(btf_id))
13520                                         ret = 0;
13521                                 break;
13522                         default:
13523                                 break;
13524                         }
13525                         if (ret) {
13526                                 bpf_log(log, "%s is not sleepable\n", tname);
13527                                 return ret;
13528                         }
13529                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13530                         if (tgt_prog) {
13531                                 bpf_log(log, "can't modify return codes of BPF programs\n");
13532                                 return -EINVAL;
13533                         }
13534                         ret = check_attach_modify_return(addr, tname);
13535                         if (ret) {
13536                                 bpf_log(log, "%s() is not modifiable\n", tname);
13537                                 return ret;
13538                         }
13539                 }
13540
13541                 break;
13542         }
13543         tgt_info->tgt_addr = addr;
13544         tgt_info->tgt_name = tname;
13545         tgt_info->tgt_type = t;
13546         return 0;
13547 }
13548
13549 BTF_SET_START(btf_id_deny)
13550 BTF_ID_UNUSED
13551 #ifdef CONFIG_SMP
13552 BTF_ID(func, migrate_disable)
13553 BTF_ID(func, migrate_enable)
13554 #endif
13555 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13556 BTF_ID(func, rcu_read_unlock_strict)
13557 #endif
13558 BTF_SET_END(btf_id_deny)
13559
13560 static int check_attach_btf_id(struct bpf_verifier_env *env)
13561 {
13562         struct bpf_prog *prog = env->prog;
13563         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13564         struct bpf_attach_target_info tgt_info = {};
13565         u32 btf_id = prog->aux->attach_btf_id;
13566         struct bpf_trampoline *tr;
13567         int ret;
13568         u64 key;
13569
13570         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13571                 if (prog->aux->sleepable)
13572                         /* attach_btf_id checked to be zero already */
13573                         return 0;
13574                 verbose(env, "Syscall programs can only be sleepable\n");
13575                 return -EINVAL;
13576         }
13577
13578         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13579             prog->type != BPF_PROG_TYPE_LSM) {
13580                 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13581                 return -EINVAL;
13582         }
13583
13584         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13585                 return check_struct_ops_btf_id(env);
13586
13587         if (prog->type != BPF_PROG_TYPE_TRACING &&
13588             prog->type != BPF_PROG_TYPE_LSM &&
13589             prog->type != BPF_PROG_TYPE_EXT)
13590                 return 0;
13591
13592         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13593         if (ret)
13594                 return ret;
13595
13596         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13597                 /* to make freplace equivalent to their targets, they need to
13598                  * inherit env->ops and expected_attach_type for the rest of the
13599                  * verification
13600                  */
13601                 env->ops = bpf_verifier_ops[tgt_prog->type];
13602                 prog->expected_attach_type = tgt_prog->expected_attach_type;
13603         }
13604
13605         /* store info about the attachment target that will be used later */
13606         prog->aux->attach_func_proto = tgt_info.tgt_type;
13607         prog->aux->attach_func_name = tgt_info.tgt_name;
13608
13609         if (tgt_prog) {
13610                 prog->aux->saved_dst_prog_type = tgt_prog->type;
13611                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13612         }
13613
13614         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13615                 prog->aux->attach_btf_trace = true;
13616                 return 0;
13617         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13618                 if (!bpf_iter_prog_supported(prog))
13619                         return -EINVAL;
13620                 return 0;
13621         }
13622
13623         if (prog->type == BPF_PROG_TYPE_LSM) {
13624                 ret = bpf_lsm_verify_prog(&env->log, prog);
13625                 if (ret < 0)
13626                         return ret;
13627         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
13628                    btf_id_set_contains(&btf_id_deny, btf_id)) {
13629                 return -EINVAL;
13630         }
13631
13632         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13633         tr = bpf_trampoline_get(key, &tgt_info);
13634         if (!tr)
13635                 return -ENOMEM;
13636
13637         prog->aux->dst_trampoline = tr;
13638         return 0;
13639 }
13640
13641 struct btf *bpf_get_btf_vmlinux(void)
13642 {
13643         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13644                 mutex_lock(&bpf_verifier_lock);
13645                 if (!btf_vmlinux)
13646                         btf_vmlinux = btf_parse_vmlinux();
13647                 mutex_unlock(&bpf_verifier_lock);
13648         }
13649         return btf_vmlinux;
13650 }
13651
13652 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
13653 {
13654         u64 start_time = ktime_get_ns();
13655         struct bpf_verifier_env *env;
13656         struct bpf_verifier_log *log;
13657         int i, len, ret = -EINVAL;
13658         bool is_priv;
13659
13660         /* no program is valid */
13661         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13662                 return -EINVAL;
13663
13664         /* 'struct bpf_verifier_env' can be global, but since it's not small,
13665          * allocate/free it every time bpf_check() is called
13666          */
13667         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13668         if (!env)
13669                 return -ENOMEM;
13670         log = &env->log;
13671
13672         len = (*prog)->len;
13673         env->insn_aux_data =
13674                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13675         ret = -ENOMEM;
13676         if (!env->insn_aux_data)
13677                 goto err_free_env;
13678         for (i = 0; i < len; i++)
13679                 env->insn_aux_data[i].orig_idx = i;
13680         env->prog = *prog;
13681         env->ops = bpf_verifier_ops[env->prog->type];
13682         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
13683         is_priv = bpf_capable();
13684
13685         bpf_get_btf_vmlinux();
13686
13687         /* grab the mutex to protect few globals used by verifier */
13688         if (!is_priv)
13689                 mutex_lock(&bpf_verifier_lock);
13690
13691         if (attr->log_level || attr->log_buf || attr->log_size) {
13692                 /* user requested verbose verifier output
13693                  * and supplied buffer to store the verification trace
13694                  */
13695                 log->level = attr->log_level;
13696                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13697                 log->len_total = attr->log_size;
13698
13699                 /* log attributes have to be sane */
13700                 if (!bpf_verifier_log_attr_valid(log)) {
13701                         ret = -EINVAL;
13702                         goto err_unlock;
13703                 }
13704         }
13705
13706         if (IS_ERR(btf_vmlinux)) {
13707                 /* Either gcc or pahole or kernel are broken. */
13708                 verbose(env, "in-kernel BTF is malformed\n");
13709                 ret = PTR_ERR(btf_vmlinux);
13710                 goto skip_full_check;
13711         }
13712
13713         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13714         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13715                 env->strict_alignment = true;
13716         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13717                 env->strict_alignment = false;
13718
13719         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13720         env->allow_uninit_stack = bpf_allow_uninit_stack();
13721         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13722         env->bypass_spec_v1 = bpf_bypass_spec_v1();
13723         env->bypass_spec_v4 = bpf_bypass_spec_v4();
13724         env->bpf_capable = bpf_capable();
13725
13726         if (is_priv)
13727                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13728
13729         env->explored_states = kvcalloc(state_htab_size(env),
13730                                        sizeof(struct bpf_verifier_state_list *),
13731                                        GFP_USER);
13732         ret = -ENOMEM;
13733         if (!env->explored_states)
13734                 goto skip_full_check;
13735
13736         ret = add_subprog_and_kfunc(env);
13737         if (ret < 0)
13738                 goto skip_full_check;
13739
13740         ret = check_subprogs(env);
13741         if (ret < 0)
13742                 goto skip_full_check;
13743
13744         ret = check_btf_info(env, attr, uattr);
13745         if (ret < 0)
13746                 goto skip_full_check;
13747
13748         ret = check_attach_btf_id(env);
13749         if (ret)
13750                 goto skip_full_check;
13751
13752         ret = resolve_pseudo_ldimm64(env);
13753         if (ret < 0)
13754                 goto skip_full_check;
13755
13756         if (bpf_prog_is_dev_bound(env->prog->aux)) {
13757                 ret = bpf_prog_offload_verifier_prep(env->prog);
13758                 if (ret)
13759                         goto skip_full_check;
13760         }
13761
13762         ret = check_cfg(env);
13763         if (ret < 0)
13764                 goto skip_full_check;
13765
13766         ret = do_check_subprogs(env);
13767         ret = ret ?: do_check_main(env);
13768
13769         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13770                 ret = bpf_prog_offload_finalize(env);
13771
13772 skip_full_check:
13773         kvfree(env->explored_states);
13774
13775         if (ret == 0)
13776                 ret = check_max_stack_depth(env);
13777
13778         /* instruction rewrites happen after this point */
13779         if (is_priv) {
13780                 if (ret == 0)
13781                         opt_hard_wire_dead_code_branches(env);
13782                 if (ret == 0)
13783                         ret = opt_remove_dead_code(env);
13784                 if (ret == 0)
13785                         ret = opt_remove_nops(env);
13786         } else {
13787                 if (ret == 0)
13788                         sanitize_dead_code(env);
13789         }
13790
13791         if (ret == 0)
13792                 /* program is valid, convert *(u32*)(ctx + off) accesses */
13793                 ret = convert_ctx_accesses(env);
13794
13795         if (ret == 0)
13796                 ret = do_misc_fixups(env);
13797
13798         /* do 32-bit optimization after insn patching has done so those patched
13799          * insns could be handled correctly.
13800          */
13801         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13802                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13803                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13804                                                                      : false;
13805         }
13806
13807         if (ret == 0)
13808                 ret = fixup_call_args(env);
13809
13810         env->verification_time = ktime_get_ns() - start_time;
13811         print_verification_stats(env);
13812
13813         if (log->level && bpf_verifier_log_full(log))
13814                 ret = -ENOSPC;
13815         if (log->level && !log->ubuf) {
13816                 ret = -EFAULT;
13817                 goto err_release_maps;
13818         }
13819
13820         if (ret)
13821                 goto err_release_maps;
13822
13823         if (env->used_map_cnt) {
13824                 /* if program passed verifier, update used_maps in bpf_prog_info */
13825                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13826                                                           sizeof(env->used_maps[0]),
13827                                                           GFP_KERNEL);
13828
13829                 if (!env->prog->aux->used_maps) {
13830                         ret = -ENOMEM;
13831                         goto err_release_maps;
13832                 }
13833
13834                 memcpy(env->prog->aux->used_maps, env->used_maps,
13835                        sizeof(env->used_maps[0]) * env->used_map_cnt);
13836                 env->prog->aux->used_map_cnt = env->used_map_cnt;
13837         }
13838         if (env->used_btf_cnt) {
13839                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13840                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13841                                                           sizeof(env->used_btfs[0]),
13842                                                           GFP_KERNEL);
13843                 if (!env->prog->aux->used_btfs) {
13844                         ret = -ENOMEM;
13845                         goto err_release_maps;
13846                 }
13847
13848                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13849                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13850                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13851         }
13852         if (env->used_map_cnt || env->used_btf_cnt) {
13853                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13854                  * bpf_ld_imm64 instructions
13855                  */
13856                 convert_pseudo_ld_imm64(env);
13857         }
13858
13859         adjust_btf_func(env);
13860
13861 err_release_maps:
13862         if (!env->prog->aux->used_maps)
13863                 /* if we didn't copy map pointers into bpf_prog_info, release
13864                  * them now. Otherwise free_used_maps() will release them.
13865                  */
13866                 release_maps(env);
13867         if (!env->prog->aux->used_btfs)
13868                 release_btfs(env);
13869
13870         /* extension progs temporarily inherit the attach_type of their targets
13871            for verification purposes, so set it back to zero before returning
13872          */
13873         if (env->prog->type == BPF_PROG_TYPE_EXT)
13874                 env->prog->expected_attach_type = 0;
13875
13876         *prog = env->prog;
13877 err_unlock:
13878         if (!is_priv)
13879                 mutex_unlock(&bpf_verifier_lock);
13880         vfree(env->insn_aux_data);
13881 err_free_env:
13882         kfree(env);
13883         return ret;
13884 }