Merge git://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next
[sfrench/cifs-2.6.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 pathes 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 ether 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_func(const struct bpf_insn *insn)
238 {
239         return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
240                insn->src_reg == BPF_PSEUDO_FUNC;
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 func_id;
253         struct btf *btf;
254         u32 btf_id;
255         struct btf *ret_btf;
256         u32 ret_btf_id;
257         u32 subprogno;
258 };
259
260 struct btf *btf_vmlinux;
261
262 static DEFINE_MUTEX(bpf_verifier_lock);
263
264 static const struct bpf_line_info *
265 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
266 {
267         const struct bpf_line_info *linfo;
268         const struct bpf_prog *prog;
269         u32 i, nr_linfo;
270
271         prog = env->prog;
272         nr_linfo = prog->aux->nr_linfo;
273
274         if (!nr_linfo || insn_off >= prog->len)
275                 return NULL;
276
277         linfo = prog->aux->linfo;
278         for (i = 1; i < nr_linfo; i++)
279                 if (insn_off < linfo[i].insn_off)
280                         break;
281
282         return &linfo[i - 1];
283 }
284
285 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
286                        va_list args)
287 {
288         unsigned int n;
289
290         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
291
292         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
293                   "verifier log line truncated - local buffer too short\n");
294
295         n = min(log->len_total - log->len_used - 1, n);
296         log->kbuf[n] = '\0';
297
298         if (log->level == BPF_LOG_KERNEL) {
299                 pr_err("BPF:%s\n", log->kbuf);
300                 return;
301         }
302         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
303                 log->len_used += n;
304         else
305                 log->ubuf = NULL;
306 }
307
308 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
309 {
310         char zero = 0;
311
312         if (!bpf_verifier_log_needed(log))
313                 return;
314
315         log->len_used = new_pos;
316         if (put_user(zero, log->ubuf + new_pos))
317                 log->ubuf = NULL;
318 }
319
320 /* log_level controls verbosity level of eBPF verifier.
321  * bpf_verifier_log_write() is used to dump the verification trace to the log,
322  * so the user can figure out what's wrong with the program
323  */
324 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
325                                            const char *fmt, ...)
326 {
327         va_list args;
328
329         if (!bpf_verifier_log_needed(&env->log))
330                 return;
331
332         va_start(args, fmt);
333         bpf_verifier_vlog(&env->log, fmt, args);
334         va_end(args);
335 }
336 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
337
338 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
339 {
340         struct bpf_verifier_env *env = private_data;
341         va_list args;
342
343         if (!bpf_verifier_log_needed(&env->log))
344                 return;
345
346         va_start(args, fmt);
347         bpf_verifier_vlog(&env->log, fmt, args);
348         va_end(args);
349 }
350
351 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
352                             const char *fmt, ...)
353 {
354         va_list args;
355
356         if (!bpf_verifier_log_needed(log))
357                 return;
358
359         va_start(args, fmt);
360         bpf_verifier_vlog(log, fmt, args);
361         va_end(args);
362 }
363
364 static const char *ltrim(const char *s)
365 {
366         while (isspace(*s))
367                 s++;
368
369         return s;
370 }
371
372 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
373                                          u32 insn_off,
374                                          const char *prefix_fmt, ...)
375 {
376         const struct bpf_line_info *linfo;
377
378         if (!bpf_verifier_log_needed(&env->log))
379                 return;
380
381         linfo = find_linfo(env, insn_off);
382         if (!linfo || linfo == env->prev_linfo)
383                 return;
384
385         if (prefix_fmt) {
386                 va_list args;
387
388                 va_start(args, prefix_fmt);
389                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
390                 va_end(args);
391         }
392
393         verbose(env, "%s\n",
394                 ltrim(btf_name_by_offset(env->prog->aux->btf,
395                                          linfo->line_off)));
396
397         env->prev_linfo = linfo;
398 }
399
400 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
401                                    struct bpf_reg_state *reg,
402                                    struct tnum *range, const char *ctx,
403                                    const char *reg_name)
404 {
405         char tn_buf[48];
406
407         verbose(env, "At %s the register %s ", ctx, reg_name);
408         if (!tnum_is_unknown(reg->var_off)) {
409                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
410                 verbose(env, "has value %s", tn_buf);
411         } else {
412                 verbose(env, "has unknown scalar value");
413         }
414         tnum_strn(tn_buf, sizeof(tn_buf), *range);
415         verbose(env, " should have been in %s\n", tn_buf);
416 }
417
418 static bool type_is_pkt_pointer(enum bpf_reg_type type)
419 {
420         return type == PTR_TO_PACKET ||
421                type == PTR_TO_PACKET_META;
422 }
423
424 static bool type_is_sk_pointer(enum bpf_reg_type type)
425 {
426         return type == PTR_TO_SOCKET ||
427                 type == PTR_TO_SOCK_COMMON ||
428                 type == PTR_TO_TCP_SOCK ||
429                 type == PTR_TO_XDP_SOCK;
430 }
431
432 static bool reg_type_not_null(enum bpf_reg_type type)
433 {
434         return type == PTR_TO_SOCKET ||
435                 type == PTR_TO_TCP_SOCK ||
436                 type == PTR_TO_MAP_VALUE ||
437                 type == PTR_TO_MAP_KEY ||
438                 type == PTR_TO_SOCK_COMMON;
439 }
440
441 static bool reg_type_may_be_null(enum bpf_reg_type type)
442 {
443         return type == PTR_TO_MAP_VALUE_OR_NULL ||
444                type == PTR_TO_SOCKET_OR_NULL ||
445                type == PTR_TO_SOCK_COMMON_OR_NULL ||
446                type == PTR_TO_TCP_SOCK_OR_NULL ||
447                type == PTR_TO_BTF_ID_OR_NULL ||
448                type == PTR_TO_MEM_OR_NULL ||
449                type == PTR_TO_RDONLY_BUF_OR_NULL ||
450                type == PTR_TO_RDWR_BUF_OR_NULL;
451 }
452
453 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
454 {
455         return reg->type == PTR_TO_MAP_VALUE &&
456                 map_value_has_spin_lock(reg->map_ptr);
457 }
458
459 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
460 {
461         return type == PTR_TO_SOCKET ||
462                 type == PTR_TO_SOCKET_OR_NULL ||
463                 type == PTR_TO_TCP_SOCK ||
464                 type == PTR_TO_TCP_SOCK_OR_NULL ||
465                 type == PTR_TO_MEM ||
466                 type == PTR_TO_MEM_OR_NULL;
467 }
468
469 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
470 {
471         return type == ARG_PTR_TO_SOCK_COMMON;
472 }
473
474 static bool arg_type_may_be_null(enum bpf_arg_type type)
475 {
476         return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
477                type == ARG_PTR_TO_MEM_OR_NULL ||
478                type == ARG_PTR_TO_CTX_OR_NULL ||
479                type == ARG_PTR_TO_SOCKET_OR_NULL ||
480                type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
481                type == ARG_PTR_TO_STACK_OR_NULL;
482 }
483
484 /* Determine whether the function releases some resources allocated by another
485  * function call. The first reference type argument will be assumed to be
486  * released by release_reference().
487  */
488 static bool is_release_function(enum bpf_func_id func_id)
489 {
490         return func_id == BPF_FUNC_sk_release ||
491                func_id == BPF_FUNC_ringbuf_submit ||
492                func_id == BPF_FUNC_ringbuf_discard;
493 }
494
495 static bool may_be_acquire_function(enum bpf_func_id func_id)
496 {
497         return func_id == BPF_FUNC_sk_lookup_tcp ||
498                 func_id == BPF_FUNC_sk_lookup_udp ||
499                 func_id == BPF_FUNC_skc_lookup_tcp ||
500                 func_id == BPF_FUNC_map_lookup_elem ||
501                 func_id == BPF_FUNC_ringbuf_reserve;
502 }
503
504 static bool is_acquire_function(enum bpf_func_id func_id,
505                                 const struct bpf_map *map)
506 {
507         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
508
509         if (func_id == BPF_FUNC_sk_lookup_tcp ||
510             func_id == BPF_FUNC_sk_lookup_udp ||
511             func_id == BPF_FUNC_skc_lookup_tcp ||
512             func_id == BPF_FUNC_ringbuf_reserve)
513                 return true;
514
515         if (func_id == BPF_FUNC_map_lookup_elem &&
516             (map_type == BPF_MAP_TYPE_SOCKMAP ||
517              map_type == BPF_MAP_TYPE_SOCKHASH))
518                 return true;
519
520         return false;
521 }
522
523 static bool is_ptr_cast_function(enum bpf_func_id func_id)
524 {
525         return func_id == BPF_FUNC_tcp_sock ||
526                 func_id == BPF_FUNC_sk_fullsock ||
527                 func_id == BPF_FUNC_skc_to_tcp_sock ||
528                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
529                 func_id == BPF_FUNC_skc_to_udp6_sock ||
530                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
531                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
532 }
533
534 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
535 {
536         return BPF_CLASS(insn->code) == BPF_STX &&
537                BPF_MODE(insn->code) == BPF_ATOMIC &&
538                insn->imm == BPF_CMPXCHG;
539 }
540
541 /* string representation of 'enum bpf_reg_type' */
542 static const char * const reg_type_str[] = {
543         [NOT_INIT]              = "?",
544         [SCALAR_VALUE]          = "inv",
545         [PTR_TO_CTX]            = "ctx",
546         [CONST_PTR_TO_MAP]      = "map_ptr",
547         [PTR_TO_MAP_VALUE]      = "map_value",
548         [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
549         [PTR_TO_STACK]          = "fp",
550         [PTR_TO_PACKET]         = "pkt",
551         [PTR_TO_PACKET_META]    = "pkt_meta",
552         [PTR_TO_PACKET_END]     = "pkt_end",
553         [PTR_TO_FLOW_KEYS]      = "flow_keys",
554         [PTR_TO_SOCKET]         = "sock",
555         [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
556         [PTR_TO_SOCK_COMMON]    = "sock_common",
557         [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
558         [PTR_TO_TCP_SOCK]       = "tcp_sock",
559         [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
560         [PTR_TO_TP_BUFFER]      = "tp_buffer",
561         [PTR_TO_XDP_SOCK]       = "xdp_sock",
562         [PTR_TO_BTF_ID]         = "ptr_",
563         [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
564         [PTR_TO_PERCPU_BTF_ID]  = "percpu_ptr_",
565         [PTR_TO_MEM]            = "mem",
566         [PTR_TO_MEM_OR_NULL]    = "mem_or_null",
567         [PTR_TO_RDONLY_BUF]     = "rdonly_buf",
568         [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
569         [PTR_TO_RDWR_BUF]       = "rdwr_buf",
570         [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
571         [PTR_TO_FUNC]           = "func",
572         [PTR_TO_MAP_KEY]        = "map_key",
573 };
574
575 static char slot_type_char[] = {
576         [STACK_INVALID] = '?',
577         [STACK_SPILL]   = 'r',
578         [STACK_MISC]    = 'm',
579         [STACK_ZERO]    = '0',
580 };
581
582 static void print_liveness(struct bpf_verifier_env *env,
583                            enum bpf_reg_liveness live)
584 {
585         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
586             verbose(env, "_");
587         if (live & REG_LIVE_READ)
588                 verbose(env, "r");
589         if (live & REG_LIVE_WRITTEN)
590                 verbose(env, "w");
591         if (live & REG_LIVE_DONE)
592                 verbose(env, "D");
593 }
594
595 static struct bpf_func_state *func(struct bpf_verifier_env *env,
596                                    const struct bpf_reg_state *reg)
597 {
598         struct bpf_verifier_state *cur = env->cur_state;
599
600         return cur->frame[reg->frameno];
601 }
602
603 static const char *kernel_type_name(const struct btf* btf, u32 id)
604 {
605         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
606 }
607
608 static void print_verifier_state(struct bpf_verifier_env *env,
609                                  const struct bpf_func_state *state)
610 {
611         const struct bpf_reg_state *reg;
612         enum bpf_reg_type t;
613         int i;
614
615         if (state->frameno)
616                 verbose(env, " frame%d:", state->frameno);
617         for (i = 0; i < MAX_BPF_REG; i++) {
618                 reg = &state->regs[i];
619                 t = reg->type;
620                 if (t == NOT_INIT)
621                         continue;
622                 verbose(env, " R%d", i);
623                 print_liveness(env, reg->live);
624                 verbose(env, "=%s", reg_type_str[t]);
625                 if (t == SCALAR_VALUE && reg->precise)
626                         verbose(env, "P");
627                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
628                     tnum_is_const(reg->var_off)) {
629                         /* reg->off should be 0 for SCALAR_VALUE */
630                         verbose(env, "%lld", reg->var_off.value + reg->off);
631                 } else {
632                         if (t == PTR_TO_BTF_ID ||
633                             t == PTR_TO_BTF_ID_OR_NULL ||
634                             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 (t == CONST_PTR_TO_MAP ||
644                                  t == PTR_TO_MAP_KEY ||
645                                  t == PTR_TO_MAP_VALUE ||
646                                  t == PTR_TO_MAP_VALUE_OR_NULL)
647                                 verbose(env, ",ks=%d,vs=%d",
648                                         reg->map_ptr->key_size,
649                                         reg->map_ptr->value_size);
650                         if (tnum_is_const(reg->var_off)) {
651                                 /* Typically an immediate SCALAR_VALUE, but
652                                  * could be a pointer whose offset is too big
653                                  * for reg->off
654                                  */
655                                 verbose(env, ",imm=%llx", reg->var_off.value);
656                         } else {
657                                 if (reg->smin_value != reg->umin_value &&
658                                     reg->smin_value != S64_MIN)
659                                         verbose(env, ",smin_value=%lld",
660                                                 (long long)reg->smin_value);
661                                 if (reg->smax_value != reg->umax_value &&
662                                     reg->smax_value != S64_MAX)
663                                         verbose(env, ",smax_value=%lld",
664                                                 (long long)reg->smax_value);
665                                 if (reg->umin_value != 0)
666                                         verbose(env, ",umin_value=%llu",
667                                                 (unsigned long long)reg->umin_value);
668                                 if (reg->umax_value != U64_MAX)
669                                         verbose(env, ",umax_value=%llu",
670                                                 (unsigned long long)reg->umax_value);
671                                 if (!tnum_is_unknown(reg->var_off)) {
672                                         char tn_buf[48];
673
674                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
675                                         verbose(env, ",var_off=%s", tn_buf);
676                                 }
677                                 if (reg->s32_min_value != reg->smin_value &&
678                                     reg->s32_min_value != S32_MIN)
679                                         verbose(env, ",s32_min_value=%d",
680                                                 (int)(reg->s32_min_value));
681                                 if (reg->s32_max_value != reg->smax_value &&
682                                     reg->s32_max_value != S32_MAX)
683                                         verbose(env, ",s32_max_value=%d",
684                                                 (int)(reg->s32_max_value));
685                                 if (reg->u32_min_value != reg->umin_value &&
686                                     reg->u32_min_value != U32_MIN)
687                                         verbose(env, ",u32_min_value=%d",
688                                                 (int)(reg->u32_min_value));
689                                 if (reg->u32_max_value != reg->umax_value &&
690                                     reg->u32_max_value != U32_MAX)
691                                         verbose(env, ",u32_max_value=%d",
692                                                 (int)(reg->u32_max_value));
693                         }
694                         verbose(env, ")");
695                 }
696         }
697         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
698                 char types_buf[BPF_REG_SIZE + 1];
699                 bool valid = false;
700                 int j;
701
702                 for (j = 0; j < BPF_REG_SIZE; j++) {
703                         if (state->stack[i].slot_type[j] != STACK_INVALID)
704                                 valid = true;
705                         types_buf[j] = slot_type_char[
706                                         state->stack[i].slot_type[j]];
707                 }
708                 types_buf[BPF_REG_SIZE] = 0;
709                 if (!valid)
710                         continue;
711                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
712                 print_liveness(env, state->stack[i].spilled_ptr.live);
713                 if (state->stack[i].slot_type[0] == STACK_SPILL) {
714                         reg = &state->stack[i].spilled_ptr;
715                         t = reg->type;
716                         verbose(env, "=%s", reg_type_str[t]);
717                         if (t == SCALAR_VALUE && reg->precise)
718                                 verbose(env, "P");
719                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
720                                 verbose(env, "%lld", reg->var_off.value + reg->off);
721                 } else {
722                         verbose(env, "=%s", types_buf);
723                 }
724         }
725         if (state->acquired_refs && state->refs[0].id) {
726                 verbose(env, " refs=%d", state->refs[0].id);
727                 for (i = 1; i < state->acquired_refs; i++)
728                         if (state->refs[i].id)
729                                 verbose(env, ",%d", state->refs[i].id);
730         }
731         verbose(env, "\n");
732 }
733
734 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)                         \
735 static int copy_##NAME##_state(struct bpf_func_state *dst,              \
736                                const struct bpf_func_state *src)        \
737 {                                                                       \
738         if (!src->FIELD)                                                \
739                 return 0;                                               \
740         if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {                    \
741                 /* internal bug, make state invalid to reject the program */ \
742                 memset(dst, 0, sizeof(*dst));                           \
743                 return -EFAULT;                                         \
744         }                                                               \
745         memcpy(dst->FIELD, src->FIELD,                                  \
746                sizeof(*src->FIELD) * (src->COUNT / SIZE));              \
747         return 0;                                                       \
748 }
749 /* copy_reference_state() */
750 COPY_STATE_FN(reference, acquired_refs, refs, 1)
751 /* copy_stack_state() */
752 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
753 #undef COPY_STATE_FN
754
755 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)                      \
756 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
757                                   bool copy_old)                        \
758 {                                                                       \
759         u32 old_size = state->COUNT;                                    \
760         struct bpf_##NAME##_state *new_##FIELD;                         \
761         int slot = size / SIZE;                                         \
762                                                                         \
763         if (size <= old_size || !size) {                                \
764                 if (copy_old)                                           \
765                         return 0;                                       \
766                 state->COUNT = slot * SIZE;                             \
767                 if (!size && old_size) {                                \
768                         kfree(state->FIELD);                            \
769                         state->FIELD = NULL;                            \
770                 }                                                       \
771                 return 0;                                               \
772         }                                                               \
773         new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
774                                     GFP_KERNEL);                        \
775         if (!new_##FIELD)                                               \
776                 return -ENOMEM;                                         \
777         if (copy_old) {                                                 \
778                 if (state->FIELD)                                       \
779                         memcpy(new_##FIELD, state->FIELD,               \
780                                sizeof(*new_##FIELD) * (old_size / SIZE)); \
781                 memset(new_##FIELD + old_size / SIZE, 0,                \
782                        sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
783         }                                                               \
784         state->COUNT = slot * SIZE;                                     \
785         kfree(state->FIELD);                                            \
786         state->FIELD = new_##FIELD;                                     \
787         return 0;                                                       \
788 }
789 /* realloc_reference_state() */
790 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
791 /* realloc_stack_state() */
792 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
793 #undef REALLOC_STATE_FN
794
795 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
796  * make it consume minimal amount of memory. check_stack_write() access from
797  * the program calls into realloc_func_state() to grow the stack size.
798  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
799  * which realloc_stack_state() copies over. It points to previous
800  * bpf_verifier_state which is never reallocated.
801  */
802 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
803                               int refs_size, bool copy_old)
804 {
805         int err = realloc_reference_state(state, refs_size, copy_old);
806         if (err)
807                 return err;
808         return realloc_stack_state(state, stack_size, copy_old);
809 }
810
811 /* Acquire a pointer id from the env and update the state->refs to include
812  * this new pointer reference.
813  * On success, returns a valid pointer id to associate with the register
814  * On failure, returns a negative errno.
815  */
816 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
817 {
818         struct bpf_func_state *state = cur_func(env);
819         int new_ofs = state->acquired_refs;
820         int id, err;
821
822         err = realloc_reference_state(state, state->acquired_refs + 1, true);
823         if (err)
824                 return err;
825         id = ++env->id_gen;
826         state->refs[new_ofs].id = id;
827         state->refs[new_ofs].insn_idx = insn_idx;
828
829         return id;
830 }
831
832 /* release function corresponding to acquire_reference_state(). Idempotent. */
833 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
834 {
835         int i, last_idx;
836
837         last_idx = state->acquired_refs - 1;
838         for (i = 0; i < state->acquired_refs; i++) {
839                 if (state->refs[i].id == ptr_id) {
840                         if (last_idx && i != last_idx)
841                                 memcpy(&state->refs[i], &state->refs[last_idx],
842                                        sizeof(*state->refs));
843                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
844                         state->acquired_refs--;
845                         return 0;
846                 }
847         }
848         return -EINVAL;
849 }
850
851 static int transfer_reference_state(struct bpf_func_state *dst,
852                                     struct bpf_func_state *src)
853 {
854         int err = realloc_reference_state(dst, src->acquired_refs, false);
855         if (err)
856                 return err;
857         err = copy_reference_state(dst, src);
858         if (err)
859                 return err;
860         return 0;
861 }
862
863 static void free_func_state(struct bpf_func_state *state)
864 {
865         if (!state)
866                 return;
867         kfree(state->refs);
868         kfree(state->stack);
869         kfree(state);
870 }
871
872 static void clear_jmp_history(struct bpf_verifier_state *state)
873 {
874         kfree(state->jmp_history);
875         state->jmp_history = NULL;
876         state->jmp_history_cnt = 0;
877 }
878
879 static void free_verifier_state(struct bpf_verifier_state *state,
880                                 bool free_self)
881 {
882         int i;
883
884         for (i = 0; i <= state->curframe; i++) {
885                 free_func_state(state->frame[i]);
886                 state->frame[i] = NULL;
887         }
888         clear_jmp_history(state);
889         if (free_self)
890                 kfree(state);
891 }
892
893 /* copy verifier state from src to dst growing dst stack space
894  * when necessary to accommodate larger src stack
895  */
896 static int copy_func_state(struct bpf_func_state *dst,
897                            const struct bpf_func_state *src)
898 {
899         int err;
900
901         err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
902                                  false);
903         if (err)
904                 return err;
905         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
906         err = copy_reference_state(dst, src);
907         if (err)
908                 return err;
909         return copy_stack_state(dst, src);
910 }
911
912 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
913                                const struct bpf_verifier_state *src)
914 {
915         struct bpf_func_state *dst;
916         u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
917         int i, err;
918
919         if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
920                 kfree(dst_state->jmp_history);
921                 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
922                 if (!dst_state->jmp_history)
923                         return -ENOMEM;
924         }
925         memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
926         dst_state->jmp_history_cnt = src->jmp_history_cnt;
927
928         /* if dst has more stack frames then src frame, free them */
929         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
930                 free_func_state(dst_state->frame[i]);
931                 dst_state->frame[i] = NULL;
932         }
933         dst_state->speculative = src->speculative;
934         dst_state->curframe = src->curframe;
935         dst_state->active_spin_lock = src->active_spin_lock;
936         dst_state->branches = src->branches;
937         dst_state->parent = src->parent;
938         dst_state->first_insn_idx = src->first_insn_idx;
939         dst_state->last_insn_idx = src->last_insn_idx;
940         for (i = 0; i <= src->curframe; i++) {
941                 dst = dst_state->frame[i];
942                 if (!dst) {
943                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
944                         if (!dst)
945                                 return -ENOMEM;
946                         dst_state->frame[i] = dst;
947                 }
948                 err = copy_func_state(dst, src->frame[i]);
949                 if (err)
950                         return err;
951         }
952         return 0;
953 }
954
955 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
956 {
957         while (st) {
958                 u32 br = --st->branches;
959
960                 /* WARN_ON(br > 1) technically makes sense here,
961                  * but see comment in push_stack(), hence:
962                  */
963                 WARN_ONCE((int)br < 0,
964                           "BUG update_branch_counts:branches_to_explore=%d\n",
965                           br);
966                 if (br)
967                         break;
968                 st = st->parent;
969         }
970 }
971
972 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
973                      int *insn_idx, bool pop_log)
974 {
975         struct bpf_verifier_state *cur = env->cur_state;
976         struct bpf_verifier_stack_elem *elem, *head = env->head;
977         int err;
978
979         if (env->head == NULL)
980                 return -ENOENT;
981
982         if (cur) {
983                 err = copy_verifier_state(cur, &head->st);
984                 if (err)
985                         return err;
986         }
987         if (pop_log)
988                 bpf_vlog_reset(&env->log, head->log_pos);
989         if (insn_idx)
990                 *insn_idx = head->insn_idx;
991         if (prev_insn_idx)
992                 *prev_insn_idx = head->prev_insn_idx;
993         elem = head->next;
994         free_verifier_state(&head->st, false);
995         kfree(head);
996         env->head = elem;
997         env->stack_size--;
998         return 0;
999 }
1000
1001 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1002                                              int insn_idx, int prev_insn_idx,
1003                                              bool speculative)
1004 {
1005         struct bpf_verifier_state *cur = env->cur_state;
1006         struct bpf_verifier_stack_elem *elem;
1007         int err;
1008
1009         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1010         if (!elem)
1011                 goto err;
1012
1013         elem->insn_idx = insn_idx;
1014         elem->prev_insn_idx = prev_insn_idx;
1015         elem->next = env->head;
1016         elem->log_pos = env->log.len_used;
1017         env->head = elem;
1018         env->stack_size++;
1019         err = copy_verifier_state(&elem->st, cur);
1020         if (err)
1021                 goto err;
1022         elem->st.speculative |= speculative;
1023         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1024                 verbose(env, "The sequence of %d jumps is too complex.\n",
1025                         env->stack_size);
1026                 goto err;
1027         }
1028         if (elem->st.parent) {
1029                 ++elem->st.parent->branches;
1030                 /* WARN_ON(branches > 2) technically makes sense here,
1031                  * but
1032                  * 1. speculative states will bump 'branches' for non-branch
1033                  * instructions
1034                  * 2. is_state_visited() heuristics may decide not to create
1035                  * a new state for a sequence of branches and all such current
1036                  * and cloned states will be pointing to a single parent state
1037                  * which might have large 'branches' count.
1038                  */
1039         }
1040         return &elem->st;
1041 err:
1042         free_verifier_state(env->cur_state, true);
1043         env->cur_state = NULL;
1044         /* pop all elements and return */
1045         while (!pop_stack(env, NULL, NULL, false));
1046         return NULL;
1047 }
1048
1049 #define CALLER_SAVED_REGS 6
1050 static const int caller_saved[CALLER_SAVED_REGS] = {
1051         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1052 };
1053
1054 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1055                                 struct bpf_reg_state *reg);
1056
1057 /* This helper doesn't clear reg->id */
1058 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1059 {
1060         reg->var_off = tnum_const(imm);
1061         reg->smin_value = (s64)imm;
1062         reg->smax_value = (s64)imm;
1063         reg->umin_value = imm;
1064         reg->umax_value = imm;
1065
1066         reg->s32_min_value = (s32)imm;
1067         reg->s32_max_value = (s32)imm;
1068         reg->u32_min_value = (u32)imm;
1069         reg->u32_max_value = (u32)imm;
1070 }
1071
1072 /* Mark the unknown part of a register (variable offset or scalar value) as
1073  * known to have the value @imm.
1074  */
1075 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1076 {
1077         /* Clear id, off, and union(map_ptr, range) */
1078         memset(((u8 *)reg) + sizeof(reg->type), 0,
1079                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1080         ___mark_reg_known(reg, imm);
1081 }
1082
1083 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1084 {
1085         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1086         reg->s32_min_value = (s32)imm;
1087         reg->s32_max_value = (s32)imm;
1088         reg->u32_min_value = (u32)imm;
1089         reg->u32_max_value = (u32)imm;
1090 }
1091
1092 /* Mark the 'variable offset' part of a register as zero.  This should be
1093  * used only on registers holding a pointer type.
1094  */
1095 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1096 {
1097         __mark_reg_known(reg, 0);
1098 }
1099
1100 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1101 {
1102         __mark_reg_known(reg, 0);
1103         reg->type = SCALAR_VALUE;
1104 }
1105
1106 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1107                                 struct bpf_reg_state *regs, u32 regno)
1108 {
1109         if (WARN_ON(regno >= MAX_BPF_REG)) {
1110                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1111                 /* Something bad happened, let's kill all regs */
1112                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1113                         __mark_reg_not_init(env, regs + regno);
1114                 return;
1115         }
1116         __mark_reg_known_zero(regs + regno);
1117 }
1118
1119 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1120 {
1121         switch (reg->type) {
1122         case PTR_TO_MAP_VALUE_OR_NULL: {
1123                 const struct bpf_map *map = reg->map_ptr;
1124
1125                 if (map->inner_map_meta) {
1126                         reg->type = CONST_PTR_TO_MAP;
1127                         reg->map_ptr = map->inner_map_meta;
1128                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1129                         reg->type = PTR_TO_XDP_SOCK;
1130                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1131                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1132                         reg->type = PTR_TO_SOCKET;
1133                 } else {
1134                         reg->type = PTR_TO_MAP_VALUE;
1135                 }
1136                 break;
1137         }
1138         case PTR_TO_SOCKET_OR_NULL:
1139                 reg->type = PTR_TO_SOCKET;
1140                 break;
1141         case PTR_TO_SOCK_COMMON_OR_NULL:
1142                 reg->type = PTR_TO_SOCK_COMMON;
1143                 break;
1144         case PTR_TO_TCP_SOCK_OR_NULL:
1145                 reg->type = PTR_TO_TCP_SOCK;
1146                 break;
1147         case PTR_TO_BTF_ID_OR_NULL:
1148                 reg->type = PTR_TO_BTF_ID;
1149                 break;
1150         case PTR_TO_MEM_OR_NULL:
1151                 reg->type = PTR_TO_MEM;
1152                 break;
1153         case PTR_TO_RDONLY_BUF_OR_NULL:
1154                 reg->type = PTR_TO_RDONLY_BUF;
1155                 break;
1156         case PTR_TO_RDWR_BUF_OR_NULL:
1157                 reg->type = PTR_TO_RDWR_BUF;
1158                 break;
1159         default:
1160                 WARN_ONCE(1, "unknown nullable register type");
1161         }
1162 }
1163
1164 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1165 {
1166         return type_is_pkt_pointer(reg->type);
1167 }
1168
1169 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1170 {
1171         return reg_is_pkt_pointer(reg) ||
1172                reg->type == PTR_TO_PACKET_END;
1173 }
1174
1175 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1176 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1177                                     enum bpf_reg_type which)
1178 {
1179         /* The register can already have a range from prior markings.
1180          * This is fine as long as it hasn't been advanced from its
1181          * origin.
1182          */
1183         return reg->type == which &&
1184                reg->id == 0 &&
1185                reg->off == 0 &&
1186                tnum_equals_const(reg->var_off, 0);
1187 }
1188
1189 /* Reset the min/max bounds of a register */
1190 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1191 {
1192         reg->smin_value = S64_MIN;
1193         reg->smax_value = S64_MAX;
1194         reg->umin_value = 0;
1195         reg->umax_value = U64_MAX;
1196
1197         reg->s32_min_value = S32_MIN;
1198         reg->s32_max_value = S32_MAX;
1199         reg->u32_min_value = 0;
1200         reg->u32_max_value = U32_MAX;
1201 }
1202
1203 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1204 {
1205         reg->smin_value = S64_MIN;
1206         reg->smax_value = S64_MAX;
1207         reg->umin_value = 0;
1208         reg->umax_value = U64_MAX;
1209 }
1210
1211 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1212 {
1213         reg->s32_min_value = S32_MIN;
1214         reg->s32_max_value = S32_MAX;
1215         reg->u32_min_value = 0;
1216         reg->u32_max_value = U32_MAX;
1217 }
1218
1219 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1220 {
1221         struct tnum var32_off = tnum_subreg(reg->var_off);
1222
1223         /* min signed is max(sign bit) | min(other bits) */
1224         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1225                         var32_off.value | (var32_off.mask & S32_MIN));
1226         /* max signed is min(sign bit) | max(other bits) */
1227         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1228                         var32_off.value | (var32_off.mask & S32_MAX));
1229         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1230         reg->u32_max_value = min(reg->u32_max_value,
1231                                  (u32)(var32_off.value | var32_off.mask));
1232 }
1233
1234 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1235 {
1236         /* min signed is max(sign bit) | min(other bits) */
1237         reg->smin_value = max_t(s64, reg->smin_value,
1238                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1239         /* max signed is min(sign bit) | max(other bits) */
1240         reg->smax_value = min_t(s64, reg->smax_value,
1241                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1242         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1243         reg->umax_value = min(reg->umax_value,
1244                               reg->var_off.value | reg->var_off.mask);
1245 }
1246
1247 static void __update_reg_bounds(struct bpf_reg_state *reg)
1248 {
1249         __update_reg32_bounds(reg);
1250         __update_reg64_bounds(reg);
1251 }
1252
1253 /* Uses signed min/max values to inform unsigned, and vice-versa */
1254 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1255 {
1256         /* Learn sign from signed bounds.
1257          * If we cannot cross the sign boundary, then signed and unsigned bounds
1258          * are the same, so combine.  This works even in the negative case, e.g.
1259          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1260          */
1261         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1262                 reg->s32_min_value = reg->u32_min_value =
1263                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1264                 reg->s32_max_value = reg->u32_max_value =
1265                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1266                 return;
1267         }
1268         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1269          * boundary, so we must be careful.
1270          */
1271         if ((s32)reg->u32_max_value >= 0) {
1272                 /* Positive.  We can't learn anything from the smin, but smax
1273                  * is positive, hence safe.
1274                  */
1275                 reg->s32_min_value = reg->u32_min_value;
1276                 reg->s32_max_value = reg->u32_max_value =
1277                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1278         } else if ((s32)reg->u32_min_value < 0) {
1279                 /* Negative.  We can't learn anything from the smax, but smin
1280                  * is negative, hence safe.
1281                  */
1282                 reg->s32_min_value = reg->u32_min_value =
1283                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1284                 reg->s32_max_value = reg->u32_max_value;
1285         }
1286 }
1287
1288 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1289 {
1290         /* Learn sign from signed bounds.
1291          * If we cannot cross the sign boundary, then signed and unsigned bounds
1292          * are the same, so combine.  This works even in the negative case, e.g.
1293          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1294          */
1295         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1296                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1297                                                           reg->umin_value);
1298                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1299                                                           reg->umax_value);
1300                 return;
1301         }
1302         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1303          * boundary, so we must be careful.
1304          */
1305         if ((s64)reg->umax_value >= 0) {
1306                 /* Positive.  We can't learn anything from the smin, but smax
1307                  * is positive, hence safe.
1308                  */
1309                 reg->smin_value = reg->umin_value;
1310                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1311                                                           reg->umax_value);
1312         } else if ((s64)reg->umin_value < 0) {
1313                 /* Negative.  We can't learn anything from the smax, but smin
1314                  * is negative, hence safe.
1315                  */
1316                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1317                                                           reg->umin_value);
1318                 reg->smax_value = reg->umax_value;
1319         }
1320 }
1321
1322 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1323 {
1324         __reg32_deduce_bounds(reg);
1325         __reg64_deduce_bounds(reg);
1326 }
1327
1328 /* Attempts to improve var_off based on unsigned min/max information */
1329 static void __reg_bound_offset(struct bpf_reg_state *reg)
1330 {
1331         struct tnum var64_off = tnum_intersect(reg->var_off,
1332                                                tnum_range(reg->umin_value,
1333                                                           reg->umax_value));
1334         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1335                                                 tnum_range(reg->u32_min_value,
1336                                                            reg->u32_max_value));
1337
1338         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1339 }
1340
1341 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1342 {
1343         reg->umin_value = reg->u32_min_value;
1344         reg->umax_value = reg->u32_max_value;
1345         /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1346          * but must be positive otherwise set to worse case bounds
1347          * and refine later from tnum.
1348          */
1349         if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1350                 reg->smax_value = reg->s32_max_value;
1351         else
1352                 reg->smax_value = U32_MAX;
1353         if (reg->s32_min_value >= 0)
1354                 reg->smin_value = reg->s32_min_value;
1355         else
1356                 reg->smin_value = 0;
1357 }
1358
1359 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1360 {
1361         /* special case when 64-bit register has upper 32-bit register
1362          * zeroed. Typically happens after zext or <<32, >>32 sequence
1363          * allowing us to use 32-bit bounds directly,
1364          */
1365         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1366                 __reg_assign_32_into_64(reg);
1367         } else {
1368                 /* Otherwise the best we can do is push lower 32bit known and
1369                  * unknown bits into register (var_off set from jmp logic)
1370                  * then learn as much as possible from the 64-bit tnum
1371                  * known and unknown bits. The previous smin/smax bounds are
1372                  * invalid here because of jmp32 compare so mark them unknown
1373                  * so they do not impact tnum bounds calculation.
1374                  */
1375                 __mark_reg64_unbounded(reg);
1376                 __update_reg_bounds(reg);
1377         }
1378
1379         /* Intersecting with the old var_off might have improved our bounds
1380          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1381          * then new var_off is (0; 0x7f...fc) which improves our umax.
1382          */
1383         __reg_deduce_bounds(reg);
1384         __reg_bound_offset(reg);
1385         __update_reg_bounds(reg);
1386 }
1387
1388 static bool __reg64_bound_s32(s64 a)
1389 {
1390         return a > S32_MIN && a < S32_MAX;
1391 }
1392
1393 static bool __reg64_bound_u32(u64 a)
1394 {
1395         if (a > U32_MIN && a < U32_MAX)
1396                 return true;
1397         return false;
1398 }
1399
1400 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1401 {
1402         __mark_reg32_unbounded(reg);
1403
1404         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1405                 reg->s32_min_value = (s32)reg->smin_value;
1406                 reg->s32_max_value = (s32)reg->smax_value;
1407         }
1408         if (__reg64_bound_u32(reg->umin_value))
1409                 reg->u32_min_value = (u32)reg->umin_value;
1410         if (__reg64_bound_u32(reg->umax_value))
1411                 reg->u32_max_value = (u32)reg->umax_value;
1412
1413         /* Intersecting with the old var_off might have improved our bounds
1414          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1415          * then new var_off is (0; 0x7f...fc) which improves our umax.
1416          */
1417         __reg_deduce_bounds(reg);
1418         __reg_bound_offset(reg);
1419         __update_reg_bounds(reg);
1420 }
1421
1422 /* Mark a register as having a completely unknown (scalar) value. */
1423 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1424                                struct bpf_reg_state *reg)
1425 {
1426         /*
1427          * Clear type, id, off, and union(map_ptr, range) and
1428          * padding between 'type' and union
1429          */
1430         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1431         reg->type = SCALAR_VALUE;
1432         reg->var_off = tnum_unknown;
1433         reg->frameno = 0;
1434         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1435         __mark_reg_unbounded(reg);
1436 }
1437
1438 static void mark_reg_unknown(struct bpf_verifier_env *env,
1439                              struct bpf_reg_state *regs, u32 regno)
1440 {
1441         if (WARN_ON(regno >= MAX_BPF_REG)) {
1442                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1443                 /* Something bad happened, let's kill all regs except FP */
1444                 for (regno = 0; regno < BPF_REG_FP; regno++)
1445                         __mark_reg_not_init(env, regs + regno);
1446                 return;
1447         }
1448         __mark_reg_unknown(env, regs + regno);
1449 }
1450
1451 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1452                                 struct bpf_reg_state *reg)
1453 {
1454         __mark_reg_unknown(env, reg);
1455         reg->type = NOT_INIT;
1456 }
1457
1458 static void mark_reg_not_init(struct bpf_verifier_env *env,
1459                               struct bpf_reg_state *regs, u32 regno)
1460 {
1461         if (WARN_ON(regno >= MAX_BPF_REG)) {
1462                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1463                 /* Something bad happened, let's kill all regs except FP */
1464                 for (regno = 0; regno < BPF_REG_FP; regno++)
1465                         __mark_reg_not_init(env, regs + regno);
1466                 return;
1467         }
1468         __mark_reg_not_init(env, regs + regno);
1469 }
1470
1471 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1472                             struct bpf_reg_state *regs, u32 regno,
1473                             enum bpf_reg_type reg_type,
1474                             struct btf *btf, u32 btf_id)
1475 {
1476         if (reg_type == SCALAR_VALUE) {
1477                 mark_reg_unknown(env, regs, regno);
1478                 return;
1479         }
1480         mark_reg_known_zero(env, regs, regno);
1481         regs[regno].type = PTR_TO_BTF_ID;
1482         regs[regno].btf = btf;
1483         regs[regno].btf_id = btf_id;
1484 }
1485
1486 #define DEF_NOT_SUBREG  (0)
1487 static void init_reg_state(struct bpf_verifier_env *env,
1488                            struct bpf_func_state *state)
1489 {
1490         struct bpf_reg_state *regs = state->regs;
1491         int i;
1492
1493         for (i = 0; i < MAX_BPF_REG; i++) {
1494                 mark_reg_not_init(env, regs, i);
1495                 regs[i].live = REG_LIVE_NONE;
1496                 regs[i].parent = NULL;
1497                 regs[i].subreg_def = DEF_NOT_SUBREG;
1498         }
1499
1500         /* frame pointer */
1501         regs[BPF_REG_FP].type = PTR_TO_STACK;
1502         mark_reg_known_zero(env, regs, BPF_REG_FP);
1503         regs[BPF_REG_FP].frameno = state->frameno;
1504 }
1505
1506 #define BPF_MAIN_FUNC (-1)
1507 static void init_func_state(struct bpf_verifier_env *env,
1508                             struct bpf_func_state *state,
1509                             int callsite, int frameno, int subprogno)
1510 {
1511         state->callsite = callsite;
1512         state->frameno = frameno;
1513         state->subprogno = subprogno;
1514         init_reg_state(env, state);
1515 }
1516
1517 enum reg_arg_type {
1518         SRC_OP,         /* register is used as source operand */
1519         DST_OP,         /* register is used as destination operand */
1520         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1521 };
1522
1523 static int cmp_subprogs(const void *a, const void *b)
1524 {
1525         return ((struct bpf_subprog_info *)a)->start -
1526                ((struct bpf_subprog_info *)b)->start;
1527 }
1528
1529 static int find_subprog(struct bpf_verifier_env *env, int off)
1530 {
1531         struct bpf_subprog_info *p;
1532
1533         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1534                     sizeof(env->subprog_info[0]), cmp_subprogs);
1535         if (!p)
1536                 return -ENOENT;
1537         return p - env->subprog_info;
1538
1539 }
1540
1541 static int add_subprog(struct bpf_verifier_env *env, int off)
1542 {
1543         int insn_cnt = env->prog->len;
1544         int ret;
1545
1546         if (off >= insn_cnt || off < 0) {
1547                 verbose(env, "call to invalid destination\n");
1548                 return -EINVAL;
1549         }
1550         ret = find_subprog(env, off);
1551         if (ret >= 0)
1552                 return ret;
1553         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1554                 verbose(env, "too many subprograms\n");
1555                 return -E2BIG;
1556         }
1557         env->subprog_info[env->subprog_cnt++].start = off;
1558         sort(env->subprog_info, env->subprog_cnt,
1559              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1560         return env->subprog_cnt - 1;
1561 }
1562
1563 static int check_subprogs(struct bpf_verifier_env *env)
1564 {
1565         int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1566         struct bpf_subprog_info *subprog = env->subprog_info;
1567         struct bpf_insn *insn = env->prog->insnsi;
1568         int insn_cnt = env->prog->len;
1569
1570         /* Add entry function. */
1571         ret = add_subprog(env, 0);
1572         if (ret < 0)
1573                 return ret;
1574
1575         /* determine subprog starts. The end is one before the next starts */
1576         for (i = 0; i < insn_cnt; i++) {
1577                 if (bpf_pseudo_func(insn + i)) {
1578                         if (!env->bpf_capable) {
1579                                 verbose(env,
1580                                         "function pointers are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1581                                 return -EPERM;
1582                         }
1583                         ret = add_subprog(env, i + insn[i].imm + 1);
1584                         if (ret < 0)
1585                                 return ret;
1586                         /* remember subprog */
1587                         insn[i + 1].imm = ret;
1588                         continue;
1589                 }
1590                 if (!bpf_pseudo_call(insn + i))
1591                         continue;
1592                 if (!env->bpf_capable) {
1593                         verbose(env,
1594                                 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1595                         return -EPERM;
1596                 }
1597                 ret = add_subprog(env, i + insn[i].imm + 1);
1598                 if (ret < 0)
1599                         return ret;
1600         }
1601
1602         /* Add a fake 'exit' subprog which could simplify subprog iteration
1603          * logic. 'subprog_cnt' should not be increased.
1604          */
1605         subprog[env->subprog_cnt].start = insn_cnt;
1606
1607         if (env->log.level & BPF_LOG_LEVEL2)
1608                 for (i = 0; i < env->subprog_cnt; i++)
1609                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
1610
1611         /* now check that all jumps are within the same subprog */
1612         subprog_start = subprog[cur_subprog].start;
1613         subprog_end = subprog[cur_subprog + 1].start;
1614         for (i = 0; i < insn_cnt; i++) {
1615                 u8 code = insn[i].code;
1616
1617                 if (code == (BPF_JMP | BPF_CALL) &&
1618                     insn[i].imm == BPF_FUNC_tail_call &&
1619                     insn[i].src_reg != BPF_PSEUDO_CALL)
1620                         subprog[cur_subprog].has_tail_call = true;
1621                 if (BPF_CLASS(code) == BPF_LD &&
1622                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1623                         subprog[cur_subprog].has_ld_abs = true;
1624                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1625                         goto next;
1626                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1627                         goto next;
1628                 off = i + insn[i].off + 1;
1629                 if (off < subprog_start || off >= subprog_end) {
1630                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
1631                         return -EINVAL;
1632                 }
1633 next:
1634                 if (i == subprog_end - 1) {
1635                         /* to avoid fall-through from one subprog into another
1636                          * the last insn of the subprog should be either exit
1637                          * or unconditional jump back
1638                          */
1639                         if (code != (BPF_JMP | BPF_EXIT) &&
1640                             code != (BPF_JMP | BPF_JA)) {
1641                                 verbose(env, "last insn is not an exit or jmp\n");
1642                                 return -EINVAL;
1643                         }
1644                         subprog_start = subprog_end;
1645                         cur_subprog++;
1646                         if (cur_subprog < env->subprog_cnt)
1647                                 subprog_end = subprog[cur_subprog + 1].start;
1648                 }
1649         }
1650         return 0;
1651 }
1652
1653 /* Parentage chain of this register (or stack slot) should take care of all
1654  * issues like callee-saved registers, stack slot allocation time, etc.
1655  */
1656 static int mark_reg_read(struct bpf_verifier_env *env,
1657                          const struct bpf_reg_state *state,
1658                          struct bpf_reg_state *parent, u8 flag)
1659 {
1660         bool writes = parent == state->parent; /* Observe write marks */
1661         int cnt = 0;
1662
1663         while (parent) {
1664                 /* if read wasn't screened by an earlier write ... */
1665                 if (writes && state->live & REG_LIVE_WRITTEN)
1666                         break;
1667                 if (parent->live & REG_LIVE_DONE) {
1668                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1669                                 reg_type_str[parent->type],
1670                                 parent->var_off.value, parent->off);
1671                         return -EFAULT;
1672                 }
1673                 /* The first condition is more likely to be true than the
1674                  * second, checked it first.
1675                  */
1676                 if ((parent->live & REG_LIVE_READ) == flag ||
1677                     parent->live & REG_LIVE_READ64)
1678                         /* The parentage chain never changes and
1679                          * this parent was already marked as LIVE_READ.
1680                          * There is no need to keep walking the chain again and
1681                          * keep re-marking all parents as LIVE_READ.
1682                          * This case happens when the same register is read
1683                          * multiple times without writes into it in-between.
1684                          * Also, if parent has the stronger REG_LIVE_READ64 set,
1685                          * then no need to set the weak REG_LIVE_READ32.
1686                          */
1687                         break;
1688                 /* ... then we depend on parent's value */
1689                 parent->live |= flag;
1690                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1691                 if (flag == REG_LIVE_READ64)
1692                         parent->live &= ~REG_LIVE_READ32;
1693                 state = parent;
1694                 parent = state->parent;
1695                 writes = true;
1696                 cnt++;
1697         }
1698
1699         if (env->longest_mark_read_walk < cnt)
1700                 env->longest_mark_read_walk = cnt;
1701         return 0;
1702 }
1703
1704 /* This function is supposed to be used by the following 32-bit optimization
1705  * code only. It returns TRUE if the source or destination register operates
1706  * on 64-bit, otherwise return FALSE.
1707  */
1708 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1709                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1710 {
1711         u8 code, class, op;
1712
1713         code = insn->code;
1714         class = BPF_CLASS(code);
1715         op = BPF_OP(code);
1716         if (class == BPF_JMP) {
1717                 /* BPF_EXIT for "main" will reach here. Return TRUE
1718                  * conservatively.
1719                  */
1720                 if (op == BPF_EXIT)
1721                         return true;
1722                 if (op == BPF_CALL) {
1723                         /* BPF to BPF call will reach here because of marking
1724                          * caller saved clobber with DST_OP_NO_MARK for which we
1725                          * don't care the register def because they are anyway
1726                          * marked as NOT_INIT already.
1727                          */
1728                         if (insn->src_reg == BPF_PSEUDO_CALL)
1729                                 return false;
1730                         /* Helper call will reach here because of arg type
1731                          * check, conservatively return TRUE.
1732                          */
1733                         if (t == SRC_OP)
1734                                 return true;
1735
1736                         return false;
1737                 }
1738         }
1739
1740         if (class == BPF_ALU64 || class == BPF_JMP ||
1741             /* BPF_END always use BPF_ALU class. */
1742             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1743                 return true;
1744
1745         if (class == BPF_ALU || class == BPF_JMP32)
1746                 return false;
1747
1748         if (class == BPF_LDX) {
1749                 if (t != SRC_OP)
1750                         return BPF_SIZE(code) == BPF_DW;
1751                 /* LDX source must be ptr. */
1752                 return true;
1753         }
1754
1755         if (class == BPF_STX) {
1756                 /* BPF_STX (including atomic variants) has multiple source
1757                  * operands, one of which is a ptr. Check whether the caller is
1758                  * asking about it.
1759                  */
1760                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
1761                         return true;
1762                 return BPF_SIZE(code) == BPF_DW;
1763         }
1764
1765         if (class == BPF_LD) {
1766                 u8 mode = BPF_MODE(code);
1767
1768                 /* LD_IMM64 */
1769                 if (mode == BPF_IMM)
1770                         return true;
1771
1772                 /* Both LD_IND and LD_ABS return 32-bit data. */
1773                 if (t != SRC_OP)
1774                         return  false;
1775
1776                 /* Implicit ctx ptr. */
1777                 if (regno == BPF_REG_6)
1778                         return true;
1779
1780                 /* Explicit source could be any width. */
1781                 return true;
1782         }
1783
1784         if (class == BPF_ST)
1785                 /* The only source register for BPF_ST is a ptr. */
1786                 return true;
1787
1788         /* Conservatively return true at default. */
1789         return true;
1790 }
1791
1792 /* Return the regno defined by the insn, or -1. */
1793 static int insn_def_regno(const struct bpf_insn *insn)
1794 {
1795         switch (BPF_CLASS(insn->code)) {
1796         case BPF_JMP:
1797         case BPF_JMP32:
1798         case BPF_ST:
1799                 return -1;
1800         case BPF_STX:
1801                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1802                     (insn->imm & BPF_FETCH)) {
1803                         if (insn->imm == BPF_CMPXCHG)
1804                                 return BPF_REG_0;
1805                         else
1806                                 return insn->src_reg;
1807                 } else {
1808                         return -1;
1809                 }
1810         default:
1811                 return insn->dst_reg;
1812         }
1813 }
1814
1815 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1816 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1817 {
1818         int dst_reg = insn_def_regno(insn);
1819
1820         if (dst_reg == -1)
1821                 return false;
1822
1823         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
1824 }
1825
1826 static void mark_insn_zext(struct bpf_verifier_env *env,
1827                            struct bpf_reg_state *reg)
1828 {
1829         s32 def_idx = reg->subreg_def;
1830
1831         if (def_idx == DEF_NOT_SUBREG)
1832                 return;
1833
1834         env->insn_aux_data[def_idx - 1].zext_dst = true;
1835         /* The dst will be zero extended, so won't be sub-register anymore. */
1836         reg->subreg_def = DEF_NOT_SUBREG;
1837 }
1838
1839 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1840                          enum reg_arg_type t)
1841 {
1842         struct bpf_verifier_state *vstate = env->cur_state;
1843         struct bpf_func_state *state = vstate->frame[vstate->curframe];
1844         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1845         struct bpf_reg_state *reg, *regs = state->regs;
1846         bool rw64;
1847
1848         if (regno >= MAX_BPF_REG) {
1849                 verbose(env, "R%d is invalid\n", regno);
1850                 return -EINVAL;
1851         }
1852
1853         reg = &regs[regno];
1854         rw64 = is_reg64(env, insn, regno, reg, t);
1855         if (t == SRC_OP) {
1856                 /* check whether register used as source operand can be read */
1857                 if (reg->type == NOT_INIT) {
1858                         verbose(env, "R%d !read_ok\n", regno);
1859                         return -EACCES;
1860                 }
1861                 /* We don't need to worry about FP liveness because it's read-only */
1862                 if (regno == BPF_REG_FP)
1863                         return 0;
1864
1865                 if (rw64)
1866                         mark_insn_zext(env, reg);
1867
1868                 return mark_reg_read(env, reg, reg->parent,
1869                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1870         } else {
1871                 /* check whether register used as dest operand can be written to */
1872                 if (regno == BPF_REG_FP) {
1873                         verbose(env, "frame pointer is read only\n");
1874                         return -EACCES;
1875                 }
1876                 reg->live |= REG_LIVE_WRITTEN;
1877                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1878                 if (t == DST_OP)
1879                         mark_reg_unknown(env, regs, regno);
1880         }
1881         return 0;
1882 }
1883
1884 /* for any branch, call, exit record the history of jmps in the given state */
1885 static int push_jmp_history(struct bpf_verifier_env *env,
1886                             struct bpf_verifier_state *cur)
1887 {
1888         u32 cnt = cur->jmp_history_cnt;
1889         struct bpf_idx_pair *p;
1890
1891         cnt++;
1892         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1893         if (!p)
1894                 return -ENOMEM;
1895         p[cnt - 1].idx = env->insn_idx;
1896         p[cnt - 1].prev_idx = env->prev_insn_idx;
1897         cur->jmp_history = p;
1898         cur->jmp_history_cnt = cnt;
1899         return 0;
1900 }
1901
1902 /* Backtrack one insn at a time. If idx is not at the top of recorded
1903  * history then previous instruction came from straight line execution.
1904  */
1905 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1906                              u32 *history)
1907 {
1908         u32 cnt = *history;
1909
1910         if (cnt && st->jmp_history[cnt - 1].idx == i) {
1911                 i = st->jmp_history[cnt - 1].prev_idx;
1912                 (*history)--;
1913         } else {
1914                 i--;
1915         }
1916         return i;
1917 }
1918
1919 /* For given verifier state backtrack_insn() is called from the last insn to
1920  * the first insn. Its purpose is to compute a bitmask of registers and
1921  * stack slots that needs precision in the parent verifier state.
1922  */
1923 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1924                           u32 *reg_mask, u64 *stack_mask)
1925 {
1926         const struct bpf_insn_cbs cbs = {
1927                 .cb_print       = verbose,
1928                 .private_data   = env,
1929         };
1930         struct bpf_insn *insn = env->prog->insnsi + idx;
1931         u8 class = BPF_CLASS(insn->code);
1932         u8 opcode = BPF_OP(insn->code);
1933         u8 mode = BPF_MODE(insn->code);
1934         u32 dreg = 1u << insn->dst_reg;
1935         u32 sreg = 1u << insn->src_reg;
1936         u32 spi;
1937
1938         if (insn->code == 0)
1939                 return 0;
1940         if (env->log.level & BPF_LOG_LEVEL) {
1941                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1942                 verbose(env, "%d: ", idx);
1943                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1944         }
1945
1946         if (class == BPF_ALU || class == BPF_ALU64) {
1947                 if (!(*reg_mask & dreg))
1948                         return 0;
1949                 if (opcode == BPF_MOV) {
1950                         if (BPF_SRC(insn->code) == BPF_X) {
1951                                 /* dreg = sreg
1952                                  * dreg needs precision after this insn
1953                                  * sreg needs precision before this insn
1954                                  */
1955                                 *reg_mask &= ~dreg;
1956                                 *reg_mask |= sreg;
1957                         } else {
1958                                 /* dreg = K
1959                                  * dreg needs precision after this insn.
1960                                  * Corresponding register is already marked
1961                                  * as precise=true in this verifier state.
1962                                  * No further markings in parent are necessary
1963                                  */
1964                                 *reg_mask &= ~dreg;
1965                         }
1966                 } else {
1967                         if (BPF_SRC(insn->code) == BPF_X) {
1968                                 /* dreg += sreg
1969                                  * both dreg and sreg need precision
1970                                  * before this insn
1971                                  */
1972                                 *reg_mask |= sreg;
1973                         } /* else dreg += K
1974                            * dreg still needs precision before this insn
1975                            */
1976                 }
1977         } else if (class == BPF_LDX) {
1978                 if (!(*reg_mask & dreg))
1979                         return 0;
1980                 *reg_mask &= ~dreg;
1981
1982                 /* scalars can only be spilled into stack w/o losing precision.
1983                  * Load from any other memory can be zero extended.
1984                  * The desire to keep that precision is already indicated
1985                  * by 'precise' mark in corresponding register of this state.
1986                  * No further tracking necessary.
1987                  */
1988                 if (insn->src_reg != BPF_REG_FP)
1989                         return 0;
1990                 if (BPF_SIZE(insn->code) != BPF_DW)
1991                         return 0;
1992
1993                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1994                  * that [fp - off] slot contains scalar that needs to be
1995                  * tracked with precision
1996                  */
1997                 spi = (-insn->off - 1) / BPF_REG_SIZE;
1998                 if (spi >= 64) {
1999                         verbose(env, "BUG spi %d\n", spi);
2000                         WARN_ONCE(1, "verifier backtracking bug");
2001                         return -EFAULT;
2002                 }
2003                 *stack_mask |= 1ull << spi;
2004         } else if (class == BPF_STX || class == BPF_ST) {
2005                 if (*reg_mask & dreg)
2006                         /* stx & st shouldn't be using _scalar_ dst_reg
2007                          * to access memory. It means backtracking
2008                          * encountered a case of pointer subtraction.
2009                          */
2010                         return -ENOTSUPP;
2011                 /* scalars can only be spilled into stack */
2012                 if (insn->dst_reg != BPF_REG_FP)
2013                         return 0;
2014                 if (BPF_SIZE(insn->code) != BPF_DW)
2015                         return 0;
2016                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2017                 if (spi >= 64) {
2018                         verbose(env, "BUG spi %d\n", spi);
2019                         WARN_ONCE(1, "verifier backtracking bug");
2020                         return -EFAULT;
2021                 }
2022                 if (!(*stack_mask & (1ull << spi)))
2023                         return 0;
2024                 *stack_mask &= ~(1ull << spi);
2025                 if (class == BPF_STX)
2026                         *reg_mask |= sreg;
2027         } else if (class == BPF_JMP || class == BPF_JMP32) {
2028                 if (opcode == BPF_CALL) {
2029                         if (insn->src_reg == BPF_PSEUDO_CALL)
2030                                 return -ENOTSUPP;
2031                         /* regular helper call sets R0 */
2032                         *reg_mask &= ~1;
2033                         if (*reg_mask & 0x3f) {
2034                                 /* if backtracing was looking for registers R1-R5
2035                                  * they should have been found already.
2036                                  */
2037                                 verbose(env, "BUG regs %x\n", *reg_mask);
2038                                 WARN_ONCE(1, "verifier backtracking bug");
2039                                 return -EFAULT;
2040                         }
2041                 } else if (opcode == BPF_EXIT) {
2042                         return -ENOTSUPP;
2043                 }
2044         } else if (class == BPF_LD) {
2045                 if (!(*reg_mask & dreg))
2046                         return 0;
2047                 *reg_mask &= ~dreg;
2048                 /* It's ld_imm64 or ld_abs or ld_ind.
2049                  * For ld_imm64 no further tracking of precision
2050                  * into parent is necessary
2051                  */
2052                 if (mode == BPF_IND || mode == BPF_ABS)
2053                         /* to be analyzed */
2054                         return -ENOTSUPP;
2055         }
2056         return 0;
2057 }
2058
2059 /* the scalar precision tracking algorithm:
2060  * . at the start all registers have precise=false.
2061  * . scalar ranges are tracked as normal through alu and jmp insns.
2062  * . once precise value of the scalar register is used in:
2063  *   .  ptr + scalar alu
2064  *   . if (scalar cond K|scalar)
2065  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2066  *   backtrack through the verifier states and mark all registers and
2067  *   stack slots with spilled constants that these scalar regisers
2068  *   should be precise.
2069  * . during state pruning two registers (or spilled stack slots)
2070  *   are equivalent if both are not precise.
2071  *
2072  * Note the verifier cannot simply walk register parentage chain,
2073  * since many different registers and stack slots could have been
2074  * used to compute single precise scalar.
2075  *
2076  * The approach of starting with precise=true for all registers and then
2077  * backtrack to mark a register as not precise when the verifier detects
2078  * that program doesn't care about specific value (e.g., when helper
2079  * takes register as ARG_ANYTHING parameter) is not safe.
2080  *
2081  * It's ok to walk single parentage chain of the verifier states.
2082  * It's possible that this backtracking will go all the way till 1st insn.
2083  * All other branches will be explored for needing precision later.
2084  *
2085  * The backtracking needs to deal with cases like:
2086  *   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)
2087  * r9 -= r8
2088  * r5 = r9
2089  * if r5 > 0x79f goto pc+7
2090  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2091  * r5 += 1
2092  * ...
2093  * call bpf_perf_event_output#25
2094  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2095  *
2096  * and this case:
2097  * r6 = 1
2098  * call foo // uses callee's r6 inside to compute r0
2099  * r0 += r6
2100  * if r0 == 0 goto
2101  *
2102  * to track above reg_mask/stack_mask needs to be independent for each frame.
2103  *
2104  * Also if parent's curframe > frame where backtracking started,
2105  * the verifier need to mark registers in both frames, otherwise callees
2106  * may incorrectly prune callers. This is similar to
2107  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2108  *
2109  * For now backtracking falls back into conservative marking.
2110  */
2111 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2112                                      struct bpf_verifier_state *st)
2113 {
2114         struct bpf_func_state *func;
2115         struct bpf_reg_state *reg;
2116         int i, j;
2117
2118         /* big hammer: mark all scalars precise in this path.
2119          * pop_stack may still get !precise scalars.
2120          */
2121         for (; st; st = st->parent)
2122                 for (i = 0; i <= st->curframe; i++) {
2123                         func = st->frame[i];
2124                         for (j = 0; j < BPF_REG_FP; j++) {
2125                                 reg = &func->regs[j];
2126                                 if (reg->type != SCALAR_VALUE)
2127                                         continue;
2128                                 reg->precise = true;
2129                         }
2130                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2131                                 if (func->stack[j].slot_type[0] != STACK_SPILL)
2132                                         continue;
2133                                 reg = &func->stack[j].spilled_ptr;
2134                                 if (reg->type != SCALAR_VALUE)
2135                                         continue;
2136                                 reg->precise = true;
2137                         }
2138                 }
2139 }
2140
2141 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2142                                   int spi)
2143 {
2144         struct bpf_verifier_state *st = env->cur_state;
2145         int first_idx = st->first_insn_idx;
2146         int last_idx = env->insn_idx;
2147         struct bpf_func_state *func;
2148         struct bpf_reg_state *reg;
2149         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2150         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2151         bool skip_first = true;
2152         bool new_marks = false;
2153         int i, err;
2154
2155         if (!env->bpf_capable)
2156                 return 0;
2157
2158         func = st->frame[st->curframe];
2159         if (regno >= 0) {
2160                 reg = &func->regs[regno];
2161                 if (reg->type != SCALAR_VALUE) {
2162                         WARN_ONCE(1, "backtracing misuse");
2163                         return -EFAULT;
2164                 }
2165                 if (!reg->precise)
2166                         new_marks = true;
2167                 else
2168                         reg_mask = 0;
2169                 reg->precise = true;
2170         }
2171
2172         while (spi >= 0) {
2173                 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2174                         stack_mask = 0;
2175                         break;
2176                 }
2177                 reg = &func->stack[spi].spilled_ptr;
2178                 if (reg->type != SCALAR_VALUE) {
2179                         stack_mask = 0;
2180                         break;
2181                 }
2182                 if (!reg->precise)
2183                         new_marks = true;
2184                 else
2185                         stack_mask = 0;
2186                 reg->precise = true;
2187                 break;
2188         }
2189
2190         if (!new_marks)
2191                 return 0;
2192         if (!reg_mask && !stack_mask)
2193                 return 0;
2194         for (;;) {
2195                 DECLARE_BITMAP(mask, 64);
2196                 u32 history = st->jmp_history_cnt;
2197
2198                 if (env->log.level & BPF_LOG_LEVEL)
2199                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2200                 for (i = last_idx;;) {
2201                         if (skip_first) {
2202                                 err = 0;
2203                                 skip_first = false;
2204                         } else {
2205                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2206                         }
2207                         if (err == -ENOTSUPP) {
2208                                 mark_all_scalars_precise(env, st);
2209                                 return 0;
2210                         } else if (err) {
2211                                 return err;
2212                         }
2213                         if (!reg_mask && !stack_mask)
2214                                 /* Found assignment(s) into tracked register in this state.
2215                                  * Since this state is already marked, just return.
2216                                  * Nothing to be tracked further in the parent state.
2217                                  */
2218                                 return 0;
2219                         if (i == first_idx)
2220                                 break;
2221                         i = get_prev_insn_idx(st, i, &history);
2222                         if (i >= env->prog->len) {
2223                                 /* This can happen if backtracking reached insn 0
2224                                  * and there are still reg_mask or stack_mask
2225                                  * to backtrack.
2226                                  * It means the backtracking missed the spot where
2227                                  * particular register was initialized with a constant.
2228                                  */
2229                                 verbose(env, "BUG backtracking idx %d\n", i);
2230                                 WARN_ONCE(1, "verifier backtracking bug");
2231                                 return -EFAULT;
2232                         }
2233                 }
2234                 st = st->parent;
2235                 if (!st)
2236                         break;
2237
2238                 new_marks = false;
2239                 func = st->frame[st->curframe];
2240                 bitmap_from_u64(mask, reg_mask);
2241                 for_each_set_bit(i, mask, 32) {
2242                         reg = &func->regs[i];
2243                         if (reg->type != SCALAR_VALUE) {
2244                                 reg_mask &= ~(1u << i);
2245                                 continue;
2246                         }
2247                         if (!reg->precise)
2248                                 new_marks = true;
2249                         reg->precise = true;
2250                 }
2251
2252                 bitmap_from_u64(mask, stack_mask);
2253                 for_each_set_bit(i, mask, 64) {
2254                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2255                                 /* the sequence of instructions:
2256                                  * 2: (bf) r3 = r10
2257                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2258                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2259                                  * doesn't contain jmps. It's backtracked
2260                                  * as a single block.
2261                                  * During backtracking insn 3 is not recognized as
2262                                  * stack access, so at the end of backtracking
2263                                  * stack slot fp-8 is still marked in stack_mask.
2264                                  * However the parent state may not have accessed
2265                                  * fp-8 and it's "unallocated" stack space.
2266                                  * In such case fallback to conservative.
2267                                  */
2268                                 mark_all_scalars_precise(env, st);
2269                                 return 0;
2270                         }
2271
2272                         if (func->stack[i].slot_type[0] != STACK_SPILL) {
2273                                 stack_mask &= ~(1ull << i);
2274                                 continue;
2275                         }
2276                         reg = &func->stack[i].spilled_ptr;
2277                         if (reg->type != SCALAR_VALUE) {
2278                                 stack_mask &= ~(1ull << i);
2279                                 continue;
2280                         }
2281                         if (!reg->precise)
2282                                 new_marks = true;
2283                         reg->precise = true;
2284                 }
2285                 if (env->log.level & BPF_LOG_LEVEL) {
2286                         print_verifier_state(env, func);
2287                         verbose(env, "parent %s regs=%x stack=%llx marks\n",
2288                                 new_marks ? "didn't have" : "already had",
2289                                 reg_mask, stack_mask);
2290                 }
2291
2292                 if (!reg_mask && !stack_mask)
2293                         break;
2294                 if (!new_marks)
2295                         break;
2296
2297                 last_idx = st->last_insn_idx;
2298                 first_idx = st->first_insn_idx;
2299         }
2300         return 0;
2301 }
2302
2303 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2304 {
2305         return __mark_chain_precision(env, regno, -1);
2306 }
2307
2308 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2309 {
2310         return __mark_chain_precision(env, -1, spi);
2311 }
2312
2313 static bool is_spillable_regtype(enum bpf_reg_type type)
2314 {
2315         switch (type) {
2316         case PTR_TO_MAP_VALUE:
2317         case PTR_TO_MAP_VALUE_OR_NULL:
2318         case PTR_TO_STACK:
2319         case PTR_TO_CTX:
2320         case PTR_TO_PACKET:
2321         case PTR_TO_PACKET_META:
2322         case PTR_TO_PACKET_END:
2323         case PTR_TO_FLOW_KEYS:
2324         case CONST_PTR_TO_MAP:
2325         case PTR_TO_SOCKET:
2326         case PTR_TO_SOCKET_OR_NULL:
2327         case PTR_TO_SOCK_COMMON:
2328         case PTR_TO_SOCK_COMMON_OR_NULL:
2329         case PTR_TO_TCP_SOCK:
2330         case PTR_TO_TCP_SOCK_OR_NULL:
2331         case PTR_TO_XDP_SOCK:
2332         case PTR_TO_BTF_ID:
2333         case PTR_TO_BTF_ID_OR_NULL:
2334         case PTR_TO_RDONLY_BUF:
2335         case PTR_TO_RDONLY_BUF_OR_NULL:
2336         case PTR_TO_RDWR_BUF:
2337         case PTR_TO_RDWR_BUF_OR_NULL:
2338         case PTR_TO_PERCPU_BTF_ID:
2339         case PTR_TO_MEM:
2340         case PTR_TO_MEM_OR_NULL:
2341         case PTR_TO_FUNC:
2342         case PTR_TO_MAP_KEY:
2343                 return true;
2344         default:
2345                 return false;
2346         }
2347 }
2348
2349 /* Does this register contain a constant zero? */
2350 static bool register_is_null(struct bpf_reg_state *reg)
2351 {
2352         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2353 }
2354
2355 static bool register_is_const(struct bpf_reg_state *reg)
2356 {
2357         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2358 }
2359
2360 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2361 {
2362         return tnum_is_unknown(reg->var_off) &&
2363                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2364                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2365                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2366                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2367 }
2368
2369 static bool register_is_bounded(struct bpf_reg_state *reg)
2370 {
2371         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2372 }
2373
2374 static bool __is_pointer_value(bool allow_ptr_leaks,
2375                                const struct bpf_reg_state *reg)
2376 {
2377         if (allow_ptr_leaks)
2378                 return false;
2379
2380         return reg->type != SCALAR_VALUE;
2381 }
2382
2383 static void save_register_state(struct bpf_func_state *state,
2384                                 int spi, struct bpf_reg_state *reg)
2385 {
2386         int i;
2387
2388         state->stack[spi].spilled_ptr = *reg;
2389         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2390
2391         for (i = 0; i < BPF_REG_SIZE; i++)
2392                 state->stack[spi].slot_type[i] = STACK_SPILL;
2393 }
2394
2395 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2396  * stack boundary and alignment are checked in check_mem_access()
2397  */
2398 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2399                                        /* stack frame we're writing to */
2400                                        struct bpf_func_state *state,
2401                                        int off, int size, int value_regno,
2402                                        int insn_idx)
2403 {
2404         struct bpf_func_state *cur; /* state of the current function */
2405         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2406         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2407         struct bpf_reg_state *reg = NULL;
2408
2409         err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2410                                  state->acquired_refs, true);
2411         if (err)
2412                 return err;
2413         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2414          * so it's aligned access and [off, off + size) are within stack limits
2415          */
2416         if (!env->allow_ptr_leaks &&
2417             state->stack[spi].slot_type[0] == STACK_SPILL &&
2418             size != BPF_REG_SIZE) {
2419                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2420                 return -EACCES;
2421         }
2422
2423         cur = env->cur_state->frame[env->cur_state->curframe];
2424         if (value_regno >= 0)
2425                 reg = &cur->regs[value_regno];
2426
2427         if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2428             !register_is_null(reg) && env->bpf_capable) {
2429                 if (dst_reg != BPF_REG_FP) {
2430                         /* The backtracking logic can only recognize explicit
2431                          * stack slot address like [fp - 8]. Other spill of
2432                          * scalar via different register has to be conervative.
2433                          * Backtrack from here and mark all registers as precise
2434                          * that contributed into 'reg' being a constant.
2435                          */
2436                         err = mark_chain_precision(env, value_regno);
2437                         if (err)
2438                                 return err;
2439                 }
2440                 save_register_state(state, spi, reg);
2441         } else if (reg && is_spillable_regtype(reg->type)) {
2442                 /* register containing pointer is being spilled into stack */
2443                 if (size != BPF_REG_SIZE) {
2444                         verbose_linfo(env, insn_idx, "; ");
2445                         verbose(env, "invalid size of register spill\n");
2446                         return -EACCES;
2447                 }
2448
2449                 if (state != cur && reg->type == PTR_TO_STACK) {
2450                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2451                         return -EINVAL;
2452                 }
2453
2454                 if (!env->bypass_spec_v4) {
2455                         bool sanitize = false;
2456
2457                         if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2458                             register_is_const(&state->stack[spi].spilled_ptr))
2459                                 sanitize = true;
2460                         for (i = 0; i < BPF_REG_SIZE; i++)
2461                                 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2462                                         sanitize = true;
2463                                         break;
2464                                 }
2465                         if (sanitize) {
2466                                 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2467                                 int soff = (-spi - 1) * BPF_REG_SIZE;
2468
2469                                 /* detected reuse of integer stack slot with a pointer
2470                                  * which means either llvm is reusing stack slot or
2471                                  * an attacker is trying to exploit CVE-2018-3639
2472                                  * (speculative store bypass)
2473                                  * Have to sanitize that slot with preemptive
2474                                  * store of zero.
2475                                  */
2476                                 if (*poff && *poff != soff) {
2477                                         /* disallow programs where single insn stores
2478                                          * into two different stack slots, since verifier
2479                                          * cannot sanitize them
2480                                          */
2481                                         verbose(env,
2482                                                 "insn %d cannot access two stack slots fp%d and fp%d",
2483                                                 insn_idx, *poff, soff);
2484                                         return -EINVAL;
2485                                 }
2486                                 *poff = soff;
2487                         }
2488                 }
2489                 save_register_state(state, spi, reg);
2490         } else {
2491                 u8 type = STACK_MISC;
2492
2493                 /* regular write of data into stack destroys any spilled ptr */
2494                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2495                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2496                 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2497                         for (i = 0; i < BPF_REG_SIZE; i++)
2498                                 state->stack[spi].slot_type[i] = STACK_MISC;
2499
2500                 /* only mark the slot as written if all 8 bytes were written
2501                  * otherwise read propagation may incorrectly stop too soon
2502                  * when stack slots are partially written.
2503                  * This heuristic means that read propagation will be
2504                  * conservative, since it will add reg_live_read marks
2505                  * to stack slots all the way to first state when programs
2506                  * writes+reads less than 8 bytes
2507                  */
2508                 if (size == BPF_REG_SIZE)
2509                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2510
2511                 /* when we zero initialize stack slots mark them as such */
2512                 if (reg && register_is_null(reg)) {
2513                         /* backtracking doesn't work for STACK_ZERO yet. */
2514                         err = mark_chain_precision(env, value_regno);
2515                         if (err)
2516                                 return err;
2517                         type = STACK_ZERO;
2518                 }
2519
2520                 /* Mark slots affected by this stack write. */
2521                 for (i = 0; i < size; i++)
2522                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2523                                 type;
2524         }
2525         return 0;
2526 }
2527
2528 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2529  * known to contain a variable offset.
2530  * This function checks whether the write is permitted and conservatively
2531  * tracks the effects of the write, considering that each stack slot in the
2532  * dynamic range is potentially written to.
2533  *
2534  * 'off' includes 'regno->off'.
2535  * 'value_regno' can be -1, meaning that an unknown value is being written to
2536  * the stack.
2537  *
2538  * Spilled pointers in range are not marked as written because we don't know
2539  * what's going to be actually written. This means that read propagation for
2540  * future reads cannot be terminated by this write.
2541  *
2542  * For privileged programs, uninitialized stack slots are considered
2543  * initialized by this write (even though we don't know exactly what offsets
2544  * are going to be written to). The idea is that we don't want the verifier to
2545  * reject future reads that access slots written to through variable offsets.
2546  */
2547 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2548                                      /* func where register points to */
2549                                      struct bpf_func_state *state,
2550                                      int ptr_regno, int off, int size,
2551                                      int value_regno, int insn_idx)
2552 {
2553         struct bpf_func_state *cur; /* state of the current function */
2554         int min_off, max_off;
2555         int i, err;
2556         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2557         bool writing_zero = false;
2558         /* set if the fact that we're writing a zero is used to let any
2559          * stack slots remain STACK_ZERO
2560          */
2561         bool zero_used = false;
2562
2563         cur = env->cur_state->frame[env->cur_state->curframe];
2564         ptr_reg = &cur->regs[ptr_regno];
2565         min_off = ptr_reg->smin_value + off;
2566         max_off = ptr_reg->smax_value + off + size;
2567         if (value_regno >= 0)
2568                 value_reg = &cur->regs[value_regno];
2569         if (value_reg && register_is_null(value_reg))
2570                 writing_zero = true;
2571
2572         err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2573                                  state->acquired_refs, true);
2574         if (err)
2575                 return err;
2576
2577
2578         /* Variable offset writes destroy any spilled pointers in range. */
2579         for (i = min_off; i < max_off; i++) {
2580                 u8 new_type, *stype;
2581                 int slot, spi;
2582
2583                 slot = -i - 1;
2584                 spi = slot / BPF_REG_SIZE;
2585                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2586
2587                 if (!env->allow_ptr_leaks
2588                                 && *stype != NOT_INIT
2589                                 && *stype != SCALAR_VALUE) {
2590                         /* Reject the write if there's are spilled pointers in
2591                          * range. If we didn't reject here, the ptr status
2592                          * would be erased below (even though not all slots are
2593                          * actually overwritten), possibly opening the door to
2594                          * leaks.
2595                          */
2596                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2597                                 insn_idx, i);
2598                         return -EINVAL;
2599                 }
2600
2601                 /* Erase all spilled pointers. */
2602                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2603
2604                 /* Update the slot type. */
2605                 new_type = STACK_MISC;
2606                 if (writing_zero && *stype == STACK_ZERO) {
2607                         new_type = STACK_ZERO;
2608                         zero_used = true;
2609                 }
2610                 /* If the slot is STACK_INVALID, we check whether it's OK to
2611                  * pretend that it will be initialized by this write. The slot
2612                  * might not actually be written to, and so if we mark it as
2613                  * initialized future reads might leak uninitialized memory.
2614                  * For privileged programs, we will accept such reads to slots
2615                  * that may or may not be written because, if we're reject
2616                  * them, the error would be too confusing.
2617                  */
2618                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2619                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2620                                         insn_idx, i);
2621                         return -EINVAL;
2622                 }
2623                 *stype = new_type;
2624         }
2625         if (zero_used) {
2626                 /* backtracking doesn't work for STACK_ZERO yet. */
2627                 err = mark_chain_precision(env, value_regno);
2628                 if (err)
2629                         return err;
2630         }
2631         return 0;
2632 }
2633
2634 /* When register 'dst_regno' is assigned some values from stack[min_off,
2635  * max_off), we set the register's type according to the types of the
2636  * respective stack slots. If all the stack values are known to be zeros, then
2637  * so is the destination reg. Otherwise, the register is considered to be
2638  * SCALAR. This function does not deal with register filling; the caller must
2639  * ensure that all spilled registers in the stack range have been marked as
2640  * read.
2641  */
2642 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2643                                 /* func where src register points to */
2644                                 struct bpf_func_state *ptr_state,
2645                                 int min_off, int max_off, int dst_regno)
2646 {
2647         struct bpf_verifier_state *vstate = env->cur_state;
2648         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2649         int i, slot, spi;
2650         u8 *stype;
2651         int zeros = 0;
2652
2653         for (i = min_off; i < max_off; i++) {
2654                 slot = -i - 1;
2655                 spi = slot / BPF_REG_SIZE;
2656                 stype = ptr_state->stack[spi].slot_type;
2657                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2658                         break;
2659                 zeros++;
2660         }
2661         if (zeros == max_off - min_off) {
2662                 /* any access_size read into register is zero extended,
2663                  * so the whole register == const_zero
2664                  */
2665                 __mark_reg_const_zero(&state->regs[dst_regno]);
2666                 /* backtracking doesn't support STACK_ZERO yet,
2667                  * so mark it precise here, so that later
2668                  * backtracking can stop here.
2669                  * Backtracking may not need this if this register
2670                  * doesn't participate in pointer adjustment.
2671                  * Forward propagation of precise flag is not
2672                  * necessary either. This mark is only to stop
2673                  * backtracking. Any register that contributed
2674                  * to const 0 was marked precise before spill.
2675                  */
2676                 state->regs[dst_regno].precise = true;
2677         } else {
2678                 /* have read misc data from the stack */
2679                 mark_reg_unknown(env, state->regs, dst_regno);
2680         }
2681         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2682 }
2683
2684 /* Read the stack at 'off' and put the results into the register indicated by
2685  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2686  * spilled reg.
2687  *
2688  * 'dst_regno' can be -1, meaning that the read value is not going to a
2689  * register.
2690  *
2691  * The access is assumed to be within the current stack bounds.
2692  */
2693 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2694                                       /* func where src register points to */
2695                                       struct bpf_func_state *reg_state,
2696                                       int off, int size, int dst_regno)
2697 {
2698         struct bpf_verifier_state *vstate = env->cur_state;
2699         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2700         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2701         struct bpf_reg_state *reg;
2702         u8 *stype;
2703
2704         stype = reg_state->stack[spi].slot_type;
2705         reg = &reg_state->stack[spi].spilled_ptr;
2706
2707         if (stype[0] == STACK_SPILL) {
2708                 if (size != BPF_REG_SIZE) {
2709                         if (reg->type != SCALAR_VALUE) {
2710                                 verbose_linfo(env, env->insn_idx, "; ");
2711                                 verbose(env, "invalid size of register fill\n");
2712                                 return -EACCES;
2713                         }
2714                         if (dst_regno >= 0) {
2715                                 mark_reg_unknown(env, state->regs, dst_regno);
2716                                 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2717                         }
2718                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2719                         return 0;
2720                 }
2721                 for (i = 1; i < BPF_REG_SIZE; i++) {
2722                         if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2723                                 verbose(env, "corrupted spill memory\n");
2724                                 return -EACCES;
2725                         }
2726                 }
2727
2728                 if (dst_regno >= 0) {
2729                         /* restore register state from stack */
2730                         state->regs[dst_regno] = *reg;
2731                         /* mark reg as written since spilled pointer state likely
2732                          * has its liveness marks cleared by is_state_visited()
2733                          * which resets stack/reg liveness for state transitions
2734                          */
2735                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2736                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2737                         /* If dst_regno==-1, the caller is asking us whether
2738                          * it is acceptable to use this value as a SCALAR_VALUE
2739                          * (e.g. for XADD).
2740                          * We must not allow unprivileged callers to do that
2741                          * with spilled pointers.
2742                          */
2743                         verbose(env, "leaking pointer from stack off %d\n",
2744                                 off);
2745                         return -EACCES;
2746                 }
2747                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2748         } else {
2749                 u8 type;
2750
2751                 for (i = 0; i < size; i++) {
2752                         type = stype[(slot - i) % BPF_REG_SIZE];
2753                         if (type == STACK_MISC)
2754                                 continue;
2755                         if (type == STACK_ZERO)
2756                                 continue;
2757                         verbose(env, "invalid read from stack off %d+%d size %d\n",
2758                                 off, i, size);
2759                         return -EACCES;
2760                 }
2761                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2762                 if (dst_regno >= 0)
2763                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2764         }
2765         return 0;
2766 }
2767
2768 enum stack_access_src {
2769         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2770         ACCESS_HELPER = 2,  /* the access is performed by a helper */
2771 };
2772
2773 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2774                                          int regno, int off, int access_size,
2775                                          bool zero_size_allowed,
2776                                          enum stack_access_src type,
2777                                          struct bpf_call_arg_meta *meta);
2778
2779 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2780 {
2781         return cur_regs(env) + regno;
2782 }
2783
2784 /* Read the stack at 'ptr_regno + off' and put the result into the register
2785  * 'dst_regno'.
2786  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2787  * but not its variable offset.
2788  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2789  *
2790  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2791  * filling registers (i.e. reads of spilled register cannot be detected when
2792  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2793  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2794  * offset; for a fixed offset check_stack_read_fixed_off should be used
2795  * instead.
2796  */
2797 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2798                                     int ptr_regno, int off, int size, int dst_regno)
2799 {
2800         /* The state of the source register. */
2801         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2802         struct bpf_func_state *ptr_state = func(env, reg);
2803         int err;
2804         int min_off, max_off;
2805
2806         /* Note that we pass a NULL meta, so raw access will not be permitted.
2807          */
2808         err = check_stack_range_initialized(env, ptr_regno, off, size,
2809                                             false, ACCESS_DIRECT, NULL);
2810         if (err)
2811                 return err;
2812
2813         min_off = reg->smin_value + off;
2814         max_off = reg->smax_value + off;
2815         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2816         return 0;
2817 }
2818
2819 /* check_stack_read dispatches to check_stack_read_fixed_off or
2820  * check_stack_read_var_off.
2821  *
2822  * The caller must ensure that the offset falls within the allocated stack
2823  * bounds.
2824  *
2825  * 'dst_regno' is a register which will receive the value from the stack. It
2826  * can be -1, meaning that the read value is not going to a register.
2827  */
2828 static int check_stack_read(struct bpf_verifier_env *env,
2829                             int ptr_regno, int off, int size,
2830                             int dst_regno)
2831 {
2832         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2833         struct bpf_func_state *state = func(env, reg);
2834         int err;
2835         /* Some accesses are only permitted with a static offset. */
2836         bool var_off = !tnum_is_const(reg->var_off);
2837
2838         /* The offset is required to be static when reads don't go to a
2839          * register, in order to not leak pointers (see
2840          * check_stack_read_fixed_off).
2841          */
2842         if (dst_regno < 0 && var_off) {
2843                 char tn_buf[48];
2844
2845                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2846                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2847                         tn_buf, off, size);
2848                 return -EACCES;
2849         }
2850         /* Variable offset is prohibited for unprivileged mode for simplicity
2851          * since it requires corresponding support in Spectre masking for stack
2852          * ALU. See also retrieve_ptr_limit().
2853          */
2854         if (!env->bypass_spec_v1 && var_off) {
2855                 char tn_buf[48];
2856
2857                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2858                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2859                                 ptr_regno, tn_buf);
2860                 return -EACCES;
2861         }
2862
2863         if (!var_off) {
2864                 off += reg->var_off.value;
2865                 err = check_stack_read_fixed_off(env, state, off, size,
2866                                                  dst_regno);
2867         } else {
2868                 /* Variable offset stack reads need more conservative handling
2869                  * than fixed offset ones. Note that dst_regno >= 0 on this
2870                  * branch.
2871                  */
2872                 err = check_stack_read_var_off(env, ptr_regno, off, size,
2873                                                dst_regno);
2874         }
2875         return err;
2876 }
2877
2878
2879 /* check_stack_write dispatches to check_stack_write_fixed_off or
2880  * check_stack_write_var_off.
2881  *
2882  * 'ptr_regno' is the register used as a pointer into the stack.
2883  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2884  * 'value_regno' is the register whose value we're writing to the stack. It can
2885  * be -1, meaning that we're not writing from a register.
2886  *
2887  * The caller must ensure that the offset falls within the maximum stack size.
2888  */
2889 static int check_stack_write(struct bpf_verifier_env *env,
2890                              int ptr_regno, int off, int size,
2891                              int value_regno, int insn_idx)
2892 {
2893         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2894         struct bpf_func_state *state = func(env, reg);
2895         int err;
2896
2897         if (tnum_is_const(reg->var_off)) {
2898                 off += reg->var_off.value;
2899                 err = check_stack_write_fixed_off(env, state, off, size,
2900                                                   value_regno, insn_idx);
2901         } else {
2902                 /* Variable offset stack reads need more conservative handling
2903                  * than fixed offset ones.
2904                  */
2905                 err = check_stack_write_var_off(env, state,
2906                                                 ptr_regno, off, size,
2907                                                 value_regno, insn_idx);
2908         }
2909         return err;
2910 }
2911
2912 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2913                                  int off, int size, enum bpf_access_type type)
2914 {
2915         struct bpf_reg_state *regs = cur_regs(env);
2916         struct bpf_map *map = regs[regno].map_ptr;
2917         u32 cap = bpf_map_flags_to_cap(map);
2918
2919         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2920                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2921                         map->value_size, off, size);
2922                 return -EACCES;
2923         }
2924
2925         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2926                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2927                         map->value_size, off, size);
2928                 return -EACCES;
2929         }
2930
2931         return 0;
2932 }
2933
2934 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2935 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2936                               int off, int size, u32 mem_size,
2937                               bool zero_size_allowed)
2938 {
2939         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2940         struct bpf_reg_state *reg;
2941
2942         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2943                 return 0;
2944
2945         reg = &cur_regs(env)[regno];
2946         switch (reg->type) {
2947         case PTR_TO_MAP_KEY:
2948                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
2949                         mem_size, off, size);
2950                 break;
2951         case PTR_TO_MAP_VALUE:
2952                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2953                         mem_size, off, size);
2954                 break;
2955         case PTR_TO_PACKET:
2956         case PTR_TO_PACKET_META:
2957         case PTR_TO_PACKET_END:
2958                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2959                         off, size, regno, reg->id, off, mem_size);
2960                 break;
2961         case PTR_TO_MEM:
2962         default:
2963                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2964                         mem_size, off, size);
2965         }
2966
2967         return -EACCES;
2968 }
2969
2970 /* check read/write into a memory region with possible variable offset */
2971 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2972                                    int off, int size, u32 mem_size,
2973                                    bool zero_size_allowed)
2974 {
2975         struct bpf_verifier_state *vstate = env->cur_state;
2976         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2977         struct bpf_reg_state *reg = &state->regs[regno];
2978         int err;
2979
2980         /* We may have adjusted the register pointing to memory region, so we
2981          * need to try adding each of min_value and max_value to off
2982          * to make sure our theoretical access will be safe.
2983          */
2984         if (env->log.level & BPF_LOG_LEVEL)
2985                 print_verifier_state(env, state);
2986
2987         /* The minimum value is only important with signed
2988          * comparisons where we can't assume the floor of a
2989          * value is 0.  If we are using signed variables for our
2990          * index'es we need to make sure that whatever we use
2991          * will have a set floor within our range.
2992          */
2993         if (reg->smin_value < 0 &&
2994             (reg->smin_value == S64_MIN ||
2995              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2996               reg->smin_value + off < 0)) {
2997                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2998                         regno);
2999                 return -EACCES;
3000         }
3001         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3002                                  mem_size, zero_size_allowed);
3003         if (err) {
3004                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3005                         regno);
3006                 return err;
3007         }
3008
3009         /* If we haven't set a max value then we need to bail since we can't be
3010          * sure we won't do bad things.
3011          * If reg->umax_value + off could overflow, treat that as unbounded too.
3012          */
3013         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3014                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3015                         regno);
3016                 return -EACCES;
3017         }
3018         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3019                                  mem_size, zero_size_allowed);
3020         if (err) {
3021                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3022                         regno);
3023                 return err;
3024         }
3025
3026         return 0;
3027 }
3028
3029 /* check read/write into a map element with possible variable offset */
3030 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3031                             int off, int size, bool zero_size_allowed)
3032 {
3033         struct bpf_verifier_state *vstate = env->cur_state;
3034         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3035         struct bpf_reg_state *reg = &state->regs[regno];
3036         struct bpf_map *map = reg->map_ptr;
3037         int err;
3038
3039         err = check_mem_region_access(env, regno, off, size, map->value_size,
3040                                       zero_size_allowed);
3041         if (err)
3042                 return err;
3043
3044         if (map_value_has_spin_lock(map)) {
3045                 u32 lock = map->spin_lock_off;
3046
3047                 /* if any part of struct bpf_spin_lock can be touched by
3048                  * load/store reject this program.
3049                  * To check that [x1, x2) overlaps with [y1, y2)
3050                  * it is sufficient to check x1 < y2 && y1 < x2.
3051                  */
3052                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3053                      lock < reg->umax_value + off + size) {
3054                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3055                         return -EACCES;
3056                 }
3057         }
3058         return err;
3059 }
3060
3061 #define MAX_PACKET_OFF 0xffff
3062
3063 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3064 {
3065         return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3066 }
3067
3068 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3069                                        const struct bpf_call_arg_meta *meta,
3070                                        enum bpf_access_type t)
3071 {
3072         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3073
3074         switch (prog_type) {
3075         /* Program types only with direct read access go here! */
3076         case BPF_PROG_TYPE_LWT_IN:
3077         case BPF_PROG_TYPE_LWT_OUT:
3078         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3079         case BPF_PROG_TYPE_SK_REUSEPORT:
3080         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3081         case BPF_PROG_TYPE_CGROUP_SKB:
3082                 if (t == BPF_WRITE)
3083                         return false;
3084                 fallthrough;
3085
3086         /* Program types with direct read + write access go here! */
3087         case BPF_PROG_TYPE_SCHED_CLS:
3088         case BPF_PROG_TYPE_SCHED_ACT:
3089         case BPF_PROG_TYPE_XDP:
3090         case BPF_PROG_TYPE_LWT_XMIT:
3091         case BPF_PROG_TYPE_SK_SKB:
3092         case BPF_PROG_TYPE_SK_MSG:
3093                 if (meta)
3094                         return meta->pkt_access;
3095
3096                 env->seen_direct_write = true;
3097                 return true;
3098
3099         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3100                 if (t == BPF_WRITE)
3101                         env->seen_direct_write = true;
3102
3103                 return true;
3104
3105         default:
3106                 return false;
3107         }
3108 }
3109
3110 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3111                                int size, bool zero_size_allowed)
3112 {
3113         struct bpf_reg_state *regs = cur_regs(env);
3114         struct bpf_reg_state *reg = &regs[regno];
3115         int err;
3116
3117         /* We may have added a variable offset to the packet pointer; but any
3118          * reg->range we have comes after that.  We are only checking the fixed
3119          * offset.
3120          */
3121
3122         /* We don't allow negative numbers, because we aren't tracking enough
3123          * detail to prove they're safe.
3124          */
3125         if (reg->smin_value < 0) {
3126                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3127                         regno);
3128                 return -EACCES;
3129         }
3130
3131         err = reg->range < 0 ? -EINVAL :
3132               __check_mem_access(env, regno, off, size, reg->range,
3133                                  zero_size_allowed);
3134         if (err) {
3135                 verbose(env, "R%d offset is outside of the packet\n", regno);
3136                 return err;
3137         }
3138
3139         /* __check_mem_access has made sure "off + size - 1" is within u16.
3140          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3141          * otherwise find_good_pkt_pointers would have refused to set range info
3142          * that __check_mem_access would have rejected this pkt access.
3143          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3144          */
3145         env->prog->aux->max_pkt_offset =
3146                 max_t(u32, env->prog->aux->max_pkt_offset,
3147                       off + reg->umax_value + size - 1);
3148
3149         return err;
3150 }
3151
3152 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3153 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3154                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
3155                             struct btf **btf, u32 *btf_id)
3156 {
3157         struct bpf_insn_access_aux info = {
3158                 .reg_type = *reg_type,
3159                 .log = &env->log,
3160         };
3161
3162         if (env->ops->is_valid_access &&
3163             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3164                 /* A non zero info.ctx_field_size indicates that this field is a
3165                  * candidate for later verifier transformation to load the whole
3166                  * field and then apply a mask when accessed with a narrower
3167                  * access than actual ctx access size. A zero info.ctx_field_size
3168                  * will only allow for whole field access and rejects any other
3169                  * type of narrower access.
3170                  */
3171                 *reg_type = info.reg_type;
3172
3173                 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3174                         *btf = info.btf;
3175                         *btf_id = info.btf_id;
3176                 } else {
3177                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3178                 }
3179                 /* remember the offset of last byte accessed in ctx */
3180                 if (env->prog->aux->max_ctx_offset < off + size)
3181                         env->prog->aux->max_ctx_offset = off + size;
3182                 return 0;
3183         }
3184
3185         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3186         return -EACCES;
3187 }
3188
3189 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3190                                   int size)
3191 {
3192         if (size < 0 || off < 0 ||
3193             (u64)off + size > sizeof(struct bpf_flow_keys)) {
3194                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3195                         off, size);
3196                 return -EACCES;
3197         }
3198         return 0;
3199 }
3200
3201 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3202                              u32 regno, int off, int size,
3203                              enum bpf_access_type t)
3204 {
3205         struct bpf_reg_state *regs = cur_regs(env);
3206         struct bpf_reg_state *reg = &regs[regno];
3207         struct bpf_insn_access_aux info = {};
3208         bool valid;
3209
3210         if (reg->smin_value < 0) {
3211                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3212                         regno);
3213                 return -EACCES;
3214         }
3215
3216         switch (reg->type) {
3217         case PTR_TO_SOCK_COMMON:
3218                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3219                 break;
3220         case PTR_TO_SOCKET:
3221                 valid = bpf_sock_is_valid_access(off, size, t, &info);
3222                 break;
3223         case PTR_TO_TCP_SOCK:
3224                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3225                 break;
3226         case PTR_TO_XDP_SOCK:
3227                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3228                 break;
3229         default:
3230                 valid = false;
3231         }
3232
3233
3234         if (valid) {
3235                 env->insn_aux_data[insn_idx].ctx_field_size =
3236                         info.ctx_field_size;
3237                 return 0;
3238         }
3239
3240         verbose(env, "R%d invalid %s access off=%d size=%d\n",
3241                 regno, reg_type_str[reg->type], off, size);
3242
3243         return -EACCES;
3244 }
3245
3246 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3247 {
3248         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3249 }
3250
3251 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3252 {
3253         const struct bpf_reg_state *reg = reg_state(env, regno);
3254
3255         return reg->type == PTR_TO_CTX;
3256 }
3257
3258 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3259 {
3260         const struct bpf_reg_state *reg = reg_state(env, regno);
3261
3262         return type_is_sk_pointer(reg->type);
3263 }
3264
3265 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3266 {
3267         const struct bpf_reg_state *reg = reg_state(env, regno);
3268
3269         return type_is_pkt_pointer(reg->type);
3270 }
3271
3272 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3273 {
3274         const struct bpf_reg_state *reg = reg_state(env, regno);
3275
3276         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3277         return reg->type == PTR_TO_FLOW_KEYS;
3278 }
3279
3280 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3281                                    const struct bpf_reg_state *reg,
3282                                    int off, int size, bool strict)
3283 {
3284         struct tnum reg_off;
3285         int ip_align;
3286
3287         /* Byte size accesses are always allowed. */
3288         if (!strict || size == 1)
3289                 return 0;
3290
3291         /* For platforms that do not have a Kconfig enabling
3292          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3293          * NET_IP_ALIGN is universally set to '2'.  And on platforms
3294          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3295          * to this code only in strict mode where we want to emulate
3296          * the NET_IP_ALIGN==2 checking.  Therefore use an
3297          * unconditional IP align value of '2'.
3298          */
3299         ip_align = 2;
3300
3301         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3302         if (!tnum_is_aligned(reg_off, size)) {
3303                 char tn_buf[48];
3304
3305                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3306                 verbose(env,
3307                         "misaligned packet access off %d+%s+%d+%d size %d\n",
3308                         ip_align, tn_buf, reg->off, off, size);
3309                 return -EACCES;
3310         }
3311
3312         return 0;
3313 }
3314
3315 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3316                                        const struct bpf_reg_state *reg,
3317                                        const char *pointer_desc,
3318                                        int off, int size, bool strict)
3319 {
3320         struct tnum reg_off;
3321
3322         /* Byte size accesses are always allowed. */
3323         if (!strict || size == 1)
3324                 return 0;
3325
3326         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3327         if (!tnum_is_aligned(reg_off, size)) {
3328                 char tn_buf[48];
3329
3330                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3331                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3332                         pointer_desc, tn_buf, reg->off, off, size);
3333                 return -EACCES;
3334         }
3335
3336         return 0;
3337 }
3338
3339 static int check_ptr_alignment(struct bpf_verifier_env *env,
3340                                const struct bpf_reg_state *reg, int off,
3341                                int size, bool strict_alignment_once)
3342 {
3343         bool strict = env->strict_alignment || strict_alignment_once;
3344         const char *pointer_desc = "";
3345
3346         switch (reg->type) {
3347         case PTR_TO_PACKET:
3348         case PTR_TO_PACKET_META:
3349                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3350                  * right in front, treat it the very same way.
3351                  */
3352                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3353         case PTR_TO_FLOW_KEYS:
3354                 pointer_desc = "flow keys ";
3355                 break;
3356         case PTR_TO_MAP_KEY:
3357                 pointer_desc = "key ";
3358                 break;
3359         case PTR_TO_MAP_VALUE:
3360                 pointer_desc = "value ";
3361                 break;
3362         case PTR_TO_CTX:
3363                 pointer_desc = "context ";
3364                 break;
3365         case PTR_TO_STACK:
3366                 pointer_desc = "stack ";
3367                 /* The stack spill tracking logic in check_stack_write_fixed_off()
3368                  * and check_stack_read_fixed_off() relies on stack accesses being
3369                  * aligned.
3370                  */
3371                 strict = true;
3372                 break;
3373         case PTR_TO_SOCKET:
3374                 pointer_desc = "sock ";
3375                 break;
3376         case PTR_TO_SOCK_COMMON:
3377                 pointer_desc = "sock_common ";
3378                 break;
3379         case PTR_TO_TCP_SOCK:
3380                 pointer_desc = "tcp_sock ";
3381                 break;
3382         case PTR_TO_XDP_SOCK:
3383                 pointer_desc = "xdp_sock ";
3384                 break;
3385         default:
3386                 break;
3387         }
3388         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3389                                            strict);
3390 }
3391
3392 static int update_stack_depth(struct bpf_verifier_env *env,
3393                               const struct bpf_func_state *func,
3394                               int off)
3395 {
3396         u16 stack = env->subprog_info[func->subprogno].stack_depth;
3397
3398         if (stack >= -off)
3399                 return 0;
3400
3401         /* update known max for given subprogram */
3402         env->subprog_info[func->subprogno].stack_depth = -off;
3403         return 0;
3404 }
3405
3406 /* starting from main bpf function walk all instructions of the function
3407  * and recursively walk all callees that given function can call.
3408  * Ignore jump and exit insns.
3409  * Since recursion is prevented by check_cfg() this algorithm
3410  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3411  */
3412 static int check_max_stack_depth(struct bpf_verifier_env *env)
3413 {
3414         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3415         struct bpf_subprog_info *subprog = env->subprog_info;
3416         struct bpf_insn *insn = env->prog->insnsi;
3417         bool tail_call_reachable = false;
3418         int ret_insn[MAX_CALL_FRAMES];
3419         int ret_prog[MAX_CALL_FRAMES];
3420         int j;
3421
3422 process_func:
3423         /* protect against potential stack overflow that might happen when
3424          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3425          * depth for such case down to 256 so that the worst case scenario
3426          * would result in 8k stack size (32 which is tailcall limit * 256 =
3427          * 8k).
3428          *
3429          * To get the idea what might happen, see an example:
3430          * func1 -> sub rsp, 128
3431          *  subfunc1 -> sub rsp, 256
3432          *  tailcall1 -> add rsp, 256
3433          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3434          *   subfunc2 -> sub rsp, 64
3435          *   subfunc22 -> sub rsp, 128
3436          *   tailcall2 -> add rsp, 128
3437          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3438          *
3439          * tailcall will unwind the current stack frame but it will not get rid
3440          * of caller's stack as shown on the example above.
3441          */
3442         if (idx && subprog[idx].has_tail_call && depth >= 256) {
3443                 verbose(env,
3444                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3445                         depth);
3446                 return -EACCES;
3447         }
3448         /* round up to 32-bytes, since this is granularity
3449          * of interpreter stack size
3450          */
3451         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3452         if (depth > MAX_BPF_STACK) {
3453                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3454                         frame + 1, depth);
3455                 return -EACCES;
3456         }
3457 continue_func:
3458         subprog_end = subprog[idx + 1].start;
3459         for (; i < subprog_end; i++) {
3460                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3461                         continue;
3462                 /* remember insn and function to return to */
3463                 ret_insn[frame] = i + 1;
3464                 ret_prog[frame] = idx;
3465
3466                 /* find the callee */
3467                 i = i + insn[i].imm + 1;
3468                 idx = find_subprog(env, i);
3469                 if (idx < 0) {
3470                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3471                                   i);
3472                         return -EFAULT;
3473                 }
3474
3475                 if (subprog[idx].has_tail_call)
3476                         tail_call_reachable = true;
3477
3478                 frame++;
3479                 if (frame >= MAX_CALL_FRAMES) {
3480                         verbose(env, "the call stack of %d frames is too deep !\n",
3481                                 frame);
3482                         return -E2BIG;
3483                 }
3484                 goto process_func;
3485         }
3486         /* if tail call got detected across bpf2bpf calls then mark each of the
3487          * currently present subprog frames as tail call reachable subprogs;
3488          * this info will be utilized by JIT so that we will be preserving the
3489          * tail call counter throughout bpf2bpf calls combined with tailcalls
3490          */
3491         if (tail_call_reachable)
3492                 for (j = 0; j < frame; j++)
3493                         subprog[ret_prog[j]].tail_call_reachable = true;
3494
3495         /* end of for() loop means the last insn of the 'subprog'
3496          * was reached. Doesn't matter whether it was JA or EXIT
3497          */
3498         if (frame == 0)
3499                 return 0;
3500         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3501         frame--;
3502         i = ret_insn[frame];
3503         idx = ret_prog[frame];
3504         goto continue_func;
3505 }
3506
3507 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3508 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3509                                   const struct bpf_insn *insn, int idx)
3510 {
3511         int start = idx + insn->imm + 1, subprog;
3512
3513         subprog = find_subprog(env, start);
3514         if (subprog < 0) {
3515                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3516                           start);
3517                 return -EFAULT;
3518         }
3519         return env->subprog_info[subprog].stack_depth;
3520 }
3521 #endif
3522
3523 int check_ctx_reg(struct bpf_verifier_env *env,
3524                   const struct bpf_reg_state *reg, int regno)
3525 {
3526         /* Access to ctx or passing it to a helper is only allowed in
3527          * its original, unmodified form.
3528          */
3529
3530         if (reg->off) {
3531                 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3532                         regno, reg->off);
3533                 return -EACCES;
3534         }
3535
3536         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3537                 char tn_buf[48];
3538
3539                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3540                 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3541                 return -EACCES;
3542         }
3543
3544         return 0;
3545 }
3546
3547 static int __check_buffer_access(struct bpf_verifier_env *env,
3548                                  const char *buf_info,
3549                                  const struct bpf_reg_state *reg,
3550                                  int regno, int off, int size)
3551 {
3552         if (off < 0) {
3553                 verbose(env,
3554                         "R%d invalid %s buffer access: off=%d, size=%d\n",
3555                         regno, buf_info, off, size);
3556                 return -EACCES;
3557         }
3558         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3559                 char tn_buf[48];
3560
3561                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3562                 verbose(env,
3563                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3564                         regno, off, tn_buf);
3565                 return -EACCES;
3566         }
3567
3568         return 0;
3569 }
3570
3571 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3572                                   const struct bpf_reg_state *reg,
3573                                   int regno, int off, int size)
3574 {
3575         int err;
3576
3577         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3578         if (err)
3579                 return err;
3580
3581         if (off + size > env->prog->aux->max_tp_access)
3582                 env->prog->aux->max_tp_access = off + size;
3583
3584         return 0;
3585 }
3586
3587 static int check_buffer_access(struct bpf_verifier_env *env,
3588                                const struct bpf_reg_state *reg,
3589                                int regno, int off, int size,
3590                                bool zero_size_allowed,
3591                                const char *buf_info,
3592                                u32 *max_access)
3593 {
3594         int err;
3595
3596         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3597         if (err)
3598                 return err;
3599
3600         if (off + size > *max_access)
3601                 *max_access = off + size;
3602
3603         return 0;
3604 }
3605
3606 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3607 static void zext_32_to_64(struct bpf_reg_state *reg)
3608 {
3609         reg->var_off = tnum_subreg(reg->var_off);
3610         __reg_assign_32_into_64(reg);
3611 }
3612
3613 /* truncate register to smaller size (in bytes)
3614  * must be called with size < BPF_REG_SIZE
3615  */
3616 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3617 {
3618         u64 mask;
3619
3620         /* clear high bits in bit representation */
3621         reg->var_off = tnum_cast(reg->var_off, size);
3622
3623         /* fix arithmetic bounds */
3624         mask = ((u64)1 << (size * 8)) - 1;
3625         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3626                 reg->umin_value &= mask;
3627                 reg->umax_value &= mask;
3628         } else {
3629                 reg->umin_value = 0;
3630                 reg->umax_value = mask;
3631         }
3632         reg->smin_value = reg->umin_value;
3633         reg->smax_value = reg->umax_value;
3634
3635         /* If size is smaller than 32bit register the 32bit register
3636          * values are also truncated so we push 64-bit bounds into
3637          * 32-bit bounds. Above were truncated < 32-bits already.
3638          */
3639         if (size >= 4)
3640                 return;
3641         __reg_combine_64_into_32(reg);
3642 }
3643
3644 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3645 {
3646         return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3647 }
3648
3649 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3650 {
3651         void *ptr;
3652         u64 addr;
3653         int err;
3654
3655         err = map->ops->map_direct_value_addr(map, &addr, off);
3656         if (err)
3657                 return err;
3658         ptr = (void *)(long)addr + off;
3659
3660         switch (size) {
3661         case sizeof(u8):
3662                 *val = (u64)*(u8 *)ptr;
3663                 break;
3664         case sizeof(u16):
3665                 *val = (u64)*(u16 *)ptr;
3666                 break;
3667         case sizeof(u32):
3668                 *val = (u64)*(u32 *)ptr;
3669                 break;
3670         case sizeof(u64):
3671                 *val = *(u64 *)ptr;
3672                 break;
3673         default:
3674                 return -EINVAL;
3675         }
3676         return 0;
3677 }
3678
3679 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3680                                    struct bpf_reg_state *regs,
3681                                    int regno, int off, int size,
3682                                    enum bpf_access_type atype,
3683                                    int value_regno)
3684 {
3685         struct bpf_reg_state *reg = regs + regno;
3686         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3687         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3688         u32 btf_id;
3689         int ret;
3690
3691         if (off < 0) {
3692                 verbose(env,
3693                         "R%d is ptr_%s invalid negative access: off=%d\n",
3694                         regno, tname, off);
3695                 return -EACCES;
3696         }
3697         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3698                 char tn_buf[48];
3699
3700                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3701                 verbose(env,
3702                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3703                         regno, tname, off, tn_buf);
3704                 return -EACCES;
3705         }
3706
3707         if (env->ops->btf_struct_access) {
3708                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3709                                                   off, size, atype, &btf_id);
3710         } else {
3711                 if (atype != BPF_READ) {
3712                         verbose(env, "only read is supported\n");
3713                         return -EACCES;
3714                 }
3715
3716                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3717                                         atype, &btf_id);
3718         }
3719
3720         if (ret < 0)
3721                 return ret;
3722
3723         if (atype == BPF_READ && value_regno >= 0)
3724                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3725
3726         return 0;
3727 }
3728
3729 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3730                                    struct bpf_reg_state *regs,
3731                                    int regno, int off, int size,
3732                                    enum bpf_access_type atype,
3733                                    int value_regno)
3734 {
3735         struct bpf_reg_state *reg = regs + regno;
3736         struct bpf_map *map = reg->map_ptr;
3737         const struct btf_type *t;
3738         const char *tname;
3739         u32 btf_id;
3740         int ret;
3741
3742         if (!btf_vmlinux) {
3743                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3744                 return -ENOTSUPP;
3745         }
3746
3747         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3748                 verbose(env, "map_ptr access not supported for map type %d\n",
3749                         map->map_type);
3750                 return -ENOTSUPP;
3751         }
3752
3753         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3754         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3755
3756         if (!env->allow_ptr_to_map_access) {
3757                 verbose(env,
3758                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3759                         tname);
3760                 return -EPERM;
3761         }
3762
3763         if (off < 0) {
3764                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3765                         regno, tname, off);
3766                 return -EACCES;
3767         }
3768
3769         if (atype != BPF_READ) {
3770                 verbose(env, "only read from %s is supported\n", tname);
3771                 return -EACCES;
3772         }
3773
3774         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
3775         if (ret < 0)
3776                 return ret;
3777
3778         if (value_regno >= 0)
3779                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
3780
3781         return 0;
3782 }
3783
3784 /* Check that the stack access at the given offset is within bounds. The
3785  * maximum valid offset is -1.
3786  *
3787  * The minimum valid offset is -MAX_BPF_STACK for writes, and
3788  * -state->allocated_stack for reads.
3789  */
3790 static int check_stack_slot_within_bounds(int off,
3791                                           struct bpf_func_state *state,
3792                                           enum bpf_access_type t)
3793 {
3794         int min_valid_off;
3795
3796         if (t == BPF_WRITE)
3797                 min_valid_off = -MAX_BPF_STACK;
3798         else
3799                 min_valid_off = -state->allocated_stack;
3800
3801         if (off < min_valid_off || off > -1)
3802                 return -EACCES;
3803         return 0;
3804 }
3805
3806 /* Check that the stack access at 'regno + off' falls within the maximum stack
3807  * bounds.
3808  *
3809  * 'off' includes `regno->offset`, but not its dynamic part (if any).
3810  */
3811 static int check_stack_access_within_bounds(
3812                 struct bpf_verifier_env *env,
3813                 int regno, int off, int access_size,
3814                 enum stack_access_src src, enum bpf_access_type type)
3815 {
3816         struct bpf_reg_state *regs = cur_regs(env);
3817         struct bpf_reg_state *reg = regs + regno;
3818         struct bpf_func_state *state = func(env, reg);
3819         int min_off, max_off;
3820         int err;
3821         char *err_extra;
3822
3823         if (src == ACCESS_HELPER)
3824                 /* We don't know if helpers are reading or writing (or both). */
3825                 err_extra = " indirect access to";
3826         else if (type == BPF_READ)
3827                 err_extra = " read from";
3828         else
3829                 err_extra = " write to";
3830
3831         if (tnum_is_const(reg->var_off)) {
3832                 min_off = reg->var_off.value + off;
3833                 if (access_size > 0)
3834                         max_off = min_off + access_size - 1;
3835                 else
3836                         max_off = min_off;
3837         } else {
3838                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3839                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
3840                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3841                                 err_extra, regno);
3842                         return -EACCES;
3843                 }
3844                 min_off = reg->smin_value + off;
3845                 if (access_size > 0)
3846                         max_off = reg->smax_value + off + access_size - 1;
3847                 else
3848                         max_off = min_off;
3849         }
3850
3851         err = check_stack_slot_within_bounds(min_off, state, type);
3852         if (!err)
3853                 err = check_stack_slot_within_bounds(max_off, state, type);
3854
3855         if (err) {
3856                 if (tnum_is_const(reg->var_off)) {
3857                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3858                                 err_extra, regno, off, access_size);
3859                 } else {
3860                         char tn_buf[48];
3861
3862                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3863                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3864                                 err_extra, regno, tn_buf, access_size);
3865                 }
3866         }
3867         return err;
3868 }
3869
3870 /* check whether memory at (regno + off) is accessible for t = (read | write)
3871  * if t==write, value_regno is a register which value is stored into memory
3872  * if t==read, value_regno is a register which will receive the value from memory
3873  * if t==write && value_regno==-1, some unknown value is stored into memory
3874  * if t==read && value_regno==-1, don't care what we read from memory
3875  */
3876 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3877                             int off, int bpf_size, enum bpf_access_type t,
3878                             int value_regno, bool strict_alignment_once)
3879 {
3880         struct bpf_reg_state *regs = cur_regs(env);
3881         struct bpf_reg_state *reg = regs + regno;
3882         struct bpf_func_state *state;
3883         int size, err = 0;
3884
3885         size = bpf_size_to_bytes(bpf_size);
3886         if (size < 0)
3887                 return size;
3888
3889         /* alignment checks will add in reg->off themselves */
3890         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3891         if (err)
3892                 return err;
3893
3894         /* for access checks, reg->off is just part of off */
3895         off += reg->off;
3896
3897         if (reg->type == PTR_TO_MAP_KEY) {
3898                 if (t == BPF_WRITE) {
3899                         verbose(env, "write to change key R%d not allowed\n", regno);
3900                         return -EACCES;
3901                 }
3902
3903                 err = check_mem_region_access(env, regno, off, size,
3904                                               reg->map_ptr->key_size, false);
3905                 if (err)
3906                         return err;
3907                 if (value_regno >= 0)
3908                         mark_reg_unknown(env, regs, value_regno);
3909         } else if (reg->type == PTR_TO_MAP_VALUE) {
3910                 if (t == BPF_WRITE && value_regno >= 0 &&
3911                     is_pointer_value(env, value_regno)) {
3912                         verbose(env, "R%d leaks addr into map\n", value_regno);
3913                         return -EACCES;
3914                 }
3915                 err = check_map_access_type(env, regno, off, size, t);
3916                 if (err)
3917                         return err;
3918                 err = check_map_access(env, regno, off, size, false);
3919                 if (!err && t == BPF_READ && value_regno >= 0) {
3920                         struct bpf_map *map = reg->map_ptr;
3921
3922                         /* if map is read-only, track its contents as scalars */
3923                         if (tnum_is_const(reg->var_off) &&
3924                             bpf_map_is_rdonly(map) &&
3925                             map->ops->map_direct_value_addr) {
3926                                 int map_off = off + reg->var_off.value;
3927                                 u64 val = 0;
3928
3929                                 err = bpf_map_direct_read(map, map_off, size,
3930                                                           &val);
3931                                 if (err)
3932                                         return err;
3933
3934                                 regs[value_regno].type = SCALAR_VALUE;
3935                                 __mark_reg_known(&regs[value_regno], val);
3936                         } else {
3937                                 mark_reg_unknown(env, regs, value_regno);
3938                         }
3939                 }
3940         } else if (reg->type == PTR_TO_MEM) {
3941                 if (t == BPF_WRITE && value_regno >= 0 &&
3942                     is_pointer_value(env, value_regno)) {
3943                         verbose(env, "R%d leaks addr into mem\n", value_regno);
3944                         return -EACCES;
3945                 }
3946                 err = check_mem_region_access(env, regno, off, size,
3947                                               reg->mem_size, false);
3948                 if (!err && t == BPF_READ && value_regno >= 0)
3949                         mark_reg_unknown(env, regs, value_regno);
3950         } else if (reg->type == PTR_TO_CTX) {
3951                 enum bpf_reg_type reg_type = SCALAR_VALUE;
3952                 struct btf *btf = NULL;
3953                 u32 btf_id = 0;
3954
3955                 if (t == BPF_WRITE && value_regno >= 0 &&
3956                     is_pointer_value(env, value_regno)) {
3957                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
3958                         return -EACCES;
3959                 }
3960
3961                 err = check_ctx_reg(env, reg, regno);
3962                 if (err < 0)
3963                         return err;
3964
3965                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
3966                 if (err)
3967                         verbose_linfo(env, insn_idx, "; ");
3968                 if (!err && t == BPF_READ && value_regno >= 0) {
3969                         /* ctx access returns either a scalar, or a
3970                          * PTR_TO_PACKET[_META,_END]. In the latter
3971                          * case, we know the offset is zero.
3972                          */
3973                         if (reg_type == SCALAR_VALUE) {
3974                                 mark_reg_unknown(env, regs, value_regno);
3975                         } else {
3976                                 mark_reg_known_zero(env, regs,
3977                                                     value_regno);
3978                                 if (reg_type_may_be_null(reg_type))
3979                                         regs[value_regno].id = ++env->id_gen;
3980                                 /* A load of ctx field could have different
3981                                  * actual load size with the one encoded in the
3982                                  * insn. When the dst is PTR, it is for sure not
3983                                  * a sub-register.
3984                                  */
3985                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3986                                 if (reg_type == PTR_TO_BTF_ID ||
3987                                     reg_type == PTR_TO_BTF_ID_OR_NULL) {
3988                                         regs[value_regno].btf = btf;
3989                                         regs[value_regno].btf_id = btf_id;
3990                                 }
3991                         }
3992                         regs[value_regno].type = reg_type;
3993                 }
3994
3995         } else if (reg->type == PTR_TO_STACK) {
3996                 /* Basic bounds checks. */
3997                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
3998                 if (err)
3999                         return err;
4000
4001                 state = func(env, reg);
4002                 err = update_stack_depth(env, state, off);
4003                 if (err)
4004                         return err;
4005
4006                 if (t == BPF_READ)
4007                         err = check_stack_read(env, regno, off, size,
4008                                                value_regno);
4009                 else
4010                         err = check_stack_write(env, regno, off, size,
4011                                                 value_regno, insn_idx);
4012         } else if (reg_is_pkt_pointer(reg)) {
4013                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4014                         verbose(env, "cannot write into packet\n");
4015                         return -EACCES;
4016                 }
4017                 if (t == BPF_WRITE && value_regno >= 0 &&
4018                     is_pointer_value(env, value_regno)) {
4019                         verbose(env, "R%d leaks addr into packet\n",
4020                                 value_regno);
4021                         return -EACCES;
4022                 }
4023                 err = check_packet_access(env, regno, off, size, false);
4024                 if (!err && t == BPF_READ && value_regno >= 0)
4025                         mark_reg_unknown(env, regs, value_regno);
4026         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4027                 if (t == BPF_WRITE && value_regno >= 0 &&
4028                     is_pointer_value(env, value_regno)) {
4029                         verbose(env, "R%d leaks addr into flow keys\n",
4030                                 value_regno);
4031                         return -EACCES;
4032                 }
4033
4034                 err = check_flow_keys_access(env, off, size);
4035                 if (!err && t == BPF_READ && value_regno >= 0)
4036                         mark_reg_unknown(env, regs, value_regno);
4037         } else if (type_is_sk_pointer(reg->type)) {
4038                 if (t == BPF_WRITE) {
4039                         verbose(env, "R%d cannot write into %s\n",
4040                                 regno, reg_type_str[reg->type]);
4041                         return -EACCES;
4042                 }
4043                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4044                 if (!err && value_regno >= 0)
4045                         mark_reg_unknown(env, regs, value_regno);
4046         } else if (reg->type == PTR_TO_TP_BUFFER) {
4047                 err = check_tp_buffer_access(env, reg, regno, off, size);
4048                 if (!err && t == BPF_READ && value_regno >= 0)
4049                         mark_reg_unknown(env, regs, value_regno);
4050         } else if (reg->type == PTR_TO_BTF_ID) {
4051                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4052                                               value_regno);
4053         } else if (reg->type == CONST_PTR_TO_MAP) {
4054                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4055                                               value_regno);
4056         } else if (reg->type == PTR_TO_RDONLY_BUF) {
4057                 if (t == BPF_WRITE) {
4058                         verbose(env, "R%d cannot write into %s\n",
4059                                 regno, reg_type_str[reg->type]);
4060                         return -EACCES;
4061                 }
4062                 err = check_buffer_access(env, reg, regno, off, size, false,
4063                                           "rdonly",
4064                                           &env->prog->aux->max_rdonly_access);
4065                 if (!err && value_regno >= 0)
4066                         mark_reg_unknown(env, regs, value_regno);
4067         } else if (reg->type == PTR_TO_RDWR_BUF) {
4068                 err = check_buffer_access(env, reg, regno, off, size, false,
4069                                           "rdwr",
4070                                           &env->prog->aux->max_rdwr_access);
4071                 if (!err && t == BPF_READ && value_regno >= 0)
4072                         mark_reg_unknown(env, regs, value_regno);
4073         } else {
4074                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4075                         reg_type_str[reg->type]);
4076                 return -EACCES;
4077         }
4078
4079         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4080             regs[value_regno].type == SCALAR_VALUE) {
4081                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4082                 coerce_reg_to_size(&regs[value_regno], size);
4083         }
4084         return err;
4085 }
4086
4087 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4088 {
4089         int load_reg;
4090         int err;
4091
4092         switch (insn->imm) {
4093         case BPF_ADD:
4094         case BPF_ADD | BPF_FETCH:
4095         case BPF_AND:
4096         case BPF_AND | BPF_FETCH:
4097         case BPF_OR:
4098         case BPF_OR | BPF_FETCH:
4099         case BPF_XOR:
4100         case BPF_XOR | BPF_FETCH:
4101         case BPF_XCHG:
4102         case BPF_CMPXCHG:
4103                 break;
4104         default:
4105                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4106                 return -EINVAL;
4107         }
4108
4109         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4110                 verbose(env, "invalid atomic operand size\n");
4111                 return -EINVAL;
4112         }
4113
4114         /* check src1 operand */
4115         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4116         if (err)
4117                 return err;
4118
4119         /* check src2 operand */
4120         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4121         if (err)
4122                 return err;
4123
4124         if (insn->imm == BPF_CMPXCHG) {
4125                 /* Check comparison of R0 with memory location */
4126                 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4127                 if (err)
4128                         return err;
4129         }
4130
4131         if (is_pointer_value(env, insn->src_reg)) {
4132                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4133                 return -EACCES;
4134         }
4135
4136         if (is_ctx_reg(env, insn->dst_reg) ||
4137             is_pkt_reg(env, insn->dst_reg) ||
4138             is_flow_key_reg(env, insn->dst_reg) ||
4139             is_sk_reg(env, insn->dst_reg)) {
4140                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4141                         insn->dst_reg,
4142                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
4143                 return -EACCES;
4144         }
4145
4146         if (insn->imm & BPF_FETCH) {
4147                 if (insn->imm == BPF_CMPXCHG)
4148                         load_reg = BPF_REG_0;
4149                 else
4150                         load_reg = insn->src_reg;
4151
4152                 /* check and record load of old value */
4153                 err = check_reg_arg(env, load_reg, DST_OP);
4154                 if (err)
4155                         return err;
4156         } else {
4157                 /* This instruction accesses a memory location but doesn't
4158                  * actually load it into a register.
4159                  */
4160                 load_reg = -1;
4161         }
4162
4163         /* check whether we can read the memory */
4164         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4165                                BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4166         if (err)
4167                 return err;
4168
4169         /* check whether we can write into the same memory */
4170         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4171                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4172         if (err)
4173                 return err;
4174
4175         return 0;
4176 }
4177
4178 /* When register 'regno' is used to read the stack (either directly or through
4179  * a helper function) make sure that it's within stack boundary and, depending
4180  * on the access type, that all elements of the stack are initialized.
4181  *
4182  * 'off' includes 'regno->off', but not its dynamic part (if any).
4183  *
4184  * All registers that have been spilled on the stack in the slots within the
4185  * read offsets are marked as read.
4186  */
4187 static int check_stack_range_initialized(
4188                 struct bpf_verifier_env *env, int regno, int off,
4189                 int access_size, bool zero_size_allowed,
4190                 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4191 {
4192         struct bpf_reg_state *reg = reg_state(env, regno);
4193         struct bpf_func_state *state = func(env, reg);
4194         int err, min_off, max_off, i, j, slot, spi;
4195         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4196         enum bpf_access_type bounds_check_type;
4197         /* Some accesses can write anything into the stack, others are
4198          * read-only.
4199          */
4200         bool clobber = false;
4201
4202         if (access_size == 0 && !zero_size_allowed) {
4203                 verbose(env, "invalid zero-sized read\n");
4204                 return -EACCES;
4205         }
4206
4207         if (type == ACCESS_HELPER) {
4208                 /* The bounds checks for writes are more permissive than for
4209                  * reads. However, if raw_mode is not set, we'll do extra
4210                  * checks below.
4211                  */
4212                 bounds_check_type = BPF_WRITE;
4213                 clobber = true;
4214         } else {
4215                 bounds_check_type = BPF_READ;
4216         }
4217         err = check_stack_access_within_bounds(env, regno, off, access_size,
4218                                                type, bounds_check_type);
4219         if (err)
4220                 return err;
4221
4222
4223         if (tnum_is_const(reg->var_off)) {
4224                 min_off = max_off = reg->var_off.value + off;
4225         } else {
4226                 /* Variable offset is prohibited for unprivileged mode for
4227                  * simplicity since it requires corresponding support in
4228                  * Spectre masking for stack ALU.
4229                  * See also retrieve_ptr_limit().
4230                  */
4231                 if (!env->bypass_spec_v1) {
4232                         char tn_buf[48];
4233
4234                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4235                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4236                                 regno, err_extra, tn_buf);
4237                         return -EACCES;
4238                 }
4239                 /* Only initialized buffer on stack is allowed to be accessed
4240                  * with variable offset. With uninitialized buffer it's hard to
4241                  * guarantee that whole memory is marked as initialized on
4242                  * helper return since specific bounds are unknown what may
4243                  * cause uninitialized stack leaking.
4244                  */
4245                 if (meta && meta->raw_mode)
4246                         meta = NULL;
4247
4248                 min_off = reg->smin_value + off;
4249                 max_off = reg->smax_value + off;
4250         }
4251
4252         if (meta && meta->raw_mode) {
4253                 meta->access_size = access_size;
4254                 meta->regno = regno;
4255                 return 0;
4256         }
4257
4258         for (i = min_off; i < max_off + access_size; i++) {
4259                 u8 *stype;
4260
4261                 slot = -i - 1;
4262                 spi = slot / BPF_REG_SIZE;
4263                 if (state->allocated_stack <= slot)
4264                         goto err;
4265                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4266                 if (*stype == STACK_MISC)
4267                         goto mark;
4268                 if (*stype == STACK_ZERO) {
4269                         if (clobber) {
4270                                 /* helper can write anything into the stack */
4271                                 *stype = STACK_MISC;
4272                         }
4273                         goto mark;
4274                 }
4275
4276                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4277                     state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4278                         goto mark;
4279
4280                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4281                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4282                      env->allow_ptr_leaks)) {
4283                         if (clobber) {
4284                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4285                                 for (j = 0; j < BPF_REG_SIZE; j++)
4286                                         state->stack[spi].slot_type[j] = STACK_MISC;
4287                         }
4288                         goto mark;
4289                 }
4290
4291 err:
4292                 if (tnum_is_const(reg->var_off)) {
4293                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4294                                 err_extra, regno, min_off, i - min_off, access_size);
4295                 } else {
4296                         char tn_buf[48];
4297
4298                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4299                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4300                                 err_extra, regno, tn_buf, i - min_off, access_size);
4301                 }
4302                 return -EACCES;
4303 mark:
4304                 /* reading any byte out of 8-byte 'spill_slot' will cause
4305                  * the whole slot to be marked as 'read'
4306                  */
4307                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4308                               state->stack[spi].spilled_ptr.parent,
4309                               REG_LIVE_READ64);
4310         }
4311         return update_stack_depth(env, state, min_off);
4312 }
4313
4314 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4315                                    int access_size, bool zero_size_allowed,
4316                                    struct bpf_call_arg_meta *meta)
4317 {
4318         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4319
4320         switch (reg->type) {
4321         case PTR_TO_PACKET:
4322         case PTR_TO_PACKET_META:
4323                 return check_packet_access(env, regno, reg->off, access_size,
4324                                            zero_size_allowed);
4325         case PTR_TO_MAP_KEY:
4326                 return check_mem_region_access(env, regno, reg->off, access_size,
4327                                                reg->map_ptr->key_size, false);
4328         case PTR_TO_MAP_VALUE:
4329                 if (check_map_access_type(env, regno, reg->off, access_size,
4330                                           meta && meta->raw_mode ? BPF_WRITE :
4331                                           BPF_READ))
4332                         return -EACCES;
4333                 return check_map_access(env, regno, reg->off, access_size,
4334                                         zero_size_allowed);
4335         case PTR_TO_MEM:
4336                 return check_mem_region_access(env, regno, reg->off,
4337                                                access_size, reg->mem_size,
4338                                                zero_size_allowed);
4339         case PTR_TO_RDONLY_BUF:
4340                 if (meta && meta->raw_mode)
4341                         return -EACCES;
4342                 return check_buffer_access(env, reg, regno, reg->off,
4343                                            access_size, zero_size_allowed,
4344                                            "rdonly",
4345                                            &env->prog->aux->max_rdonly_access);
4346         case PTR_TO_RDWR_BUF:
4347                 return check_buffer_access(env, reg, regno, reg->off,
4348                                            access_size, zero_size_allowed,
4349                                            "rdwr",
4350                                            &env->prog->aux->max_rdwr_access);
4351         case PTR_TO_STACK:
4352                 return check_stack_range_initialized(
4353                                 env,
4354                                 regno, reg->off, access_size,
4355                                 zero_size_allowed, ACCESS_HELPER, meta);
4356         default: /* scalar_value or invalid ptr */
4357                 /* Allow zero-byte read from NULL, regardless of pointer type */
4358                 if (zero_size_allowed && access_size == 0 &&
4359                     register_is_null(reg))
4360                         return 0;
4361
4362                 verbose(env, "R%d type=%s expected=%s\n", regno,
4363                         reg_type_str[reg->type],
4364                         reg_type_str[PTR_TO_STACK]);
4365                 return -EACCES;
4366         }
4367 }
4368
4369 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4370                    u32 regno, u32 mem_size)
4371 {
4372         if (register_is_null(reg))
4373                 return 0;
4374
4375         if (reg_type_may_be_null(reg->type)) {
4376                 /* Assuming that the register contains a value check if the memory
4377                  * access is safe. Temporarily save and restore the register's state as
4378                  * the conversion shouldn't be visible to a caller.
4379                  */
4380                 const struct bpf_reg_state saved_reg = *reg;
4381                 int rv;
4382
4383                 mark_ptr_not_null_reg(reg);
4384                 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4385                 *reg = saved_reg;
4386                 return rv;
4387         }
4388
4389         return check_helper_mem_access(env, regno, mem_size, true, NULL);
4390 }
4391
4392 /* Implementation details:
4393  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4394  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4395  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4396  * value_or_null->value transition, since the verifier only cares about
4397  * the range of access to valid map value pointer and doesn't care about actual
4398  * address of the map element.
4399  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4400  * reg->id > 0 after value_or_null->value transition. By doing so
4401  * two bpf_map_lookups will be considered two different pointers that
4402  * point to different bpf_spin_locks.
4403  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4404  * dead-locks.
4405  * Since only one bpf_spin_lock is allowed the checks are simpler than
4406  * reg_is_refcounted() logic. The verifier needs to remember only
4407  * one spin_lock instead of array of acquired_refs.
4408  * cur_state->active_spin_lock remembers which map value element got locked
4409  * and clears it after bpf_spin_unlock.
4410  */
4411 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4412                              bool is_lock)
4413 {
4414         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4415         struct bpf_verifier_state *cur = env->cur_state;
4416         bool is_const = tnum_is_const(reg->var_off);
4417         struct bpf_map *map = reg->map_ptr;
4418         u64 val = reg->var_off.value;
4419
4420         if (!is_const) {
4421                 verbose(env,
4422                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4423                         regno);
4424                 return -EINVAL;
4425         }
4426         if (!map->btf) {
4427                 verbose(env,
4428                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4429                         map->name);
4430                 return -EINVAL;
4431         }
4432         if (!map_value_has_spin_lock(map)) {
4433                 if (map->spin_lock_off == -E2BIG)
4434                         verbose(env,
4435                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4436                                 map->name);
4437                 else if (map->spin_lock_off == -ENOENT)
4438                         verbose(env,
4439                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4440                                 map->name);
4441                 else
4442                         verbose(env,
4443                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4444                                 map->name);
4445                 return -EINVAL;
4446         }
4447         if (map->spin_lock_off != val + reg->off) {
4448                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4449                         val + reg->off);
4450                 return -EINVAL;
4451         }
4452         if (is_lock) {
4453                 if (cur->active_spin_lock) {
4454                         verbose(env,
4455                                 "Locking two bpf_spin_locks are not allowed\n");
4456                         return -EINVAL;
4457                 }
4458                 cur->active_spin_lock = reg->id;
4459         } else {
4460                 if (!cur->active_spin_lock) {
4461                         verbose(env, "bpf_spin_unlock without taking a lock\n");
4462                         return -EINVAL;
4463                 }
4464                 if (cur->active_spin_lock != reg->id) {
4465                         verbose(env, "bpf_spin_unlock of different lock\n");
4466                         return -EINVAL;
4467                 }
4468                 cur->active_spin_lock = 0;
4469         }
4470         return 0;
4471 }
4472
4473 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4474 {
4475         return type == ARG_PTR_TO_MEM ||
4476                type == ARG_PTR_TO_MEM_OR_NULL ||
4477                type == ARG_PTR_TO_UNINIT_MEM;
4478 }
4479
4480 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4481 {
4482         return type == ARG_CONST_SIZE ||
4483                type == ARG_CONST_SIZE_OR_ZERO;
4484 }
4485
4486 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4487 {
4488         return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4489 }
4490
4491 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4492 {
4493         return type == ARG_PTR_TO_INT ||
4494                type == ARG_PTR_TO_LONG;
4495 }
4496
4497 static int int_ptr_type_to_size(enum bpf_arg_type type)
4498 {
4499         if (type == ARG_PTR_TO_INT)
4500                 return sizeof(u32);
4501         else if (type == ARG_PTR_TO_LONG)
4502                 return sizeof(u64);
4503
4504         return -EINVAL;
4505 }
4506
4507 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4508                                  const struct bpf_call_arg_meta *meta,
4509                                  enum bpf_arg_type *arg_type)
4510 {
4511         if (!meta->map_ptr) {
4512                 /* kernel subsystem misconfigured verifier */
4513                 verbose(env, "invalid map_ptr to access map->type\n");
4514                 return -EACCES;
4515         }
4516
4517         switch (meta->map_ptr->map_type) {
4518         case BPF_MAP_TYPE_SOCKMAP:
4519         case BPF_MAP_TYPE_SOCKHASH:
4520                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4521                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4522                 } else {
4523                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
4524                         return -EINVAL;
4525                 }
4526                 break;
4527
4528         default:
4529                 break;
4530         }
4531         return 0;
4532 }
4533
4534 struct bpf_reg_types {
4535         const enum bpf_reg_type types[10];
4536         u32 *btf_id;
4537 };
4538
4539 static const struct bpf_reg_types map_key_value_types = {
4540         .types = {
4541                 PTR_TO_STACK,
4542                 PTR_TO_PACKET,
4543                 PTR_TO_PACKET_META,
4544                 PTR_TO_MAP_KEY,
4545                 PTR_TO_MAP_VALUE,
4546         },
4547 };
4548
4549 static const struct bpf_reg_types sock_types = {
4550         .types = {
4551                 PTR_TO_SOCK_COMMON,
4552                 PTR_TO_SOCKET,
4553                 PTR_TO_TCP_SOCK,
4554                 PTR_TO_XDP_SOCK,
4555         },
4556 };
4557
4558 #ifdef CONFIG_NET
4559 static const struct bpf_reg_types btf_id_sock_common_types = {
4560         .types = {
4561                 PTR_TO_SOCK_COMMON,
4562                 PTR_TO_SOCKET,
4563                 PTR_TO_TCP_SOCK,
4564                 PTR_TO_XDP_SOCK,
4565                 PTR_TO_BTF_ID,
4566         },
4567         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4568 };
4569 #endif
4570
4571 static const struct bpf_reg_types mem_types = {
4572         .types = {
4573                 PTR_TO_STACK,
4574                 PTR_TO_PACKET,
4575                 PTR_TO_PACKET_META,
4576                 PTR_TO_MAP_KEY,
4577                 PTR_TO_MAP_VALUE,
4578                 PTR_TO_MEM,
4579                 PTR_TO_RDONLY_BUF,
4580                 PTR_TO_RDWR_BUF,
4581         },
4582 };
4583
4584 static const struct bpf_reg_types int_ptr_types = {
4585         .types = {
4586                 PTR_TO_STACK,
4587                 PTR_TO_PACKET,
4588                 PTR_TO_PACKET_META,
4589                 PTR_TO_MAP_KEY,
4590                 PTR_TO_MAP_VALUE,
4591         },
4592 };
4593
4594 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4595 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4596 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4597 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4598 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4599 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4600 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4601 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4602 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4603 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
4604
4605 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4606         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
4607         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
4608         [ARG_PTR_TO_UNINIT_MAP_VALUE]   = &map_key_value_types,
4609         [ARG_PTR_TO_MAP_VALUE_OR_NULL]  = &map_key_value_types,
4610         [ARG_CONST_SIZE]                = &scalar_types,
4611         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
4612         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
4613         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
4614         [ARG_PTR_TO_CTX]                = &context_types,
4615         [ARG_PTR_TO_CTX_OR_NULL]        = &context_types,
4616         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
4617 #ifdef CONFIG_NET
4618         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4619 #endif
4620         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
4621         [ARG_PTR_TO_SOCKET_OR_NULL]     = &fullsock_types,
4622         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
4623         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
4624         [ARG_PTR_TO_MEM]                = &mem_types,
4625         [ARG_PTR_TO_MEM_OR_NULL]        = &mem_types,
4626         [ARG_PTR_TO_UNINIT_MEM]         = &mem_types,
4627         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
4628         [ARG_PTR_TO_ALLOC_MEM_OR_NULL]  = &alloc_mem_types,
4629         [ARG_PTR_TO_INT]                = &int_ptr_types,
4630         [ARG_PTR_TO_LONG]               = &int_ptr_types,
4631         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
4632         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
4633         [ARG_PTR_TO_STACK_OR_NULL]      = &stack_ptr_types,
4634 };
4635
4636 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4637                           enum bpf_arg_type arg_type,
4638                           const u32 *arg_btf_id)
4639 {
4640         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4641         enum bpf_reg_type expected, type = reg->type;
4642         const struct bpf_reg_types *compatible;
4643         int i, j;
4644
4645         compatible = compatible_reg_types[arg_type];
4646         if (!compatible) {
4647                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4648                 return -EFAULT;
4649         }
4650
4651         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4652                 expected = compatible->types[i];
4653                 if (expected == NOT_INIT)
4654                         break;
4655
4656                 if (type == expected)
4657                         goto found;
4658         }
4659
4660         verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4661         for (j = 0; j + 1 < i; j++)
4662                 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4663         verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4664         return -EACCES;
4665
4666 found:
4667         if (type == PTR_TO_BTF_ID) {
4668                 if (!arg_btf_id) {
4669                         if (!compatible->btf_id) {
4670                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4671                                 return -EFAULT;
4672                         }
4673                         arg_btf_id = compatible->btf_id;
4674                 }
4675
4676                 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4677                                           btf_vmlinux, *arg_btf_id)) {
4678                         verbose(env, "R%d is of type %s but %s is expected\n",
4679                                 regno, kernel_type_name(reg->btf, reg->btf_id),
4680                                 kernel_type_name(btf_vmlinux, *arg_btf_id));
4681                         return -EACCES;
4682                 }
4683
4684                 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4685                         verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4686                                 regno);
4687                         return -EACCES;
4688                 }
4689         }
4690
4691         return 0;
4692 }
4693
4694 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4695                           struct bpf_call_arg_meta *meta,
4696                           const struct bpf_func_proto *fn)
4697 {
4698         u32 regno = BPF_REG_1 + arg;
4699         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4700         enum bpf_arg_type arg_type = fn->arg_type[arg];
4701         enum bpf_reg_type type = reg->type;
4702         int err = 0;
4703
4704         if (arg_type == ARG_DONTCARE)
4705                 return 0;
4706
4707         err = check_reg_arg(env, regno, SRC_OP);
4708         if (err)
4709                 return err;
4710
4711         if (arg_type == ARG_ANYTHING) {
4712                 if (is_pointer_value(env, regno)) {
4713                         verbose(env, "R%d leaks addr into helper function\n",
4714                                 regno);
4715                         return -EACCES;
4716                 }
4717                 return 0;
4718         }
4719
4720         if (type_is_pkt_pointer(type) &&
4721             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4722                 verbose(env, "helper access to the packet is not allowed\n");
4723                 return -EACCES;
4724         }
4725
4726         if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4727             arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4728             arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4729                 err = resolve_map_arg_type(env, meta, &arg_type);
4730                 if (err)
4731                         return err;
4732         }
4733
4734         if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4735                 /* A NULL register has a SCALAR_VALUE type, so skip
4736                  * type checking.
4737                  */
4738                 goto skip_type_check;
4739
4740         err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4741         if (err)
4742                 return err;
4743
4744         if (type == PTR_TO_CTX) {
4745                 err = check_ctx_reg(env, reg, regno);
4746                 if (err < 0)
4747                         return err;
4748         }
4749
4750 skip_type_check:
4751         if (reg->ref_obj_id) {
4752                 if (meta->ref_obj_id) {
4753                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4754                                 regno, reg->ref_obj_id,
4755                                 meta->ref_obj_id);
4756                         return -EFAULT;
4757                 }
4758                 meta->ref_obj_id = reg->ref_obj_id;
4759         }
4760
4761         if (arg_type == ARG_CONST_MAP_PTR) {
4762                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4763                 meta->map_ptr = reg->map_ptr;
4764         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4765                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4766                  * check that [key, key + map->key_size) are within
4767                  * stack limits and initialized
4768                  */
4769                 if (!meta->map_ptr) {
4770                         /* in function declaration map_ptr must come before
4771                          * map_key, so that it's verified and known before
4772                          * we have to check map_key here. Otherwise it means
4773                          * that kernel subsystem misconfigured verifier
4774                          */
4775                         verbose(env, "invalid map_ptr to access map->key\n");
4776                         return -EACCES;
4777                 }
4778                 err = check_helper_mem_access(env, regno,
4779                                               meta->map_ptr->key_size, false,
4780                                               NULL);
4781         } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4782                    (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4783                     !register_is_null(reg)) ||
4784                    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4785                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4786                  * check [value, value + map->value_size) validity
4787                  */
4788                 if (!meta->map_ptr) {
4789                         /* kernel subsystem misconfigured verifier */
4790                         verbose(env, "invalid map_ptr to access map->value\n");
4791                         return -EACCES;
4792                 }
4793                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4794                 err = check_helper_mem_access(env, regno,
4795                                               meta->map_ptr->value_size, false,
4796                                               meta);
4797         } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4798                 if (!reg->btf_id) {
4799                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4800                         return -EACCES;
4801                 }
4802                 meta->ret_btf = reg->btf;
4803                 meta->ret_btf_id = reg->btf_id;
4804         } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4805                 if (meta->func_id == BPF_FUNC_spin_lock) {
4806                         if (process_spin_lock(env, regno, true))
4807                                 return -EACCES;
4808                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4809                         if (process_spin_lock(env, regno, false))
4810                                 return -EACCES;
4811                 } else {
4812                         verbose(env, "verifier internal error\n");
4813                         return -EFAULT;
4814                 }
4815         } else if (arg_type == ARG_PTR_TO_FUNC) {
4816                 meta->subprogno = reg->subprogno;
4817         } else if (arg_type_is_mem_ptr(arg_type)) {
4818                 /* The access to this pointer is only checked when we hit the
4819                  * next is_mem_size argument below.
4820                  */
4821                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4822         } else if (arg_type_is_mem_size(arg_type)) {
4823                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4824
4825                 /* This is used to refine r0 return value bounds for helpers
4826                  * that enforce this value as an upper bound on return values.
4827                  * See do_refine_retval_range() for helpers that can refine
4828                  * the return value. C type of helper is u32 so we pull register
4829                  * bound from umax_value however, if negative verifier errors
4830                  * out. Only upper bounds can be learned because retval is an
4831                  * int type and negative retvals are allowed.
4832                  */
4833                 meta->msize_max_value = reg->umax_value;
4834
4835                 /* The register is SCALAR_VALUE; the access check
4836                  * happens using its boundaries.
4837                  */
4838                 if (!tnum_is_const(reg->var_off))
4839                         /* For unprivileged variable accesses, disable raw
4840                          * mode so that the program is required to
4841                          * initialize all the memory that the helper could
4842                          * just partially fill up.
4843                          */
4844                         meta = NULL;
4845
4846                 if (reg->smin_value < 0) {
4847                         verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4848                                 regno);
4849                         return -EACCES;
4850                 }
4851
4852                 if (reg->umin_value == 0) {
4853                         err = check_helper_mem_access(env, regno - 1, 0,
4854                                                       zero_size_allowed,
4855                                                       meta);
4856                         if (err)
4857                                 return err;
4858                 }
4859
4860                 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4861                         verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4862                                 regno);
4863                         return -EACCES;
4864                 }
4865                 err = check_helper_mem_access(env, regno - 1,
4866                                               reg->umax_value,
4867                                               zero_size_allowed, meta);
4868                 if (!err)
4869                         err = mark_chain_precision(env, regno);
4870         } else if (arg_type_is_alloc_size(arg_type)) {
4871                 if (!tnum_is_const(reg->var_off)) {
4872                         verbose(env, "R%d is not a known constant'\n",
4873                                 regno);
4874                         return -EACCES;
4875                 }
4876                 meta->mem_size = reg->var_off.value;
4877         } else if (arg_type_is_int_ptr(arg_type)) {
4878                 int size = int_ptr_type_to_size(arg_type);
4879
4880                 err = check_helper_mem_access(env, regno, size, false, meta);
4881                 if (err)
4882                         return err;
4883                 err = check_ptr_alignment(env, reg, 0, size, true);
4884         }
4885
4886         return err;
4887 }
4888
4889 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4890 {
4891         enum bpf_attach_type eatype = env->prog->expected_attach_type;
4892         enum bpf_prog_type type = resolve_prog_type(env->prog);
4893
4894         if (func_id != BPF_FUNC_map_update_elem)
4895                 return false;
4896
4897         /* It's not possible to get access to a locked struct sock in these
4898          * contexts, so updating is safe.
4899          */
4900         switch (type) {
4901         case BPF_PROG_TYPE_TRACING:
4902                 if (eatype == BPF_TRACE_ITER)
4903                         return true;
4904                 break;
4905         case BPF_PROG_TYPE_SOCKET_FILTER:
4906         case BPF_PROG_TYPE_SCHED_CLS:
4907         case BPF_PROG_TYPE_SCHED_ACT:
4908         case BPF_PROG_TYPE_XDP:
4909         case BPF_PROG_TYPE_SK_REUSEPORT:
4910         case BPF_PROG_TYPE_FLOW_DISSECTOR:
4911         case BPF_PROG_TYPE_SK_LOOKUP:
4912                 return true;
4913         default:
4914                 break;
4915         }
4916
4917         verbose(env, "cannot update sockmap in this context\n");
4918         return false;
4919 }
4920
4921 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4922 {
4923         return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4924 }
4925
4926 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4927                                         struct bpf_map *map, int func_id)
4928 {
4929         if (!map)
4930                 return 0;
4931
4932         /* We need a two way check, first is from map perspective ... */
4933         switch (map->map_type) {
4934         case BPF_MAP_TYPE_PROG_ARRAY:
4935                 if (func_id != BPF_FUNC_tail_call)
4936                         goto error;
4937                 break;
4938         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4939                 if (func_id != BPF_FUNC_perf_event_read &&
4940                     func_id != BPF_FUNC_perf_event_output &&
4941                     func_id != BPF_FUNC_skb_output &&
4942                     func_id != BPF_FUNC_perf_event_read_value &&
4943                     func_id != BPF_FUNC_xdp_output)
4944                         goto error;
4945                 break;
4946         case BPF_MAP_TYPE_RINGBUF:
4947                 if (func_id != BPF_FUNC_ringbuf_output &&
4948                     func_id != BPF_FUNC_ringbuf_reserve &&
4949                     func_id != BPF_FUNC_ringbuf_submit &&
4950                     func_id != BPF_FUNC_ringbuf_discard &&
4951                     func_id != BPF_FUNC_ringbuf_query)
4952                         goto error;
4953                 break;
4954         case BPF_MAP_TYPE_STACK_TRACE:
4955                 if (func_id != BPF_FUNC_get_stackid)
4956                         goto error;
4957                 break;
4958         case BPF_MAP_TYPE_CGROUP_ARRAY:
4959                 if (func_id != BPF_FUNC_skb_under_cgroup &&
4960                     func_id != BPF_FUNC_current_task_under_cgroup)
4961                         goto error;
4962                 break;
4963         case BPF_MAP_TYPE_CGROUP_STORAGE:
4964         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4965                 if (func_id != BPF_FUNC_get_local_storage)
4966                         goto error;
4967                 break;
4968         case BPF_MAP_TYPE_DEVMAP:
4969         case BPF_MAP_TYPE_DEVMAP_HASH:
4970                 if (func_id != BPF_FUNC_redirect_map &&
4971                     func_id != BPF_FUNC_map_lookup_elem)
4972                         goto error;
4973                 break;
4974         /* Restrict bpf side of cpumap and xskmap, open when use-cases
4975          * appear.
4976          */
4977         case BPF_MAP_TYPE_CPUMAP:
4978                 if (func_id != BPF_FUNC_redirect_map)
4979                         goto error;
4980                 break;
4981         case BPF_MAP_TYPE_XSKMAP:
4982                 if (func_id != BPF_FUNC_redirect_map &&
4983                     func_id != BPF_FUNC_map_lookup_elem)
4984                         goto error;
4985                 break;
4986         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4987         case BPF_MAP_TYPE_HASH_OF_MAPS:
4988                 if (func_id != BPF_FUNC_map_lookup_elem)
4989                         goto error;
4990                 break;
4991         case BPF_MAP_TYPE_SOCKMAP:
4992                 if (func_id != BPF_FUNC_sk_redirect_map &&
4993                     func_id != BPF_FUNC_sock_map_update &&
4994                     func_id != BPF_FUNC_map_delete_elem &&
4995                     func_id != BPF_FUNC_msg_redirect_map &&
4996                     func_id != BPF_FUNC_sk_select_reuseport &&
4997                     func_id != BPF_FUNC_map_lookup_elem &&
4998                     !may_update_sockmap(env, func_id))
4999                         goto error;
5000                 break;
5001         case BPF_MAP_TYPE_SOCKHASH:
5002                 if (func_id != BPF_FUNC_sk_redirect_hash &&
5003                     func_id != BPF_FUNC_sock_hash_update &&
5004                     func_id != BPF_FUNC_map_delete_elem &&
5005                     func_id != BPF_FUNC_msg_redirect_hash &&
5006                     func_id != BPF_FUNC_sk_select_reuseport &&
5007                     func_id != BPF_FUNC_map_lookup_elem &&
5008                     !may_update_sockmap(env, func_id))
5009                         goto error;
5010                 break;
5011         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5012                 if (func_id != BPF_FUNC_sk_select_reuseport)
5013                         goto error;
5014                 break;
5015         case BPF_MAP_TYPE_QUEUE:
5016         case BPF_MAP_TYPE_STACK:
5017                 if (func_id != BPF_FUNC_map_peek_elem &&
5018                     func_id != BPF_FUNC_map_pop_elem &&
5019                     func_id != BPF_FUNC_map_push_elem)
5020                         goto error;
5021                 break;
5022         case BPF_MAP_TYPE_SK_STORAGE:
5023                 if (func_id != BPF_FUNC_sk_storage_get &&
5024                     func_id != BPF_FUNC_sk_storage_delete)
5025                         goto error;
5026                 break;
5027         case BPF_MAP_TYPE_INODE_STORAGE:
5028                 if (func_id != BPF_FUNC_inode_storage_get &&
5029                     func_id != BPF_FUNC_inode_storage_delete)
5030                         goto error;
5031                 break;
5032         case BPF_MAP_TYPE_TASK_STORAGE:
5033                 if (func_id != BPF_FUNC_task_storage_get &&
5034                     func_id != BPF_FUNC_task_storage_delete)
5035                         goto error;
5036                 break;
5037         default:
5038                 break;
5039         }
5040
5041         /* ... and second from the function itself. */
5042         switch (func_id) {
5043         case BPF_FUNC_tail_call:
5044                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5045                         goto error;
5046                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5047                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5048                         return -EINVAL;
5049                 }
5050                 break;
5051         case BPF_FUNC_perf_event_read:
5052         case BPF_FUNC_perf_event_output:
5053         case BPF_FUNC_perf_event_read_value:
5054         case BPF_FUNC_skb_output:
5055         case BPF_FUNC_xdp_output:
5056                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5057                         goto error;
5058                 break;
5059         case BPF_FUNC_get_stackid:
5060                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5061                         goto error;
5062                 break;
5063         case BPF_FUNC_current_task_under_cgroup:
5064         case BPF_FUNC_skb_under_cgroup:
5065                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5066                         goto error;
5067                 break;
5068         case BPF_FUNC_redirect_map:
5069                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5070                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5071                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
5072                     map->map_type != BPF_MAP_TYPE_XSKMAP)
5073                         goto error;
5074                 break;
5075         case BPF_FUNC_sk_redirect_map:
5076         case BPF_FUNC_msg_redirect_map:
5077         case BPF_FUNC_sock_map_update:
5078                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5079                         goto error;
5080                 break;
5081         case BPF_FUNC_sk_redirect_hash:
5082         case BPF_FUNC_msg_redirect_hash:
5083         case BPF_FUNC_sock_hash_update:
5084                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5085                         goto error;
5086                 break;
5087         case BPF_FUNC_get_local_storage:
5088                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5089                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5090                         goto error;
5091                 break;
5092         case BPF_FUNC_sk_select_reuseport:
5093                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5094                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5095                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
5096                         goto error;
5097                 break;
5098         case BPF_FUNC_map_peek_elem:
5099         case BPF_FUNC_map_pop_elem:
5100         case BPF_FUNC_map_push_elem:
5101                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5102                     map->map_type != BPF_MAP_TYPE_STACK)
5103                         goto error;
5104                 break;
5105         case BPF_FUNC_sk_storage_get:
5106         case BPF_FUNC_sk_storage_delete:
5107                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5108                         goto error;
5109                 break;
5110         case BPF_FUNC_inode_storage_get:
5111         case BPF_FUNC_inode_storage_delete:
5112                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5113                         goto error;
5114                 break;
5115         case BPF_FUNC_task_storage_get:
5116         case BPF_FUNC_task_storage_delete:
5117                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5118                         goto error;
5119                 break;
5120         default:
5121                 break;
5122         }
5123
5124         return 0;
5125 error:
5126         verbose(env, "cannot pass map_type %d into func %s#%d\n",
5127                 map->map_type, func_id_name(func_id), func_id);
5128         return -EINVAL;
5129 }
5130
5131 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5132 {
5133         int count = 0;
5134
5135         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5136                 count++;
5137         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5138                 count++;
5139         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5140                 count++;
5141         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5142                 count++;
5143         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5144                 count++;
5145
5146         /* We only support one arg being in raw mode at the moment,
5147          * which is sufficient for the helper functions we have
5148          * right now.
5149          */
5150         return count <= 1;
5151 }
5152
5153 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5154                                     enum bpf_arg_type arg_next)
5155 {
5156         return (arg_type_is_mem_ptr(arg_curr) &&
5157                 !arg_type_is_mem_size(arg_next)) ||
5158                (!arg_type_is_mem_ptr(arg_curr) &&
5159                 arg_type_is_mem_size(arg_next));
5160 }
5161
5162 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5163 {
5164         /* bpf_xxx(..., buf, len) call will access 'len'
5165          * bytes from memory 'buf'. Both arg types need
5166          * to be paired, so make sure there's no buggy
5167          * helper function specification.
5168          */
5169         if (arg_type_is_mem_size(fn->arg1_type) ||
5170             arg_type_is_mem_ptr(fn->arg5_type)  ||
5171             check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5172             check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5173             check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5174             check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5175                 return false;
5176
5177         return true;
5178 }
5179
5180 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5181 {
5182         int count = 0;
5183
5184         if (arg_type_may_be_refcounted(fn->arg1_type))
5185                 count++;
5186         if (arg_type_may_be_refcounted(fn->arg2_type))
5187                 count++;
5188         if (arg_type_may_be_refcounted(fn->arg3_type))
5189                 count++;
5190         if (arg_type_may_be_refcounted(fn->arg4_type))
5191                 count++;
5192         if (arg_type_may_be_refcounted(fn->arg5_type))
5193                 count++;
5194
5195         /* A reference acquiring function cannot acquire
5196          * another refcounted ptr.
5197          */
5198         if (may_be_acquire_function(func_id) && count)
5199                 return false;
5200
5201         /* We only support one arg being unreferenced at the moment,
5202          * which is sufficient for the helper functions we have right now.
5203          */
5204         return count <= 1;
5205 }
5206
5207 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5208 {
5209         int i;
5210
5211         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5212                 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5213                         return false;
5214
5215                 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5216                         return false;
5217         }
5218
5219         return true;
5220 }
5221
5222 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5223 {
5224         return check_raw_mode_ok(fn) &&
5225                check_arg_pair_ok(fn) &&
5226                check_btf_id_ok(fn) &&
5227                check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5228 }
5229
5230 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5231  * are now invalid, so turn them into unknown SCALAR_VALUE.
5232  */
5233 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5234                                      struct bpf_func_state *state)
5235 {
5236         struct bpf_reg_state *regs = state->regs, *reg;
5237         int i;
5238
5239         for (i = 0; i < MAX_BPF_REG; i++)
5240                 if (reg_is_pkt_pointer_any(&regs[i]))
5241                         mark_reg_unknown(env, regs, i);
5242
5243         bpf_for_each_spilled_reg(i, state, reg) {
5244                 if (!reg)
5245                         continue;
5246                 if (reg_is_pkt_pointer_any(reg))
5247                         __mark_reg_unknown(env, reg);
5248         }
5249 }
5250
5251 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5252 {
5253         struct bpf_verifier_state *vstate = env->cur_state;
5254         int i;
5255
5256         for (i = 0; i <= vstate->curframe; i++)
5257                 __clear_all_pkt_pointers(env, vstate->frame[i]);
5258 }
5259
5260 enum {
5261         AT_PKT_END = -1,
5262         BEYOND_PKT_END = -2,
5263 };
5264
5265 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5266 {
5267         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5268         struct bpf_reg_state *reg = &state->regs[regn];
5269
5270         if (reg->type != PTR_TO_PACKET)
5271                 /* PTR_TO_PACKET_META is not supported yet */
5272                 return;
5273
5274         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5275          * How far beyond pkt_end it goes is unknown.
5276          * if (!range_open) it's the case of pkt >= pkt_end
5277          * if (range_open) it's the case of pkt > pkt_end
5278          * hence this pointer is at least 1 byte bigger than pkt_end
5279          */
5280         if (range_open)
5281                 reg->range = BEYOND_PKT_END;
5282         else
5283                 reg->range = AT_PKT_END;
5284 }
5285
5286 static void release_reg_references(struct bpf_verifier_env *env,
5287                                    struct bpf_func_state *state,
5288                                    int ref_obj_id)
5289 {
5290         struct bpf_reg_state *regs = state->regs, *reg;
5291         int i;
5292
5293         for (i = 0; i < MAX_BPF_REG; i++)
5294                 if (regs[i].ref_obj_id == ref_obj_id)
5295                         mark_reg_unknown(env, regs, i);
5296
5297         bpf_for_each_spilled_reg(i, state, reg) {
5298                 if (!reg)
5299                         continue;
5300                 if (reg->ref_obj_id == ref_obj_id)
5301                         __mark_reg_unknown(env, reg);
5302         }
5303 }
5304
5305 /* The pointer with the specified id has released its reference to kernel
5306  * resources. Identify all copies of the same pointer and clear the reference.
5307  */
5308 static int release_reference(struct bpf_verifier_env *env,
5309                              int ref_obj_id)
5310 {
5311         struct bpf_verifier_state *vstate = env->cur_state;
5312         int err;
5313         int i;
5314
5315         err = release_reference_state(cur_func(env), ref_obj_id);
5316         if (err)
5317                 return err;
5318
5319         for (i = 0; i <= vstate->curframe; i++)
5320                 release_reg_references(env, vstate->frame[i], ref_obj_id);
5321
5322         return 0;
5323 }
5324
5325 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5326                                     struct bpf_reg_state *regs)
5327 {
5328         int i;
5329
5330         /* after the call registers r0 - r5 were scratched */
5331         for (i = 0; i < CALLER_SAVED_REGS; i++) {
5332                 mark_reg_not_init(env, regs, caller_saved[i]);
5333                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5334         }
5335 }
5336
5337 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5338                                    struct bpf_func_state *caller,
5339                                    struct bpf_func_state *callee,
5340                                    int insn_idx);
5341
5342 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5343                              int *insn_idx, int subprog,
5344                              set_callee_state_fn set_callee_state_cb)
5345 {
5346         struct bpf_verifier_state *state = env->cur_state;
5347         struct bpf_func_info_aux *func_info_aux;
5348         struct bpf_func_state *caller, *callee;
5349         int err;
5350         bool is_global = false;
5351
5352         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5353                 verbose(env, "the call stack of %d frames is too deep\n",
5354                         state->curframe + 2);
5355                 return -E2BIG;
5356         }
5357
5358         caller = state->frame[state->curframe];
5359         if (state->frame[state->curframe + 1]) {
5360                 verbose(env, "verifier bug. Frame %d already allocated\n",
5361                         state->curframe + 1);
5362                 return -EFAULT;
5363         }
5364
5365         func_info_aux = env->prog->aux->func_info_aux;
5366         if (func_info_aux)
5367                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5368         err = btf_check_func_arg_match(env, subprog, caller->regs);
5369         if (err == -EFAULT)
5370                 return err;
5371         if (is_global) {
5372                 if (err) {
5373                         verbose(env, "Caller passes invalid args into func#%d\n",
5374                                 subprog);
5375                         return err;
5376                 } else {
5377                         if (env->log.level & BPF_LOG_LEVEL)
5378                                 verbose(env,
5379                                         "Func#%d is global and valid. Skipping.\n",
5380                                         subprog);
5381                         clear_caller_saved_regs(env, caller->regs);
5382
5383                         /* All global functions return a 64-bit SCALAR_VALUE */
5384                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
5385                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5386
5387                         /* continue with next insn after call */
5388                         return 0;
5389                 }
5390         }
5391
5392         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5393         if (!callee)
5394                 return -ENOMEM;
5395         state->frame[state->curframe + 1] = callee;
5396
5397         /* callee cannot access r0, r6 - r9 for reading and has to write
5398          * into its own stack before reading from it.
5399          * callee can read/write into caller's stack
5400          */
5401         init_func_state(env, callee,
5402                         /* remember the callsite, it will be used by bpf_exit */
5403                         *insn_idx /* callsite */,
5404                         state->curframe + 1 /* frameno within this callchain */,
5405                         subprog /* subprog number within this prog */);
5406
5407         /* Transfer references to the callee */
5408         err = transfer_reference_state(callee, caller);
5409         if (err)
5410                 return err;
5411
5412         err = set_callee_state_cb(env, caller, callee, *insn_idx);
5413         if (err)
5414                 return err;
5415
5416         clear_caller_saved_regs(env, caller->regs);
5417
5418         /* only increment it after check_reg_arg() finished */
5419         state->curframe++;
5420
5421         /* and go analyze first insn of the callee */
5422         *insn_idx = env->subprog_info[subprog].start - 1;
5423
5424         if (env->log.level & BPF_LOG_LEVEL) {
5425                 verbose(env, "caller:\n");
5426                 print_verifier_state(env, caller);
5427                 verbose(env, "callee:\n");
5428                 print_verifier_state(env, callee);
5429         }
5430         return 0;
5431 }
5432
5433 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5434                                    struct bpf_func_state *caller,
5435                                    struct bpf_func_state *callee)
5436 {
5437         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5438          *      void *callback_ctx, u64 flags);
5439          * callback_fn(struct bpf_map *map, void *key, void *value,
5440          *      void *callback_ctx);
5441          */
5442         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5443
5444         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5445         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5446         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5447
5448         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5449         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5450         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5451
5452         /* pointer to stack or null */
5453         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5454
5455         /* unused */
5456         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5457         return 0;
5458 }
5459
5460 static int set_callee_state(struct bpf_verifier_env *env,
5461                             struct bpf_func_state *caller,
5462                             struct bpf_func_state *callee, int insn_idx)
5463 {
5464         int i;
5465
5466         /* copy r1 - r5 args that callee can access.  The copy includes parent
5467          * pointers, which connects us up to the liveness chain
5468          */
5469         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5470                 callee->regs[i] = caller->regs[i];
5471         return 0;
5472 }
5473
5474 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5475                            int *insn_idx)
5476 {
5477         int subprog, target_insn;
5478
5479         target_insn = *insn_idx + insn->imm + 1;
5480         subprog = find_subprog(env, target_insn);
5481         if (subprog < 0) {
5482                 verbose(env, "verifier bug. No program starts at insn %d\n",
5483                         target_insn);
5484                 return -EFAULT;
5485         }
5486
5487         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5488 }
5489
5490 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5491                                        struct bpf_func_state *caller,
5492                                        struct bpf_func_state *callee,
5493                                        int insn_idx)
5494 {
5495         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5496         struct bpf_map *map;
5497         int err;
5498
5499         if (bpf_map_ptr_poisoned(insn_aux)) {
5500                 verbose(env, "tail_call abusing map_ptr\n");
5501                 return -EINVAL;
5502         }
5503
5504         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5505         if (!map->ops->map_set_for_each_callback_args ||
5506             !map->ops->map_for_each_callback) {
5507                 verbose(env, "callback function not allowed for map\n");
5508                 return -ENOTSUPP;
5509         }
5510
5511         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5512         if (err)
5513                 return err;
5514
5515         callee->in_callback_fn = true;
5516         return 0;
5517 }
5518
5519 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5520 {
5521         struct bpf_verifier_state *state = env->cur_state;
5522         struct bpf_func_state *caller, *callee;
5523         struct bpf_reg_state *r0;
5524         int err;
5525
5526         callee = state->frame[state->curframe];
5527         r0 = &callee->regs[BPF_REG_0];
5528         if (r0->type == PTR_TO_STACK) {
5529                 /* technically it's ok to return caller's stack pointer
5530                  * (or caller's caller's pointer) back to the caller,
5531                  * since these pointers are valid. Only current stack
5532                  * pointer will be invalid as soon as function exits,
5533                  * but let's be conservative
5534                  */
5535                 verbose(env, "cannot return stack pointer to the caller\n");
5536                 return -EINVAL;
5537         }
5538
5539         state->curframe--;
5540         caller = state->frame[state->curframe];
5541         if (callee->in_callback_fn) {
5542                 /* enforce R0 return value range [0, 1]. */
5543                 struct tnum range = tnum_range(0, 1);
5544
5545                 if (r0->type != SCALAR_VALUE) {
5546                         verbose(env, "R0 not a scalar value\n");
5547                         return -EACCES;
5548                 }
5549                 if (!tnum_in(range, r0->var_off)) {
5550                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5551                         return -EINVAL;
5552                 }
5553         } else {
5554                 /* return to the caller whatever r0 had in the callee */
5555                 caller->regs[BPF_REG_0] = *r0;
5556         }
5557
5558         /* Transfer references to the caller */
5559         err = transfer_reference_state(caller, callee);
5560         if (err)
5561                 return err;
5562
5563         *insn_idx = callee->callsite + 1;
5564         if (env->log.level & BPF_LOG_LEVEL) {
5565                 verbose(env, "returning from callee:\n");
5566                 print_verifier_state(env, callee);
5567                 verbose(env, "to caller at %d:\n", *insn_idx);
5568                 print_verifier_state(env, caller);
5569         }
5570         /* clear everything in the callee */
5571         free_func_state(callee);
5572         state->frame[state->curframe + 1] = NULL;
5573         return 0;
5574 }
5575
5576 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5577                                    int func_id,
5578                                    struct bpf_call_arg_meta *meta)
5579 {
5580         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5581
5582         if (ret_type != RET_INTEGER ||
5583             (func_id != BPF_FUNC_get_stack &&
5584              func_id != BPF_FUNC_probe_read_str &&
5585              func_id != BPF_FUNC_probe_read_kernel_str &&
5586              func_id != BPF_FUNC_probe_read_user_str))
5587                 return;
5588
5589         ret_reg->smax_value = meta->msize_max_value;
5590         ret_reg->s32_max_value = meta->msize_max_value;
5591         ret_reg->smin_value = -MAX_ERRNO;
5592         ret_reg->s32_min_value = -MAX_ERRNO;
5593         __reg_deduce_bounds(ret_reg);
5594         __reg_bound_offset(ret_reg);
5595         __update_reg_bounds(ret_reg);
5596 }
5597
5598 static int
5599 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5600                 int func_id, int insn_idx)
5601 {
5602         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5603         struct bpf_map *map = meta->map_ptr;
5604
5605         if (func_id != BPF_FUNC_tail_call &&
5606             func_id != BPF_FUNC_map_lookup_elem &&
5607             func_id != BPF_FUNC_map_update_elem &&
5608             func_id != BPF_FUNC_map_delete_elem &&
5609             func_id != BPF_FUNC_map_push_elem &&
5610             func_id != BPF_FUNC_map_pop_elem &&
5611             func_id != BPF_FUNC_map_peek_elem &&
5612             func_id != BPF_FUNC_for_each_map_elem &&
5613             func_id != BPF_FUNC_redirect_map)
5614                 return 0;
5615
5616         if (map == NULL) {
5617                 verbose(env, "kernel subsystem misconfigured verifier\n");
5618                 return -EINVAL;
5619         }
5620
5621         /* In case of read-only, some additional restrictions
5622          * need to be applied in order to prevent altering the
5623          * state of the map from program side.
5624          */
5625         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5626             (func_id == BPF_FUNC_map_delete_elem ||
5627              func_id == BPF_FUNC_map_update_elem ||
5628              func_id == BPF_FUNC_map_push_elem ||
5629              func_id == BPF_FUNC_map_pop_elem)) {
5630                 verbose(env, "write into map forbidden\n");
5631                 return -EACCES;
5632         }
5633
5634         if (!BPF_MAP_PTR(aux->map_ptr_state))
5635                 bpf_map_ptr_store(aux, meta->map_ptr,
5636                                   !meta->map_ptr->bypass_spec_v1);
5637         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5638                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5639                                   !meta->map_ptr->bypass_spec_v1);
5640         return 0;
5641 }
5642
5643 static int
5644 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5645                 int func_id, int insn_idx)
5646 {
5647         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5648         struct bpf_reg_state *regs = cur_regs(env), *reg;
5649         struct bpf_map *map = meta->map_ptr;
5650         struct tnum range;
5651         u64 val;
5652         int err;
5653
5654         if (func_id != BPF_FUNC_tail_call)
5655                 return 0;
5656         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5657                 verbose(env, "kernel subsystem misconfigured verifier\n");
5658                 return -EINVAL;
5659         }
5660
5661         range = tnum_range(0, map->max_entries - 1);
5662         reg = &regs[BPF_REG_3];
5663
5664         if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5665                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5666                 return 0;
5667         }
5668
5669         err = mark_chain_precision(env, BPF_REG_3);
5670         if (err)
5671                 return err;
5672
5673         val = reg->var_off.value;
5674         if (bpf_map_key_unseen(aux))
5675                 bpf_map_key_store(aux, val);
5676         else if (!bpf_map_key_poisoned(aux) &&
5677                   bpf_map_key_immediate(aux) != val)
5678                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5679         return 0;
5680 }
5681
5682 static int check_reference_leak(struct bpf_verifier_env *env)
5683 {
5684         struct bpf_func_state *state = cur_func(env);
5685         int i;
5686
5687         for (i = 0; i < state->acquired_refs; i++) {
5688                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5689                         state->refs[i].id, state->refs[i].insn_idx);
5690         }
5691         return state->acquired_refs ? -EINVAL : 0;
5692 }
5693
5694 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5695                              int *insn_idx_p)
5696 {
5697         const struct bpf_func_proto *fn = NULL;
5698         struct bpf_reg_state *regs;
5699         struct bpf_call_arg_meta meta;
5700         int insn_idx = *insn_idx_p;
5701         bool changes_data;
5702         int i, err, func_id;
5703
5704         /* find function prototype */
5705         func_id = insn->imm;
5706         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5707                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5708                         func_id);
5709                 return -EINVAL;
5710         }
5711
5712         if (env->ops->get_func_proto)
5713                 fn = env->ops->get_func_proto(func_id, env->prog);
5714         if (!fn) {
5715                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5716                         func_id);
5717                 return -EINVAL;
5718         }
5719
5720         /* eBPF programs must be GPL compatible to use GPL-ed functions */
5721         if (!env->prog->gpl_compatible && fn->gpl_only) {
5722                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5723                 return -EINVAL;
5724         }
5725
5726         if (fn->allowed && !fn->allowed(env->prog)) {
5727                 verbose(env, "helper call is not allowed in probe\n");
5728                 return -EINVAL;
5729         }
5730
5731         /* With LD_ABS/IND some JITs save/restore skb from r1. */
5732         changes_data = bpf_helper_changes_pkt_data(fn->func);
5733         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5734                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5735                         func_id_name(func_id), func_id);
5736                 return -EINVAL;
5737         }
5738
5739         memset(&meta, 0, sizeof(meta));
5740         meta.pkt_access = fn->pkt_access;
5741
5742         err = check_func_proto(fn, func_id);
5743         if (err) {
5744                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5745                         func_id_name(func_id), func_id);
5746                 return err;
5747         }
5748
5749         meta.func_id = func_id;
5750         /* check args */
5751         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
5752                 err = check_func_arg(env, i, &meta, fn);
5753                 if (err)
5754                         return err;
5755         }
5756
5757         err = record_func_map(env, &meta, func_id, insn_idx);
5758         if (err)
5759                 return err;
5760
5761         err = record_func_key(env, &meta, func_id, insn_idx);
5762         if (err)
5763                 return err;
5764
5765         /* Mark slots with STACK_MISC in case of raw mode, stack offset
5766          * is inferred from register state.
5767          */
5768         for (i = 0; i < meta.access_size; i++) {
5769                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5770                                        BPF_WRITE, -1, false);
5771                 if (err)
5772                         return err;
5773         }
5774
5775         if (func_id == BPF_FUNC_tail_call) {
5776                 err = check_reference_leak(env);
5777                 if (err) {
5778                         verbose(env, "tail_call would lead to reference leak\n");
5779                         return err;
5780                 }
5781         } else if (is_release_function(func_id)) {
5782                 err = release_reference(env, meta.ref_obj_id);
5783                 if (err) {
5784                         verbose(env, "func %s#%d reference has not been acquired before\n",
5785                                 func_id_name(func_id), func_id);
5786                         return err;
5787                 }
5788         }
5789
5790         regs = cur_regs(env);
5791
5792         /* check that flags argument in get_local_storage(map, flags) is 0,
5793          * this is required because get_local_storage() can't return an error.
5794          */
5795         if (func_id == BPF_FUNC_get_local_storage &&
5796             !register_is_null(&regs[BPF_REG_2])) {
5797                 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5798                 return -EINVAL;
5799         }
5800
5801         if (func_id == BPF_FUNC_for_each_map_elem) {
5802                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
5803                                         set_map_elem_callback_state);
5804                 if (err < 0)
5805                         return -EINVAL;
5806         }
5807
5808         /* reset caller saved regs */
5809         for (i = 0; i < CALLER_SAVED_REGS; i++) {
5810                 mark_reg_not_init(env, regs, caller_saved[i]);
5811                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5812         }
5813
5814         /* helper call returns 64-bit value. */
5815         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5816
5817         /* update return register (already marked as written above) */
5818         if (fn->ret_type == RET_INTEGER) {
5819                 /* sets type to SCALAR_VALUE */
5820                 mark_reg_unknown(env, regs, BPF_REG_0);
5821         } else if (fn->ret_type == RET_VOID) {
5822                 regs[BPF_REG_0].type = NOT_INIT;
5823         } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5824                    fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5825                 /* There is no offset yet applied, variable or fixed */
5826                 mark_reg_known_zero(env, regs, BPF_REG_0);
5827                 /* remember map_ptr, so that check_map_access()
5828                  * can check 'value_size' boundary of memory access
5829                  * to map element returned from bpf_map_lookup_elem()
5830                  */
5831                 if (meta.map_ptr == NULL) {
5832                         verbose(env,
5833                                 "kernel subsystem misconfigured verifier\n");
5834                         return -EINVAL;
5835                 }
5836                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
5837                 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5838                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
5839                         if (map_value_has_spin_lock(meta.map_ptr))
5840                                 regs[BPF_REG_0].id = ++env->id_gen;
5841                 } else {
5842                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5843                 }
5844         } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5845                 mark_reg_known_zero(env, regs, BPF_REG_0);
5846                 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
5847         } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5848                 mark_reg_known_zero(env, regs, BPF_REG_0);
5849                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5850         } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5851                 mark_reg_known_zero(env, regs, BPF_REG_0);
5852                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5853         } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5854                 mark_reg_known_zero(env, regs, BPF_REG_0);
5855                 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5856                 regs[BPF_REG_0].mem_size = meta.mem_size;
5857         } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5858                    fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
5859                 const struct btf_type *t;
5860
5861                 mark_reg_known_zero(env, regs, BPF_REG_0);
5862                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
5863                 if (!btf_type_is_struct(t)) {
5864                         u32 tsize;
5865                         const struct btf_type *ret;
5866                         const char *tname;
5867
5868                         /* resolve the type size of ksym. */
5869                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
5870                         if (IS_ERR(ret)) {
5871                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
5872                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5873                                         tname, PTR_ERR(ret));
5874                                 return -EINVAL;
5875                         }
5876                         regs[BPF_REG_0].type =
5877                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5878                                 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
5879                         regs[BPF_REG_0].mem_size = tsize;
5880                 } else {
5881                         regs[BPF_REG_0].type =
5882                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5883                                 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
5884                         regs[BPF_REG_0].btf = meta.ret_btf;
5885                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5886                 }
5887         } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5888                    fn->ret_type == RET_PTR_TO_BTF_ID) {
5889                 int ret_btf_id;
5890
5891                 mark_reg_known_zero(env, regs, BPF_REG_0);
5892                 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5893                                                      PTR_TO_BTF_ID :
5894                                                      PTR_TO_BTF_ID_OR_NULL;
5895                 ret_btf_id = *fn->ret_btf_id;
5896                 if (ret_btf_id == 0) {
5897                         verbose(env, "invalid return type %d of func %s#%d\n",
5898                                 fn->ret_type, func_id_name(func_id), func_id);
5899                         return -EINVAL;
5900                 }
5901                 /* current BPF helper definitions are only coming from
5902                  * built-in code with type IDs from  vmlinux BTF
5903                  */
5904                 regs[BPF_REG_0].btf = btf_vmlinux;
5905                 regs[BPF_REG_0].btf_id = ret_btf_id;
5906         } else {
5907                 verbose(env, "unknown return type %d of func %s#%d\n",
5908                         fn->ret_type, func_id_name(func_id), func_id);
5909                 return -EINVAL;
5910         }
5911
5912         if (reg_type_may_be_null(regs[BPF_REG_0].type))
5913                 regs[BPF_REG_0].id = ++env->id_gen;
5914
5915         if (is_ptr_cast_function(func_id)) {
5916                 /* For release_reference() */
5917                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5918         } else if (is_acquire_function(func_id, meta.map_ptr)) {
5919                 int id = acquire_reference_state(env, insn_idx);
5920
5921                 if (id < 0)
5922                         return id;
5923                 /* For mark_ptr_or_null_reg() */
5924                 regs[BPF_REG_0].id = id;
5925                 /* For release_reference() */
5926                 regs[BPF_REG_0].ref_obj_id = id;
5927         }
5928
5929         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5930
5931         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5932         if (err)
5933                 return err;
5934
5935         if ((func_id == BPF_FUNC_get_stack ||
5936              func_id == BPF_FUNC_get_task_stack) &&
5937             !env->prog->has_callchain_buf) {
5938                 const char *err_str;
5939
5940 #ifdef CONFIG_PERF_EVENTS
5941                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5942                 err_str = "cannot get callchain buffer for func %s#%d\n";
5943 #else
5944                 err = -ENOTSUPP;
5945                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5946 #endif
5947                 if (err) {
5948                         verbose(env, err_str, func_id_name(func_id), func_id);
5949                         return err;
5950                 }
5951
5952                 env->prog->has_callchain_buf = true;
5953         }
5954
5955         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5956                 env->prog->call_get_stack = true;
5957
5958         if (changes_data)
5959                 clear_all_pkt_pointers(env);
5960         return 0;
5961 }
5962
5963 static bool signed_add_overflows(s64 a, s64 b)
5964 {
5965         /* Do the add in u64, where overflow is well-defined */
5966         s64 res = (s64)((u64)a + (u64)b);
5967
5968         if (b < 0)
5969                 return res > a;
5970         return res < a;
5971 }
5972
5973 static bool signed_add32_overflows(s32 a, s32 b)
5974 {
5975         /* Do the add in u32, where overflow is well-defined */
5976         s32 res = (s32)((u32)a + (u32)b);
5977
5978         if (b < 0)
5979                 return res > a;
5980         return res < a;
5981 }
5982
5983 static bool signed_sub_overflows(s64 a, s64 b)
5984 {
5985         /* Do the sub in u64, where overflow is well-defined */
5986         s64 res = (s64)((u64)a - (u64)b);
5987
5988         if (b < 0)
5989                 return res < a;
5990         return res > a;
5991 }
5992
5993 static bool signed_sub32_overflows(s32 a, s32 b)
5994 {
5995         /* Do the sub in u32, where overflow is well-defined */
5996         s32 res = (s32)((u32)a - (u32)b);
5997
5998         if (b < 0)
5999                 return res < a;
6000         return res > a;
6001 }
6002
6003 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6004                                   const struct bpf_reg_state *reg,
6005                                   enum bpf_reg_type type)
6006 {
6007         bool known = tnum_is_const(reg->var_off);
6008         s64 val = reg->var_off.value;
6009         s64 smin = reg->smin_value;
6010
6011         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6012                 verbose(env, "math between %s pointer and %lld is not allowed\n",
6013                         reg_type_str[type], val);
6014                 return false;
6015         }
6016
6017         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6018                 verbose(env, "%s pointer offset %d is not allowed\n",
6019                         reg_type_str[type], reg->off);
6020                 return false;
6021         }
6022
6023         if (smin == S64_MIN) {
6024                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6025                         reg_type_str[type]);
6026                 return false;
6027         }
6028
6029         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6030                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6031                         smin, reg_type_str[type]);
6032                 return false;
6033         }
6034
6035         return true;
6036 }
6037
6038 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6039 {
6040         return &env->insn_aux_data[env->insn_idx];
6041 }
6042
6043 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6044                               u32 *ptr_limit, u8 opcode, bool off_is_neg)
6045 {
6046         bool mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6047                             (opcode == BPF_SUB && !off_is_neg);
6048         u32 off;
6049
6050         switch (ptr_reg->type) {
6051         case PTR_TO_STACK:
6052                 /* Indirect variable offset stack access is prohibited in
6053                  * unprivileged mode so it's not handled here.
6054                  */
6055                 off = ptr_reg->off + ptr_reg->var_off.value;
6056                 if (mask_to_left)
6057                         *ptr_limit = MAX_BPF_STACK + off;
6058                 else
6059                         *ptr_limit = -off;
6060                 return 0;
6061         case PTR_TO_MAP_KEY:
6062                 /* Currently, this code is not exercised as the only use
6063                  * is bpf_for_each_map_elem() helper which requires
6064                  * bpf_capble. The code has been tested manually for
6065                  * future use.
6066                  */
6067                 if (mask_to_left) {
6068                         *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
6069                 } else {
6070                         off = ptr_reg->smin_value + ptr_reg->off;
6071                         *ptr_limit = ptr_reg->map_ptr->key_size - off;
6072                 }
6073                 return 0;
6074         case PTR_TO_MAP_VALUE:
6075                 if (mask_to_left) {
6076                         *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
6077                 } else {
6078                         off = ptr_reg->smin_value + ptr_reg->off;
6079                         *ptr_limit = ptr_reg->map_ptr->value_size - off;
6080                 }
6081                 return 0;
6082         default:
6083                 return -EINVAL;
6084         }
6085 }
6086
6087 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6088                                     const struct bpf_insn *insn)
6089 {
6090         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6091 }
6092
6093 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6094                                        u32 alu_state, u32 alu_limit)
6095 {
6096         /* If we arrived here from different branches with different
6097          * state or limits to sanitize, then this won't work.
6098          */
6099         if (aux->alu_state &&
6100             (aux->alu_state != alu_state ||
6101              aux->alu_limit != alu_limit))
6102                 return -EACCES;
6103
6104         /* Corresponding fixup done in do_misc_fixups(). */
6105         aux->alu_state = alu_state;
6106         aux->alu_limit = alu_limit;
6107         return 0;
6108 }
6109
6110 static int sanitize_val_alu(struct bpf_verifier_env *env,
6111                             struct bpf_insn *insn)
6112 {
6113         struct bpf_insn_aux_data *aux = cur_aux(env);
6114
6115         if (can_skip_alu_sanitation(env, insn))
6116                 return 0;
6117
6118         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6119 }
6120
6121 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6122                             struct bpf_insn *insn,
6123                             const struct bpf_reg_state *ptr_reg,
6124                             struct bpf_reg_state *dst_reg,
6125                             bool off_is_neg)
6126 {
6127         struct bpf_verifier_state *vstate = env->cur_state;
6128         struct bpf_insn_aux_data *aux = cur_aux(env);
6129         bool ptr_is_dst_reg = ptr_reg == dst_reg;
6130         u8 opcode = BPF_OP(insn->code);
6131         u32 alu_state, alu_limit;
6132         struct bpf_reg_state tmp;
6133         bool ret;
6134
6135         if (can_skip_alu_sanitation(env, insn))
6136                 return 0;
6137
6138         /* We already marked aux for masking from non-speculative
6139          * paths, thus we got here in the first place. We only care
6140          * to explore bad access from here.
6141          */
6142         if (vstate->speculative)
6143                 goto do_sim;
6144
6145         alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6146         alu_state |= ptr_is_dst_reg ?
6147                      BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6148
6149         if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
6150                 return 0;
6151         if (update_alu_sanitation_state(aux, alu_state, alu_limit))
6152                 return -EACCES;
6153 do_sim:
6154         /* Simulate and find potential out-of-bounds access under
6155          * speculative execution from truncation as a result of
6156          * masking when off was not within expected range. If off
6157          * sits in dst, then we temporarily need to move ptr there
6158          * to simulate dst (== 0) +/-= ptr. Needed, for example,
6159          * for cases where we use K-based arithmetic in one direction
6160          * and truncated reg-based in the other in order to explore
6161          * bad access.
6162          */
6163         if (!ptr_is_dst_reg) {
6164                 tmp = *dst_reg;
6165                 *dst_reg = *ptr_reg;
6166         }
6167         ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
6168         if (!ptr_is_dst_reg && ret)
6169                 *dst_reg = tmp;
6170         return !ret ? -EFAULT : 0;
6171 }
6172
6173 /* check that stack access falls within stack limits and that 'reg' doesn't
6174  * have a variable offset.
6175  *
6176  * Variable offset is prohibited for unprivileged mode for simplicity since it
6177  * requires corresponding support in Spectre masking for stack ALU.  See also
6178  * retrieve_ptr_limit().
6179  *
6180  *
6181  * 'off' includes 'reg->off'.
6182  */
6183 static int check_stack_access_for_ptr_arithmetic(
6184                                 struct bpf_verifier_env *env,
6185                                 int regno,
6186                                 const struct bpf_reg_state *reg,
6187                                 int off)
6188 {
6189         if (!tnum_is_const(reg->var_off)) {
6190                 char tn_buf[48];
6191
6192                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6193                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6194                         regno, tn_buf, off);
6195                 return -EACCES;
6196         }
6197
6198         if (off >= 0 || off < -MAX_BPF_STACK) {
6199                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6200                         "prohibited for !root; off=%d\n", regno, off);
6201                 return -EACCES;
6202         }
6203
6204         return 0;
6205 }
6206
6207
6208 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6209  * Caller should also handle BPF_MOV case separately.
6210  * If we return -EACCES, caller may want to try again treating pointer as a
6211  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6212  */
6213 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6214                                    struct bpf_insn *insn,
6215                                    const struct bpf_reg_state *ptr_reg,
6216                                    const struct bpf_reg_state *off_reg)
6217 {
6218         struct bpf_verifier_state *vstate = env->cur_state;
6219         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6220         struct bpf_reg_state *regs = state->regs, *dst_reg;
6221         bool known = tnum_is_const(off_reg->var_off);
6222         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6223             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6224         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6225             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6226         u32 dst = insn->dst_reg, src = insn->src_reg;
6227         u8 opcode = BPF_OP(insn->code);
6228         int ret;
6229
6230         dst_reg = &regs[dst];
6231
6232         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6233             smin_val > smax_val || umin_val > umax_val) {
6234                 /* Taint dst register if offset had invalid bounds derived from
6235                  * e.g. dead branches.
6236                  */
6237                 __mark_reg_unknown(env, dst_reg);
6238                 return 0;
6239         }
6240
6241         if (BPF_CLASS(insn->code) != BPF_ALU64) {
6242                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6243                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6244                         __mark_reg_unknown(env, dst_reg);
6245                         return 0;
6246                 }
6247
6248                 verbose(env,
6249                         "R%d 32-bit pointer arithmetic prohibited\n",
6250                         dst);
6251                 return -EACCES;
6252         }
6253
6254         switch (ptr_reg->type) {
6255         case PTR_TO_MAP_VALUE_OR_NULL:
6256                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6257                         dst, reg_type_str[ptr_reg->type]);
6258                 return -EACCES;
6259         case CONST_PTR_TO_MAP:
6260                 /* smin_val represents the known value */
6261                 if (known && smin_val == 0 && opcode == BPF_ADD)
6262                         break;
6263                 fallthrough;
6264         case PTR_TO_PACKET_END:
6265         case PTR_TO_SOCKET:
6266         case PTR_TO_SOCKET_OR_NULL:
6267         case PTR_TO_SOCK_COMMON:
6268         case PTR_TO_SOCK_COMMON_OR_NULL:
6269         case PTR_TO_TCP_SOCK:
6270         case PTR_TO_TCP_SOCK_OR_NULL:
6271         case PTR_TO_XDP_SOCK:
6272                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6273                         dst, reg_type_str[ptr_reg->type]);
6274                 return -EACCES;
6275         case PTR_TO_MAP_KEY:
6276         case PTR_TO_MAP_VALUE:
6277                 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
6278                         verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
6279                                 off_reg == dst_reg ? dst : src);
6280                         return -EACCES;
6281                 }
6282                 fallthrough;
6283         default:
6284                 break;
6285         }
6286
6287         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6288          * The id may be overwritten later if we create a new variable offset.
6289          */
6290         dst_reg->type = ptr_reg->type;
6291         dst_reg->id = ptr_reg->id;
6292
6293         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6294             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6295                 return -EINVAL;
6296
6297         /* pointer types do not carry 32-bit bounds at the moment. */
6298         __mark_reg32_unbounded(dst_reg);
6299
6300         switch (opcode) {
6301         case BPF_ADD:
6302                 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6303                 if (ret < 0) {
6304                         verbose(env, "R%d tried to add from different maps or paths\n", dst);
6305                         return ret;
6306                 }
6307                 /* We can take a fixed offset as long as it doesn't overflow
6308                  * the s32 'off' field
6309                  */
6310                 if (known && (ptr_reg->off + smin_val ==
6311                               (s64)(s32)(ptr_reg->off + smin_val))) {
6312                         /* pointer += K.  Accumulate it into fixed offset */
6313                         dst_reg->smin_value = smin_ptr;
6314                         dst_reg->smax_value = smax_ptr;
6315                         dst_reg->umin_value = umin_ptr;
6316                         dst_reg->umax_value = umax_ptr;
6317                         dst_reg->var_off = ptr_reg->var_off;
6318                         dst_reg->off = ptr_reg->off + smin_val;
6319                         dst_reg->raw = ptr_reg->raw;
6320                         break;
6321                 }
6322                 /* A new variable offset is created.  Note that off_reg->off
6323                  * == 0, since it's a scalar.
6324                  * dst_reg gets the pointer type and since some positive
6325                  * integer value was added to the pointer, give it a new 'id'
6326                  * if it's a PTR_TO_PACKET.
6327                  * this creates a new 'base' pointer, off_reg (variable) gets
6328                  * added into the variable offset, and we copy the fixed offset
6329                  * from ptr_reg.
6330                  */
6331                 if (signed_add_overflows(smin_ptr, smin_val) ||
6332                     signed_add_overflows(smax_ptr, smax_val)) {
6333                         dst_reg->smin_value = S64_MIN;
6334                         dst_reg->smax_value = S64_MAX;
6335                 } else {
6336                         dst_reg->smin_value = smin_ptr + smin_val;
6337                         dst_reg->smax_value = smax_ptr + smax_val;
6338                 }
6339                 if (umin_ptr + umin_val < umin_ptr ||
6340                     umax_ptr + umax_val < umax_ptr) {
6341                         dst_reg->umin_value = 0;
6342                         dst_reg->umax_value = U64_MAX;
6343                 } else {
6344                         dst_reg->umin_value = umin_ptr + umin_val;
6345                         dst_reg->umax_value = umax_ptr + umax_val;
6346                 }
6347                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6348                 dst_reg->off = ptr_reg->off;
6349                 dst_reg->raw = ptr_reg->raw;
6350                 if (reg_is_pkt_pointer(ptr_reg)) {
6351                         dst_reg->id = ++env->id_gen;
6352                         /* something was added to pkt_ptr, set range to zero */
6353                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6354                 }
6355                 break;
6356         case BPF_SUB:
6357                 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6358                 if (ret < 0) {
6359                         verbose(env, "R%d tried to sub from different maps or paths\n", dst);
6360                         return ret;
6361                 }
6362                 if (dst_reg == off_reg) {
6363                         /* scalar -= pointer.  Creates an unknown scalar */
6364                         verbose(env, "R%d tried to subtract pointer from scalar\n",
6365                                 dst);
6366                         return -EACCES;
6367                 }
6368                 /* We don't allow subtraction from FP, because (according to
6369                  * test_verifier.c test "invalid fp arithmetic", JITs might not
6370                  * be able to deal with it.
6371                  */
6372                 if (ptr_reg->type == PTR_TO_STACK) {
6373                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
6374                                 dst);
6375                         return -EACCES;
6376                 }
6377                 if (known && (ptr_reg->off - smin_val ==
6378                               (s64)(s32)(ptr_reg->off - smin_val))) {
6379                         /* pointer -= K.  Subtract it from fixed offset */
6380                         dst_reg->smin_value = smin_ptr;
6381                         dst_reg->smax_value = smax_ptr;
6382                         dst_reg->umin_value = umin_ptr;
6383                         dst_reg->umax_value = umax_ptr;
6384                         dst_reg->var_off = ptr_reg->var_off;
6385                         dst_reg->id = ptr_reg->id;
6386                         dst_reg->off = ptr_reg->off - smin_val;
6387                         dst_reg->raw = ptr_reg->raw;
6388                         break;
6389                 }
6390                 /* A new variable offset is created.  If the subtrahend is known
6391                  * nonnegative, then any reg->range we had before is still good.
6392                  */
6393                 if (signed_sub_overflows(smin_ptr, smax_val) ||
6394                     signed_sub_overflows(smax_ptr, smin_val)) {
6395                         /* Overflow possible, we know nothing */
6396                         dst_reg->smin_value = S64_MIN;
6397                         dst_reg->smax_value = S64_MAX;
6398                 } else {
6399                         dst_reg->smin_value = smin_ptr - smax_val;
6400                         dst_reg->smax_value = smax_ptr - smin_val;
6401                 }
6402                 if (umin_ptr < umax_val) {
6403                         /* Overflow possible, we know nothing */
6404                         dst_reg->umin_value = 0;
6405                         dst_reg->umax_value = U64_MAX;
6406                 } else {
6407                         /* Cannot overflow (as long as bounds are consistent) */
6408                         dst_reg->umin_value = umin_ptr - umax_val;
6409                         dst_reg->umax_value = umax_ptr - umin_val;
6410                 }
6411                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6412                 dst_reg->off = ptr_reg->off;
6413                 dst_reg->raw = ptr_reg->raw;
6414                 if (reg_is_pkt_pointer(ptr_reg)) {
6415                         dst_reg->id = ++env->id_gen;
6416                         /* something was added to pkt_ptr, set range to zero */
6417                         if (smin_val < 0)
6418                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6419                 }
6420                 break;
6421         case BPF_AND:
6422         case BPF_OR:
6423         case BPF_XOR:
6424                 /* bitwise ops on pointers are troublesome, prohibit. */
6425                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6426                         dst, bpf_alu_string[opcode >> 4]);
6427                 return -EACCES;
6428         default:
6429                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6430                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6431                         dst, bpf_alu_string[opcode >> 4]);
6432                 return -EACCES;
6433         }
6434
6435         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6436                 return -EINVAL;
6437
6438         __update_reg_bounds(dst_reg);
6439         __reg_deduce_bounds(dst_reg);
6440         __reg_bound_offset(dst_reg);
6441
6442         /* For unprivileged we require that resulting offset must be in bounds
6443          * in order to be able to sanitize access later on.
6444          */
6445         if (!env->bypass_spec_v1) {
6446                 if (dst_reg->type == PTR_TO_MAP_VALUE &&
6447                     check_map_access(env, dst, dst_reg->off, 1, false)) {
6448                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6449                                 "prohibited for !root\n", dst);
6450                         return -EACCES;
6451                 } else if (dst_reg->type == PTR_TO_STACK &&
6452                            check_stack_access_for_ptr_arithmetic(
6453                                    env, dst, dst_reg, dst_reg->off +
6454                                    dst_reg->var_off.value)) {
6455                         return -EACCES;
6456                 }
6457         }
6458
6459         return 0;
6460 }
6461
6462 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6463                                  struct bpf_reg_state *src_reg)
6464 {
6465         s32 smin_val = src_reg->s32_min_value;
6466         s32 smax_val = src_reg->s32_max_value;
6467         u32 umin_val = src_reg->u32_min_value;
6468         u32 umax_val = src_reg->u32_max_value;
6469
6470         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6471             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6472                 dst_reg->s32_min_value = S32_MIN;
6473                 dst_reg->s32_max_value = S32_MAX;
6474         } else {
6475                 dst_reg->s32_min_value += smin_val;
6476                 dst_reg->s32_max_value += smax_val;
6477         }
6478         if (dst_reg->u32_min_value + umin_val < umin_val ||
6479             dst_reg->u32_max_value + umax_val < umax_val) {
6480                 dst_reg->u32_min_value = 0;
6481                 dst_reg->u32_max_value = U32_MAX;
6482         } else {
6483                 dst_reg->u32_min_value += umin_val;
6484                 dst_reg->u32_max_value += umax_val;
6485         }
6486 }
6487
6488 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6489                                struct bpf_reg_state *src_reg)
6490 {
6491         s64 smin_val = src_reg->smin_value;
6492         s64 smax_val = src_reg->smax_value;
6493         u64 umin_val = src_reg->umin_value;
6494         u64 umax_val = src_reg->umax_value;
6495
6496         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6497             signed_add_overflows(dst_reg->smax_value, smax_val)) {
6498                 dst_reg->smin_value = S64_MIN;
6499                 dst_reg->smax_value = S64_MAX;
6500         } else {
6501                 dst_reg->smin_value += smin_val;
6502                 dst_reg->smax_value += smax_val;
6503         }
6504         if (dst_reg->umin_value + umin_val < umin_val ||
6505             dst_reg->umax_value + umax_val < umax_val) {
6506                 dst_reg->umin_value = 0;
6507                 dst_reg->umax_value = U64_MAX;
6508         } else {
6509                 dst_reg->umin_value += umin_val;
6510                 dst_reg->umax_value += umax_val;
6511         }
6512 }
6513
6514 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6515                                  struct bpf_reg_state *src_reg)
6516 {
6517         s32 smin_val = src_reg->s32_min_value;
6518         s32 smax_val = src_reg->s32_max_value;
6519         u32 umin_val = src_reg->u32_min_value;
6520         u32 umax_val = src_reg->u32_max_value;
6521
6522         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6523             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6524                 /* Overflow possible, we know nothing */
6525                 dst_reg->s32_min_value = S32_MIN;
6526                 dst_reg->s32_max_value = S32_MAX;
6527         } else {
6528                 dst_reg->s32_min_value -= smax_val;
6529                 dst_reg->s32_max_value -= smin_val;
6530         }
6531         if (dst_reg->u32_min_value < umax_val) {
6532                 /* Overflow possible, we know nothing */
6533                 dst_reg->u32_min_value = 0;
6534                 dst_reg->u32_max_value = U32_MAX;
6535         } else {
6536                 /* Cannot overflow (as long as bounds are consistent) */
6537                 dst_reg->u32_min_value -= umax_val;
6538                 dst_reg->u32_max_value -= umin_val;
6539         }
6540 }
6541
6542 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6543                                struct bpf_reg_state *src_reg)
6544 {
6545         s64 smin_val = src_reg->smin_value;
6546         s64 smax_val = src_reg->smax_value;
6547         u64 umin_val = src_reg->umin_value;
6548         u64 umax_val = src_reg->umax_value;
6549
6550         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6551             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6552                 /* Overflow possible, we know nothing */
6553                 dst_reg->smin_value = S64_MIN;
6554                 dst_reg->smax_value = S64_MAX;
6555         } else {
6556                 dst_reg->smin_value -= smax_val;
6557                 dst_reg->smax_value -= smin_val;
6558         }
6559         if (dst_reg->umin_value < umax_val) {
6560                 /* Overflow possible, we know nothing */
6561                 dst_reg->umin_value = 0;
6562                 dst_reg->umax_value = U64_MAX;
6563         } else {
6564                 /* Cannot overflow (as long as bounds are consistent) */
6565                 dst_reg->umin_value -= umax_val;
6566                 dst_reg->umax_value -= umin_val;
6567         }
6568 }
6569
6570 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6571                                  struct bpf_reg_state *src_reg)
6572 {
6573         s32 smin_val = src_reg->s32_min_value;
6574         u32 umin_val = src_reg->u32_min_value;
6575         u32 umax_val = src_reg->u32_max_value;
6576
6577         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6578                 /* Ain't nobody got time to multiply that sign */
6579                 __mark_reg32_unbounded(dst_reg);
6580                 return;
6581         }
6582         /* Both values are positive, so we can work with unsigned and
6583          * copy the result to signed (unless it exceeds S32_MAX).
6584          */
6585         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6586                 /* Potential overflow, we know nothing */
6587                 __mark_reg32_unbounded(dst_reg);
6588                 return;
6589         }
6590         dst_reg->u32_min_value *= umin_val;
6591         dst_reg->u32_max_value *= umax_val;
6592         if (dst_reg->u32_max_value > S32_MAX) {
6593                 /* Overflow possible, we know nothing */
6594                 dst_reg->s32_min_value = S32_MIN;
6595                 dst_reg->s32_max_value = S32_MAX;
6596         } else {
6597                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6598                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6599         }
6600 }
6601
6602 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6603                                struct bpf_reg_state *src_reg)
6604 {
6605         s64 smin_val = src_reg->smin_value;
6606         u64 umin_val = src_reg->umin_value;
6607         u64 umax_val = src_reg->umax_value;
6608
6609         if (smin_val < 0 || dst_reg->smin_value < 0) {
6610                 /* Ain't nobody got time to multiply that sign */
6611                 __mark_reg64_unbounded(dst_reg);
6612                 return;
6613         }
6614         /* Both values are positive, so we can work with unsigned and
6615          * copy the result to signed (unless it exceeds S64_MAX).
6616          */
6617         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6618                 /* Potential overflow, we know nothing */
6619                 __mark_reg64_unbounded(dst_reg);
6620                 return;
6621         }
6622         dst_reg->umin_value *= umin_val;
6623         dst_reg->umax_value *= umax_val;
6624         if (dst_reg->umax_value > S64_MAX) {
6625                 /* Overflow possible, we know nothing */
6626                 dst_reg->smin_value = S64_MIN;
6627                 dst_reg->smax_value = S64_MAX;
6628         } else {
6629                 dst_reg->smin_value = dst_reg->umin_value;
6630                 dst_reg->smax_value = dst_reg->umax_value;
6631         }
6632 }
6633
6634 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6635                                  struct bpf_reg_state *src_reg)
6636 {
6637         bool src_known = tnum_subreg_is_const(src_reg->var_off);
6638         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6639         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6640         s32 smin_val = src_reg->s32_min_value;
6641         u32 umax_val = src_reg->u32_max_value;
6642
6643         /* Assuming scalar64_min_max_and will be called so its safe
6644          * to skip updating register for known 32-bit case.
6645          */
6646         if (src_known && dst_known)
6647                 return;
6648
6649         /* We get our minimum from the var_off, since that's inherently
6650          * bitwise.  Our maximum is the minimum of the operands' maxima.
6651          */
6652         dst_reg->u32_min_value = var32_off.value;
6653         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6654         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6655                 /* Lose signed bounds when ANDing negative numbers,
6656                  * ain't nobody got time for that.
6657                  */
6658                 dst_reg->s32_min_value = S32_MIN;
6659                 dst_reg->s32_max_value = S32_MAX;
6660         } else {
6661                 /* ANDing two positives gives a positive, so safe to
6662                  * cast result into s64.
6663                  */
6664                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6665                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6666         }
6667
6668 }
6669
6670 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6671                                struct bpf_reg_state *src_reg)
6672 {
6673         bool src_known = tnum_is_const(src_reg->var_off);
6674         bool dst_known = tnum_is_const(dst_reg->var_off);
6675         s64 smin_val = src_reg->smin_value;
6676         u64 umax_val = src_reg->umax_value;
6677
6678         if (src_known && dst_known) {
6679                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6680                 return;
6681         }
6682
6683         /* We get our minimum from the var_off, since that's inherently
6684          * bitwise.  Our maximum is the minimum of the operands' maxima.
6685          */
6686         dst_reg->umin_value = dst_reg->var_off.value;
6687         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6688         if (dst_reg->smin_value < 0 || smin_val < 0) {
6689                 /* Lose signed bounds when ANDing negative numbers,
6690                  * ain't nobody got time for that.
6691                  */
6692                 dst_reg->smin_value = S64_MIN;
6693                 dst_reg->smax_value = S64_MAX;
6694         } else {
6695                 /* ANDing two positives gives a positive, so safe to
6696                  * cast result into s64.
6697                  */
6698                 dst_reg->smin_value = dst_reg->umin_value;
6699                 dst_reg->smax_value = dst_reg->umax_value;
6700         }
6701         /* We may learn something more from the var_off */
6702         __update_reg_bounds(dst_reg);
6703 }
6704
6705 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6706                                 struct bpf_reg_state *src_reg)
6707 {
6708         bool src_known = tnum_subreg_is_const(src_reg->var_off);
6709         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6710         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6711         s32 smin_val = src_reg->s32_min_value;
6712         u32 umin_val = src_reg->u32_min_value;
6713
6714         /* Assuming scalar64_min_max_or will be called so it is safe
6715          * to skip updating register for known case.
6716          */
6717         if (src_known && dst_known)
6718                 return;
6719
6720         /* We get our maximum from the var_off, and our minimum is the
6721          * maximum of the operands' minima
6722          */
6723         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6724         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6725         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6726                 /* Lose signed bounds when ORing negative numbers,
6727                  * ain't nobody got time for that.
6728                  */
6729                 dst_reg->s32_min_value = S32_MIN;
6730                 dst_reg->s32_max_value = S32_MAX;
6731         } else {
6732                 /* ORing two positives gives a positive, so safe to
6733                  * cast result into s64.
6734                  */
6735                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6736                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6737         }
6738 }
6739
6740 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6741                               struct bpf_reg_state *src_reg)
6742 {
6743         bool src_known = tnum_is_const(src_reg->var_off);
6744         bool dst_known = tnum_is_const(dst_reg->var_off);
6745         s64 smin_val = src_reg->smin_value;
6746         u64 umin_val = src_reg->umin_value;
6747
6748         if (src_known && dst_known) {
6749                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6750                 return;
6751         }
6752
6753         /* We get our maximum from the var_off, and our minimum is the
6754          * maximum of the operands' minima
6755          */
6756         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6757         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6758         if (dst_reg->smin_value < 0 || smin_val < 0) {
6759                 /* Lose signed bounds when ORing negative numbers,
6760                  * ain't nobody got time for that.
6761                  */
6762                 dst_reg->smin_value = S64_MIN;
6763                 dst_reg->smax_value = S64_MAX;
6764         } else {
6765                 /* ORing two positives gives a positive, so safe to
6766                  * cast result into s64.
6767                  */
6768                 dst_reg->smin_value = dst_reg->umin_value;
6769                 dst_reg->smax_value = dst_reg->umax_value;
6770         }
6771         /* We may learn something more from the var_off */
6772         __update_reg_bounds(dst_reg);
6773 }
6774
6775 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6776                                  struct bpf_reg_state *src_reg)
6777 {
6778         bool src_known = tnum_subreg_is_const(src_reg->var_off);
6779         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6780         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6781         s32 smin_val = src_reg->s32_min_value;
6782
6783         /* Assuming scalar64_min_max_xor will be called so it is safe
6784          * to skip updating register for known case.
6785          */
6786         if (src_known && dst_known)
6787                 return;
6788
6789         /* We get both minimum and maximum from the var32_off. */
6790         dst_reg->u32_min_value = var32_off.value;
6791         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6792
6793         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6794                 /* XORing two positive sign numbers gives a positive,
6795                  * so safe to cast u32 result into s32.
6796                  */
6797                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6798                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6799         } else {
6800                 dst_reg->s32_min_value = S32_MIN;
6801                 dst_reg->s32_max_value = S32_MAX;
6802         }
6803 }
6804
6805 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6806                                struct bpf_reg_state *src_reg)
6807 {
6808         bool src_known = tnum_is_const(src_reg->var_off);
6809         bool dst_known = tnum_is_const(dst_reg->var_off);
6810         s64 smin_val = src_reg->smin_value;
6811
6812         if (src_known && dst_known) {
6813                 /* dst_reg->var_off.value has been updated earlier */
6814                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6815                 return;
6816         }
6817
6818         /* We get both minimum and maximum from the var_off. */
6819         dst_reg->umin_value = dst_reg->var_off.value;
6820         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6821
6822         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6823                 /* XORing two positive sign numbers gives a positive,
6824                  * so safe to cast u64 result into s64.
6825                  */
6826                 dst_reg->smin_value = dst_reg->umin_value;
6827                 dst_reg->smax_value = dst_reg->umax_value;
6828         } else {
6829                 dst_reg->smin_value = S64_MIN;
6830                 dst_reg->smax_value = S64_MAX;
6831         }
6832
6833         __update_reg_bounds(dst_reg);
6834 }
6835
6836 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6837                                    u64 umin_val, u64 umax_val)
6838 {
6839         /* We lose all sign bit information (except what we can pick
6840          * up from var_off)
6841          */
6842         dst_reg->s32_min_value = S32_MIN;
6843         dst_reg->s32_max_value = S32_MAX;
6844         /* If we might shift our top bit out, then we know nothing */
6845         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6846                 dst_reg->u32_min_value = 0;
6847                 dst_reg->u32_max_value = U32_MAX;
6848         } else {
6849                 dst_reg->u32_min_value <<= umin_val;
6850                 dst_reg->u32_max_value <<= umax_val;
6851         }
6852 }
6853
6854 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6855                                  struct bpf_reg_state *src_reg)
6856 {
6857         u32 umax_val = src_reg->u32_max_value;
6858         u32 umin_val = src_reg->u32_min_value;
6859         /* u32 alu operation will zext upper bits */
6860         struct tnum subreg = tnum_subreg(dst_reg->var_off);
6861
6862         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6863         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6864         /* Not required but being careful mark reg64 bounds as unknown so
6865          * that we are forced to pick them up from tnum and zext later and
6866          * if some path skips this step we are still safe.
6867          */
6868         __mark_reg64_unbounded(dst_reg);
6869         __update_reg32_bounds(dst_reg);
6870 }
6871
6872 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6873                                    u64 umin_val, u64 umax_val)
6874 {
6875         /* Special case <<32 because it is a common compiler pattern to sign
6876          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6877          * positive we know this shift will also be positive so we can track
6878          * bounds correctly. Otherwise we lose all sign bit information except
6879          * what we can pick up from var_off. Perhaps we can generalize this
6880          * later to shifts of any length.
6881          */
6882         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6883                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6884         else
6885                 dst_reg->smax_value = S64_MAX;
6886
6887         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6888                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6889         else
6890                 dst_reg->smin_value = S64_MIN;
6891
6892         /* If we might shift our top bit out, then we know nothing */
6893         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6894                 dst_reg->umin_value = 0;
6895                 dst_reg->umax_value = U64_MAX;
6896         } else {
6897                 dst_reg->umin_value <<= umin_val;
6898                 dst_reg->umax_value <<= umax_val;
6899         }
6900 }
6901
6902 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6903                                struct bpf_reg_state *src_reg)
6904 {
6905         u64 umax_val = src_reg->umax_value;
6906         u64 umin_val = src_reg->umin_value;
6907
6908         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6909         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6910         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6911
6912         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6913         /* We may learn something more from the var_off */
6914         __update_reg_bounds(dst_reg);
6915 }
6916
6917 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6918                                  struct bpf_reg_state *src_reg)
6919 {
6920         struct tnum subreg = tnum_subreg(dst_reg->var_off);
6921         u32 umax_val = src_reg->u32_max_value;
6922         u32 umin_val = src_reg->u32_min_value;
6923
6924         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6925          * be negative, then either:
6926          * 1) src_reg might be zero, so the sign bit of the result is
6927          *    unknown, so we lose our signed bounds
6928          * 2) it's known negative, thus the unsigned bounds capture the
6929          *    signed bounds
6930          * 3) the signed bounds cross zero, so they tell us nothing
6931          *    about the result
6932          * If the value in dst_reg is known nonnegative, then again the
6933          * unsigned bounds capture the signed bounds.
6934          * Thus, in all cases it suffices to blow away our signed bounds
6935          * and rely on inferring new ones from the unsigned bounds and
6936          * var_off of the result.
6937          */
6938         dst_reg->s32_min_value = S32_MIN;
6939         dst_reg->s32_max_value = S32_MAX;
6940
6941         dst_reg->var_off = tnum_rshift(subreg, umin_val);
6942         dst_reg->u32_min_value >>= umax_val;
6943         dst_reg->u32_max_value >>= umin_val;
6944
6945         __mark_reg64_unbounded(dst_reg);
6946         __update_reg32_bounds(dst_reg);
6947 }
6948
6949 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6950                                struct bpf_reg_state *src_reg)
6951 {
6952         u64 umax_val = src_reg->umax_value;
6953         u64 umin_val = src_reg->umin_value;
6954
6955         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6956          * be negative, then either:
6957          * 1) src_reg might be zero, so the sign bit of the result is
6958          *    unknown, so we lose our signed bounds
6959          * 2) it's known negative, thus the unsigned bounds capture the
6960          *    signed bounds
6961          * 3) the signed bounds cross zero, so they tell us nothing
6962          *    about the result
6963          * If the value in dst_reg is known nonnegative, then again the
6964          * unsigned bounds capture the signed bounds.
6965          * Thus, in all cases it suffices to blow away our signed bounds
6966          * and rely on inferring new ones from the unsigned bounds and
6967          * var_off of the result.
6968          */
6969         dst_reg->smin_value = S64_MIN;
6970         dst_reg->smax_value = S64_MAX;
6971         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6972         dst_reg->umin_value >>= umax_val;
6973         dst_reg->umax_value >>= umin_val;
6974
6975         /* Its not easy to operate on alu32 bounds here because it depends
6976          * on bits being shifted in. Take easy way out and mark unbounded
6977          * so we can recalculate later from tnum.
6978          */
6979         __mark_reg32_unbounded(dst_reg);
6980         __update_reg_bounds(dst_reg);
6981 }
6982
6983 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6984                                   struct bpf_reg_state *src_reg)
6985 {
6986         u64 umin_val = src_reg->u32_min_value;
6987
6988         /* Upon reaching here, src_known is true and
6989          * umax_val is equal to umin_val.
6990          */
6991         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6992         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6993
6994         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6995
6996         /* blow away the dst_reg umin_value/umax_value and rely on
6997          * dst_reg var_off to refine the result.
6998          */
6999         dst_reg->u32_min_value = 0;
7000         dst_reg->u32_max_value = U32_MAX;
7001
7002         __mark_reg64_unbounded(dst_reg);
7003         __update_reg32_bounds(dst_reg);
7004 }
7005
7006 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7007                                 struct bpf_reg_state *src_reg)
7008 {
7009         u64 umin_val = src_reg->umin_value;
7010
7011         /* Upon reaching here, src_known is true and umax_val is equal
7012          * to umin_val.
7013          */
7014         dst_reg->smin_value >>= umin_val;
7015         dst_reg->smax_value >>= umin_val;
7016
7017         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7018
7019         /* blow away the dst_reg umin_value/umax_value and rely on
7020          * dst_reg var_off to refine the result.
7021          */
7022         dst_reg->umin_value = 0;
7023         dst_reg->umax_value = U64_MAX;
7024
7025         /* Its not easy to operate on alu32 bounds here because it depends
7026          * on bits being shifted in from upper 32-bits. Take easy way out
7027          * and mark unbounded so we can recalculate later from tnum.
7028          */
7029         __mark_reg32_unbounded(dst_reg);
7030         __update_reg_bounds(dst_reg);
7031 }
7032
7033 /* WARNING: This function does calculations on 64-bit values, but the actual
7034  * execution may occur on 32-bit values. Therefore, things like bitshifts
7035  * need extra checks in the 32-bit case.
7036  */
7037 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7038                                       struct bpf_insn *insn,
7039                                       struct bpf_reg_state *dst_reg,
7040                                       struct bpf_reg_state src_reg)
7041 {
7042         struct bpf_reg_state *regs = cur_regs(env);
7043         u8 opcode = BPF_OP(insn->code);
7044         bool src_known;
7045         s64 smin_val, smax_val;
7046         u64 umin_val, umax_val;
7047         s32 s32_min_val, s32_max_val;
7048         u32 u32_min_val, u32_max_val;
7049         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7050         u32 dst = insn->dst_reg;
7051         int ret;
7052         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7053
7054         smin_val = src_reg.smin_value;
7055         smax_val = src_reg.smax_value;
7056         umin_val = src_reg.umin_value;
7057         umax_val = src_reg.umax_value;
7058
7059         s32_min_val = src_reg.s32_min_value;
7060         s32_max_val = src_reg.s32_max_value;
7061         u32_min_val = src_reg.u32_min_value;
7062         u32_max_val = src_reg.u32_max_value;
7063
7064         if (alu32) {
7065                 src_known = tnum_subreg_is_const(src_reg.var_off);
7066                 if ((src_known &&
7067                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7068                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7069                         /* Taint dst register if offset had invalid bounds
7070                          * derived from e.g. dead branches.
7071                          */
7072                         __mark_reg_unknown(env, dst_reg);
7073                         return 0;
7074                 }
7075         } else {
7076                 src_known = tnum_is_const(src_reg.var_off);
7077                 if ((src_known &&
7078                      (smin_val != smax_val || umin_val != umax_val)) ||
7079                     smin_val > smax_val || umin_val > umax_val) {
7080                         /* Taint dst register if offset had invalid bounds
7081                          * derived from e.g. dead branches.
7082                          */
7083                         __mark_reg_unknown(env, dst_reg);
7084                         return 0;
7085                 }
7086         }
7087
7088         if (!src_known &&
7089             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7090                 __mark_reg_unknown(env, dst_reg);
7091                 return 0;
7092         }
7093
7094         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7095          * There are two classes of instructions: The first class we track both
7096          * alu32 and alu64 sign/unsigned bounds independently this provides the
7097          * greatest amount of precision when alu operations are mixed with jmp32
7098          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7099          * and BPF_OR. This is possible because these ops have fairly easy to
7100          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7101          * See alu32 verifier tests for examples. The second class of
7102          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7103          * with regards to tracking sign/unsigned bounds because the bits may
7104          * cross subreg boundaries in the alu64 case. When this happens we mark
7105          * the reg unbounded in the subreg bound space and use the resulting
7106          * tnum to calculate an approximation of the sign/unsigned bounds.
7107          */
7108         switch (opcode) {
7109         case BPF_ADD:
7110                 ret = sanitize_val_alu(env, insn);
7111                 if (ret < 0) {
7112                         verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
7113                         return ret;
7114                 }
7115                 scalar32_min_max_add(dst_reg, &src_reg);
7116                 scalar_min_max_add(dst_reg, &src_reg);
7117                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7118                 break;
7119         case BPF_SUB:
7120                 ret = sanitize_val_alu(env, insn);
7121                 if (ret < 0) {
7122                         verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
7123                         return ret;
7124                 }
7125                 scalar32_min_max_sub(dst_reg, &src_reg);
7126                 scalar_min_max_sub(dst_reg, &src_reg);
7127                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7128                 break;
7129         case BPF_MUL:
7130                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7131                 scalar32_min_max_mul(dst_reg, &src_reg);
7132                 scalar_min_max_mul(dst_reg, &src_reg);
7133                 break;
7134         case BPF_AND:
7135                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7136                 scalar32_min_max_and(dst_reg, &src_reg);
7137                 scalar_min_max_and(dst_reg, &src_reg);
7138                 break;
7139         case BPF_OR:
7140                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7141                 scalar32_min_max_or(dst_reg, &src_reg);
7142                 scalar_min_max_or(dst_reg, &src_reg);
7143                 break;
7144         case BPF_XOR:
7145                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7146                 scalar32_min_max_xor(dst_reg, &src_reg);
7147                 scalar_min_max_xor(dst_reg, &src_reg);
7148                 break;
7149         case BPF_LSH:
7150                 if (umax_val >= insn_bitness) {
7151                         /* Shifts greater than 31 or 63 are undefined.
7152                          * This includes shifts by a negative number.
7153                          */
7154                         mark_reg_unknown(env, regs, insn->dst_reg);
7155                         break;
7156                 }
7157                 if (alu32)
7158                         scalar32_min_max_lsh(dst_reg, &src_reg);
7159                 else
7160                         scalar_min_max_lsh(dst_reg, &src_reg);
7161                 break;
7162         case BPF_RSH:
7163                 if (umax_val >= insn_bitness) {
7164                         /* Shifts greater than 31 or 63 are undefined.
7165                          * This includes shifts by a negative number.
7166                          */
7167                         mark_reg_unknown(env, regs, insn->dst_reg);
7168                         break;
7169                 }
7170                 if (alu32)
7171                         scalar32_min_max_rsh(dst_reg, &src_reg);
7172                 else
7173                         scalar_min_max_rsh(dst_reg, &src_reg);
7174                 break;
7175         case BPF_ARSH:
7176                 if (umax_val >= insn_bitness) {
7177                         /* Shifts greater than 31 or 63 are undefined.
7178                          * This includes shifts by a negative number.
7179                          */
7180                         mark_reg_unknown(env, regs, insn->dst_reg);
7181                         break;
7182                 }
7183                 if (alu32)
7184                         scalar32_min_max_arsh(dst_reg, &src_reg);
7185                 else
7186                         scalar_min_max_arsh(dst_reg, &src_reg);
7187                 break;
7188         default:
7189                 mark_reg_unknown(env, regs, insn->dst_reg);
7190                 break;
7191         }
7192
7193         /* ALU32 ops are zero extended into 64bit register */
7194         if (alu32)
7195                 zext_32_to_64(dst_reg);
7196
7197         __update_reg_bounds(dst_reg);
7198         __reg_deduce_bounds(dst_reg);
7199         __reg_bound_offset(dst_reg);
7200         return 0;
7201 }
7202
7203 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7204  * and var_off.
7205  */
7206 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7207                                    struct bpf_insn *insn)
7208 {
7209         struct bpf_verifier_state *vstate = env->cur_state;
7210         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7211         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7212         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7213         u8 opcode = BPF_OP(insn->code);
7214         int err;
7215
7216         dst_reg = &regs[insn->dst_reg];
7217         src_reg = NULL;
7218         if (dst_reg->type != SCALAR_VALUE)
7219                 ptr_reg = dst_reg;
7220         else
7221                 /* Make sure ID is cleared otherwise dst_reg min/max could be
7222                  * incorrectly propagated into other registers by find_equal_scalars()
7223                  */
7224                 dst_reg->id = 0;
7225         if (BPF_SRC(insn->code) == BPF_X) {
7226                 src_reg = &regs[insn->src_reg];
7227                 if (src_reg->type != SCALAR_VALUE) {
7228                         if (dst_reg->type != SCALAR_VALUE) {
7229                                 /* Combining two pointers by any ALU op yields
7230                                  * an arbitrary scalar. Disallow all math except
7231                                  * pointer subtraction
7232                                  */
7233                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7234                                         mark_reg_unknown(env, regs, insn->dst_reg);
7235                                         return 0;
7236                                 }
7237                                 verbose(env, "R%d pointer %s pointer prohibited\n",
7238                                         insn->dst_reg,
7239                                         bpf_alu_string[opcode >> 4]);
7240                                 return -EACCES;
7241                         } else {
7242                                 /* scalar += pointer
7243                                  * This is legal, but we have to reverse our
7244                                  * src/dest handling in computing the range
7245                                  */
7246                                 err = mark_chain_precision(env, insn->dst_reg);
7247                                 if (err)
7248                                         return err;
7249                                 return adjust_ptr_min_max_vals(env, insn,
7250                                                                src_reg, dst_reg);
7251                         }
7252                 } else if (ptr_reg) {
7253                         /* pointer += scalar */
7254                         err = mark_chain_precision(env, insn->src_reg);
7255                         if (err)
7256                                 return err;
7257                         return adjust_ptr_min_max_vals(env, insn,
7258                                                        dst_reg, src_reg);
7259                 }
7260         } else {
7261                 /* Pretend the src is a reg with a known value, since we only
7262                  * need to be able to read from this state.
7263                  */
7264                 off_reg.type = SCALAR_VALUE;
7265                 __mark_reg_known(&off_reg, insn->imm);
7266                 src_reg = &off_reg;
7267                 if (ptr_reg) /* pointer += K */
7268                         return adjust_ptr_min_max_vals(env, insn,
7269                                                        ptr_reg, src_reg);
7270         }
7271
7272         /* Got here implies adding two SCALAR_VALUEs */
7273         if (WARN_ON_ONCE(ptr_reg)) {
7274                 print_verifier_state(env, state);
7275                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7276                 return -EINVAL;
7277         }
7278         if (WARN_ON(!src_reg)) {
7279                 print_verifier_state(env, state);
7280                 verbose(env, "verifier internal error: no src_reg\n");
7281                 return -EINVAL;
7282         }
7283         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7284 }
7285
7286 /* check validity of 32-bit and 64-bit arithmetic operations */
7287 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7288 {
7289         struct bpf_reg_state *regs = cur_regs(env);
7290         u8 opcode = BPF_OP(insn->code);
7291         int err;
7292
7293         if (opcode == BPF_END || opcode == BPF_NEG) {
7294                 if (opcode == BPF_NEG) {
7295                         if (BPF_SRC(insn->code) != 0 ||
7296                             insn->src_reg != BPF_REG_0 ||
7297                             insn->off != 0 || insn->imm != 0) {
7298                                 verbose(env, "BPF_NEG uses reserved fields\n");
7299                                 return -EINVAL;
7300                         }
7301                 } else {
7302                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7303                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7304                             BPF_CLASS(insn->code) == BPF_ALU64) {
7305                                 verbose(env, "BPF_END uses reserved fields\n");
7306                                 return -EINVAL;
7307                         }
7308                 }
7309
7310                 /* check src operand */
7311                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7312                 if (err)
7313                         return err;
7314
7315                 if (is_pointer_value(env, insn->dst_reg)) {
7316                         verbose(env, "R%d pointer arithmetic prohibited\n",
7317                                 insn->dst_reg);
7318                         return -EACCES;
7319                 }
7320
7321                 /* check dest operand */
7322                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7323                 if (err)
7324                         return err;
7325
7326         } else if (opcode == BPF_MOV) {
7327
7328                 if (BPF_SRC(insn->code) == BPF_X) {
7329                         if (insn->imm != 0 || insn->off != 0) {
7330                                 verbose(env, "BPF_MOV uses reserved fields\n");
7331                                 return -EINVAL;
7332                         }
7333
7334                         /* check src operand */
7335                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
7336                         if (err)
7337                                 return err;
7338                 } else {
7339                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7340                                 verbose(env, "BPF_MOV uses reserved fields\n");
7341                                 return -EINVAL;
7342                         }
7343                 }
7344
7345                 /* check dest operand, mark as required later */
7346                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7347                 if (err)
7348                         return err;
7349
7350                 if (BPF_SRC(insn->code) == BPF_X) {
7351                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
7352                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7353
7354                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
7355                                 /* case: R1 = R2
7356                                  * copy register state to dest reg
7357                                  */
7358                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7359                                         /* Assign src and dst registers the same ID
7360                                          * that will be used by find_equal_scalars()
7361                                          * to propagate min/max range.
7362                                          */
7363                                         src_reg->id = ++env->id_gen;
7364                                 *dst_reg = *src_reg;
7365                                 dst_reg->live |= REG_LIVE_WRITTEN;
7366                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
7367                         } else {
7368                                 /* R1 = (u32) R2 */
7369                                 if (is_pointer_value(env, insn->src_reg)) {
7370                                         verbose(env,
7371                                                 "R%d partial copy of pointer\n",
7372                                                 insn->src_reg);
7373                                         return -EACCES;
7374                                 } else if (src_reg->type == SCALAR_VALUE) {
7375                                         *dst_reg = *src_reg;
7376                                         /* Make sure ID is cleared otherwise
7377                                          * dst_reg min/max could be incorrectly
7378                                          * propagated into src_reg by find_equal_scalars()
7379                                          */
7380                                         dst_reg->id = 0;
7381                                         dst_reg->live |= REG_LIVE_WRITTEN;
7382                                         dst_reg->subreg_def = env->insn_idx + 1;
7383                                 } else {
7384                                         mark_reg_unknown(env, regs,
7385                                                          insn->dst_reg);
7386                                 }
7387                                 zext_32_to_64(dst_reg);
7388                         }
7389                 } else {
7390                         /* case: R = imm
7391                          * remember the value we stored into this reg
7392                          */
7393                         /* clear any state __mark_reg_known doesn't set */
7394                         mark_reg_unknown(env, regs, insn->dst_reg);
7395                         regs[insn->dst_reg].type = SCALAR_VALUE;
7396                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
7397                                 __mark_reg_known(regs + insn->dst_reg,
7398                                                  insn->imm);
7399                         } else {
7400                                 __mark_reg_known(regs + insn->dst_reg,
7401                                                  (u32)insn->imm);
7402                         }
7403                 }
7404
7405         } else if (opcode > BPF_END) {
7406                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7407                 return -EINVAL;
7408
7409         } else {        /* all other ALU ops: and, sub, xor, add, ... */
7410
7411                 if (BPF_SRC(insn->code) == BPF_X) {
7412                         if (insn->imm != 0 || insn->off != 0) {
7413                                 verbose(env, "BPF_ALU uses reserved fields\n");
7414                                 return -EINVAL;
7415                         }
7416                         /* check src1 operand */
7417                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
7418                         if (err)
7419                                 return err;
7420                 } else {
7421                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7422                                 verbose(env, "BPF_ALU uses reserved fields\n");
7423                                 return -EINVAL;
7424                         }
7425                 }
7426
7427                 /* check src2 operand */
7428                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7429                 if (err)
7430                         return err;
7431
7432                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7433                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7434                         verbose(env, "div by zero\n");
7435                         return -EINVAL;
7436                 }
7437
7438                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7439                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7440                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7441
7442                         if (insn->imm < 0 || insn->imm >= size) {
7443                                 verbose(env, "invalid shift %d\n", insn->imm);
7444                                 return -EINVAL;
7445                         }
7446                 }
7447
7448                 /* check dest operand */
7449                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7450                 if (err)
7451                         return err;
7452
7453                 return adjust_reg_min_max_vals(env, insn);
7454         }
7455
7456         return 0;
7457 }
7458
7459 static void __find_good_pkt_pointers(struct bpf_func_state *state,
7460                                      struct bpf_reg_state *dst_reg,
7461                                      enum bpf_reg_type type, int new_range)
7462 {
7463         struct bpf_reg_state *reg;
7464         int i;
7465
7466         for (i = 0; i < MAX_BPF_REG; i++) {
7467                 reg = &state->regs[i];
7468                 if (reg->type == type && reg->id == dst_reg->id)
7469                         /* keep the maximum range already checked */
7470                         reg->range = max(reg->range, new_range);
7471         }
7472
7473         bpf_for_each_spilled_reg(i, state, reg) {
7474                 if (!reg)
7475                         continue;
7476                 if (reg->type == type && reg->id == dst_reg->id)
7477                         reg->range = max(reg->range, new_range);
7478         }
7479 }
7480
7481 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7482                                    struct bpf_reg_state *dst_reg,
7483                                    enum bpf_reg_type type,
7484                                    bool range_right_open)
7485 {
7486         int new_range, i;
7487
7488         if (dst_reg->off < 0 ||
7489             (dst_reg->off == 0 && range_right_open))
7490                 /* This doesn't give us any range */
7491                 return;
7492
7493         if (dst_reg->umax_value > MAX_PACKET_OFF ||
7494             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7495                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
7496                  * than pkt_end, but that's because it's also less than pkt.
7497                  */
7498                 return;
7499
7500         new_range = dst_reg->off;
7501         if (range_right_open)
7502                 new_range--;
7503
7504         /* Examples for register markings:
7505          *
7506          * pkt_data in dst register:
7507          *
7508          *   r2 = r3;
7509          *   r2 += 8;
7510          *   if (r2 > pkt_end) goto <handle exception>
7511          *   <access okay>
7512          *
7513          *   r2 = r3;
7514          *   r2 += 8;
7515          *   if (r2 < pkt_end) goto <access okay>
7516          *   <handle exception>
7517          *
7518          *   Where:
7519          *     r2 == dst_reg, pkt_end == src_reg
7520          *     r2=pkt(id=n,off=8,r=0)
7521          *     r3=pkt(id=n,off=0,r=0)
7522          *
7523          * pkt_data in src register:
7524          *
7525          *   r2 = r3;
7526          *   r2 += 8;
7527          *   if (pkt_end >= r2) goto <access okay>
7528          *   <handle exception>
7529          *
7530          *   r2 = r3;
7531          *   r2 += 8;
7532          *   if (pkt_end <= r2) goto <handle exception>
7533          *   <access okay>
7534          *
7535          *   Where:
7536          *     pkt_end == dst_reg, r2 == src_reg
7537          *     r2=pkt(id=n,off=8,r=0)
7538          *     r3=pkt(id=n,off=0,r=0)
7539          *
7540          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7541          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7542          * and [r3, r3 + 8-1) respectively is safe to access depending on
7543          * the check.
7544          */
7545
7546         /* If our ids match, then we must have the same max_value.  And we
7547          * don't care about the other reg's fixed offset, since if it's too big
7548          * the range won't allow anything.
7549          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7550          */
7551         for (i = 0; i <= vstate->curframe; i++)
7552                 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7553                                          new_range);
7554 }
7555
7556 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7557 {
7558         struct tnum subreg = tnum_subreg(reg->var_off);
7559         s32 sval = (s32)val;
7560
7561         switch (opcode) {
7562         case BPF_JEQ:
7563                 if (tnum_is_const(subreg))
7564                         return !!tnum_equals_const(subreg, val);
7565                 break;
7566         case BPF_JNE:
7567                 if (tnum_is_const(subreg))
7568                         return !tnum_equals_const(subreg, val);
7569                 break;
7570         case BPF_JSET:
7571                 if ((~subreg.mask & subreg.value) & val)
7572                         return 1;
7573                 if (!((subreg.mask | subreg.value) & val))
7574                         return 0;
7575                 break;
7576         case BPF_JGT:
7577                 if (reg->u32_min_value > val)
7578                         return 1;
7579                 else if (reg->u32_max_value <= val)
7580                         return 0;
7581                 break;
7582         case BPF_JSGT:
7583                 if (reg->s32_min_value > sval)
7584                         return 1;
7585                 else if (reg->s32_max_value <= sval)
7586                         return 0;
7587                 break;
7588         case BPF_JLT:
7589                 if (reg->u32_max_value < val)
7590                         return 1;
7591                 else if (reg->u32_min_value >= val)
7592                         return 0;
7593                 break;
7594         case BPF_JSLT:
7595                 if (reg->s32_max_value < sval)
7596                         return 1;
7597                 else if (reg->s32_min_value >= sval)
7598                         return 0;
7599                 break;
7600         case BPF_JGE:
7601                 if (reg->u32_min_value >= val)
7602                         return 1;
7603                 else if (reg->u32_max_value < val)
7604                         return 0;
7605                 break;
7606         case BPF_JSGE:
7607                 if (reg->s32_min_value >= sval)
7608                         return 1;
7609                 else if (reg->s32_max_value < sval)
7610                         return 0;
7611                 break;
7612         case BPF_JLE:
7613                 if (reg->u32_max_value <= val)
7614                         return 1;
7615                 else if (reg->u32_min_value > val)
7616                         return 0;
7617                 break;
7618         case BPF_JSLE:
7619                 if (reg->s32_max_value <= sval)
7620                         return 1;
7621                 else if (reg->s32_min_value > sval)
7622                         return 0;
7623                 break;
7624         }
7625
7626         return -1;
7627 }
7628
7629
7630 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7631 {
7632         s64 sval = (s64)val;
7633
7634         switch (opcode) {
7635         case BPF_JEQ:
7636                 if (tnum_is_const(reg->var_off))
7637                         return !!tnum_equals_const(reg->var_off, val);
7638                 break;
7639         case BPF_JNE:
7640                 if (tnum_is_const(reg->var_off))
7641                         return !tnum_equals_const(reg->var_off, val);
7642                 break;
7643         case BPF_JSET:
7644                 if ((~reg->var_off.mask & reg->var_off.value) & val)
7645                         return 1;
7646                 if (!((reg->var_off.mask | reg->var_off.value) & val))
7647                         return 0;
7648                 break;
7649         case BPF_JGT:
7650                 if (reg->umin_value > val)
7651                         return 1;
7652                 else if (reg->umax_value <= val)
7653                         return 0;
7654                 break;
7655         case BPF_JSGT:
7656                 if (reg->smin_value > sval)
7657                         return 1;
7658                 else if (reg->smax_value <= sval)
7659                         return 0;
7660                 break;
7661         case BPF_JLT:
7662                 if (reg->umax_value < val)
7663                         return 1;
7664                 else if (reg->umin_value >= val)
7665                         return 0;
7666                 break;
7667         case BPF_JSLT:
7668                 if (reg->smax_value < sval)
7669                         return 1;
7670                 else if (reg->smin_value >= sval)
7671                         return 0;
7672                 break;
7673         case BPF_JGE:
7674                 if (reg->umin_value >= val)
7675                         return 1;
7676                 else if (reg->umax_value < val)
7677                         return 0;
7678                 break;
7679         case BPF_JSGE:
7680                 if (reg->smin_value >= sval)
7681                         return 1;
7682                 else if (reg->smax_value < sval)
7683                         return 0;
7684                 break;
7685         case BPF_JLE:
7686                 if (reg->umax_value <= val)
7687                         return 1;
7688                 else if (reg->umin_value > val)
7689                         return 0;
7690                 break;
7691         case BPF_JSLE:
7692                 if (reg->smax_value <= sval)
7693                         return 1;
7694                 else if (reg->smin_value > sval)
7695                         return 0;
7696                 break;
7697         }
7698
7699         return -1;
7700 }
7701
7702 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7703  * and return:
7704  *  1 - branch will be taken and "goto target" will be executed
7705  *  0 - branch will not be taken and fall-through to next insn
7706  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7707  *      range [0,10]
7708  */
7709 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7710                            bool is_jmp32)
7711 {
7712         if (__is_pointer_value(false, reg)) {
7713                 if (!reg_type_not_null(reg->type))
7714                         return -1;
7715
7716                 /* If pointer is valid tests against zero will fail so we can
7717                  * use this to direct branch taken.
7718                  */
7719                 if (val != 0)
7720                         return -1;
7721
7722                 switch (opcode) {
7723                 case BPF_JEQ:
7724                         return 0;
7725                 case BPF_JNE:
7726                         return 1;
7727                 default:
7728                         return -1;
7729                 }
7730         }
7731
7732         if (is_jmp32)
7733                 return is_branch32_taken(reg, val, opcode);
7734         return is_branch64_taken(reg, val, opcode);
7735 }
7736
7737 static int flip_opcode(u32 opcode)
7738 {
7739         /* How can we transform "a <op> b" into "b <op> a"? */
7740         static const u8 opcode_flip[16] = {
7741                 /* these stay the same */
7742                 [BPF_JEQ  >> 4] = BPF_JEQ,
7743                 [BPF_JNE  >> 4] = BPF_JNE,
7744                 [BPF_JSET >> 4] = BPF_JSET,
7745                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7746                 [BPF_JGE  >> 4] = BPF_JLE,
7747                 [BPF_JGT  >> 4] = BPF_JLT,
7748                 [BPF_JLE  >> 4] = BPF_JGE,
7749                 [BPF_JLT  >> 4] = BPF_JGT,
7750                 [BPF_JSGE >> 4] = BPF_JSLE,
7751                 [BPF_JSGT >> 4] = BPF_JSLT,
7752                 [BPF_JSLE >> 4] = BPF_JSGE,
7753                 [BPF_JSLT >> 4] = BPF_JSGT
7754         };
7755         return opcode_flip[opcode >> 4];
7756 }
7757
7758 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7759                                    struct bpf_reg_state *src_reg,
7760                                    u8 opcode)
7761 {
7762         struct bpf_reg_state *pkt;
7763
7764         if (src_reg->type == PTR_TO_PACKET_END) {
7765                 pkt = dst_reg;
7766         } else if (dst_reg->type == PTR_TO_PACKET_END) {
7767                 pkt = src_reg;
7768                 opcode = flip_opcode(opcode);
7769         } else {
7770                 return -1;
7771         }
7772
7773         if (pkt->range >= 0)
7774                 return -1;
7775
7776         switch (opcode) {
7777         case BPF_JLE:
7778                 /* pkt <= pkt_end */
7779                 fallthrough;
7780         case BPF_JGT:
7781                 /* pkt > pkt_end */
7782                 if (pkt->range == BEYOND_PKT_END)
7783                         /* pkt has at last one extra byte beyond pkt_end */
7784                         return opcode == BPF_JGT;
7785                 break;
7786         case BPF_JLT:
7787                 /* pkt < pkt_end */
7788                 fallthrough;
7789         case BPF_JGE:
7790                 /* pkt >= pkt_end */
7791                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7792                         return opcode == BPF_JGE;
7793                 break;
7794         }
7795         return -1;
7796 }
7797
7798 /* Adjusts the register min/max values in the case that the dst_reg is the
7799  * variable register that we are working on, and src_reg is a constant or we're
7800  * simply doing a BPF_K check.
7801  * In JEQ/JNE cases we also adjust the var_off values.
7802  */
7803 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7804                             struct bpf_reg_state *false_reg,
7805                             u64 val, u32 val32,
7806                             u8 opcode, bool is_jmp32)
7807 {
7808         struct tnum false_32off = tnum_subreg(false_reg->var_off);
7809         struct tnum false_64off = false_reg->var_off;
7810         struct tnum true_32off = tnum_subreg(true_reg->var_off);
7811         struct tnum true_64off = true_reg->var_off;
7812         s64 sval = (s64)val;
7813         s32 sval32 = (s32)val32;
7814
7815         /* If the dst_reg is a pointer, we can't learn anything about its
7816          * variable offset from the compare (unless src_reg were a pointer into
7817          * the same object, but we don't bother with that.
7818          * Since false_reg and true_reg have the same type by construction, we
7819          * only need to check one of them for pointerness.
7820          */
7821         if (__is_pointer_value(false, false_reg))
7822                 return;
7823
7824         switch (opcode) {
7825         case BPF_JEQ:
7826         case BPF_JNE:
7827         {
7828                 struct bpf_reg_state *reg =
7829                         opcode == BPF_JEQ ? true_reg : false_reg;
7830
7831                 /* JEQ/JNE comparison doesn't change the register equivalence.
7832                  * r1 = r2;
7833                  * if (r1 == 42) goto label;
7834                  * ...
7835                  * label: // here both r1 and r2 are known to be 42.
7836                  *
7837                  * Hence when marking register as known preserve it's ID.
7838                  */
7839                 if (is_jmp32)
7840                         __mark_reg32_known(reg, val32);
7841                 else
7842                         ___mark_reg_known(reg, val);
7843                 break;
7844         }
7845         case BPF_JSET:
7846                 if (is_jmp32) {
7847                         false_32off = tnum_and(false_32off, tnum_const(~val32));
7848                         if (is_power_of_2(val32))
7849                                 true_32off = tnum_or(true_32off,
7850                                                      tnum_const(val32));
7851                 } else {
7852                         false_64off = tnum_and(false_64off, tnum_const(~val));
7853                         if (is_power_of_2(val))
7854                                 true_64off = tnum_or(true_64off,
7855                                                      tnum_const(val));
7856                 }
7857                 break;
7858         case BPF_JGE:
7859         case BPF_JGT:
7860         {
7861                 if (is_jmp32) {
7862                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
7863                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7864
7865                         false_reg->u32_max_value = min(false_reg->u32_max_value,
7866                                                        false_umax);
7867                         true_reg->u32_min_value = max(true_reg->u32_min_value,
7868                                                       true_umin);
7869                 } else {
7870                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
7871                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7872
7873                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
7874                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
7875                 }
7876                 break;
7877         }
7878         case BPF_JSGE:
7879         case BPF_JSGT:
7880         {
7881                 if (is_jmp32) {
7882                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
7883                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7884
7885                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7886                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7887                 } else {
7888                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
7889                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7890
7891                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
7892                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
7893                 }
7894                 break;
7895         }
7896         case BPF_JLE:
7897         case BPF_JLT:
7898         {
7899                 if (is_jmp32) {
7900                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
7901                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7902
7903                         false_reg->u32_min_value = max(false_reg->u32_min_value,
7904                                                        false_umin);
7905                         true_reg->u32_max_value = min(true_reg->u32_max_value,
7906                                                       true_umax);
7907                 } else {
7908                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
7909                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7910
7911                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
7912                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
7913                 }
7914                 break;
7915         }
7916         case BPF_JSLE:
7917         case BPF_JSLT:
7918         {
7919                 if (is_jmp32) {
7920                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
7921                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7922
7923                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7924                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7925                 } else {
7926                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
7927                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7928
7929                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
7930                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
7931                 }
7932                 break;
7933         }
7934         default:
7935                 return;
7936         }
7937
7938         if (is_jmp32) {
7939                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7940                                              tnum_subreg(false_32off));
7941                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7942                                             tnum_subreg(true_32off));
7943                 __reg_combine_32_into_64(false_reg);
7944                 __reg_combine_32_into_64(true_reg);
7945         } else {
7946                 false_reg->var_off = false_64off;
7947                 true_reg->var_off = true_64off;
7948                 __reg_combine_64_into_32(false_reg);
7949                 __reg_combine_64_into_32(true_reg);
7950         }
7951 }
7952
7953 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7954  * the variable reg.
7955  */
7956 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7957                                 struct bpf_reg_state *false_reg,
7958                                 u64 val, u32 val32,
7959                                 u8 opcode, bool is_jmp32)
7960 {
7961         opcode = flip_opcode(opcode);
7962         /* This uses zero as "not present in table"; luckily the zero opcode,
7963          * BPF_JA, can't get here.
7964          */
7965         if (opcode)
7966                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7967 }
7968
7969 /* Regs are known to be equal, so intersect their min/max/var_off */
7970 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7971                                   struct bpf_reg_state *dst_reg)
7972 {
7973         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7974                                                         dst_reg->umin_value);
7975         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7976                                                         dst_reg->umax_value);
7977         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7978                                                         dst_reg->smin_value);
7979         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7980                                                         dst_reg->smax_value);
7981         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7982                                                              dst_reg->var_off);
7983         /* We might have learned new bounds from the var_off. */
7984         __update_reg_bounds(src_reg);
7985         __update_reg_bounds(dst_reg);
7986         /* We might have learned something about the sign bit. */
7987         __reg_deduce_bounds(src_reg);
7988         __reg_deduce_bounds(dst_reg);
7989         /* We might have learned some bits from the bounds. */
7990         __reg_bound_offset(src_reg);
7991         __reg_bound_offset(dst_reg);
7992         /* Intersecting with the old var_off might have improved our bounds
7993          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7994          * then new var_off is (0; 0x7f...fc) which improves our umax.
7995          */
7996         __update_reg_bounds(src_reg);
7997         __update_reg_bounds(dst_reg);
7998 }
7999
8000 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8001                                 struct bpf_reg_state *true_dst,
8002                                 struct bpf_reg_state *false_src,
8003                                 struct bpf_reg_state *false_dst,
8004                                 u8 opcode)
8005 {
8006         switch (opcode) {
8007         case BPF_JEQ:
8008                 __reg_combine_min_max(true_src, true_dst);
8009                 break;
8010         case BPF_JNE:
8011                 __reg_combine_min_max(false_src, false_dst);
8012                 break;
8013         }
8014 }
8015
8016 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8017                                  struct bpf_reg_state *reg, u32 id,
8018                                  bool is_null)
8019 {
8020         if (reg_type_may_be_null(reg->type) && reg->id == id &&
8021             !WARN_ON_ONCE(!reg->id)) {
8022                 /* Old offset (both fixed and variable parts) should
8023                  * have been known-zero, because we don't allow pointer
8024                  * arithmetic on pointers that might be NULL.
8025                  */
8026                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8027                                  !tnum_equals_const(reg->var_off, 0) ||
8028                                  reg->off)) {
8029                         __mark_reg_known_zero(reg);
8030                         reg->off = 0;
8031                 }
8032                 if (is_null) {
8033                         reg->type = SCALAR_VALUE;
8034                         /* We don't need id and ref_obj_id from this point
8035                          * onwards anymore, thus we should better reset it,
8036                          * so that state pruning has chances to take effect.
8037                          */
8038                         reg->id = 0;
8039                         reg->ref_obj_id = 0;
8040
8041                         return;
8042                 }
8043
8044                 mark_ptr_not_null_reg(reg);
8045
8046                 if (!reg_may_point_to_spin_lock(reg)) {
8047                         /* For not-NULL ptr, reg->ref_obj_id will be reset
8048                          * in release_reg_references().
8049                          *
8050                          * reg->id is still used by spin_lock ptr. Other
8051                          * than spin_lock ptr type, reg->id can be reset.
8052                          */
8053                         reg->id = 0;
8054                 }
8055         }
8056 }
8057
8058 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8059                                     bool is_null)
8060 {
8061         struct bpf_reg_state *reg;
8062         int i;
8063
8064         for (i = 0; i < MAX_BPF_REG; i++)
8065                 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8066
8067         bpf_for_each_spilled_reg(i, state, reg) {
8068                 if (!reg)
8069                         continue;
8070                 mark_ptr_or_null_reg(state, reg, id, is_null);
8071         }
8072 }
8073
8074 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8075  * be folded together at some point.
8076  */
8077 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8078                                   bool is_null)
8079 {
8080         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8081         struct bpf_reg_state *regs = state->regs;
8082         u32 ref_obj_id = regs[regno].ref_obj_id;
8083         u32 id = regs[regno].id;
8084         int i;
8085
8086         if (ref_obj_id && ref_obj_id == id && is_null)
8087                 /* regs[regno] is in the " == NULL" branch.
8088                  * No one could have freed the reference state before
8089                  * doing the NULL check.
8090                  */
8091                 WARN_ON_ONCE(release_reference_state(state, id));
8092
8093         for (i = 0; i <= vstate->curframe; i++)
8094                 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
8095 }
8096
8097 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8098                                    struct bpf_reg_state *dst_reg,
8099                                    struct bpf_reg_state *src_reg,
8100                                    struct bpf_verifier_state *this_branch,
8101                                    struct bpf_verifier_state *other_branch)
8102 {
8103         if (BPF_SRC(insn->code) != BPF_X)
8104                 return false;
8105
8106         /* Pointers are always 64-bit. */
8107         if (BPF_CLASS(insn->code) == BPF_JMP32)
8108                 return false;
8109
8110         switch (BPF_OP(insn->code)) {
8111         case BPF_JGT:
8112                 if ((dst_reg->type == PTR_TO_PACKET &&
8113                      src_reg->type == PTR_TO_PACKET_END) ||
8114                     (dst_reg->type == PTR_TO_PACKET_META &&
8115                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8116                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8117                         find_good_pkt_pointers(this_branch, dst_reg,
8118                                                dst_reg->type, false);
8119                         mark_pkt_end(other_branch, insn->dst_reg, true);
8120                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8121                             src_reg->type == PTR_TO_PACKET) ||
8122                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8123                             src_reg->type == PTR_TO_PACKET_META)) {
8124                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8125                         find_good_pkt_pointers(other_branch, src_reg,
8126                                                src_reg->type, true);
8127                         mark_pkt_end(this_branch, insn->src_reg, false);
8128                 } else {
8129                         return false;
8130                 }
8131                 break;
8132         case BPF_JLT:
8133                 if ((dst_reg->type == PTR_TO_PACKET &&
8134                      src_reg->type == PTR_TO_PACKET_END) ||
8135                     (dst_reg->type == PTR_TO_PACKET_META &&
8136                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8137                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8138                         find_good_pkt_pointers(other_branch, dst_reg,
8139                                                dst_reg->type, true);
8140                         mark_pkt_end(this_branch, insn->dst_reg, false);
8141                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8142                             src_reg->type == PTR_TO_PACKET) ||
8143                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8144                             src_reg->type == PTR_TO_PACKET_META)) {
8145                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8146                         find_good_pkt_pointers(this_branch, src_reg,
8147                                                src_reg->type, false);
8148                         mark_pkt_end(other_branch, insn->src_reg, true);
8149                 } else {
8150                         return false;
8151                 }
8152                 break;
8153         case BPF_JGE:
8154                 if ((dst_reg->type == PTR_TO_PACKET &&
8155                      src_reg->type == PTR_TO_PACKET_END) ||
8156                     (dst_reg->type == PTR_TO_PACKET_META &&
8157                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8158                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8159                         find_good_pkt_pointers(this_branch, dst_reg,
8160                                                dst_reg->type, true);
8161                         mark_pkt_end(other_branch, insn->dst_reg, false);
8162                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8163                             src_reg->type == PTR_TO_PACKET) ||
8164                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8165                             src_reg->type == PTR_TO_PACKET_META)) {
8166                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8167                         find_good_pkt_pointers(other_branch, src_reg,
8168                                                src_reg->type, false);
8169                         mark_pkt_end(this_branch, insn->src_reg, true);
8170                 } else {
8171                         return false;
8172                 }
8173                 break;
8174         case BPF_JLE:
8175                 if ((dst_reg->type == PTR_TO_PACKET &&
8176                      src_reg->type == PTR_TO_PACKET_END) ||
8177                     (dst_reg->type == PTR_TO_PACKET_META &&
8178                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8179                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8180                         find_good_pkt_pointers(other_branch, dst_reg,
8181                                                dst_reg->type, false);
8182                         mark_pkt_end(this_branch, insn->dst_reg, true);
8183                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8184                             src_reg->type == PTR_TO_PACKET) ||
8185                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8186                             src_reg->type == PTR_TO_PACKET_META)) {
8187                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8188                         find_good_pkt_pointers(this_branch, src_reg,
8189                                                src_reg->type, true);
8190                         mark_pkt_end(other_branch, insn->src_reg, false);
8191                 } else {
8192                         return false;
8193                 }
8194                 break;
8195         default:
8196                 return false;
8197         }
8198
8199         return true;
8200 }
8201
8202 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8203                                struct bpf_reg_state *known_reg)
8204 {
8205         struct bpf_func_state *state;
8206         struct bpf_reg_state *reg;
8207         int i, j;
8208
8209         for (i = 0; i <= vstate->curframe; i++) {
8210                 state = vstate->frame[i];
8211                 for (j = 0; j < MAX_BPF_REG; j++) {
8212                         reg = &state->regs[j];
8213                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8214                                 *reg = *known_reg;
8215                 }
8216
8217                 bpf_for_each_spilled_reg(j, state, reg) {
8218                         if (!reg)
8219                                 continue;
8220                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8221                                 *reg = *known_reg;
8222                 }
8223         }
8224 }
8225
8226 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8227                              struct bpf_insn *insn, int *insn_idx)
8228 {
8229         struct bpf_verifier_state *this_branch = env->cur_state;
8230         struct bpf_verifier_state *other_branch;
8231         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8232         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8233         u8 opcode = BPF_OP(insn->code);
8234         bool is_jmp32;
8235         int pred = -1;
8236         int err;
8237
8238         /* Only conditional jumps are expected to reach here. */
8239         if (opcode == BPF_JA || opcode > BPF_JSLE) {
8240                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8241                 return -EINVAL;
8242         }
8243
8244         if (BPF_SRC(insn->code) == BPF_X) {
8245                 if (insn->imm != 0) {
8246                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8247                         return -EINVAL;
8248                 }
8249
8250                 /* check src1 operand */
8251                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8252                 if (err)
8253                         return err;
8254
8255                 if (is_pointer_value(env, insn->src_reg)) {
8256                         verbose(env, "R%d pointer comparison prohibited\n",
8257                                 insn->src_reg);
8258                         return -EACCES;
8259                 }
8260                 src_reg = &regs[insn->src_reg];
8261         } else {
8262                 if (insn->src_reg != BPF_REG_0) {
8263                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8264                         return -EINVAL;
8265                 }
8266         }
8267
8268         /* check src2 operand */
8269         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8270         if (err)
8271                 return err;
8272
8273         dst_reg = &regs[insn->dst_reg];
8274         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8275
8276         if (BPF_SRC(insn->code) == BPF_K) {
8277                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8278         } else if (src_reg->type == SCALAR_VALUE &&
8279                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8280                 pred = is_branch_taken(dst_reg,
8281                                        tnum_subreg(src_reg->var_off).value,
8282                                        opcode,
8283                                        is_jmp32);
8284         } else if (src_reg->type == SCALAR_VALUE &&
8285                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8286                 pred = is_branch_taken(dst_reg,
8287                                        src_reg->var_off.value,
8288                                        opcode,
8289                                        is_jmp32);
8290         } else if (reg_is_pkt_pointer_any(dst_reg) &&
8291                    reg_is_pkt_pointer_any(src_reg) &&
8292                    !is_jmp32) {
8293                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8294         }
8295
8296         if (pred >= 0) {
8297                 /* If we get here with a dst_reg pointer type it is because
8298                  * above is_branch_taken() special cased the 0 comparison.
8299                  */
8300                 if (!__is_pointer_value(false, dst_reg))
8301                         err = mark_chain_precision(env, insn->dst_reg);
8302                 if (BPF_SRC(insn->code) == BPF_X && !err &&
8303                     !__is_pointer_value(false, src_reg))
8304                         err = mark_chain_precision(env, insn->src_reg);
8305                 if (err)
8306                         return err;
8307         }
8308         if (pred == 1) {
8309                 /* only follow the goto, ignore fall-through */
8310                 *insn_idx += insn->off;
8311                 return 0;
8312         } else if (pred == 0) {
8313                 /* only follow fall-through branch, since
8314                  * that's where the program will go
8315                  */
8316                 return 0;
8317         }
8318
8319         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8320                                   false);
8321         if (!other_branch)
8322                 return -EFAULT;
8323         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8324
8325         /* detect if we are comparing against a constant value so we can adjust
8326          * our min/max values for our dst register.
8327          * this is only legit if both are scalars (or pointers to the same
8328          * object, I suppose, but we don't support that right now), because
8329          * otherwise the different base pointers mean the offsets aren't
8330          * comparable.
8331          */
8332         if (BPF_SRC(insn->code) == BPF_X) {
8333                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8334
8335                 if (dst_reg->type == SCALAR_VALUE &&
8336                     src_reg->type == SCALAR_VALUE) {
8337                         if (tnum_is_const(src_reg->var_off) ||
8338                             (is_jmp32 &&
8339                              tnum_is_const(tnum_subreg(src_reg->var_off))))
8340                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8341                                                 dst_reg,
8342                                                 src_reg->var_off.value,
8343                                                 tnum_subreg(src_reg->var_off).value,
8344                                                 opcode, is_jmp32);
8345                         else if (tnum_is_const(dst_reg->var_off) ||
8346                                  (is_jmp32 &&
8347                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
8348                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8349                                                     src_reg,
8350                                                     dst_reg->var_off.value,
8351                                                     tnum_subreg(dst_reg->var_off).value,
8352                                                     opcode, is_jmp32);
8353                         else if (!is_jmp32 &&
8354                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
8355                                 /* Comparing for equality, we can combine knowledge */
8356                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8357                                                     &other_branch_regs[insn->dst_reg],
8358                                                     src_reg, dst_reg, opcode);
8359                         if (src_reg->id &&
8360                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8361                                 find_equal_scalars(this_branch, src_reg);
8362                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8363                         }
8364
8365                 }
8366         } else if (dst_reg->type == SCALAR_VALUE) {
8367                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8368                                         dst_reg, insn->imm, (u32)insn->imm,
8369                                         opcode, is_jmp32);
8370         }
8371
8372         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8373             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8374                 find_equal_scalars(this_branch, dst_reg);
8375                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8376         }
8377
8378         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8379          * NOTE: these optimizations below are related with pointer comparison
8380          *       which will never be JMP32.
8381          */
8382         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8383             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8384             reg_type_may_be_null(dst_reg->type)) {
8385                 /* Mark all identical registers in each branch as either
8386                  * safe or unknown depending R == 0 or R != 0 conditional.
8387                  */
8388                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8389                                       opcode == BPF_JNE);
8390                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8391                                       opcode == BPF_JEQ);
8392         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8393                                            this_branch, other_branch) &&
8394                    is_pointer_value(env, insn->dst_reg)) {
8395                 verbose(env, "R%d pointer comparison prohibited\n",
8396                         insn->dst_reg);
8397                 return -EACCES;
8398         }
8399         if (env->log.level & BPF_LOG_LEVEL)
8400                 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8401         return 0;
8402 }
8403
8404 /* verify BPF_LD_IMM64 instruction */
8405 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8406 {
8407         struct bpf_insn_aux_data *aux = cur_aux(env);
8408         struct bpf_reg_state *regs = cur_regs(env);
8409         struct bpf_reg_state *dst_reg;
8410         struct bpf_map *map;
8411         int err;
8412
8413         if (BPF_SIZE(insn->code) != BPF_DW) {
8414                 verbose(env, "invalid BPF_LD_IMM insn\n");
8415                 return -EINVAL;
8416         }
8417         if (insn->off != 0) {
8418                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8419                 return -EINVAL;
8420         }
8421
8422         err = check_reg_arg(env, insn->dst_reg, DST_OP);
8423         if (err)
8424                 return err;
8425
8426         dst_reg = &regs[insn->dst_reg];
8427         if (insn->src_reg == 0) {
8428                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8429
8430                 dst_reg->type = SCALAR_VALUE;
8431                 __mark_reg_known(&regs[insn->dst_reg], imm);
8432                 return 0;
8433         }
8434
8435         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8436                 mark_reg_known_zero(env, regs, insn->dst_reg);
8437
8438                 dst_reg->type = aux->btf_var.reg_type;
8439                 switch (dst_reg->type) {
8440                 case PTR_TO_MEM:
8441                         dst_reg->mem_size = aux->btf_var.mem_size;
8442                         break;
8443                 case PTR_TO_BTF_ID:
8444                 case PTR_TO_PERCPU_BTF_ID:
8445                         dst_reg->btf = aux->btf_var.btf;
8446                         dst_reg->btf_id = aux->btf_var.btf_id;
8447                         break;
8448                 default:
8449                         verbose(env, "bpf verifier is misconfigured\n");
8450                         return -EFAULT;
8451                 }
8452                 return 0;
8453         }
8454
8455         if (insn->src_reg == BPF_PSEUDO_FUNC) {
8456                 struct bpf_prog_aux *aux = env->prog->aux;
8457                 u32 subprogno = insn[1].imm;
8458
8459                 if (!aux->func_info) {
8460                         verbose(env, "missing btf func_info\n");
8461                         return -EINVAL;
8462                 }
8463                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8464                         verbose(env, "callback function not static\n");
8465                         return -EINVAL;
8466                 }
8467
8468                 dst_reg->type = PTR_TO_FUNC;
8469                 dst_reg->subprogno = subprogno;
8470                 return 0;
8471         }
8472
8473         map = env->used_maps[aux->map_index];
8474         mark_reg_known_zero(env, regs, insn->dst_reg);
8475         dst_reg->map_ptr = map;
8476
8477         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8478                 dst_reg->type = PTR_TO_MAP_VALUE;
8479                 dst_reg->off = aux->map_off;
8480                 if (map_value_has_spin_lock(map))
8481                         dst_reg->id = ++env->id_gen;
8482         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8483                 dst_reg->type = CONST_PTR_TO_MAP;
8484         } else {
8485                 verbose(env, "bpf verifier is misconfigured\n");
8486                 return -EINVAL;
8487         }
8488
8489         return 0;
8490 }
8491
8492 static bool may_access_skb(enum bpf_prog_type type)
8493 {
8494         switch (type) {
8495         case BPF_PROG_TYPE_SOCKET_FILTER:
8496         case BPF_PROG_TYPE_SCHED_CLS:
8497         case BPF_PROG_TYPE_SCHED_ACT:
8498                 return true;
8499         default:
8500                 return false;
8501         }
8502 }
8503
8504 /* verify safety of LD_ABS|LD_IND instructions:
8505  * - they can only appear in the programs where ctx == skb
8506  * - since they are wrappers of function calls, they scratch R1-R5 registers,
8507  *   preserve R6-R9, and store return value into R0
8508  *
8509  * Implicit input:
8510  *   ctx == skb == R6 == CTX
8511  *
8512  * Explicit input:
8513  *   SRC == any register
8514  *   IMM == 32-bit immediate
8515  *
8516  * Output:
8517  *   R0 - 8/16/32-bit skb data converted to cpu endianness
8518  */
8519 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8520 {
8521         struct bpf_reg_state *regs = cur_regs(env);
8522         static const int ctx_reg = BPF_REG_6;
8523         u8 mode = BPF_MODE(insn->code);
8524         int i, err;
8525
8526         if (!may_access_skb(resolve_prog_type(env->prog))) {
8527                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8528                 return -EINVAL;
8529         }
8530
8531         if (!env->ops->gen_ld_abs) {
8532                 verbose(env, "bpf verifier is misconfigured\n");
8533                 return -EINVAL;
8534         }
8535
8536         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8537             BPF_SIZE(insn->code) == BPF_DW ||
8538             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8539                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8540                 return -EINVAL;
8541         }
8542
8543         /* check whether implicit source operand (register R6) is readable */
8544         err = check_reg_arg(env, ctx_reg, SRC_OP);
8545         if (err)
8546                 return err;
8547
8548         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8549          * gen_ld_abs() may terminate the program at runtime, leading to
8550          * reference leak.
8551          */
8552         err = check_reference_leak(env);
8553         if (err) {
8554                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8555                 return err;
8556         }
8557
8558         if (env->cur_state->active_spin_lock) {
8559                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8560                 return -EINVAL;
8561         }
8562
8563         if (regs[ctx_reg].type != PTR_TO_CTX) {
8564                 verbose(env,
8565                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8566                 return -EINVAL;
8567         }
8568
8569         if (mode == BPF_IND) {
8570                 /* check explicit source operand */
8571                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8572                 if (err)
8573                         return err;
8574         }
8575
8576         err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8577         if (err < 0)
8578                 return err;
8579
8580         /* reset caller saved regs to unreadable */
8581         for (i = 0; i < CALLER_SAVED_REGS; i++) {
8582                 mark_reg_not_init(env, regs, caller_saved[i]);
8583                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8584         }
8585
8586         /* mark destination R0 register as readable, since it contains
8587          * the value fetched from the packet.
8588          * Already marked as written above.
8589          */
8590         mark_reg_unknown(env, regs, BPF_REG_0);
8591         /* ld_abs load up to 32-bit skb data. */
8592         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8593         return 0;
8594 }
8595
8596 static int check_return_code(struct bpf_verifier_env *env)
8597 {
8598         struct tnum enforce_attach_type_range = tnum_unknown;
8599         const struct bpf_prog *prog = env->prog;
8600         struct bpf_reg_state *reg;
8601         struct tnum range = tnum_range(0, 1);
8602         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8603         int err;
8604         const bool is_subprog = env->cur_state->frame[0]->subprogno;
8605
8606         /* LSM and struct_ops func-ptr's return type could be "void" */
8607         if (!is_subprog &&
8608             (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8609              prog_type == BPF_PROG_TYPE_LSM) &&
8610             !prog->aux->attach_func_proto->type)
8611                 return 0;
8612
8613         /* eBPF calling convetion is such that R0 is used
8614          * to return the value from eBPF program.
8615          * Make sure that it's readable at this time
8616          * of bpf_exit, which means that program wrote
8617          * something into it earlier
8618          */
8619         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8620         if (err)
8621                 return err;
8622
8623         if (is_pointer_value(env, BPF_REG_0)) {
8624                 verbose(env, "R0 leaks addr as return value\n");
8625                 return -EACCES;
8626         }
8627
8628         reg = cur_regs(env) + BPF_REG_0;
8629         if (is_subprog) {
8630                 if (reg->type != SCALAR_VALUE) {
8631                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8632                                 reg_type_str[reg->type]);
8633                         return -EINVAL;
8634                 }
8635                 return 0;
8636         }
8637
8638         switch (prog_type) {
8639         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8640                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8641                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8642                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8643                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8644                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8645                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8646                         range = tnum_range(1, 1);
8647                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
8648                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
8649                         range = tnum_range(0, 3);
8650                 break;
8651         case BPF_PROG_TYPE_CGROUP_SKB:
8652                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8653                         range = tnum_range(0, 3);
8654                         enforce_attach_type_range = tnum_range(2, 3);
8655                 }
8656                 break;
8657         case BPF_PROG_TYPE_CGROUP_SOCK:
8658         case BPF_PROG_TYPE_SOCK_OPS:
8659         case BPF_PROG_TYPE_CGROUP_DEVICE:
8660         case BPF_PROG_TYPE_CGROUP_SYSCTL:
8661         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8662                 break;
8663         case BPF_PROG_TYPE_RAW_TRACEPOINT:
8664                 if (!env->prog->aux->attach_btf_id)
8665                         return 0;
8666                 range = tnum_const(0);
8667                 break;
8668         case BPF_PROG_TYPE_TRACING:
8669                 switch (env->prog->expected_attach_type) {
8670                 case BPF_TRACE_FENTRY:
8671                 case BPF_TRACE_FEXIT:
8672                         range = tnum_const(0);
8673                         break;
8674                 case BPF_TRACE_RAW_TP:
8675                 case BPF_MODIFY_RETURN:
8676                         return 0;
8677                 case BPF_TRACE_ITER:
8678                         break;
8679                 default:
8680                         return -ENOTSUPP;
8681                 }
8682                 break;
8683         case BPF_PROG_TYPE_SK_LOOKUP:
8684                 range = tnum_range(SK_DROP, SK_PASS);
8685                 break;
8686         case BPF_PROG_TYPE_EXT:
8687                 /* freplace program can return anything as its return value
8688                  * depends on the to-be-replaced kernel func or bpf program.
8689                  */
8690         default:
8691                 return 0;
8692         }
8693
8694         if (reg->type != SCALAR_VALUE) {
8695                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8696                         reg_type_str[reg->type]);
8697                 return -EINVAL;
8698         }
8699
8700         if (!tnum_in(range, reg->var_off)) {
8701                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
8702                 return -EINVAL;
8703         }
8704
8705         if (!tnum_is_unknown(enforce_attach_type_range) &&
8706             tnum_in(enforce_attach_type_range, reg->var_off))
8707                 env->prog->enforce_expected_attach_type = 1;
8708         return 0;
8709 }
8710
8711 /* non-recursive DFS pseudo code
8712  * 1  procedure DFS-iterative(G,v):
8713  * 2      label v as discovered
8714  * 3      let S be a stack
8715  * 4      S.push(v)
8716  * 5      while S is not empty
8717  * 6            t <- S.pop()
8718  * 7            if t is what we're looking for:
8719  * 8                return t
8720  * 9            for all edges e in G.adjacentEdges(t) do
8721  * 10               if edge e is already labelled
8722  * 11                   continue with the next edge
8723  * 12               w <- G.adjacentVertex(t,e)
8724  * 13               if vertex w is not discovered and not explored
8725  * 14                   label e as tree-edge
8726  * 15                   label w as discovered
8727  * 16                   S.push(w)
8728  * 17                   continue at 5
8729  * 18               else if vertex w is discovered
8730  * 19                   label e as back-edge
8731  * 20               else
8732  * 21                   // vertex w is explored
8733  * 22                   label e as forward- or cross-edge
8734  * 23           label t as explored
8735  * 24           S.pop()
8736  *
8737  * convention:
8738  * 0x10 - discovered
8739  * 0x11 - discovered and fall-through edge labelled
8740  * 0x12 - discovered and fall-through and branch edges labelled
8741  * 0x20 - explored
8742  */
8743
8744 enum {
8745         DISCOVERED = 0x10,
8746         EXPLORED = 0x20,
8747         FALLTHROUGH = 1,
8748         BRANCH = 2,
8749 };
8750
8751 static u32 state_htab_size(struct bpf_verifier_env *env)
8752 {
8753         return env->prog->len;
8754 }
8755
8756 static struct bpf_verifier_state_list **explored_state(
8757                                         struct bpf_verifier_env *env,
8758                                         int idx)
8759 {
8760         struct bpf_verifier_state *cur = env->cur_state;
8761         struct bpf_func_state *state = cur->frame[cur->curframe];
8762
8763         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8764 }
8765
8766 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8767 {
8768         env->insn_aux_data[idx].prune_point = true;
8769 }
8770
8771 enum {
8772         DONE_EXPLORING = 0,
8773         KEEP_EXPLORING = 1,
8774 };
8775
8776 /* t, w, e - match pseudo-code above:
8777  * t - index of current instruction
8778  * w - next instruction
8779  * e - edge
8780  */
8781 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8782                      bool loop_ok)
8783 {
8784         int *insn_stack = env->cfg.insn_stack;
8785         int *insn_state = env->cfg.insn_state;
8786
8787         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8788                 return DONE_EXPLORING;
8789
8790         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8791                 return DONE_EXPLORING;
8792
8793         if (w < 0 || w >= env->prog->len) {
8794                 verbose_linfo(env, t, "%d: ", t);
8795                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
8796                 return -EINVAL;
8797         }
8798
8799         if (e == BRANCH)
8800                 /* mark branch target for state pruning */
8801                 init_explored_state(env, w);
8802
8803         if (insn_state[w] == 0) {
8804                 /* tree-edge */
8805                 insn_state[t] = DISCOVERED | e;
8806                 insn_state[w] = DISCOVERED;
8807                 if (env->cfg.cur_stack >= env->prog->len)
8808                         return -E2BIG;
8809                 insn_stack[env->cfg.cur_stack++] = w;
8810                 return KEEP_EXPLORING;
8811         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8812                 if (loop_ok && env->bpf_capable)
8813                         return DONE_EXPLORING;
8814                 verbose_linfo(env, t, "%d: ", t);
8815                 verbose_linfo(env, w, "%d: ", w);
8816                 verbose(env, "back-edge from insn %d to %d\n", t, w);
8817                 return -EINVAL;
8818         } else if (insn_state[w] == EXPLORED) {
8819                 /* forward- or cross-edge */
8820                 insn_state[t] = DISCOVERED | e;
8821         } else {
8822                 verbose(env, "insn state internal bug\n");
8823                 return -EFAULT;
8824         }
8825         return DONE_EXPLORING;
8826 }
8827
8828 static int visit_func_call_insn(int t, int insn_cnt,
8829                                 struct bpf_insn *insns,
8830                                 struct bpf_verifier_env *env,
8831                                 bool visit_callee)
8832 {
8833         int ret;
8834
8835         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8836         if (ret)
8837                 return ret;
8838
8839         if (t + 1 < insn_cnt)
8840                 init_explored_state(env, t + 1);
8841         if (visit_callee) {
8842                 init_explored_state(env, t);
8843                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8844                                 env, false);
8845         }
8846         return ret;
8847 }
8848
8849 /* Visits the instruction at index t and returns one of the following:
8850  *  < 0 - an error occurred
8851  *  DONE_EXPLORING - the instruction was fully explored
8852  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
8853  */
8854 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8855 {
8856         struct bpf_insn *insns = env->prog->insnsi;
8857         int ret;
8858
8859         if (bpf_pseudo_func(insns + t))
8860                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
8861
8862         /* All non-branch instructions have a single fall-through edge. */
8863         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8864             BPF_CLASS(insns[t].code) != BPF_JMP32)
8865                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
8866
8867         switch (BPF_OP(insns[t].code)) {
8868         case BPF_EXIT:
8869                 return DONE_EXPLORING;
8870
8871         case BPF_CALL:
8872                 return visit_func_call_insn(t, insn_cnt, insns, env,
8873                                             insns[t].src_reg == BPF_PSEUDO_CALL);
8874
8875         case BPF_JA:
8876                 if (BPF_SRC(insns[t].code) != BPF_K)
8877                         return -EINVAL;
8878
8879                 /* unconditional jump with single edge */
8880                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8881                                 true);
8882                 if (ret)
8883                         return ret;
8884
8885                 /* unconditional jmp is not a good pruning point,
8886                  * but it's marked, since backtracking needs
8887                  * to record jmp history in is_state_visited().
8888                  */
8889                 init_explored_state(env, t + insns[t].off + 1);
8890                 /* tell verifier to check for equivalent states
8891                  * after every call and jump
8892                  */
8893                 if (t + 1 < insn_cnt)
8894                         init_explored_state(env, t + 1);
8895
8896                 return ret;
8897
8898         default:
8899                 /* conditional jump with two edges */
8900                 init_explored_state(env, t);
8901                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8902                 if (ret)
8903                         return ret;
8904
8905                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8906         }
8907 }
8908
8909 /* non-recursive depth-first-search to detect loops in BPF program
8910  * loop == back-edge in directed graph
8911  */
8912 static int check_cfg(struct bpf_verifier_env *env)
8913 {
8914         int insn_cnt = env->prog->len;
8915         int *insn_stack, *insn_state;
8916         int ret = 0;
8917         int i;
8918
8919         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8920         if (!insn_state)
8921                 return -ENOMEM;
8922
8923         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8924         if (!insn_stack) {
8925                 kvfree(insn_state);
8926                 return -ENOMEM;
8927         }
8928
8929         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8930         insn_stack[0] = 0; /* 0 is the first instruction */
8931         env->cfg.cur_stack = 1;
8932
8933         while (env->cfg.cur_stack > 0) {
8934                 int t = insn_stack[env->cfg.cur_stack - 1];
8935
8936                 ret = visit_insn(t, insn_cnt, env);
8937                 switch (ret) {
8938                 case DONE_EXPLORING:
8939                         insn_state[t] = EXPLORED;
8940                         env->cfg.cur_stack--;
8941                         break;
8942                 case KEEP_EXPLORING:
8943                         break;
8944                 default:
8945                         if (ret > 0) {
8946                                 verbose(env, "visit_insn internal bug\n");
8947                                 ret = -EFAULT;
8948                         }
8949                         goto err_free;
8950                 }
8951         }
8952
8953         if (env->cfg.cur_stack < 0) {
8954                 verbose(env, "pop stack internal bug\n");
8955                 ret = -EFAULT;
8956                 goto err_free;
8957         }
8958
8959         for (i = 0; i < insn_cnt; i++) {
8960                 if (insn_state[i] != EXPLORED) {
8961                         verbose(env, "unreachable insn %d\n", i);
8962                         ret = -EINVAL;
8963                         goto err_free;
8964                 }
8965         }
8966         ret = 0; /* cfg looks good */
8967
8968 err_free:
8969         kvfree(insn_state);
8970         kvfree(insn_stack);
8971         env->cfg.insn_state = env->cfg.insn_stack = NULL;
8972         return ret;
8973 }
8974
8975 static int check_abnormal_return(struct bpf_verifier_env *env)
8976 {
8977         int i;
8978
8979         for (i = 1; i < env->subprog_cnt; i++) {
8980                 if (env->subprog_info[i].has_ld_abs) {
8981                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8982                         return -EINVAL;
8983                 }
8984                 if (env->subprog_info[i].has_tail_call) {
8985                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8986                         return -EINVAL;
8987                 }
8988         }
8989         return 0;
8990 }
8991
8992 /* The minimum supported BTF func info size */
8993 #define MIN_BPF_FUNCINFO_SIZE   8
8994 #define MAX_FUNCINFO_REC_SIZE   252
8995
8996 static int check_btf_func(struct bpf_verifier_env *env,
8997                           const union bpf_attr *attr,
8998                           union bpf_attr __user *uattr)
8999 {
9000         const struct btf_type *type, *func_proto, *ret_type;
9001         u32 i, nfuncs, urec_size, min_size;
9002         u32 krec_size = sizeof(struct bpf_func_info);
9003         struct bpf_func_info *krecord;
9004         struct bpf_func_info_aux *info_aux = NULL;
9005         struct bpf_prog *prog;
9006         const struct btf *btf;
9007         void __user *urecord;
9008         u32 prev_offset = 0;
9009         bool scalar_return;
9010         int ret = -ENOMEM;
9011
9012         nfuncs = attr->func_info_cnt;
9013         if (!nfuncs) {
9014                 if (check_abnormal_return(env))
9015                         return -EINVAL;
9016                 return 0;
9017         }
9018
9019         if (nfuncs != env->subprog_cnt) {
9020                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9021                 return -EINVAL;
9022         }
9023
9024         urec_size = attr->func_info_rec_size;
9025         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9026             urec_size > MAX_FUNCINFO_REC_SIZE ||
9027             urec_size % sizeof(u32)) {
9028                 verbose(env, "invalid func info rec size %u\n", urec_size);
9029                 return -EINVAL;
9030         }
9031
9032         prog = env->prog;
9033         btf = prog->aux->btf;
9034
9035         urecord = u64_to_user_ptr(attr->func_info);
9036         min_size = min_t(u32, krec_size, urec_size);
9037
9038         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9039         if (!krecord)
9040                 return -ENOMEM;
9041         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9042         if (!info_aux)
9043                 goto err_free;
9044
9045         for (i = 0; i < nfuncs; i++) {
9046                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9047                 if (ret) {
9048                         if (ret == -E2BIG) {
9049                                 verbose(env, "nonzero tailing record in func info");
9050                                 /* set the size kernel expects so loader can zero
9051                                  * out the rest of the record.
9052                                  */
9053                                 if (put_user(min_size, &uattr->func_info_rec_size))
9054                                         ret = -EFAULT;
9055                         }
9056                         goto err_free;
9057                 }
9058
9059                 if (copy_from_user(&krecord[i], urecord, min_size)) {
9060                         ret = -EFAULT;
9061                         goto err_free;
9062                 }
9063
9064                 /* check insn_off */
9065                 ret = -EINVAL;
9066                 if (i == 0) {
9067                         if (krecord[i].insn_off) {
9068                                 verbose(env,
9069                                         "nonzero insn_off %u for the first func info record",
9070                                         krecord[i].insn_off);
9071                                 goto err_free;
9072                         }
9073                 } else if (krecord[i].insn_off <= prev_offset) {
9074                         verbose(env,
9075                                 "same or smaller insn offset (%u) than previous func info record (%u)",
9076                                 krecord[i].insn_off, prev_offset);
9077                         goto err_free;
9078                 }
9079
9080                 if (env->subprog_info[i].start != krecord[i].insn_off) {
9081                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9082                         goto err_free;
9083                 }
9084
9085                 /* check type_id */
9086                 type = btf_type_by_id(btf, krecord[i].type_id);
9087                 if (!type || !btf_type_is_func(type)) {
9088                         verbose(env, "invalid type id %d in func info",
9089                                 krecord[i].type_id);
9090                         goto err_free;
9091                 }
9092                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9093
9094                 func_proto = btf_type_by_id(btf, type->type);
9095                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9096                         /* btf_func_check() already verified it during BTF load */
9097                         goto err_free;
9098                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9099                 scalar_return =
9100                         btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9101                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9102                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9103                         goto err_free;
9104                 }
9105                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9106                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9107                         goto err_free;
9108                 }
9109
9110                 prev_offset = krecord[i].insn_off;
9111                 urecord += urec_size;
9112         }
9113
9114         prog->aux->func_info = krecord;
9115         prog->aux->func_info_cnt = nfuncs;
9116         prog->aux->func_info_aux = info_aux;
9117         return 0;
9118
9119 err_free:
9120         kvfree(krecord);
9121         kfree(info_aux);
9122         return ret;
9123 }
9124
9125 static void adjust_btf_func(struct bpf_verifier_env *env)
9126 {
9127         struct bpf_prog_aux *aux = env->prog->aux;
9128         int i;
9129
9130         if (!aux->func_info)
9131                 return;
9132
9133         for (i = 0; i < env->subprog_cnt; i++)
9134                 aux->func_info[i].insn_off = env->subprog_info[i].start;
9135 }
9136
9137 #define MIN_BPF_LINEINFO_SIZE   (offsetof(struct bpf_line_info, line_col) + \
9138                 sizeof(((struct bpf_line_info *)(0))->line_col))
9139 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
9140
9141 static int check_btf_line(struct bpf_verifier_env *env,
9142                           const union bpf_attr *attr,
9143                           union bpf_attr __user *uattr)
9144 {
9145         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9146         struct bpf_subprog_info *sub;
9147         struct bpf_line_info *linfo;
9148         struct bpf_prog *prog;
9149         const struct btf *btf;
9150         void __user *ulinfo;
9151         int err;
9152
9153         nr_linfo = attr->line_info_cnt;
9154         if (!nr_linfo)
9155                 return 0;
9156
9157         rec_size = attr->line_info_rec_size;
9158         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9159             rec_size > MAX_LINEINFO_REC_SIZE ||
9160             rec_size & (sizeof(u32) - 1))
9161                 return -EINVAL;
9162
9163         /* Need to zero it in case the userspace may
9164          * pass in a smaller bpf_line_info object.
9165          */
9166         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9167                          GFP_KERNEL | __GFP_NOWARN);
9168         if (!linfo)
9169                 return -ENOMEM;
9170
9171         prog = env->prog;
9172         btf = prog->aux->btf;
9173
9174         s = 0;
9175         sub = env->subprog_info;
9176         ulinfo = u64_to_user_ptr(attr->line_info);
9177         expected_size = sizeof(struct bpf_line_info);
9178         ncopy = min_t(u32, expected_size, rec_size);
9179         for (i = 0; i < nr_linfo; i++) {
9180                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9181                 if (err) {
9182                         if (err == -E2BIG) {
9183                                 verbose(env, "nonzero tailing record in line_info");
9184                                 if (put_user(expected_size,
9185                                              &uattr->line_info_rec_size))
9186                                         err = -EFAULT;
9187                         }
9188                         goto err_free;
9189                 }
9190
9191                 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9192                         err = -EFAULT;
9193                         goto err_free;
9194                 }
9195
9196                 /*
9197                  * Check insn_off to ensure
9198                  * 1) strictly increasing AND
9199                  * 2) bounded by prog->len
9200                  *
9201                  * The linfo[0].insn_off == 0 check logically falls into
9202                  * the later "missing bpf_line_info for func..." case
9203                  * because the first linfo[0].insn_off must be the
9204                  * first sub also and the first sub must have
9205                  * subprog_info[0].start == 0.
9206                  */
9207                 if ((i && linfo[i].insn_off <= prev_offset) ||
9208                     linfo[i].insn_off >= prog->len) {
9209                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9210                                 i, linfo[i].insn_off, prev_offset,
9211                                 prog->len);
9212                         err = -EINVAL;
9213                         goto err_free;
9214                 }
9215
9216                 if (!prog->insnsi[linfo[i].insn_off].code) {
9217                         verbose(env,
9218                                 "Invalid insn code at line_info[%u].insn_off\n",
9219                                 i);
9220                         err = -EINVAL;
9221                         goto err_free;
9222                 }
9223
9224                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9225                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9226                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9227                         err = -EINVAL;
9228                         goto err_free;
9229                 }
9230
9231                 if (s != env->subprog_cnt) {
9232                         if (linfo[i].insn_off == sub[s].start) {
9233                                 sub[s].linfo_idx = i;
9234                                 s++;
9235                         } else if (sub[s].start < linfo[i].insn_off) {
9236                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
9237                                 err = -EINVAL;
9238                                 goto err_free;
9239                         }
9240                 }
9241
9242                 prev_offset = linfo[i].insn_off;
9243                 ulinfo += rec_size;
9244         }
9245
9246         if (s != env->subprog_cnt) {
9247                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9248                         env->subprog_cnt - s, s);
9249                 err = -EINVAL;
9250                 goto err_free;
9251         }
9252
9253         prog->aux->linfo = linfo;
9254         prog->aux->nr_linfo = nr_linfo;
9255
9256         return 0;
9257
9258 err_free:
9259         kvfree(linfo);
9260         return err;
9261 }
9262
9263 static int check_btf_info(struct bpf_verifier_env *env,
9264                           const union bpf_attr *attr,
9265                           union bpf_attr __user *uattr)
9266 {
9267         struct btf *btf;
9268         int err;
9269
9270         if (!attr->func_info_cnt && !attr->line_info_cnt) {
9271                 if (check_abnormal_return(env))
9272                         return -EINVAL;
9273                 return 0;
9274         }
9275
9276         btf = btf_get_by_fd(attr->prog_btf_fd);
9277         if (IS_ERR(btf))
9278                 return PTR_ERR(btf);
9279         env->prog->aux->btf = btf;
9280
9281         err = check_btf_func(env, attr, uattr);
9282         if (err)
9283                 return err;
9284
9285         err = check_btf_line(env, attr, uattr);
9286         if (err)
9287                 return err;
9288
9289         return 0;
9290 }
9291
9292 /* check %cur's range satisfies %old's */
9293 static bool range_within(struct bpf_reg_state *old,
9294                          struct bpf_reg_state *cur)
9295 {
9296         return old->umin_value <= cur->umin_value &&
9297                old->umax_value >= cur->umax_value &&
9298                old->smin_value <= cur->smin_value &&
9299                old->smax_value >= cur->smax_value &&
9300                old->u32_min_value <= cur->u32_min_value &&
9301                old->u32_max_value >= cur->u32_max_value &&
9302                old->s32_min_value <= cur->s32_min_value &&
9303                old->s32_max_value >= cur->s32_max_value;
9304 }
9305
9306 /* Maximum number of register states that can exist at once */
9307 #define ID_MAP_SIZE     (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9308 struct idpair {
9309         u32 old;
9310         u32 cur;
9311 };
9312
9313 /* If in the old state two registers had the same id, then they need to have
9314  * the same id in the new state as well.  But that id could be different from
9315  * the old state, so we need to track the mapping from old to new ids.
9316  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9317  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9318  * regs with a different old id could still have new id 9, we don't care about
9319  * that.
9320  * So we look through our idmap to see if this old id has been seen before.  If
9321  * so, we require the new id to match; otherwise, we add the id pair to the map.
9322  */
9323 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9324 {
9325         unsigned int i;
9326
9327         for (i = 0; i < ID_MAP_SIZE; i++) {
9328                 if (!idmap[i].old) {
9329                         /* Reached an empty slot; haven't seen this id before */
9330                         idmap[i].old = old_id;
9331                         idmap[i].cur = cur_id;
9332                         return true;
9333                 }
9334                 if (idmap[i].old == old_id)
9335                         return idmap[i].cur == cur_id;
9336         }
9337         /* We ran out of idmap slots, which should be impossible */
9338         WARN_ON_ONCE(1);
9339         return false;
9340 }
9341
9342 static void clean_func_state(struct bpf_verifier_env *env,
9343                              struct bpf_func_state *st)
9344 {
9345         enum bpf_reg_liveness live;
9346         int i, j;
9347
9348         for (i = 0; i < BPF_REG_FP; i++) {
9349                 live = st->regs[i].live;
9350                 /* liveness must not touch this register anymore */
9351                 st->regs[i].live |= REG_LIVE_DONE;
9352                 if (!(live & REG_LIVE_READ))
9353                         /* since the register is unused, clear its state
9354                          * to make further comparison simpler
9355                          */
9356                         __mark_reg_not_init(env, &st->regs[i]);
9357         }
9358
9359         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9360                 live = st->stack[i].spilled_ptr.live;
9361                 /* liveness must not touch this stack slot anymore */
9362                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9363                 if (!(live & REG_LIVE_READ)) {
9364                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9365                         for (j = 0; j < BPF_REG_SIZE; j++)
9366                                 st->stack[i].slot_type[j] = STACK_INVALID;
9367                 }
9368         }
9369 }
9370
9371 static void clean_verifier_state(struct bpf_verifier_env *env,
9372                                  struct bpf_verifier_state *st)
9373 {
9374         int i;
9375
9376         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9377                 /* all regs in this state in all frames were already marked */
9378                 return;
9379
9380         for (i = 0; i <= st->curframe; i++)
9381                 clean_func_state(env, st->frame[i]);
9382 }
9383
9384 /* the parentage chains form a tree.
9385  * the verifier states are added to state lists at given insn and
9386  * pushed into state stack for future exploration.
9387  * when the verifier reaches bpf_exit insn some of the verifer states
9388  * stored in the state lists have their final liveness state already,
9389  * but a lot of states will get revised from liveness point of view when
9390  * the verifier explores other branches.
9391  * Example:
9392  * 1: r0 = 1
9393  * 2: if r1 == 100 goto pc+1
9394  * 3: r0 = 2
9395  * 4: exit
9396  * when the verifier reaches exit insn the register r0 in the state list of
9397  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9398  * of insn 2 and goes exploring further. At the insn 4 it will walk the
9399  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9400  *
9401  * Since the verifier pushes the branch states as it sees them while exploring
9402  * the program the condition of walking the branch instruction for the second
9403  * time means that all states below this branch were already explored and
9404  * their final liveness markes are already propagated.
9405  * Hence when the verifier completes the search of state list in is_state_visited()
9406  * we can call this clean_live_states() function to mark all liveness states
9407  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9408  * will not be used.
9409  * This function also clears the registers and stack for states that !READ
9410  * to simplify state merging.
9411  *
9412  * Important note here that walking the same branch instruction in the callee
9413  * doesn't meant that the states are DONE. The verifier has to compare
9414  * the callsites
9415  */
9416 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9417                               struct bpf_verifier_state *cur)
9418 {
9419         struct bpf_verifier_state_list *sl;
9420         int i;
9421
9422         sl = *explored_state(env, insn);
9423         while (sl) {
9424                 if (sl->state.branches)
9425                         goto next;
9426                 if (sl->state.insn_idx != insn ||
9427                     sl->state.curframe != cur->curframe)
9428                         goto next;
9429                 for (i = 0; i <= cur->curframe; i++)
9430                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9431                                 goto next;
9432                 clean_verifier_state(env, &sl->state);
9433 next:
9434                 sl = sl->next;
9435         }
9436 }
9437
9438 /* Returns true if (rold safe implies rcur safe) */
9439 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9440                     struct idpair *idmap)
9441 {
9442         bool equal;
9443
9444         if (!(rold->live & REG_LIVE_READ))
9445                 /* explored state didn't use this */
9446                 return true;
9447
9448         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9449
9450         if (rold->type == PTR_TO_STACK)
9451                 /* two stack pointers are equal only if they're pointing to
9452                  * the same stack frame, since fp-8 in foo != fp-8 in bar
9453                  */
9454                 return equal && rold->frameno == rcur->frameno;
9455
9456         if (equal)
9457                 return true;
9458
9459         if (rold->type == NOT_INIT)
9460                 /* explored state can't have used this */
9461                 return true;
9462         if (rcur->type == NOT_INIT)
9463                 return false;
9464         switch (rold->type) {
9465         case SCALAR_VALUE:
9466                 if (rcur->type == SCALAR_VALUE) {
9467                         if (!rold->precise && !rcur->precise)
9468                                 return true;
9469                         /* new val must satisfy old val knowledge */
9470                         return range_within(rold, rcur) &&
9471                                tnum_in(rold->var_off, rcur->var_off);
9472                 } else {
9473                         /* We're trying to use a pointer in place of a scalar.
9474                          * Even if the scalar was unbounded, this could lead to
9475                          * pointer leaks because scalars are allowed to leak
9476                          * while pointers are not. We could make this safe in
9477                          * special cases if root is calling us, but it's
9478                          * probably not worth the hassle.
9479                          */
9480                         return false;
9481                 }
9482         case PTR_TO_MAP_KEY:
9483         case PTR_TO_MAP_VALUE:
9484                 /* If the new min/max/var_off satisfy the old ones and
9485                  * everything else matches, we are OK.
9486                  * 'id' is not compared, since it's only used for maps with
9487                  * bpf_spin_lock inside map element and in such cases if
9488                  * the rest of the prog is valid for one map element then
9489                  * it's valid for all map elements regardless of the key
9490                  * used in bpf_map_lookup()
9491                  */
9492                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9493                        range_within(rold, rcur) &&
9494                        tnum_in(rold->var_off, rcur->var_off);
9495         case PTR_TO_MAP_VALUE_OR_NULL:
9496                 /* a PTR_TO_MAP_VALUE could be safe to use as a
9497                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9498                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9499                  * checked, doing so could have affected others with the same
9500                  * id, and we can't check for that because we lost the id when
9501                  * we converted to a PTR_TO_MAP_VALUE.
9502                  */
9503                 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9504                         return false;
9505                 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9506                         return false;
9507                 /* Check our ids match any regs they're supposed to */
9508                 return check_ids(rold->id, rcur->id, idmap);
9509         case PTR_TO_PACKET_META:
9510         case PTR_TO_PACKET:
9511                 if (rcur->type != rold->type)
9512                         return false;
9513                 /* We must have at least as much range as the old ptr
9514                  * did, so that any accesses which were safe before are
9515                  * still safe.  This is true even if old range < old off,
9516                  * since someone could have accessed through (ptr - k), or
9517                  * even done ptr -= k in a register, to get a safe access.
9518                  */
9519                 if (rold->range > rcur->range)
9520                         return false;
9521                 /* If the offsets don't match, we can't trust our alignment;
9522                  * nor can we be sure that we won't fall out of range.
9523                  */
9524                 if (rold->off != rcur->off)
9525                         return false;
9526                 /* id relations must be preserved */
9527                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9528                         return false;
9529                 /* new val must satisfy old val knowledge */
9530                 return range_within(rold, rcur) &&
9531                        tnum_in(rold->var_off, rcur->var_off);
9532         case PTR_TO_CTX:
9533         case CONST_PTR_TO_MAP:
9534         case PTR_TO_PACKET_END:
9535         case PTR_TO_FLOW_KEYS:
9536         case PTR_TO_SOCKET:
9537         case PTR_TO_SOCKET_OR_NULL:
9538         case PTR_TO_SOCK_COMMON:
9539         case PTR_TO_SOCK_COMMON_OR_NULL:
9540         case PTR_TO_TCP_SOCK:
9541         case PTR_TO_TCP_SOCK_OR_NULL:
9542         case PTR_TO_XDP_SOCK:
9543                 /* Only valid matches are exact, which memcmp() above
9544                  * would have accepted
9545                  */
9546         default:
9547                 /* Don't know what's going on, just say it's not safe */
9548                 return false;
9549         }
9550
9551         /* Shouldn't get here; if we do, say it's not safe */
9552         WARN_ON_ONCE(1);
9553         return false;
9554 }
9555
9556 static bool stacksafe(struct bpf_func_state *old,
9557                       struct bpf_func_state *cur,
9558                       struct idpair *idmap)
9559 {
9560         int i, spi;
9561
9562         /* walk slots of the explored stack and ignore any additional
9563          * slots in the current stack, since explored(safe) state
9564          * didn't use them
9565          */
9566         for (i = 0; i < old->allocated_stack; i++) {
9567                 spi = i / BPF_REG_SIZE;
9568
9569                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9570                         i += BPF_REG_SIZE - 1;
9571                         /* explored state didn't use this */
9572                         continue;
9573                 }
9574
9575                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9576                         continue;
9577
9578                 /* explored stack has more populated slots than current stack
9579                  * and these slots were used
9580                  */
9581                 if (i >= cur->allocated_stack)
9582                         return false;
9583
9584                 /* if old state was safe with misc data in the stack
9585                  * it will be safe with zero-initialized stack.
9586                  * The opposite is not true
9587                  */
9588                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9589                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9590                         continue;
9591                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9592                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9593                         /* Ex: old explored (safe) state has STACK_SPILL in
9594                          * this stack slot, but current has STACK_MISC ->
9595                          * this verifier states are not equivalent,
9596                          * return false to continue verification of this path
9597                          */
9598                         return false;
9599                 if (i % BPF_REG_SIZE)
9600                         continue;
9601                 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9602                         continue;
9603                 if (!regsafe(&old->stack[spi].spilled_ptr,
9604                              &cur->stack[spi].spilled_ptr,
9605                              idmap))
9606                         /* when explored and current stack slot are both storing
9607                          * spilled registers, check that stored pointers types
9608                          * are the same as well.
9609                          * Ex: explored safe path could have stored
9610                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9611                          * but current path has stored:
9612                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9613                          * such verifier states are not equivalent.
9614                          * return false to continue verification of this path
9615                          */
9616                         return false;
9617         }
9618         return true;
9619 }
9620
9621 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9622 {
9623         if (old->acquired_refs != cur->acquired_refs)
9624                 return false;
9625         return !memcmp(old->refs, cur->refs,
9626                        sizeof(*old->refs) * old->acquired_refs);
9627 }
9628
9629 /* compare two verifier states
9630  *
9631  * all states stored in state_list are known to be valid, since
9632  * verifier reached 'bpf_exit' instruction through them
9633  *
9634  * this function is called when verifier exploring different branches of
9635  * execution popped from the state stack. If it sees an old state that has
9636  * more strict register state and more strict stack state then this execution
9637  * branch doesn't need to be explored further, since verifier already
9638  * concluded that more strict state leads to valid finish.
9639  *
9640  * Therefore two states are equivalent if register state is more conservative
9641  * and explored stack state is more conservative than the current one.
9642  * Example:
9643  *       explored                   current
9644  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9645  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9646  *
9647  * In other words if current stack state (one being explored) has more
9648  * valid slots than old one that already passed validation, it means
9649  * the verifier can stop exploring and conclude that current state is valid too
9650  *
9651  * Similarly with registers. If explored state has register type as invalid
9652  * whereas register type in current state is meaningful, it means that
9653  * the current state will reach 'bpf_exit' instruction safely
9654  */
9655 static bool func_states_equal(struct bpf_func_state *old,
9656                               struct bpf_func_state *cur)
9657 {
9658         struct idpair *idmap;
9659         bool ret = false;
9660         int i;
9661
9662         idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9663         /* If we failed to allocate the idmap, just say it's not safe */
9664         if (!idmap)
9665                 return false;
9666
9667         for (i = 0; i < MAX_BPF_REG; i++) {
9668                 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
9669                         goto out_free;
9670         }
9671
9672         if (!stacksafe(old, cur, idmap))
9673                 goto out_free;
9674
9675         if (!refsafe(old, cur))
9676                 goto out_free;
9677         ret = true;
9678 out_free:
9679         kfree(idmap);
9680         return ret;
9681 }
9682
9683 static bool states_equal(struct bpf_verifier_env *env,
9684                          struct bpf_verifier_state *old,
9685                          struct bpf_verifier_state *cur)
9686 {
9687         int i;
9688
9689         if (old->curframe != cur->curframe)
9690                 return false;
9691
9692         /* Verification state from speculative execution simulation
9693          * must never prune a non-speculative execution one.
9694          */
9695         if (old->speculative && !cur->speculative)
9696                 return false;
9697
9698         if (old->active_spin_lock != cur->active_spin_lock)
9699                 return false;
9700
9701         /* for states to be equal callsites have to be the same
9702          * and all frame states need to be equivalent
9703          */
9704         for (i = 0; i <= old->curframe; i++) {
9705                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9706                         return false;
9707                 if (!func_states_equal(old->frame[i], cur->frame[i]))
9708                         return false;
9709         }
9710         return true;
9711 }
9712
9713 /* Return 0 if no propagation happened. Return negative error code if error
9714  * happened. Otherwise, return the propagated bit.
9715  */
9716 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9717                                   struct bpf_reg_state *reg,
9718                                   struct bpf_reg_state *parent_reg)
9719 {
9720         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9721         u8 flag = reg->live & REG_LIVE_READ;
9722         int err;
9723
9724         /* When comes here, read flags of PARENT_REG or REG could be any of
9725          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9726          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9727          */
9728         if (parent_flag == REG_LIVE_READ64 ||
9729             /* Or if there is no read flag from REG. */
9730             !flag ||
9731             /* Or if the read flag from REG is the same as PARENT_REG. */
9732             parent_flag == flag)
9733                 return 0;
9734
9735         err = mark_reg_read(env, reg, parent_reg, flag);
9736         if (err)
9737                 return err;
9738
9739         return flag;
9740 }
9741
9742 /* A write screens off any subsequent reads; but write marks come from the
9743  * straight-line code between a state and its parent.  When we arrive at an
9744  * equivalent state (jump target or such) we didn't arrive by the straight-line
9745  * code, so read marks in the state must propagate to the parent regardless
9746  * of the state's write marks. That's what 'parent == state->parent' comparison
9747  * in mark_reg_read() is for.
9748  */
9749 static int propagate_liveness(struct bpf_verifier_env *env,
9750                               const struct bpf_verifier_state *vstate,
9751                               struct bpf_verifier_state *vparent)
9752 {
9753         struct bpf_reg_state *state_reg, *parent_reg;
9754         struct bpf_func_state *state, *parent;
9755         int i, frame, err = 0;
9756
9757         if (vparent->curframe != vstate->curframe) {
9758                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9759                      vparent->curframe, vstate->curframe);
9760                 return -EFAULT;
9761         }
9762         /* Propagate read liveness of registers... */
9763         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9764         for (frame = 0; frame <= vstate->curframe; frame++) {
9765                 parent = vparent->frame[frame];
9766                 state = vstate->frame[frame];
9767                 parent_reg = parent->regs;
9768                 state_reg = state->regs;
9769                 /* We don't need to worry about FP liveness, it's read-only */
9770                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9771                         err = propagate_liveness_reg(env, &state_reg[i],
9772                                                      &parent_reg[i]);
9773                         if (err < 0)
9774                                 return err;
9775                         if (err == REG_LIVE_READ64)
9776                                 mark_insn_zext(env, &parent_reg[i]);
9777                 }
9778
9779                 /* Propagate stack slots. */
9780                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9781                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9782                         parent_reg = &parent->stack[i].spilled_ptr;
9783                         state_reg = &state->stack[i].spilled_ptr;
9784                         err = propagate_liveness_reg(env, state_reg,
9785                                                      parent_reg);
9786                         if (err < 0)
9787                                 return err;
9788                 }
9789         }
9790         return 0;
9791 }
9792
9793 /* find precise scalars in the previous equivalent state and
9794  * propagate them into the current state
9795  */
9796 static int propagate_precision(struct bpf_verifier_env *env,
9797                                const struct bpf_verifier_state *old)
9798 {
9799         struct bpf_reg_state *state_reg;
9800         struct bpf_func_state *state;
9801         int i, err = 0;
9802
9803         state = old->frame[old->curframe];
9804         state_reg = state->regs;
9805         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9806                 if (state_reg->type != SCALAR_VALUE ||
9807                     !state_reg->precise)
9808                         continue;
9809                 if (env->log.level & BPF_LOG_LEVEL2)
9810                         verbose(env, "propagating r%d\n", i);
9811                 err = mark_chain_precision(env, i);
9812                 if (err < 0)
9813                         return err;
9814         }
9815
9816         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9817                 if (state->stack[i].slot_type[0] != STACK_SPILL)
9818                         continue;
9819                 state_reg = &state->stack[i].spilled_ptr;
9820                 if (state_reg->type != SCALAR_VALUE ||
9821                     !state_reg->precise)
9822                         continue;
9823                 if (env->log.level & BPF_LOG_LEVEL2)
9824                         verbose(env, "propagating fp%d\n",
9825                                 (-i - 1) * BPF_REG_SIZE);
9826                 err = mark_chain_precision_stack(env, i);
9827                 if (err < 0)
9828                         return err;
9829         }
9830         return 0;
9831 }
9832
9833 static bool states_maybe_looping(struct bpf_verifier_state *old,
9834                                  struct bpf_verifier_state *cur)
9835 {
9836         struct bpf_func_state *fold, *fcur;
9837         int i, fr = cur->curframe;
9838
9839         if (old->curframe != fr)
9840                 return false;
9841
9842         fold = old->frame[fr];
9843         fcur = cur->frame[fr];
9844         for (i = 0; i < MAX_BPF_REG; i++)
9845                 if (memcmp(&fold->regs[i], &fcur->regs[i],
9846                            offsetof(struct bpf_reg_state, parent)))
9847                         return false;
9848         return true;
9849 }
9850
9851
9852 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9853 {
9854         struct bpf_verifier_state_list *new_sl;
9855         struct bpf_verifier_state_list *sl, **pprev;
9856         struct bpf_verifier_state *cur = env->cur_state, *new;
9857         int i, j, err, states_cnt = 0;
9858         bool add_new_state = env->test_state_freq ? true : false;
9859
9860         cur->last_insn_idx = env->prev_insn_idx;
9861         if (!env->insn_aux_data[insn_idx].prune_point)
9862                 /* this 'insn_idx' instruction wasn't marked, so we will not
9863                  * be doing state search here
9864                  */
9865                 return 0;
9866
9867         /* bpf progs typically have pruning point every 4 instructions
9868          * http://vger.kernel.org/bpfconf2019.html#session-1
9869          * Do not add new state for future pruning if the verifier hasn't seen
9870          * at least 2 jumps and at least 8 instructions.
9871          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9872          * In tests that amounts to up to 50% reduction into total verifier
9873          * memory consumption and 20% verifier time speedup.
9874          */
9875         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9876             env->insn_processed - env->prev_insn_processed >= 8)
9877                 add_new_state = true;
9878
9879         pprev = explored_state(env, insn_idx);
9880         sl = *pprev;
9881
9882         clean_live_states(env, insn_idx, cur);
9883
9884         while (sl) {
9885                 states_cnt++;
9886                 if (sl->state.insn_idx != insn_idx)
9887                         goto next;
9888                 if (sl->state.branches) {
9889                         if (states_maybe_looping(&sl->state, cur) &&
9890                             states_equal(env, &sl->state, cur)) {
9891                                 verbose_linfo(env, insn_idx, "; ");
9892                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9893                                 return -EINVAL;
9894                         }
9895                         /* if the verifier is processing a loop, avoid adding new state
9896                          * too often, since different loop iterations have distinct
9897                          * states and may not help future pruning.
9898                          * This threshold shouldn't be too low to make sure that
9899                          * a loop with large bound will be rejected quickly.
9900                          * The most abusive loop will be:
9901                          * r1 += 1
9902                          * if r1 < 1000000 goto pc-2
9903                          * 1M insn_procssed limit / 100 == 10k peak states.
9904                          * This threshold shouldn't be too high either, since states
9905                          * at the end of the loop are likely to be useful in pruning.
9906                          */
9907                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9908                             env->insn_processed - env->prev_insn_processed < 100)
9909                                 add_new_state = false;
9910                         goto miss;
9911                 }
9912                 if (states_equal(env, &sl->state, cur)) {
9913                         sl->hit_cnt++;
9914                         /* reached equivalent register/stack state,
9915                          * prune the search.
9916                          * Registers read by the continuation are read by us.
9917                          * If we have any write marks in env->cur_state, they
9918                          * will prevent corresponding reads in the continuation
9919                          * from reaching our parent (an explored_state).  Our
9920                          * own state will get the read marks recorded, but
9921                          * they'll be immediately forgotten as we're pruning
9922                          * this state and will pop a new one.
9923                          */
9924                         err = propagate_liveness(env, &sl->state, cur);
9925
9926                         /* if previous state reached the exit with precision and
9927                          * current state is equivalent to it (except precsion marks)
9928                          * the precision needs to be propagated back in
9929                          * the current state.
9930                          */
9931                         err = err ? : push_jmp_history(env, cur);
9932                         err = err ? : propagate_precision(env, &sl->state);
9933                         if (err)
9934                                 return err;
9935                         return 1;
9936                 }
9937 miss:
9938                 /* when new state is not going to be added do not increase miss count.
9939                  * Otherwise several loop iterations will remove the state
9940                  * recorded earlier. The goal of these heuristics is to have
9941                  * states from some iterations of the loop (some in the beginning
9942                  * and some at the end) to help pruning.
9943                  */
9944                 if (add_new_state)
9945                         sl->miss_cnt++;
9946                 /* heuristic to determine whether this state is beneficial
9947                  * to keep checking from state equivalence point of view.
9948                  * Higher numbers increase max_states_per_insn and verification time,
9949                  * but do not meaningfully decrease insn_processed.
9950                  */
9951                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9952                         /* the state is unlikely to be useful. Remove it to
9953                          * speed up verification
9954                          */
9955                         *pprev = sl->next;
9956                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9957                                 u32 br = sl->state.branches;
9958
9959                                 WARN_ONCE(br,
9960                                           "BUG live_done but branches_to_explore %d\n",
9961                                           br);
9962                                 free_verifier_state(&sl->state, false);
9963                                 kfree(sl);
9964                                 env->peak_states--;
9965                         } else {
9966                                 /* cannot free this state, since parentage chain may
9967                                  * walk it later. Add it for free_list instead to
9968                                  * be freed at the end of verification
9969                                  */
9970                                 sl->next = env->free_list;
9971                                 env->free_list = sl;
9972                         }
9973                         sl = *pprev;
9974                         continue;
9975                 }
9976 next:
9977                 pprev = &sl->next;
9978                 sl = *pprev;
9979         }
9980
9981         if (env->max_states_per_insn < states_cnt)
9982                 env->max_states_per_insn = states_cnt;
9983
9984         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9985                 return push_jmp_history(env, cur);
9986
9987         if (!add_new_state)
9988                 return push_jmp_history(env, cur);
9989
9990         /* There were no equivalent states, remember the current one.
9991          * Technically the current state is not proven to be safe yet,
9992          * but it will either reach outer most bpf_exit (which means it's safe)
9993          * or it will be rejected. When there are no loops the verifier won't be
9994          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9995          * again on the way to bpf_exit.
9996          * When looping the sl->state.branches will be > 0 and this state
9997          * will not be considered for equivalence until branches == 0.
9998          */
9999         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10000         if (!new_sl)
10001                 return -ENOMEM;
10002         env->total_states++;
10003         env->peak_states++;
10004         env->prev_jmps_processed = env->jmps_processed;
10005         env->prev_insn_processed = env->insn_processed;
10006
10007         /* add new state to the head of linked list */
10008         new = &new_sl->state;
10009         err = copy_verifier_state(new, cur);
10010         if (err) {
10011                 free_verifier_state(new, false);
10012                 kfree(new_sl);
10013                 return err;
10014         }
10015         new->insn_idx = insn_idx;
10016         WARN_ONCE(new->branches != 1,
10017                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10018
10019         cur->parent = new;
10020         cur->first_insn_idx = insn_idx;
10021         clear_jmp_history(cur);
10022         new_sl->next = *explored_state(env, insn_idx);
10023         *explored_state(env, insn_idx) = new_sl;
10024         /* connect new state to parentage chain. Current frame needs all
10025          * registers connected. Only r6 - r9 of the callers are alive (pushed
10026          * to the stack implicitly by JITs) so in callers' frames connect just
10027          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10028          * the state of the call instruction (with WRITTEN set), and r0 comes
10029          * from callee with its full parentage chain, anyway.
10030          */
10031         /* clear write marks in current state: the writes we did are not writes
10032          * our child did, so they don't screen off its reads from us.
10033          * (There are no read marks in current state, because reads always mark
10034          * their parent and current state never has children yet.  Only
10035          * explored_states can get read marks.)
10036          */
10037         for (j = 0; j <= cur->curframe; j++) {
10038                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10039                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10040                 for (i = 0; i < BPF_REG_FP; i++)
10041                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10042         }
10043
10044         /* all stack frames are accessible from callee, clear them all */
10045         for (j = 0; j <= cur->curframe; j++) {
10046                 struct bpf_func_state *frame = cur->frame[j];
10047                 struct bpf_func_state *newframe = new->frame[j];
10048
10049                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10050                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10051                         frame->stack[i].spilled_ptr.parent =
10052                                                 &newframe->stack[i].spilled_ptr;
10053                 }
10054         }
10055         return 0;
10056 }
10057
10058 /* Return true if it's OK to have the same insn return a different type. */
10059 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10060 {
10061         switch (type) {
10062         case PTR_TO_CTX:
10063         case PTR_TO_SOCKET:
10064         case PTR_TO_SOCKET_OR_NULL:
10065         case PTR_TO_SOCK_COMMON:
10066         case PTR_TO_SOCK_COMMON_OR_NULL:
10067         case PTR_TO_TCP_SOCK:
10068         case PTR_TO_TCP_SOCK_OR_NULL:
10069         case PTR_TO_XDP_SOCK:
10070         case PTR_TO_BTF_ID:
10071         case PTR_TO_BTF_ID_OR_NULL:
10072                 return false;
10073         default:
10074                 return true;
10075         }
10076 }
10077
10078 /* If an instruction was previously used with particular pointer types, then we
10079  * need to be careful to avoid cases such as the below, where it may be ok
10080  * for one branch accessing the pointer, but not ok for the other branch:
10081  *
10082  * R1 = sock_ptr
10083  * goto X;
10084  * ...
10085  * R1 = some_other_valid_ptr;
10086  * goto X;
10087  * ...
10088  * R2 = *(u32 *)(R1 + 0);
10089  */
10090 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10091 {
10092         return src != prev && (!reg_type_mismatch_ok(src) ||
10093                                !reg_type_mismatch_ok(prev));
10094 }
10095
10096 static int do_check(struct bpf_verifier_env *env)
10097 {
10098         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10099         struct bpf_verifier_state *state = env->cur_state;
10100         struct bpf_insn *insns = env->prog->insnsi;
10101         struct bpf_reg_state *regs;
10102         int insn_cnt = env->prog->len;
10103         bool do_print_state = false;
10104         int prev_insn_idx = -1;
10105
10106         for (;;) {
10107                 struct bpf_insn *insn;
10108                 u8 class;
10109                 int err;
10110
10111                 env->prev_insn_idx = prev_insn_idx;
10112                 if (env->insn_idx >= insn_cnt) {
10113                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
10114                                 env->insn_idx, insn_cnt);
10115                         return -EFAULT;
10116                 }
10117
10118                 insn = &insns[env->insn_idx];
10119                 class = BPF_CLASS(insn->code);
10120
10121                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10122                         verbose(env,
10123                                 "BPF program is too large. Processed %d insn\n",
10124                                 env->insn_processed);
10125                         return -E2BIG;
10126                 }
10127
10128                 err = is_state_visited(env, env->insn_idx);
10129                 if (err < 0)
10130                         return err;
10131                 if (err == 1) {
10132                         /* found equivalent state, can prune the search */
10133                         if (env->log.level & BPF_LOG_LEVEL) {
10134                                 if (do_print_state)
10135                                         verbose(env, "\nfrom %d to %d%s: safe\n",
10136                                                 env->prev_insn_idx, env->insn_idx,
10137                                                 env->cur_state->speculative ?
10138                                                 " (speculative execution)" : "");
10139                                 else
10140                                         verbose(env, "%d: safe\n", env->insn_idx);
10141                         }
10142                         goto process_bpf_exit;
10143                 }
10144
10145                 if (signal_pending(current))
10146                         return -EAGAIN;
10147
10148                 if (need_resched())
10149                         cond_resched();
10150
10151                 if (env->log.level & BPF_LOG_LEVEL2 ||
10152                     (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10153                         if (env->log.level & BPF_LOG_LEVEL2)
10154                                 verbose(env, "%d:", env->insn_idx);
10155                         else
10156                                 verbose(env, "\nfrom %d to %d%s:",
10157                                         env->prev_insn_idx, env->insn_idx,
10158                                         env->cur_state->speculative ?
10159                                         " (speculative execution)" : "");
10160                         print_verifier_state(env, state->frame[state->curframe]);
10161                         do_print_state = false;
10162                 }
10163
10164                 if (env->log.level & BPF_LOG_LEVEL) {
10165                         const struct bpf_insn_cbs cbs = {
10166                                 .cb_print       = verbose,
10167                                 .private_data   = env,
10168                         };
10169
10170                         verbose_linfo(env, env->insn_idx, "; ");
10171                         verbose(env, "%d: ", env->insn_idx);
10172                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10173                 }
10174
10175                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10176                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10177                                                            env->prev_insn_idx);
10178                         if (err)
10179                                 return err;
10180                 }
10181
10182                 regs = cur_regs(env);
10183                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10184                 prev_insn_idx = env->insn_idx;
10185
10186                 if (class == BPF_ALU || class == BPF_ALU64) {
10187                         err = check_alu_op(env, insn);
10188                         if (err)
10189                                 return err;
10190
10191                 } else if (class == BPF_LDX) {
10192                         enum bpf_reg_type *prev_src_type, src_reg_type;
10193
10194                         /* check for reserved fields is already done */
10195
10196                         /* check src operand */
10197                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10198                         if (err)
10199                                 return err;
10200
10201                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10202                         if (err)
10203                                 return err;
10204
10205                         src_reg_type = regs[insn->src_reg].type;
10206
10207                         /* check that memory (src_reg + off) is readable,
10208                          * the state of dst_reg will be updated by this func
10209                          */
10210                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
10211                                                insn->off, BPF_SIZE(insn->code),
10212                                                BPF_READ, insn->dst_reg, false);
10213                         if (err)
10214                                 return err;
10215
10216                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10217
10218                         if (*prev_src_type == NOT_INIT) {
10219                                 /* saw a valid insn
10220                                  * dst_reg = *(u32 *)(src_reg + off)
10221                                  * save type to validate intersecting paths
10222                                  */
10223                                 *prev_src_type = src_reg_type;
10224
10225                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10226                                 /* ABuser program is trying to use the same insn
10227                                  * dst_reg = *(u32*) (src_reg + off)
10228                                  * with different pointer types:
10229                                  * src_reg == ctx in one branch and
10230                                  * src_reg == stack|map in some other branch.
10231                                  * Reject it.
10232                                  */
10233                                 verbose(env, "same insn cannot be used with different pointers\n");
10234                                 return -EINVAL;
10235                         }
10236
10237                 } else if (class == BPF_STX) {
10238                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
10239
10240                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10241                                 err = check_atomic(env, env->insn_idx, insn);
10242                                 if (err)
10243                                         return err;
10244                                 env->insn_idx++;
10245                                 continue;
10246                         }
10247
10248                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10249                                 verbose(env, "BPF_STX uses reserved fields\n");
10250                                 return -EINVAL;
10251                         }
10252
10253                         /* check src1 operand */
10254                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10255                         if (err)
10256                                 return err;
10257                         /* check src2 operand */
10258                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10259                         if (err)
10260                                 return err;
10261
10262                         dst_reg_type = regs[insn->dst_reg].type;
10263
10264                         /* check that memory (dst_reg + off) is writeable */
10265                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10266                                                insn->off, BPF_SIZE(insn->code),
10267                                                BPF_WRITE, insn->src_reg, false);
10268                         if (err)
10269                                 return err;
10270
10271                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10272
10273                         if (*prev_dst_type == NOT_INIT) {
10274                                 *prev_dst_type = dst_reg_type;
10275                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10276                                 verbose(env, "same insn cannot be used with different pointers\n");
10277                                 return -EINVAL;
10278                         }
10279
10280                 } else if (class == BPF_ST) {
10281                         if (BPF_MODE(insn->code) != BPF_MEM ||
10282                             insn->src_reg != BPF_REG_0) {
10283                                 verbose(env, "BPF_ST uses reserved fields\n");
10284                                 return -EINVAL;
10285                         }
10286                         /* check src operand */
10287                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10288                         if (err)
10289                                 return err;
10290
10291                         if (is_ctx_reg(env, insn->dst_reg)) {
10292                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10293                                         insn->dst_reg,
10294                                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
10295                                 return -EACCES;
10296                         }
10297
10298                         /* check that memory (dst_reg + off) is writeable */
10299                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10300                                                insn->off, BPF_SIZE(insn->code),
10301                                                BPF_WRITE, -1, false);
10302                         if (err)
10303                                 return err;
10304
10305                 } else if (class == BPF_JMP || class == BPF_JMP32) {
10306                         u8 opcode = BPF_OP(insn->code);
10307
10308                         env->jmps_processed++;
10309                         if (opcode == BPF_CALL) {
10310                                 if (BPF_SRC(insn->code) != BPF_K ||
10311                                     insn->off != 0 ||
10312                                     (insn->src_reg != BPF_REG_0 &&
10313                                      insn->src_reg != BPF_PSEUDO_CALL) ||
10314                                     insn->dst_reg != BPF_REG_0 ||
10315                                     class == BPF_JMP32) {
10316                                         verbose(env, "BPF_CALL uses reserved fields\n");
10317                                         return -EINVAL;
10318                                 }
10319
10320                                 if (env->cur_state->active_spin_lock &&
10321                                     (insn->src_reg == BPF_PSEUDO_CALL ||
10322                                      insn->imm != BPF_FUNC_spin_unlock)) {
10323                                         verbose(env, "function calls are not allowed while holding a lock\n");
10324                                         return -EINVAL;
10325                                 }
10326                                 if (insn->src_reg == BPF_PSEUDO_CALL)
10327                                         err = check_func_call(env, insn, &env->insn_idx);
10328                                 else
10329                                         err = check_helper_call(env, insn, &env->insn_idx);
10330                                 if (err)
10331                                         return err;
10332                         } else if (opcode == BPF_JA) {
10333                                 if (BPF_SRC(insn->code) != BPF_K ||
10334                                     insn->imm != 0 ||
10335                                     insn->src_reg != BPF_REG_0 ||
10336                                     insn->dst_reg != BPF_REG_0 ||
10337                                     class == BPF_JMP32) {
10338                                         verbose(env, "BPF_JA uses reserved fields\n");
10339                                         return -EINVAL;
10340                                 }
10341
10342                                 env->insn_idx += insn->off + 1;
10343                                 continue;
10344
10345                         } else if (opcode == BPF_EXIT) {
10346                                 if (BPF_SRC(insn->code) != BPF_K ||
10347                                     insn->imm != 0 ||
10348                                     insn->src_reg != BPF_REG_0 ||
10349                                     insn->dst_reg != BPF_REG_0 ||
10350                                     class == BPF_JMP32) {
10351                                         verbose(env, "BPF_EXIT uses reserved fields\n");
10352                                         return -EINVAL;
10353                                 }
10354
10355                                 if (env->cur_state->active_spin_lock) {
10356                                         verbose(env, "bpf_spin_unlock is missing\n");
10357                                         return -EINVAL;
10358                                 }
10359
10360                                 if (state->curframe) {
10361                                         /* exit from nested function */
10362                                         err = prepare_func_exit(env, &env->insn_idx);
10363                                         if (err)
10364                                                 return err;
10365                                         do_print_state = true;
10366                                         continue;
10367                                 }
10368
10369                                 err = check_reference_leak(env);
10370                                 if (err)
10371                                         return err;
10372
10373                                 err = check_return_code(env);
10374                                 if (err)
10375                                         return err;
10376 process_bpf_exit:
10377                                 update_branch_counts(env, env->cur_state);
10378                                 err = pop_stack(env, &prev_insn_idx,
10379                                                 &env->insn_idx, pop_log);
10380                                 if (err < 0) {
10381                                         if (err != -ENOENT)
10382                                                 return err;
10383                                         break;
10384                                 } else {
10385                                         do_print_state = true;
10386                                         continue;
10387                                 }
10388                         } else {
10389                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
10390                                 if (err)
10391                                         return err;
10392                         }
10393                 } else if (class == BPF_LD) {
10394                         u8 mode = BPF_MODE(insn->code);
10395
10396                         if (mode == BPF_ABS || mode == BPF_IND) {
10397                                 err = check_ld_abs(env, insn);
10398                                 if (err)
10399                                         return err;
10400
10401                         } else if (mode == BPF_IMM) {
10402                                 err = check_ld_imm(env, insn);
10403                                 if (err)
10404                                         return err;
10405
10406                                 env->insn_idx++;
10407                                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10408                         } else {
10409                                 verbose(env, "invalid BPF_LD mode\n");
10410                                 return -EINVAL;
10411                         }
10412                 } else {
10413                         verbose(env, "unknown insn class %d\n", class);
10414                         return -EINVAL;
10415                 }
10416
10417                 env->insn_idx++;
10418         }
10419
10420         return 0;
10421 }
10422
10423 static int find_btf_percpu_datasec(struct btf *btf)
10424 {
10425         const struct btf_type *t;
10426         const char *tname;
10427         int i, n;
10428
10429         /*
10430          * Both vmlinux and module each have their own ".data..percpu"
10431          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10432          * types to look at only module's own BTF types.
10433          */
10434         n = btf_nr_types(btf);
10435         if (btf_is_module(btf))
10436                 i = btf_nr_types(btf_vmlinux);
10437         else
10438                 i = 1;
10439
10440         for(; i < n; i++) {
10441                 t = btf_type_by_id(btf, i);
10442                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10443                         continue;
10444
10445                 tname = btf_name_by_offset(btf, t->name_off);
10446                 if (!strcmp(tname, ".data..percpu"))
10447                         return i;
10448         }
10449
10450         return -ENOENT;
10451 }
10452
10453 /* replace pseudo btf_id with kernel symbol address */
10454 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10455                                struct bpf_insn *insn,
10456                                struct bpf_insn_aux_data *aux)
10457 {
10458         const struct btf_var_secinfo *vsi;
10459         const struct btf_type *datasec;
10460         struct btf_mod_pair *btf_mod;
10461         const struct btf_type *t;
10462         const char *sym_name;
10463         bool percpu = false;
10464         u32 type, id = insn->imm;
10465         struct btf *btf;
10466         s32 datasec_id;
10467         u64 addr;
10468         int i, btf_fd, err;
10469
10470         btf_fd = insn[1].imm;
10471         if (btf_fd) {
10472                 btf = btf_get_by_fd(btf_fd);
10473                 if (IS_ERR(btf)) {
10474                         verbose(env, "invalid module BTF object FD specified.\n");
10475                         return -EINVAL;
10476                 }
10477         } else {
10478                 if (!btf_vmlinux) {
10479                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10480                         return -EINVAL;
10481                 }
10482                 btf = btf_vmlinux;
10483                 btf_get(btf);
10484         }
10485
10486         t = btf_type_by_id(btf, id);
10487         if (!t) {
10488                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10489                 err = -ENOENT;
10490                 goto err_put;
10491         }
10492
10493         if (!btf_type_is_var(t)) {
10494                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10495                 err = -EINVAL;
10496                 goto err_put;
10497         }
10498
10499         sym_name = btf_name_by_offset(btf, t->name_off);
10500         addr = kallsyms_lookup_name(sym_name);
10501         if (!addr) {
10502                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10503                         sym_name);
10504                 err = -ENOENT;
10505                 goto err_put;
10506         }
10507
10508         datasec_id = find_btf_percpu_datasec(btf);
10509         if (datasec_id > 0) {
10510                 datasec = btf_type_by_id(btf, datasec_id);
10511                 for_each_vsi(i, datasec, vsi) {
10512                         if (vsi->type == id) {
10513                                 percpu = true;
10514                                 break;
10515                         }
10516                 }
10517         }
10518
10519         insn[0].imm = (u32)addr;
10520         insn[1].imm = addr >> 32;
10521
10522         type = t->type;
10523         t = btf_type_skip_modifiers(btf, type, NULL);
10524         if (percpu) {
10525                 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10526                 aux->btf_var.btf = btf;
10527                 aux->btf_var.btf_id = type;
10528         } else if (!btf_type_is_struct(t)) {
10529                 const struct btf_type *ret;
10530                 const char *tname;
10531                 u32 tsize;
10532
10533                 /* resolve the type size of ksym. */
10534                 ret = btf_resolve_size(btf, t, &tsize);
10535                 if (IS_ERR(ret)) {
10536                         tname = btf_name_by_offset(btf, t->name_off);
10537                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10538                                 tname, PTR_ERR(ret));
10539                         err = -EINVAL;
10540                         goto err_put;
10541                 }
10542                 aux->btf_var.reg_type = PTR_TO_MEM;
10543                 aux->btf_var.mem_size = tsize;
10544         } else {
10545                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
10546                 aux->btf_var.btf = btf;
10547                 aux->btf_var.btf_id = type;
10548         }
10549
10550         /* check whether we recorded this BTF (and maybe module) already */
10551         for (i = 0; i < env->used_btf_cnt; i++) {
10552                 if (env->used_btfs[i].btf == btf) {
10553                         btf_put(btf);
10554                         return 0;
10555                 }
10556         }
10557
10558         if (env->used_btf_cnt >= MAX_USED_BTFS) {
10559                 err = -E2BIG;
10560                 goto err_put;
10561         }
10562
10563         btf_mod = &env->used_btfs[env->used_btf_cnt];
10564         btf_mod->btf = btf;
10565         btf_mod->module = NULL;
10566
10567         /* if we reference variables from kernel module, bump its refcount */
10568         if (btf_is_module(btf)) {
10569                 btf_mod->module = btf_try_get_module(btf);
10570                 if (!btf_mod->module) {
10571                         err = -ENXIO;
10572                         goto err_put;
10573                 }
10574         }
10575
10576         env->used_btf_cnt++;
10577
10578         return 0;
10579 err_put:
10580         btf_put(btf);
10581         return err;
10582 }
10583
10584 static int check_map_prealloc(struct bpf_map *map)
10585 {
10586         return (map->map_type != BPF_MAP_TYPE_HASH &&
10587                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10588                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10589                 !(map->map_flags & BPF_F_NO_PREALLOC);
10590 }
10591
10592 static bool is_tracing_prog_type(enum bpf_prog_type type)
10593 {
10594         switch (type) {
10595         case BPF_PROG_TYPE_KPROBE:
10596         case BPF_PROG_TYPE_TRACEPOINT:
10597         case BPF_PROG_TYPE_PERF_EVENT:
10598         case BPF_PROG_TYPE_RAW_TRACEPOINT:
10599                 return true;
10600         default:
10601                 return false;
10602         }
10603 }
10604
10605 static bool is_preallocated_map(struct bpf_map *map)
10606 {
10607         if (!check_map_prealloc(map))
10608                 return false;
10609         if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10610                 return false;
10611         return true;
10612 }
10613
10614 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10615                                         struct bpf_map *map,
10616                                         struct bpf_prog *prog)
10617
10618 {
10619         enum bpf_prog_type prog_type = resolve_prog_type(prog);
10620         /*
10621          * Validate that trace type programs use preallocated hash maps.
10622          *
10623          * For programs attached to PERF events this is mandatory as the
10624          * perf NMI can hit any arbitrary code sequence.
10625          *
10626          * All other trace types using preallocated hash maps are unsafe as
10627          * well because tracepoint or kprobes can be inside locked regions
10628          * of the memory allocator or at a place where a recursion into the
10629          * memory allocator would see inconsistent state.
10630          *
10631          * On RT enabled kernels run-time allocation of all trace type
10632          * programs is strictly prohibited due to lock type constraints. On
10633          * !RT kernels it is allowed for backwards compatibility reasons for
10634          * now, but warnings are emitted so developers are made aware of
10635          * the unsafety and can fix their programs before this is enforced.
10636          */
10637         if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10638                 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10639                         verbose(env, "perf_event programs can only use preallocated hash map\n");
10640                         return -EINVAL;
10641                 }
10642                 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10643                         verbose(env, "trace type programs can only use preallocated hash map\n");
10644                         return -EINVAL;
10645                 }
10646                 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10647                 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10648         }
10649
10650         if (map_value_has_spin_lock(map)) {
10651                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10652                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10653                         return -EINVAL;
10654                 }
10655
10656                 if (is_tracing_prog_type(prog_type)) {
10657                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10658                         return -EINVAL;
10659                 }
10660
10661                 if (prog->aux->sleepable) {
10662                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10663                         return -EINVAL;
10664                 }
10665         }
10666
10667         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10668             !bpf_offload_prog_map_match(prog, map)) {
10669                 verbose(env, "offload device mismatch between prog and map\n");
10670                 return -EINVAL;
10671         }
10672
10673         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10674                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10675                 return -EINVAL;
10676         }
10677
10678         if (prog->aux->sleepable)
10679                 switch (map->map_type) {
10680                 case BPF_MAP_TYPE_HASH:
10681                 case BPF_MAP_TYPE_LRU_HASH:
10682                 case BPF_MAP_TYPE_ARRAY:
10683                 case BPF_MAP_TYPE_PERCPU_HASH:
10684                 case BPF_MAP_TYPE_PERCPU_ARRAY:
10685                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10686                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10687                 case BPF_MAP_TYPE_HASH_OF_MAPS:
10688                         if (!is_preallocated_map(map)) {
10689                                 verbose(env,
10690                                         "Sleepable programs can only use preallocated maps\n");
10691                                 return -EINVAL;
10692                         }
10693                         break;
10694                 case BPF_MAP_TYPE_RINGBUF:
10695                         break;
10696                 default:
10697                         verbose(env,
10698                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
10699                         return -EINVAL;
10700                 }
10701
10702         return 0;
10703 }
10704
10705 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10706 {
10707         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10708                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10709 }
10710
10711 /* find and rewrite pseudo imm in ld_imm64 instructions:
10712  *
10713  * 1. if it accesses map FD, replace it with actual map pointer.
10714  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10715  *
10716  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10717  */
10718 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10719 {
10720         struct bpf_insn *insn = env->prog->insnsi;
10721         int insn_cnt = env->prog->len;
10722         int i, j, err;
10723
10724         err = bpf_prog_calc_tag(env->prog);
10725         if (err)
10726                 return err;
10727
10728         for (i = 0; i < insn_cnt; i++, insn++) {
10729                 if (BPF_CLASS(insn->code) == BPF_LDX &&
10730                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10731                         verbose(env, "BPF_LDX uses reserved fields\n");
10732                         return -EINVAL;
10733                 }
10734
10735                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10736                         struct bpf_insn_aux_data *aux;
10737                         struct bpf_map *map;
10738                         struct fd f;
10739                         u64 addr;
10740
10741                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
10742                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10743                             insn[1].off != 0) {
10744                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
10745                                 return -EINVAL;
10746                         }
10747
10748                         if (insn[0].src_reg == 0)
10749                                 /* valid generic load 64-bit imm */
10750                                 goto next_insn;
10751
10752                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10753                                 aux = &env->insn_aux_data[i];
10754                                 err = check_pseudo_btf_id(env, insn, aux);
10755                                 if (err)
10756                                         return err;
10757                                 goto next_insn;
10758                         }
10759
10760                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
10761                                 aux = &env->insn_aux_data[i];
10762                                 aux->ptr_type = PTR_TO_FUNC;
10763                                 goto next_insn;
10764                         }
10765
10766                         /* In final convert_pseudo_ld_imm64() step, this is
10767                          * converted into regular 64-bit imm load insn.
10768                          */
10769                         if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10770                              insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10771                             (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10772                              insn[1].imm != 0)) {
10773                                 verbose(env,
10774                                         "unrecognized bpf_ld_imm64 insn\n");
10775                                 return -EINVAL;
10776                         }
10777
10778                         f = fdget(insn[0].imm);
10779                         map = __bpf_map_get(f);
10780                         if (IS_ERR(map)) {
10781                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
10782                                         insn[0].imm);
10783                                 return PTR_ERR(map);
10784                         }
10785
10786                         err = check_map_prog_compatibility(env, map, env->prog);
10787                         if (err) {
10788                                 fdput(f);
10789                                 return err;
10790                         }
10791
10792                         aux = &env->insn_aux_data[i];
10793                         if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10794                                 addr = (unsigned long)map;
10795                         } else {
10796                                 u32 off = insn[1].imm;
10797
10798                                 if (off >= BPF_MAX_VAR_OFF) {
10799                                         verbose(env, "direct value offset of %u is not allowed\n", off);
10800                                         fdput(f);
10801                                         return -EINVAL;
10802                                 }
10803
10804                                 if (!map->ops->map_direct_value_addr) {
10805                                         verbose(env, "no direct value access support for this map type\n");
10806                                         fdput(f);
10807                                         return -EINVAL;
10808                                 }
10809
10810                                 err = map->ops->map_direct_value_addr(map, &addr, off);
10811                                 if (err) {
10812                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10813                                                 map->value_size, off);
10814                                         fdput(f);
10815                                         return err;
10816                                 }
10817
10818                                 aux->map_off = off;
10819                                 addr += off;
10820                         }
10821
10822                         insn[0].imm = (u32)addr;
10823                         insn[1].imm = addr >> 32;
10824
10825                         /* check whether we recorded this map already */
10826                         for (j = 0; j < env->used_map_cnt; j++) {
10827                                 if (env->used_maps[j] == map) {
10828                                         aux->map_index = j;
10829                                         fdput(f);
10830                                         goto next_insn;
10831                                 }
10832                         }
10833
10834                         if (env->used_map_cnt >= MAX_USED_MAPS) {
10835                                 fdput(f);
10836                                 return -E2BIG;
10837                         }
10838
10839                         /* hold the map. If the program is rejected by verifier,
10840                          * the map will be released by release_maps() or it
10841                          * will be used by the valid program until it's unloaded
10842                          * and all maps are released in free_used_maps()
10843                          */
10844                         bpf_map_inc(map);
10845
10846                         aux->map_index = env->used_map_cnt;
10847                         env->used_maps[env->used_map_cnt++] = map;
10848
10849                         if (bpf_map_is_cgroup_storage(map) &&
10850                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
10851                                 verbose(env, "only one cgroup storage of each type is allowed\n");
10852                                 fdput(f);
10853                                 return -EBUSY;
10854                         }
10855
10856                         fdput(f);
10857 next_insn:
10858                         insn++;
10859                         i++;
10860                         continue;
10861                 }
10862
10863                 /* Basic sanity check before we invest more work here. */
10864                 if (!bpf_opcode_in_insntable(insn->code)) {
10865                         verbose(env, "unknown opcode %02x\n", insn->code);
10866                         return -EINVAL;
10867                 }
10868         }
10869
10870         /* now all pseudo BPF_LD_IMM64 instructions load valid
10871          * 'struct bpf_map *' into a register instead of user map_fd.
10872          * These pointers will be used later by verifier to validate map access.
10873          */
10874         return 0;
10875 }
10876
10877 /* drop refcnt of maps used by the rejected program */
10878 static void release_maps(struct bpf_verifier_env *env)
10879 {
10880         __bpf_free_used_maps(env->prog->aux, env->used_maps,
10881                              env->used_map_cnt);
10882 }
10883
10884 /* drop refcnt of maps used by the rejected program */
10885 static void release_btfs(struct bpf_verifier_env *env)
10886 {
10887         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
10888                              env->used_btf_cnt);
10889 }
10890
10891 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10892 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10893 {
10894         struct bpf_insn *insn = env->prog->insnsi;
10895         int insn_cnt = env->prog->len;
10896         int i;
10897
10898         for (i = 0; i < insn_cnt; i++, insn++) {
10899                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
10900                         continue;
10901                 if (insn->src_reg == BPF_PSEUDO_FUNC)
10902                         continue;
10903                 insn->src_reg = 0;
10904         }
10905 }
10906
10907 /* single env->prog->insni[off] instruction was replaced with the range
10908  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
10909  * [0, off) and [off, end) to new locations, so the patched range stays zero
10910  */
10911 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10912                                 struct bpf_prog *new_prog, u32 off, u32 cnt)
10913 {
10914         struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
10915         struct bpf_insn *insn = new_prog->insnsi;
10916         u32 prog_len;
10917         int i;
10918
10919         /* aux info at OFF always needs adjustment, no matter fast path
10920          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10921          * original insn at old prog.
10922          */
10923         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10924
10925         if (cnt == 1)
10926                 return 0;
10927         prog_len = new_prog->len;
10928         new_data = vzalloc(array_size(prog_len,
10929                                       sizeof(struct bpf_insn_aux_data)));
10930         if (!new_data)
10931                 return -ENOMEM;
10932         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10933         memcpy(new_data + off + cnt - 1, old_data + off,
10934                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10935         for (i = off; i < off + cnt - 1; i++) {
10936                 new_data[i].seen = env->pass_cnt;
10937                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10938         }
10939         env->insn_aux_data = new_data;
10940         vfree(old_data);
10941         return 0;
10942 }
10943
10944 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10945 {
10946         int i;
10947
10948         if (len == 1)
10949                 return;
10950         /* NOTE: fake 'exit' subprog should be updated as well. */
10951         for (i = 0; i <= env->subprog_cnt; i++) {
10952                 if (env->subprog_info[i].start <= off)
10953                         continue;
10954                 env->subprog_info[i].start += len - 1;
10955         }
10956 }
10957
10958 static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10959 {
10960         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10961         int i, sz = prog->aux->size_poke_tab;
10962         struct bpf_jit_poke_descriptor *desc;
10963
10964         for (i = 0; i < sz; i++) {
10965                 desc = &tab[i];
10966                 desc->insn_idx += len - 1;
10967         }
10968 }
10969
10970 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10971                                             const struct bpf_insn *patch, u32 len)
10972 {
10973         struct bpf_prog *new_prog;
10974
10975         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10976         if (IS_ERR(new_prog)) {
10977                 if (PTR_ERR(new_prog) == -ERANGE)
10978                         verbose(env,
10979                                 "insn %d cannot be patched due to 16-bit range\n",
10980                                 env->insn_aux_data[off].orig_idx);
10981                 return NULL;
10982         }
10983         if (adjust_insn_aux_data(env, new_prog, off, len))
10984                 return NULL;
10985         adjust_subprog_starts(env, off, len);
10986         adjust_poke_descs(new_prog, len);
10987         return new_prog;
10988 }
10989
10990 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10991                                               u32 off, u32 cnt)
10992 {
10993         int i, j;
10994
10995         /* find first prog starting at or after off (first to remove) */
10996         for (i = 0; i < env->subprog_cnt; i++)
10997                 if (env->subprog_info[i].start >= off)
10998                         break;
10999         /* find first prog starting at or after off + cnt (first to stay) */
11000         for (j = i; j < env->subprog_cnt; j++)
11001                 if (env->subprog_info[j].start >= off + cnt)
11002                         break;
11003         /* if j doesn't start exactly at off + cnt, we are just removing
11004          * the front of previous prog
11005          */
11006         if (env->subprog_info[j].start != off + cnt)
11007                 j--;
11008
11009         if (j > i) {
11010                 struct bpf_prog_aux *aux = env->prog->aux;
11011                 int move;
11012
11013                 /* move fake 'exit' subprog as well */
11014                 move = env->subprog_cnt + 1 - j;
11015
11016                 memmove(env->subprog_info + i,
11017                         env->subprog_info + j,
11018                         sizeof(*env->subprog_info) * move);
11019                 env->subprog_cnt -= j - i;
11020
11021                 /* remove func_info */
11022                 if (aux->func_info) {
11023                         move = aux->func_info_cnt - j;
11024
11025                         memmove(aux->func_info + i,
11026                                 aux->func_info + j,
11027                                 sizeof(*aux->func_info) * move);
11028                         aux->func_info_cnt -= j - i;
11029                         /* func_info->insn_off is set after all code rewrites,
11030                          * in adjust_btf_func() - no need to adjust
11031                          */
11032                 }
11033         } else {
11034                 /* convert i from "first prog to remove" to "first to adjust" */
11035                 if (env->subprog_info[i].start == off)
11036                         i++;
11037         }
11038
11039         /* update fake 'exit' subprog as well */
11040         for (; i <= env->subprog_cnt; i++)
11041                 env->subprog_info[i].start -= cnt;
11042
11043         return 0;
11044 }
11045
11046 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11047                                       u32 cnt)
11048 {
11049         struct bpf_prog *prog = env->prog;
11050         u32 i, l_off, l_cnt, nr_linfo;
11051         struct bpf_line_info *linfo;
11052
11053         nr_linfo = prog->aux->nr_linfo;
11054         if (!nr_linfo)
11055                 return 0;
11056
11057         linfo = prog->aux->linfo;
11058
11059         /* find first line info to remove, count lines to be removed */
11060         for (i = 0; i < nr_linfo; i++)
11061                 if (linfo[i].insn_off >= off)
11062                         break;
11063
11064         l_off = i;
11065         l_cnt = 0;
11066         for (; i < nr_linfo; i++)
11067                 if (linfo[i].insn_off < off + cnt)
11068                         l_cnt++;
11069                 else
11070                         break;
11071
11072         /* First live insn doesn't match first live linfo, it needs to "inherit"
11073          * last removed linfo.  prog is already modified, so prog->len == off
11074          * means no live instructions after (tail of the program was removed).
11075          */
11076         if (prog->len != off && l_cnt &&
11077             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11078                 l_cnt--;
11079                 linfo[--i].insn_off = off + cnt;
11080         }
11081
11082         /* remove the line info which refer to the removed instructions */
11083         if (l_cnt) {
11084                 memmove(linfo + l_off, linfo + i,
11085                         sizeof(*linfo) * (nr_linfo - i));
11086
11087                 prog->aux->nr_linfo -= l_cnt;
11088                 nr_linfo = prog->aux->nr_linfo;
11089         }
11090
11091         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11092         for (i = l_off; i < nr_linfo; i++)
11093                 linfo[i].insn_off -= cnt;
11094
11095         /* fix up all subprogs (incl. 'exit') which start >= off */
11096         for (i = 0; i <= env->subprog_cnt; i++)
11097                 if (env->subprog_info[i].linfo_idx > l_off) {
11098                         /* program may have started in the removed region but
11099                          * may not be fully removed
11100                          */
11101                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11102                                 env->subprog_info[i].linfo_idx -= l_cnt;
11103                         else
11104                                 env->subprog_info[i].linfo_idx = l_off;
11105                 }
11106
11107         return 0;
11108 }
11109
11110 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11111 {
11112         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11113         unsigned int orig_prog_len = env->prog->len;
11114         int err;
11115
11116         if (bpf_prog_is_dev_bound(env->prog->aux))
11117                 bpf_prog_offload_remove_insns(env, off, cnt);
11118
11119         err = bpf_remove_insns(env->prog, off, cnt);
11120         if (err)
11121                 return err;
11122
11123         err = adjust_subprog_starts_after_remove(env, off, cnt);
11124         if (err)
11125                 return err;
11126
11127         err = bpf_adj_linfo_after_remove(env, off, cnt);
11128         if (err)
11129                 return err;
11130
11131         memmove(aux_data + off, aux_data + off + cnt,
11132                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11133
11134         return 0;
11135 }
11136
11137 /* The verifier does more data flow analysis than llvm and will not
11138  * explore branches that are dead at run time. Malicious programs can
11139  * have dead code too. Therefore replace all dead at-run-time code
11140  * with 'ja -1'.
11141  *
11142  * Just nops are not optimal, e.g. if they would sit at the end of the
11143  * program and through another bug we would manage to jump there, then
11144  * we'd execute beyond program memory otherwise. Returning exception
11145  * code also wouldn't work since we can have subprogs where the dead
11146  * code could be located.
11147  */
11148 static void sanitize_dead_code(struct bpf_verifier_env *env)
11149 {
11150         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11151         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11152         struct bpf_insn *insn = env->prog->insnsi;
11153         const int insn_cnt = env->prog->len;
11154         int i;
11155
11156         for (i = 0; i < insn_cnt; i++) {
11157                 if (aux_data[i].seen)
11158                         continue;
11159                 memcpy(insn + i, &trap, sizeof(trap));
11160         }
11161 }
11162
11163 static bool insn_is_cond_jump(u8 code)
11164 {
11165         u8 op;
11166
11167         if (BPF_CLASS(code) == BPF_JMP32)
11168                 return true;
11169
11170         if (BPF_CLASS(code) != BPF_JMP)
11171                 return false;
11172
11173         op = BPF_OP(code);
11174         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11175 }
11176
11177 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11178 {
11179         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11180         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11181         struct bpf_insn *insn = env->prog->insnsi;
11182         const int insn_cnt = env->prog->len;
11183         int i;
11184
11185         for (i = 0; i < insn_cnt; i++, insn++) {
11186                 if (!insn_is_cond_jump(insn->code))
11187                         continue;
11188
11189                 if (!aux_data[i + 1].seen)
11190                         ja.off = insn->off;
11191                 else if (!aux_data[i + 1 + insn->off].seen)
11192                         ja.off = 0;
11193                 else
11194                         continue;
11195
11196                 if (bpf_prog_is_dev_bound(env->prog->aux))
11197                         bpf_prog_offload_replace_insn(env, i, &ja);
11198
11199                 memcpy(insn, &ja, sizeof(ja));
11200         }
11201 }
11202
11203 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11204 {
11205         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11206         int insn_cnt = env->prog->len;
11207         int i, err;
11208
11209         for (i = 0; i < insn_cnt; i++) {
11210                 int j;
11211
11212                 j = 0;
11213                 while (i + j < insn_cnt && !aux_data[i + j].seen)
11214                         j++;
11215                 if (!j)
11216                         continue;
11217
11218                 err = verifier_remove_insns(env, i, j);
11219                 if (err)
11220                         return err;
11221                 insn_cnt = env->prog->len;
11222         }
11223
11224         return 0;
11225 }
11226
11227 static int opt_remove_nops(struct bpf_verifier_env *env)
11228 {
11229         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11230         struct bpf_insn *insn = env->prog->insnsi;
11231         int insn_cnt = env->prog->len;
11232         int i, err;
11233
11234         for (i = 0; i < insn_cnt; i++) {
11235                 if (memcmp(&insn[i], &ja, sizeof(ja)))
11236                         continue;
11237
11238                 err = verifier_remove_insns(env, i, 1);
11239                 if (err)
11240                         return err;
11241                 insn_cnt--;
11242                 i--;
11243         }
11244
11245         return 0;
11246 }
11247
11248 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11249                                          const union bpf_attr *attr)
11250 {
11251         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11252         struct bpf_insn_aux_data *aux = env->insn_aux_data;
11253         int i, patch_len, delta = 0, len = env->prog->len;
11254         struct bpf_insn *insns = env->prog->insnsi;
11255         struct bpf_prog *new_prog;
11256         bool rnd_hi32;
11257
11258         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11259         zext_patch[1] = BPF_ZEXT_REG(0);
11260         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11261         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11262         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11263         for (i = 0; i < len; i++) {
11264                 int adj_idx = i + delta;
11265                 struct bpf_insn insn;
11266                 int load_reg;
11267
11268                 insn = insns[adj_idx];
11269                 load_reg = insn_def_regno(&insn);
11270                 if (!aux[adj_idx].zext_dst) {
11271                         u8 code, class;
11272                         u32 imm_rnd;
11273
11274                         if (!rnd_hi32)
11275                                 continue;
11276
11277                         code = insn.code;
11278                         class = BPF_CLASS(code);
11279                         if (load_reg == -1)
11280                                 continue;
11281
11282                         /* NOTE: arg "reg" (the fourth one) is only used for
11283                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
11284                          *       here.
11285                          */
11286                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
11287                                 if (class == BPF_LD &&
11288                                     BPF_MODE(code) == BPF_IMM)
11289                                         i++;
11290                                 continue;
11291                         }
11292
11293                         /* ctx load could be transformed into wider load. */
11294                         if (class == BPF_LDX &&
11295                             aux[adj_idx].ptr_type == PTR_TO_CTX)
11296                                 continue;
11297
11298                         imm_rnd = get_random_int();
11299                         rnd_hi32_patch[0] = insn;
11300                         rnd_hi32_patch[1].imm = imm_rnd;
11301                         rnd_hi32_patch[3].dst_reg = load_reg;
11302                         patch = rnd_hi32_patch;
11303                         patch_len = 4;
11304                         goto apply_patch_buffer;
11305                 }
11306
11307                 /* Add in an zero-extend instruction if a) the JIT has requested
11308                  * it or b) it's a CMPXCHG.
11309                  *
11310                  * The latter is because: BPF_CMPXCHG always loads a value into
11311                  * R0, therefore always zero-extends. However some archs'
11312                  * equivalent instruction only does this load when the
11313                  * comparison is successful. This detail of CMPXCHG is
11314                  * orthogonal to the general zero-extension behaviour of the
11315                  * CPU, so it's treated independently of bpf_jit_needs_zext.
11316                  */
11317                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
11318                         continue;
11319
11320                 if (WARN_ON(load_reg == -1)) {
11321                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11322                         return -EFAULT;
11323                 }
11324
11325                 zext_patch[0] = insn;
11326                 zext_patch[1].dst_reg = load_reg;
11327                 zext_patch[1].src_reg = load_reg;
11328                 patch = zext_patch;
11329                 patch_len = 2;
11330 apply_patch_buffer:
11331                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11332                 if (!new_prog)
11333                         return -ENOMEM;
11334                 env->prog = new_prog;
11335                 insns = new_prog->insnsi;
11336                 aux = env->insn_aux_data;
11337                 delta += patch_len - 1;
11338         }
11339
11340         return 0;
11341 }
11342
11343 /* convert load instructions that access fields of a context type into a
11344  * sequence of instructions that access fields of the underlying structure:
11345  *     struct __sk_buff    -> struct sk_buff
11346  *     struct bpf_sock_ops -> struct sock
11347  */
11348 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11349 {
11350         const struct bpf_verifier_ops *ops = env->ops;
11351         int i, cnt, size, ctx_field_size, delta = 0;
11352         const int insn_cnt = env->prog->len;
11353         struct bpf_insn insn_buf[16], *insn;
11354         u32 target_size, size_default, off;
11355         struct bpf_prog *new_prog;
11356         enum bpf_access_type type;
11357         bool is_narrower_load;
11358
11359         if (ops->gen_prologue || env->seen_direct_write) {
11360                 if (!ops->gen_prologue) {
11361                         verbose(env, "bpf verifier is misconfigured\n");
11362                         return -EINVAL;
11363                 }
11364                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11365                                         env->prog);
11366                 if (cnt >= ARRAY_SIZE(insn_buf)) {
11367                         verbose(env, "bpf verifier is misconfigured\n");
11368                         return -EINVAL;
11369                 } else if (cnt) {
11370                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11371                         if (!new_prog)
11372                                 return -ENOMEM;
11373
11374                         env->prog = new_prog;
11375                         delta += cnt - 1;
11376                 }
11377         }
11378
11379         if (bpf_prog_is_dev_bound(env->prog->aux))
11380                 return 0;
11381
11382         insn = env->prog->insnsi + delta;
11383
11384         for (i = 0; i < insn_cnt; i++, insn++) {
11385                 bpf_convert_ctx_access_t convert_ctx_access;
11386
11387                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11388                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11389                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11390                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
11391                         type = BPF_READ;
11392                 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11393                          insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11394                          insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11395                          insn->code == (BPF_STX | BPF_MEM | BPF_DW))
11396                         type = BPF_WRITE;
11397                 else
11398                         continue;
11399
11400                 if (type == BPF_WRITE &&
11401                     env->insn_aux_data[i + delta].sanitize_stack_off) {
11402                         struct bpf_insn patch[] = {
11403                                 /* Sanitize suspicious stack slot with zero.
11404                                  * There are no memory dependencies for this store,
11405                                  * since it's only using frame pointer and immediate
11406                                  * constant of zero
11407                                  */
11408                                 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11409                                            env->insn_aux_data[i + delta].sanitize_stack_off,
11410                                            0),
11411                                 /* the original STX instruction will immediately
11412                                  * overwrite the same stack slot with appropriate value
11413                                  */
11414                                 *insn,
11415                         };
11416
11417                         cnt = ARRAY_SIZE(patch);
11418                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11419                         if (!new_prog)
11420                                 return -ENOMEM;
11421
11422                         delta    += cnt - 1;
11423                         env->prog = new_prog;
11424                         insn      = new_prog->insnsi + i + delta;
11425                         continue;
11426                 }
11427
11428                 switch (env->insn_aux_data[i + delta].ptr_type) {
11429                 case PTR_TO_CTX:
11430                         if (!ops->convert_ctx_access)
11431                                 continue;
11432                         convert_ctx_access = ops->convert_ctx_access;
11433                         break;
11434                 case PTR_TO_SOCKET:
11435                 case PTR_TO_SOCK_COMMON:
11436                         convert_ctx_access = bpf_sock_convert_ctx_access;
11437                         break;
11438                 case PTR_TO_TCP_SOCK:
11439                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11440                         break;
11441                 case PTR_TO_XDP_SOCK:
11442                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11443                         break;
11444                 case PTR_TO_BTF_ID:
11445                         if (type == BPF_READ) {
11446                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
11447                                         BPF_SIZE((insn)->code);
11448                                 env->prog->aux->num_exentries++;
11449                         } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11450                                 verbose(env, "Writes through BTF pointers are not allowed\n");
11451                                 return -EINVAL;
11452                         }
11453                         continue;
11454                 default:
11455                         continue;
11456                 }
11457
11458                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11459                 size = BPF_LDST_BYTES(insn);
11460
11461                 /* If the read access is a narrower load of the field,
11462                  * convert to a 4/8-byte load, to minimum program type specific
11463                  * convert_ctx_access changes. If conversion is successful,
11464                  * we will apply proper mask to the result.
11465                  */
11466                 is_narrower_load = size < ctx_field_size;
11467                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11468                 off = insn->off;
11469                 if (is_narrower_load) {
11470                         u8 size_code;
11471
11472                         if (type == BPF_WRITE) {
11473                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11474                                 return -EINVAL;
11475                         }
11476
11477                         size_code = BPF_H;
11478                         if (ctx_field_size == 4)
11479                                 size_code = BPF_W;
11480                         else if (ctx_field_size == 8)
11481                                 size_code = BPF_DW;
11482
11483                         insn->off = off & ~(size_default - 1);
11484                         insn->code = BPF_LDX | BPF_MEM | size_code;
11485                 }
11486
11487                 target_size = 0;
11488                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11489                                          &target_size);
11490                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11491                     (ctx_field_size && !target_size)) {
11492                         verbose(env, "bpf verifier is misconfigured\n");
11493                         return -EINVAL;
11494                 }
11495
11496                 if (is_narrower_load && size < target_size) {
11497                         u8 shift = bpf_ctx_narrow_access_offset(
11498                                 off, size, size_default) * 8;
11499                         if (ctx_field_size <= 4) {
11500                                 if (shift)
11501                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11502                                                                         insn->dst_reg,
11503                                                                         shift);
11504                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11505                                                                 (1 << size * 8) - 1);
11506                         } else {
11507                                 if (shift)
11508                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11509                                                                         insn->dst_reg,
11510                                                                         shift);
11511                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
11512                                                                 (1ULL << size * 8) - 1);
11513                         }
11514                 }
11515
11516                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11517                 if (!new_prog)
11518                         return -ENOMEM;
11519
11520                 delta += cnt - 1;
11521
11522                 /* keep walking new program and skip insns we just inserted */
11523                 env->prog = new_prog;
11524                 insn      = new_prog->insnsi + i + delta;
11525         }
11526
11527         return 0;
11528 }
11529
11530 static int jit_subprogs(struct bpf_verifier_env *env)
11531 {
11532         struct bpf_prog *prog = env->prog, **func, *tmp;
11533         int i, j, subprog_start, subprog_end = 0, len, subprog;
11534         struct bpf_map *map_ptr;
11535         struct bpf_insn *insn;
11536         void *old_bpf_func;
11537         int err, num_exentries;
11538
11539         if (env->subprog_cnt <= 1)
11540                 return 0;
11541
11542         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11543                 if (bpf_pseudo_func(insn)) {
11544                         env->insn_aux_data[i].call_imm = insn->imm;
11545                         /* subprog is encoded in insn[1].imm */
11546                         continue;
11547                 }
11548
11549                 if (!bpf_pseudo_call(insn))
11550                         continue;
11551                 /* Upon error here we cannot fall back to interpreter but
11552                  * need a hard reject of the program. Thus -EFAULT is
11553                  * propagated in any case.
11554                  */
11555                 subprog = find_subprog(env, i + insn->imm + 1);
11556                 if (subprog < 0) {
11557                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11558                                   i + insn->imm + 1);
11559                         return -EFAULT;
11560                 }
11561                 /* temporarily remember subprog id inside insn instead of
11562                  * aux_data, since next loop will split up all insns into funcs
11563                  */
11564                 insn->off = subprog;
11565                 /* remember original imm in case JIT fails and fallback
11566                  * to interpreter will be needed
11567                  */
11568                 env->insn_aux_data[i].call_imm = insn->imm;
11569                 /* point imm to __bpf_call_base+1 from JITs point of view */
11570                 insn->imm = 1;
11571         }
11572
11573         err = bpf_prog_alloc_jited_linfo(prog);
11574         if (err)
11575                 goto out_undo_insn;
11576
11577         err = -ENOMEM;
11578         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11579         if (!func)
11580                 goto out_undo_insn;
11581
11582         for (i = 0; i < env->subprog_cnt; i++) {
11583                 subprog_start = subprog_end;
11584                 subprog_end = env->subprog_info[i + 1].start;
11585
11586                 len = subprog_end - subprog_start;
11587                 /* BPF_PROG_RUN doesn't call subprogs directly,
11588                  * hence main prog stats include the runtime of subprogs.
11589                  * subprogs don't have IDs and not reachable via prog_get_next_id
11590                  * func[i]->stats will never be accessed and stays NULL
11591                  */
11592                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11593                 if (!func[i])
11594                         goto out_free;
11595                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11596                        len * sizeof(struct bpf_insn));
11597                 func[i]->type = prog->type;
11598                 func[i]->len = len;
11599                 if (bpf_prog_calc_tag(func[i]))
11600                         goto out_free;
11601                 func[i]->is_func = 1;
11602                 func[i]->aux->func_idx = i;
11603                 /* the btf and func_info will be freed only at prog->aux */
11604                 func[i]->aux->btf = prog->aux->btf;
11605                 func[i]->aux->func_info = prog->aux->func_info;
11606
11607                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11608                         u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11609                         int ret;
11610
11611                         if (!(insn_idx >= subprog_start &&
11612                               insn_idx <= subprog_end))
11613                                 continue;
11614
11615                         ret = bpf_jit_add_poke_descriptor(func[i],
11616                                                           &prog->aux->poke_tab[j]);
11617                         if (ret < 0) {
11618                                 verbose(env, "adding tail call poke descriptor failed\n");
11619                                 goto out_free;
11620                         }
11621
11622                         func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11623
11624                         map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11625                         ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11626                         if (ret < 0) {
11627                                 verbose(env, "tracking tail call prog failed\n");
11628                                 goto out_free;
11629                         }
11630                 }
11631
11632                 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11633                  * Long term would need debug info to populate names
11634                  */
11635                 func[i]->aux->name[0] = 'F';
11636                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11637                 func[i]->jit_requested = 1;
11638                 func[i]->aux->linfo = prog->aux->linfo;
11639                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11640                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11641                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11642                 num_exentries = 0;
11643                 insn = func[i]->insnsi;
11644                 for (j = 0; j < func[i]->len; j++, insn++) {
11645                         if (BPF_CLASS(insn->code) == BPF_LDX &&
11646                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
11647                                 num_exentries++;
11648                 }
11649                 func[i]->aux->num_exentries = num_exentries;
11650                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11651                 func[i] = bpf_int_jit_compile(func[i]);
11652                 if (!func[i]->jited) {
11653                         err = -ENOTSUPP;
11654                         goto out_free;
11655                 }
11656                 cond_resched();
11657         }
11658
11659         /* Untrack main program's aux structs so that during map_poke_run()
11660          * we will not stumble upon the unfilled poke descriptors; each
11661          * of the main program's poke descs got distributed across subprogs
11662          * and got tracked onto map, so we are sure that none of them will
11663          * be missed after the operation below
11664          */
11665         for (i = 0; i < prog->aux->size_poke_tab; i++) {
11666                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11667
11668                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11669         }
11670
11671         /* at this point all bpf functions were successfully JITed
11672          * now populate all bpf_calls with correct addresses and
11673          * run last pass of JIT
11674          */
11675         for (i = 0; i < env->subprog_cnt; i++) {
11676                 insn = func[i]->insnsi;
11677                 for (j = 0; j < func[i]->len; j++, insn++) {
11678                         if (bpf_pseudo_func(insn)) {
11679                                 subprog = insn[1].imm;
11680                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
11681                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
11682                                 continue;
11683                         }
11684                         if (!bpf_pseudo_call(insn))
11685                                 continue;
11686                         subprog = insn->off;
11687                         insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11688                                     __bpf_call_base;
11689                 }
11690
11691                 /* we use the aux data to keep a list of the start addresses
11692                  * of the JITed images for each function in the program
11693                  *
11694                  * for some architectures, such as powerpc64, the imm field
11695                  * might not be large enough to hold the offset of the start
11696                  * address of the callee's JITed image from __bpf_call_base
11697                  *
11698                  * in such cases, we can lookup the start address of a callee
11699                  * by using its subprog id, available from the off field of
11700                  * the call instruction, as an index for this list
11701                  */
11702                 func[i]->aux->func = func;
11703                 func[i]->aux->func_cnt = env->subprog_cnt;
11704         }
11705         for (i = 0; i < env->subprog_cnt; i++) {
11706                 old_bpf_func = func[i]->bpf_func;
11707                 tmp = bpf_int_jit_compile(func[i]);
11708                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11709                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11710                         err = -ENOTSUPP;
11711                         goto out_free;
11712                 }
11713                 cond_resched();
11714         }
11715
11716         /* finally lock prog and jit images for all functions and
11717          * populate kallsysm
11718          */
11719         for (i = 0; i < env->subprog_cnt; i++) {
11720                 bpf_prog_lock_ro(func[i]);
11721                 bpf_prog_kallsyms_add(func[i]);
11722         }
11723
11724         /* Last step: make now unused interpreter insns from main
11725          * prog consistent for later dump requests, so they can
11726          * later look the same as if they were interpreted only.
11727          */
11728         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11729                 if (bpf_pseudo_func(insn)) {
11730                         insn[0].imm = env->insn_aux_data[i].call_imm;
11731                         insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
11732                         continue;
11733                 }
11734                 if (!bpf_pseudo_call(insn))
11735                         continue;
11736                 insn->off = env->insn_aux_data[i].call_imm;
11737                 subprog = find_subprog(env, i + insn->off + 1);
11738                 insn->imm = subprog;
11739         }
11740
11741         prog->jited = 1;
11742         prog->bpf_func = func[0]->bpf_func;
11743         prog->aux->func = func;
11744         prog->aux->func_cnt = env->subprog_cnt;
11745         bpf_prog_free_unused_jited_linfo(prog);
11746         return 0;
11747 out_free:
11748         for (i = 0; i < env->subprog_cnt; i++) {
11749                 if (!func[i])
11750                         continue;
11751
11752                 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11753                         map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11754                         map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11755                 }
11756                 bpf_jit_free(func[i]);
11757         }
11758         kfree(func);
11759 out_undo_insn:
11760         /* cleanup main prog to be interpreted */
11761         prog->jit_requested = 0;
11762         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11763                 if (!bpf_pseudo_call(insn))
11764                         continue;
11765                 insn->off = 0;
11766                 insn->imm = env->insn_aux_data[i].call_imm;
11767         }
11768         bpf_prog_free_jited_linfo(prog);
11769         return err;
11770 }
11771
11772 static int fixup_call_args(struct bpf_verifier_env *env)
11773 {
11774 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11775         struct bpf_prog *prog = env->prog;
11776         struct bpf_insn *insn = prog->insnsi;
11777         int i, depth;
11778 #endif
11779         int err = 0;
11780
11781         if (env->prog->jit_requested &&
11782             !bpf_prog_is_dev_bound(env->prog->aux)) {
11783                 err = jit_subprogs(env);
11784                 if (err == 0)
11785                         return 0;
11786                 if (err == -EFAULT)
11787                         return err;
11788         }
11789 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11790         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11791                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11792                  * have to be rejected, since interpreter doesn't support them yet.
11793                  */
11794                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11795                 return -EINVAL;
11796         }
11797         for (i = 0; i < prog->len; i++, insn++) {
11798                 if (bpf_pseudo_func(insn)) {
11799                         /* When JIT fails the progs with callback calls
11800                          * have to be rejected, since interpreter doesn't support them yet.
11801                          */
11802                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
11803                         return -EINVAL;
11804                 }
11805
11806                 if (!bpf_pseudo_call(insn))
11807                         continue;
11808                 depth = get_callee_stack_depth(env, insn, i);
11809                 if (depth < 0)
11810                         return depth;
11811                 bpf_patch_call_args(insn, depth);
11812         }
11813         err = 0;
11814 #endif
11815         return err;
11816 }
11817
11818 /* Do various post-verification rewrites in a single program pass.
11819  * These rewrites simplify JIT and interpreter implementations.
11820  */
11821 static int do_misc_fixups(struct bpf_verifier_env *env)
11822 {
11823         struct bpf_prog *prog = env->prog;
11824         bool expect_blinding = bpf_jit_blinding_enabled(prog);
11825         struct bpf_insn *insn = prog->insnsi;
11826         const struct bpf_func_proto *fn;
11827         const int insn_cnt = prog->len;
11828         const struct bpf_map_ops *ops;
11829         struct bpf_insn_aux_data *aux;
11830         struct bpf_insn insn_buf[16];
11831         struct bpf_prog *new_prog;
11832         struct bpf_map *map_ptr;
11833         int i, ret, cnt, delta = 0;
11834
11835         for (i = 0; i < insn_cnt; i++, insn++) {
11836                 /* Make divide-by-zero exceptions impossible. */
11837                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11838                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11839                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11840                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11841                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11842                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11843                         struct bpf_insn *patchlet;
11844                         struct bpf_insn chk_and_div[] = {
11845                                 /* [R,W]x div 0 -> 0 */
11846                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11847                                              BPF_JNE | BPF_K, insn->src_reg,
11848                                              0, 2, 0),
11849                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11850                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11851                                 *insn,
11852                         };
11853                         struct bpf_insn chk_and_mod[] = {
11854                                 /* [R,W]x mod 0 -> [R,W]x */
11855                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11856                                              BPF_JEQ | BPF_K, insn->src_reg,
11857                                              0, 1 + (is64 ? 0 : 1), 0),
11858                                 *insn,
11859                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11860                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11861                         };
11862
11863                         patchlet = isdiv ? chk_and_div : chk_and_mod;
11864                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11865                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11866
11867                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11868                         if (!new_prog)
11869                                 return -ENOMEM;
11870
11871                         delta    += cnt - 1;
11872                         env->prog = prog = new_prog;
11873                         insn      = new_prog->insnsi + i + delta;
11874                         continue;
11875                 }
11876
11877                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
11878                 if (BPF_CLASS(insn->code) == BPF_LD &&
11879                     (BPF_MODE(insn->code) == BPF_ABS ||
11880                      BPF_MODE(insn->code) == BPF_IND)) {
11881                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
11882                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11883                                 verbose(env, "bpf verifier is misconfigured\n");
11884                                 return -EINVAL;
11885                         }
11886
11887                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11888                         if (!new_prog)
11889                                 return -ENOMEM;
11890
11891                         delta    += cnt - 1;
11892                         env->prog = prog = new_prog;
11893                         insn      = new_prog->insnsi + i + delta;
11894                         continue;
11895                 }
11896
11897                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
11898                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11899                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11900                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11901                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11902                         struct bpf_insn insn_buf[16];
11903                         struct bpf_insn *patch = &insn_buf[0];
11904                         bool issrc, isneg;
11905                         u32 off_reg;
11906
11907                         aux = &env->insn_aux_data[i + delta];
11908                         if (!aux->alu_state ||
11909                             aux->alu_state == BPF_ALU_NON_POINTER)
11910                                 continue;
11911
11912                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11913                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11914                                 BPF_ALU_SANITIZE_SRC;
11915
11916                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
11917                         if (isneg)
11918                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11919                         *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
11920                         *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11921                         *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11922                         *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11923                         *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11924                         if (issrc) {
11925                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
11926                                                          off_reg);
11927                                 insn->src_reg = BPF_REG_AX;
11928                         } else {
11929                                 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
11930                                                          BPF_REG_AX);
11931                         }
11932                         if (isneg)
11933                                 insn->code = insn->code == code_add ?
11934                                              code_sub : code_add;
11935                         *patch++ = *insn;
11936                         if (issrc && isneg)
11937                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11938                         cnt = patch - insn_buf;
11939
11940                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11941                         if (!new_prog)
11942                                 return -ENOMEM;
11943
11944                         delta    += cnt - 1;
11945                         env->prog = prog = new_prog;
11946                         insn      = new_prog->insnsi + i + delta;
11947                         continue;
11948                 }
11949
11950                 if (insn->code != (BPF_JMP | BPF_CALL))
11951                         continue;
11952                 if (insn->src_reg == BPF_PSEUDO_CALL)
11953                         continue;
11954
11955                 if (insn->imm == BPF_FUNC_get_route_realm)
11956                         prog->dst_needed = 1;
11957                 if (insn->imm == BPF_FUNC_get_prandom_u32)
11958                         bpf_user_rnd_init_once();
11959                 if (insn->imm == BPF_FUNC_override_return)
11960                         prog->kprobe_override = 1;
11961                 if (insn->imm == BPF_FUNC_tail_call) {
11962                         /* If we tail call into other programs, we
11963                          * cannot make any assumptions since they can
11964                          * be replaced dynamically during runtime in
11965                          * the program array.
11966                          */
11967                         prog->cb_access = 1;
11968                         if (!allow_tail_call_in_subprogs(env))
11969                                 prog->aux->stack_depth = MAX_BPF_STACK;
11970                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11971
11972                         /* mark bpf_tail_call as different opcode to avoid
11973                          * conditional branch in the interpeter for every normal
11974                          * call and to prevent accidental JITing by JIT compiler
11975                          * that doesn't support bpf_tail_call yet
11976                          */
11977                         insn->imm = 0;
11978                         insn->code = BPF_JMP | BPF_TAIL_CALL;
11979
11980                         aux = &env->insn_aux_data[i + delta];
11981                         if (env->bpf_capable && !expect_blinding &&
11982                             prog->jit_requested &&
11983                             !bpf_map_key_poisoned(aux) &&
11984                             !bpf_map_ptr_poisoned(aux) &&
11985                             !bpf_map_ptr_unpriv(aux)) {
11986                                 struct bpf_jit_poke_descriptor desc = {
11987                                         .reason = BPF_POKE_REASON_TAIL_CALL,
11988                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11989                                         .tail_call.key = bpf_map_key_immediate(aux),
11990                                         .insn_idx = i + delta,
11991                                 };
11992
11993                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11994                                 if (ret < 0) {
11995                                         verbose(env, "adding tail call poke descriptor failed\n");
11996                                         return ret;
11997                                 }
11998
11999                                 insn->imm = ret + 1;
12000                                 continue;
12001                         }
12002
12003                         if (!bpf_map_ptr_unpriv(aux))
12004                                 continue;
12005
12006                         /* instead of changing every JIT dealing with tail_call
12007                          * emit two extra insns:
12008                          * if (index >= max_entries) goto out;
12009                          * index &= array->index_mask;
12010                          * to avoid out-of-bounds cpu speculation
12011                          */
12012                         if (bpf_map_ptr_poisoned(aux)) {
12013                                 verbose(env, "tail_call abusing map_ptr\n");
12014                                 return -EINVAL;
12015                         }
12016
12017                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12018                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12019                                                   map_ptr->max_entries, 2);
12020                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12021                                                     container_of(map_ptr,
12022                                                                  struct bpf_array,
12023                                                                  map)->index_mask);
12024                         insn_buf[2] = *insn;
12025                         cnt = 3;
12026                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12027                         if (!new_prog)
12028                                 return -ENOMEM;
12029
12030                         delta    += cnt - 1;
12031                         env->prog = prog = new_prog;
12032                         insn      = new_prog->insnsi + i + delta;
12033                         continue;
12034                 }
12035
12036                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
12037                  * and other inlining handlers are currently limited to 64 bit
12038                  * only.
12039                  */
12040                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12041                     (insn->imm == BPF_FUNC_map_lookup_elem ||
12042                      insn->imm == BPF_FUNC_map_update_elem ||
12043                      insn->imm == BPF_FUNC_map_delete_elem ||
12044                      insn->imm == BPF_FUNC_map_push_elem   ||
12045                      insn->imm == BPF_FUNC_map_pop_elem    ||
12046                      insn->imm == BPF_FUNC_map_peek_elem   ||
12047                      insn->imm == BPF_FUNC_redirect_map)) {
12048                         aux = &env->insn_aux_data[i + delta];
12049                         if (bpf_map_ptr_poisoned(aux))
12050                                 goto patch_call_imm;
12051
12052                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12053                         ops = map_ptr->ops;
12054                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
12055                             ops->map_gen_lookup) {
12056                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
12057                                 if (cnt == -EOPNOTSUPP)
12058                                         goto patch_map_ops_generic;
12059                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12060                                         verbose(env, "bpf verifier is misconfigured\n");
12061                                         return -EINVAL;
12062                                 }
12063
12064                                 new_prog = bpf_patch_insn_data(env, i + delta,
12065                                                                insn_buf, cnt);
12066                                 if (!new_prog)
12067                                         return -ENOMEM;
12068
12069                                 delta    += cnt - 1;
12070                                 env->prog = prog = new_prog;
12071                                 insn      = new_prog->insnsi + i + delta;
12072                                 continue;
12073                         }
12074
12075                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12076                                      (void *(*)(struct bpf_map *map, void *key))NULL));
12077                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12078                                      (int (*)(struct bpf_map *map, void *key))NULL));
12079                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12080                                      (int (*)(struct bpf_map *map, void *key, void *value,
12081                                               u64 flags))NULL));
12082                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12083                                      (int (*)(struct bpf_map *map, void *value,
12084                                               u64 flags))NULL));
12085                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12086                                      (int (*)(struct bpf_map *map, void *value))NULL));
12087                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12088                                      (int (*)(struct bpf_map *map, void *value))NULL));
12089                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
12090                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12091
12092 patch_map_ops_generic:
12093                         switch (insn->imm) {
12094                         case BPF_FUNC_map_lookup_elem:
12095                                 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12096                                             __bpf_call_base;
12097                                 continue;
12098                         case BPF_FUNC_map_update_elem:
12099                                 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12100                                             __bpf_call_base;
12101                                 continue;
12102                         case BPF_FUNC_map_delete_elem:
12103                                 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12104                                             __bpf_call_base;
12105                                 continue;
12106                         case BPF_FUNC_map_push_elem:
12107                                 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12108                                             __bpf_call_base;
12109                                 continue;
12110                         case BPF_FUNC_map_pop_elem:
12111                                 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12112                                             __bpf_call_base;
12113                                 continue;
12114                         case BPF_FUNC_map_peek_elem:
12115                                 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12116                                             __bpf_call_base;
12117                                 continue;
12118                         case BPF_FUNC_redirect_map:
12119                                 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12120                                             __bpf_call_base;
12121                                 continue;
12122                         }
12123
12124                         goto patch_call_imm;
12125                 }
12126
12127                 /* Implement bpf_jiffies64 inline. */
12128                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12129                     insn->imm == BPF_FUNC_jiffies64) {
12130                         struct bpf_insn ld_jiffies_addr[2] = {
12131                                 BPF_LD_IMM64(BPF_REG_0,
12132                                              (unsigned long)&jiffies),
12133                         };
12134
12135                         insn_buf[0] = ld_jiffies_addr[0];
12136                         insn_buf[1] = ld_jiffies_addr[1];
12137                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12138                                                   BPF_REG_0, 0);
12139                         cnt = 3;
12140
12141                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12142                                                        cnt);
12143                         if (!new_prog)
12144                                 return -ENOMEM;
12145
12146                         delta    += cnt - 1;
12147                         env->prog = prog = new_prog;
12148                         insn      = new_prog->insnsi + i + delta;
12149                         continue;
12150                 }
12151
12152 patch_call_imm:
12153                 fn = env->ops->get_func_proto(insn->imm, env->prog);
12154                 /* all functions that have prototype and verifier allowed
12155                  * programs to call them, must be real in-kernel functions
12156                  */
12157                 if (!fn->func) {
12158                         verbose(env,
12159                                 "kernel subsystem misconfigured func %s#%d\n",
12160                                 func_id_name(insn->imm), insn->imm);
12161                         return -EFAULT;
12162                 }
12163                 insn->imm = fn->func - __bpf_call_base;
12164         }
12165
12166         /* Since poke tab is now finalized, publish aux to tracker. */
12167         for (i = 0; i < prog->aux->size_poke_tab; i++) {
12168                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12169                 if (!map_ptr->ops->map_poke_track ||
12170                     !map_ptr->ops->map_poke_untrack ||
12171                     !map_ptr->ops->map_poke_run) {
12172                         verbose(env, "bpf verifier is misconfigured\n");
12173                         return -EINVAL;
12174                 }
12175
12176                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12177                 if (ret < 0) {
12178                         verbose(env, "tracking tail call prog failed\n");
12179                         return ret;
12180                 }
12181         }
12182
12183         return 0;
12184 }
12185
12186 static void free_states(struct bpf_verifier_env *env)
12187 {
12188         struct bpf_verifier_state_list *sl, *sln;
12189         int i;
12190
12191         sl = env->free_list;
12192         while (sl) {
12193                 sln = sl->next;
12194                 free_verifier_state(&sl->state, false);
12195                 kfree(sl);
12196                 sl = sln;
12197         }
12198         env->free_list = NULL;
12199
12200         if (!env->explored_states)
12201                 return;
12202
12203         for (i = 0; i < state_htab_size(env); i++) {
12204                 sl = env->explored_states[i];
12205
12206                 while (sl) {
12207                         sln = sl->next;
12208                         free_verifier_state(&sl->state, false);
12209                         kfree(sl);
12210                         sl = sln;
12211                 }
12212                 env->explored_states[i] = NULL;
12213         }
12214 }
12215
12216 /* The verifier is using insn_aux_data[] to store temporary data during
12217  * verification and to store information for passes that run after the
12218  * verification like dead code sanitization. do_check_common() for subprogram N
12219  * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12220  * temporary data after do_check_common() finds that subprogram N cannot be
12221  * verified independently. pass_cnt counts the number of times
12222  * do_check_common() was run and insn->aux->seen tells the pass number
12223  * insn_aux_data was touched. These variables are compared to clear temporary
12224  * data from failed pass. For testing and experiments do_check_common() can be
12225  * run multiple times even when prior attempt to verify is unsuccessful.
12226  */
12227 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12228 {
12229         struct bpf_insn *insn = env->prog->insnsi;
12230         struct bpf_insn_aux_data *aux;
12231         int i, class;
12232
12233         for (i = 0; i < env->prog->len; i++) {
12234                 class = BPF_CLASS(insn[i].code);
12235                 if (class != BPF_LDX && class != BPF_STX)
12236                         continue;
12237                 aux = &env->insn_aux_data[i];
12238                 if (aux->seen != env->pass_cnt)
12239                         continue;
12240                 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12241         }
12242 }
12243
12244 static int do_check_common(struct bpf_verifier_env *env, int subprog)
12245 {
12246         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12247         struct bpf_verifier_state *state;
12248         struct bpf_reg_state *regs;
12249         int ret, i;
12250
12251         env->prev_linfo = NULL;
12252         env->pass_cnt++;
12253
12254         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12255         if (!state)
12256                 return -ENOMEM;
12257         state->curframe = 0;
12258         state->speculative = false;
12259         state->branches = 1;
12260         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12261         if (!state->frame[0]) {
12262                 kfree(state);
12263                 return -ENOMEM;
12264         }
12265         env->cur_state = state;
12266         init_func_state(env, state->frame[0],
12267                         BPF_MAIN_FUNC /* callsite */,
12268                         0 /* frameno */,
12269                         subprog);
12270
12271         regs = state->frame[state->curframe]->regs;
12272         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12273                 ret = btf_prepare_func_args(env, subprog, regs);
12274                 if (ret)
12275                         goto out;
12276                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12277                         if (regs[i].type == PTR_TO_CTX)
12278                                 mark_reg_known_zero(env, regs, i);
12279                         else if (regs[i].type == SCALAR_VALUE)
12280                                 mark_reg_unknown(env, regs, i);
12281                         else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12282                                 const u32 mem_size = regs[i].mem_size;
12283
12284                                 mark_reg_known_zero(env, regs, i);
12285                                 regs[i].mem_size = mem_size;
12286                                 regs[i].id = ++env->id_gen;
12287                         }
12288                 }
12289         } else {
12290                 /* 1st arg to a function */
12291                 regs[BPF_REG_1].type = PTR_TO_CTX;
12292                 mark_reg_known_zero(env, regs, BPF_REG_1);
12293                 ret = btf_check_func_arg_match(env, subprog, regs);
12294                 if (ret == -EFAULT)
12295                         /* unlikely verifier bug. abort.
12296                          * ret == 0 and ret < 0 are sadly acceptable for
12297                          * main() function due to backward compatibility.
12298                          * Like socket filter program may be written as:
12299                          * int bpf_prog(struct pt_regs *ctx)
12300                          * and never dereference that ctx in the program.
12301                          * 'struct pt_regs' is a type mismatch for socket
12302                          * filter that should be using 'struct __sk_buff'.
12303                          */
12304                         goto out;
12305         }
12306
12307         ret = do_check(env);
12308 out:
12309         /* check for NULL is necessary, since cur_state can be freed inside
12310          * do_check() under memory pressure.
12311          */
12312         if (env->cur_state) {
12313                 free_verifier_state(env->cur_state, true);
12314                 env->cur_state = NULL;
12315         }
12316         while (!pop_stack(env, NULL, NULL, false));
12317         if (!ret && pop_log)
12318                 bpf_vlog_reset(&env->log, 0);
12319         free_states(env);
12320         if (ret)
12321                 /* clean aux data in case subprog was rejected */
12322                 sanitize_insn_aux_data(env);
12323         return ret;
12324 }
12325
12326 /* Verify all global functions in a BPF program one by one based on their BTF.
12327  * All global functions must pass verification. Otherwise the whole program is rejected.
12328  * Consider:
12329  * int bar(int);
12330  * int foo(int f)
12331  * {
12332  *    return bar(f);
12333  * }
12334  * int bar(int b)
12335  * {
12336  *    ...
12337  * }
12338  * foo() will be verified first for R1=any_scalar_value. During verification it
12339  * will be assumed that bar() already verified successfully and call to bar()
12340  * from foo() will be checked for type match only. Later bar() will be verified
12341  * independently to check that it's safe for R1=any_scalar_value.
12342  */
12343 static int do_check_subprogs(struct bpf_verifier_env *env)
12344 {
12345         struct bpf_prog_aux *aux = env->prog->aux;
12346         int i, ret;
12347
12348         if (!aux->func_info)
12349                 return 0;
12350
12351         for (i = 1; i < env->subprog_cnt; i++) {
12352                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12353                         continue;
12354                 env->insn_idx = env->subprog_info[i].start;
12355                 WARN_ON_ONCE(env->insn_idx == 0);
12356                 ret = do_check_common(env, i);
12357                 if (ret) {
12358                         return ret;
12359                 } else if (env->log.level & BPF_LOG_LEVEL) {
12360                         verbose(env,
12361                                 "Func#%d is safe for any args that match its prototype\n",
12362                                 i);
12363                 }
12364         }
12365         return 0;
12366 }
12367
12368 static int do_check_main(struct bpf_verifier_env *env)
12369 {
12370         int ret;
12371
12372         env->insn_idx = 0;
12373         ret = do_check_common(env, 0);
12374         if (!ret)
12375                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12376         return ret;
12377 }
12378
12379
12380 static void print_verification_stats(struct bpf_verifier_env *env)
12381 {
12382         int i;
12383
12384         if (env->log.level & BPF_LOG_STATS) {
12385                 verbose(env, "verification time %lld usec\n",
12386                         div_u64(env->verification_time, 1000));
12387                 verbose(env, "stack depth ");
12388                 for (i = 0; i < env->subprog_cnt; i++) {
12389                         u32 depth = env->subprog_info[i].stack_depth;
12390
12391                         verbose(env, "%d", depth);
12392                         if (i + 1 < env->subprog_cnt)
12393                                 verbose(env, "+");
12394                 }
12395                 verbose(env, "\n");
12396         }
12397         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12398                 "total_states %d peak_states %d mark_read %d\n",
12399                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12400                 env->max_states_per_insn, env->total_states,
12401                 env->peak_states, env->longest_mark_read_walk);
12402 }
12403
12404 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12405 {
12406         const struct btf_type *t, *func_proto;
12407         const struct bpf_struct_ops *st_ops;
12408         const struct btf_member *member;
12409         struct bpf_prog *prog = env->prog;
12410         u32 btf_id, member_idx;
12411         const char *mname;
12412
12413         btf_id = prog->aux->attach_btf_id;
12414         st_ops = bpf_struct_ops_find(btf_id);
12415         if (!st_ops) {
12416                 verbose(env, "attach_btf_id %u is not a supported struct\n",
12417                         btf_id);
12418                 return -ENOTSUPP;
12419         }
12420
12421         t = st_ops->type;
12422         member_idx = prog->expected_attach_type;
12423         if (member_idx >= btf_type_vlen(t)) {
12424                 verbose(env, "attach to invalid member idx %u of struct %s\n",
12425                         member_idx, st_ops->name);
12426                 return -EINVAL;
12427         }
12428
12429         member = &btf_type_member(t)[member_idx];
12430         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12431         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12432                                                NULL);
12433         if (!func_proto) {
12434                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12435                         mname, member_idx, st_ops->name);
12436                 return -EINVAL;
12437         }
12438
12439         if (st_ops->check_member) {
12440                 int err = st_ops->check_member(t, member);
12441
12442                 if (err) {
12443                         verbose(env, "attach to unsupported member %s of struct %s\n",
12444                                 mname, st_ops->name);
12445                         return err;
12446                 }
12447         }
12448
12449         prog->aux->attach_func_proto = func_proto;
12450         prog->aux->attach_func_name = mname;
12451         env->ops = st_ops->verifier_ops;
12452
12453         return 0;
12454 }
12455 #define SECURITY_PREFIX "security_"
12456
12457 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12458 {
12459         if (within_error_injection_list(addr) ||
12460             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12461                 return 0;
12462
12463         return -EINVAL;
12464 }
12465
12466 /* list of non-sleepable functions that are otherwise on
12467  * ALLOW_ERROR_INJECTION list
12468  */
12469 BTF_SET_START(btf_non_sleepable_error_inject)
12470 /* Three functions below can be called from sleepable and non-sleepable context.
12471  * Assume non-sleepable from bpf safety point of view.
12472  */
12473 BTF_ID(func, __add_to_page_cache_locked)
12474 BTF_ID(func, should_fail_alloc_page)
12475 BTF_ID(func, should_failslab)
12476 BTF_SET_END(btf_non_sleepable_error_inject)
12477
12478 static int check_non_sleepable_error_inject(u32 btf_id)
12479 {
12480         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12481 }
12482
12483 int bpf_check_attach_target(struct bpf_verifier_log *log,
12484                             const struct bpf_prog *prog,
12485                             const struct bpf_prog *tgt_prog,
12486                             u32 btf_id,
12487                             struct bpf_attach_target_info *tgt_info)
12488 {
12489         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12490         const char prefix[] = "btf_trace_";
12491         int ret = 0, subprog = -1, i;
12492         const struct btf_type *t;
12493         bool conservative = true;
12494         const char *tname;
12495         struct btf *btf;
12496         long addr = 0;
12497
12498         if (!btf_id) {
12499                 bpf_log(log, "Tracing programs must provide btf_id\n");
12500                 return -EINVAL;
12501         }
12502         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
12503         if (!btf) {
12504                 bpf_log(log,
12505                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12506                 return -EINVAL;
12507         }
12508         t = btf_type_by_id(btf, btf_id);
12509         if (!t) {
12510                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12511                 return -EINVAL;
12512         }
12513         tname = btf_name_by_offset(btf, t->name_off);
12514         if (!tname) {
12515                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12516                 return -EINVAL;
12517         }
12518         if (tgt_prog) {
12519                 struct bpf_prog_aux *aux = tgt_prog->aux;
12520
12521                 for (i = 0; i < aux->func_info_cnt; i++)
12522                         if (aux->func_info[i].type_id == btf_id) {
12523                                 subprog = i;
12524                                 break;
12525                         }
12526                 if (subprog == -1) {
12527                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
12528                         return -EINVAL;
12529                 }
12530                 conservative = aux->func_info_aux[subprog].unreliable;
12531                 if (prog_extension) {
12532                         if (conservative) {
12533                                 bpf_log(log,
12534                                         "Cannot replace static functions\n");
12535                                 return -EINVAL;
12536                         }
12537                         if (!prog->jit_requested) {
12538                                 bpf_log(log,
12539                                         "Extension programs should be JITed\n");
12540                                 return -EINVAL;
12541                         }
12542                 }
12543                 if (!tgt_prog->jited) {
12544                         bpf_log(log, "Can attach to only JITed progs\n");
12545                         return -EINVAL;
12546                 }
12547                 if (tgt_prog->type == prog->type) {
12548                         /* Cannot fentry/fexit another fentry/fexit program.
12549                          * Cannot attach program extension to another extension.
12550                          * It's ok to attach fentry/fexit to extension program.
12551                          */
12552                         bpf_log(log, "Cannot recursively attach\n");
12553                         return -EINVAL;
12554                 }
12555                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12556                     prog_extension &&
12557                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12558                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12559                         /* Program extensions can extend all program types
12560                          * except fentry/fexit. The reason is the following.
12561                          * The fentry/fexit programs are used for performance
12562                          * analysis, stats and can be attached to any program
12563                          * type except themselves. When extension program is
12564                          * replacing XDP function it is necessary to allow
12565                          * performance analysis of all functions. Both original
12566                          * XDP program and its program extension. Hence
12567                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12568                          * allowed. If extending of fentry/fexit was allowed it
12569                          * would be possible to create long call chain
12570                          * fentry->extension->fentry->extension beyond
12571                          * reasonable stack size. Hence extending fentry is not
12572                          * allowed.
12573                          */
12574                         bpf_log(log, "Cannot extend fentry/fexit\n");
12575                         return -EINVAL;
12576                 }
12577         } else {
12578                 if (prog_extension) {
12579                         bpf_log(log, "Cannot replace kernel functions\n");
12580                         return -EINVAL;
12581                 }
12582         }
12583
12584         switch (prog->expected_attach_type) {
12585         case BPF_TRACE_RAW_TP:
12586                 if (tgt_prog) {
12587                         bpf_log(log,
12588                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12589                         return -EINVAL;
12590                 }
12591                 if (!btf_type_is_typedef(t)) {
12592                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
12593                                 btf_id);
12594                         return -EINVAL;
12595                 }
12596                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12597                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12598                                 btf_id, tname);
12599                         return -EINVAL;
12600                 }
12601                 tname += sizeof(prefix) - 1;
12602                 t = btf_type_by_id(btf, t->type);
12603                 if (!btf_type_is_ptr(t))
12604                         /* should never happen in valid vmlinux build */
12605                         return -EINVAL;
12606                 t = btf_type_by_id(btf, t->type);
12607                 if (!btf_type_is_func_proto(t))
12608                         /* should never happen in valid vmlinux build */
12609                         return -EINVAL;
12610
12611                 break;
12612         case BPF_TRACE_ITER:
12613                 if (!btf_type_is_func(t)) {
12614                         bpf_log(log, "attach_btf_id %u is not a function\n",
12615                                 btf_id);
12616                         return -EINVAL;
12617                 }
12618                 t = btf_type_by_id(btf, t->type);
12619                 if (!btf_type_is_func_proto(t))
12620                         return -EINVAL;
12621                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12622                 if (ret)
12623                         return ret;
12624                 break;
12625         default:
12626                 if (!prog_extension)
12627                         return -EINVAL;
12628                 fallthrough;
12629         case BPF_MODIFY_RETURN:
12630         case BPF_LSM_MAC:
12631         case BPF_TRACE_FENTRY:
12632         case BPF_TRACE_FEXIT:
12633                 if (!btf_type_is_func(t)) {
12634                         bpf_log(log, "attach_btf_id %u is not a function\n",
12635                                 btf_id);
12636                         return -EINVAL;
12637                 }
12638                 if (prog_extension &&
12639                     btf_check_type_match(log, prog, btf, t))
12640                         return -EINVAL;
12641                 t = btf_type_by_id(btf, t->type);
12642                 if (!btf_type_is_func_proto(t))
12643                         return -EINVAL;
12644
12645                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12646                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12647                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12648                         return -EINVAL;
12649
12650                 if (tgt_prog && conservative)
12651                         t = NULL;
12652
12653                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12654                 if (ret < 0)
12655                         return ret;
12656
12657                 if (tgt_prog) {
12658                         if (subprog == 0)
12659                                 addr = (long) tgt_prog->bpf_func;
12660                         else
12661                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12662                 } else {
12663                         addr = kallsyms_lookup_name(tname);
12664                         if (!addr) {
12665                                 bpf_log(log,
12666                                         "The address of function %s cannot be found\n",
12667                                         tname);
12668                                 return -ENOENT;
12669                         }
12670                 }
12671
12672                 if (prog->aux->sleepable) {
12673                         ret = -EINVAL;
12674                         switch (prog->type) {
12675                         case BPF_PROG_TYPE_TRACING:
12676                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12677                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12678                                  */
12679                                 if (!check_non_sleepable_error_inject(btf_id) &&
12680                                     within_error_injection_list(addr))
12681                                         ret = 0;
12682                                 break;
12683                         case BPF_PROG_TYPE_LSM:
12684                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12685                                  * Only some of them are sleepable.
12686                                  */
12687                                 if (bpf_lsm_is_sleepable_hook(btf_id))
12688                                         ret = 0;
12689                                 break;
12690                         default:
12691                                 break;
12692                         }
12693                         if (ret) {
12694                                 bpf_log(log, "%s is not sleepable\n", tname);
12695                                 return ret;
12696                         }
12697                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12698                         if (tgt_prog) {
12699                                 bpf_log(log, "can't modify return codes of BPF programs\n");
12700                                 return -EINVAL;
12701                         }
12702                         ret = check_attach_modify_return(addr, tname);
12703                         if (ret) {
12704                                 bpf_log(log, "%s() is not modifiable\n", tname);
12705                                 return ret;
12706                         }
12707                 }
12708
12709                 break;
12710         }
12711         tgt_info->tgt_addr = addr;
12712         tgt_info->tgt_name = tname;
12713         tgt_info->tgt_type = t;
12714         return 0;
12715 }
12716
12717 static int check_attach_btf_id(struct bpf_verifier_env *env)
12718 {
12719         struct bpf_prog *prog = env->prog;
12720         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12721         struct bpf_attach_target_info tgt_info = {};
12722         u32 btf_id = prog->aux->attach_btf_id;
12723         struct bpf_trampoline *tr;
12724         int ret;
12725         u64 key;
12726
12727         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12728             prog->type != BPF_PROG_TYPE_LSM) {
12729                 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12730                 return -EINVAL;
12731         }
12732
12733         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12734                 return check_struct_ops_btf_id(env);
12735
12736         if (prog->type != BPF_PROG_TYPE_TRACING &&
12737             prog->type != BPF_PROG_TYPE_LSM &&
12738             prog->type != BPF_PROG_TYPE_EXT)
12739                 return 0;
12740
12741         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12742         if (ret)
12743                 return ret;
12744
12745         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12746                 /* to make freplace equivalent to their targets, they need to
12747                  * inherit env->ops and expected_attach_type for the rest of the
12748                  * verification
12749                  */
12750                 env->ops = bpf_verifier_ops[tgt_prog->type];
12751                 prog->expected_attach_type = tgt_prog->expected_attach_type;
12752         }
12753
12754         /* store info about the attachment target that will be used later */
12755         prog->aux->attach_func_proto = tgt_info.tgt_type;
12756         prog->aux->attach_func_name = tgt_info.tgt_name;
12757
12758         if (tgt_prog) {
12759                 prog->aux->saved_dst_prog_type = tgt_prog->type;
12760                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12761         }
12762
12763         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12764                 prog->aux->attach_btf_trace = true;
12765                 return 0;
12766         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12767                 if (!bpf_iter_prog_supported(prog))
12768                         return -EINVAL;
12769                 return 0;
12770         }
12771
12772         if (prog->type == BPF_PROG_TYPE_LSM) {
12773                 ret = bpf_lsm_verify_prog(&env->log, prog);
12774                 if (ret < 0)
12775                         return ret;
12776         }
12777
12778         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
12779         tr = bpf_trampoline_get(key, &tgt_info);
12780         if (!tr)
12781                 return -ENOMEM;
12782
12783         prog->aux->dst_trampoline = tr;
12784         return 0;
12785 }
12786
12787 struct btf *bpf_get_btf_vmlinux(void)
12788 {
12789         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12790                 mutex_lock(&bpf_verifier_lock);
12791                 if (!btf_vmlinux)
12792                         btf_vmlinux = btf_parse_vmlinux();
12793                 mutex_unlock(&bpf_verifier_lock);
12794         }
12795         return btf_vmlinux;
12796 }
12797
12798 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12799               union bpf_attr __user *uattr)
12800 {
12801         u64 start_time = ktime_get_ns();
12802         struct bpf_verifier_env *env;
12803         struct bpf_verifier_log *log;
12804         int i, len, ret = -EINVAL;
12805         bool is_priv;
12806
12807         /* no program is valid */
12808         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12809                 return -EINVAL;
12810
12811         /* 'struct bpf_verifier_env' can be global, but since it's not small,
12812          * allocate/free it every time bpf_check() is called
12813          */
12814         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12815         if (!env)
12816                 return -ENOMEM;
12817         log = &env->log;
12818
12819         len = (*prog)->len;
12820         env->insn_aux_data =
12821                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12822         ret = -ENOMEM;
12823         if (!env->insn_aux_data)
12824                 goto err_free_env;
12825         for (i = 0; i < len; i++)
12826                 env->insn_aux_data[i].orig_idx = i;
12827         env->prog = *prog;
12828         env->ops = bpf_verifier_ops[env->prog->type];
12829         is_priv = bpf_capable();
12830
12831         bpf_get_btf_vmlinux();
12832
12833         /* grab the mutex to protect few globals used by verifier */
12834         if (!is_priv)
12835                 mutex_lock(&bpf_verifier_lock);
12836
12837         if (attr->log_level || attr->log_buf || attr->log_size) {
12838                 /* user requested verbose verifier output
12839                  * and supplied buffer to store the verification trace
12840                  */
12841                 log->level = attr->log_level;
12842                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12843                 log->len_total = attr->log_size;
12844
12845                 ret = -EINVAL;
12846                 /* log attributes have to be sane */
12847                 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
12848                     !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
12849                         goto err_unlock;
12850         }
12851
12852         if (IS_ERR(btf_vmlinux)) {
12853                 /* Either gcc or pahole or kernel are broken. */
12854                 verbose(env, "in-kernel BTF is malformed\n");
12855                 ret = PTR_ERR(btf_vmlinux);
12856                 goto skip_full_check;
12857         }
12858
12859         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12860         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12861                 env->strict_alignment = true;
12862         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12863                 env->strict_alignment = false;
12864
12865         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12866         env->allow_uninit_stack = bpf_allow_uninit_stack();
12867         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12868         env->bypass_spec_v1 = bpf_bypass_spec_v1();
12869         env->bypass_spec_v4 = bpf_bypass_spec_v4();
12870         env->bpf_capable = bpf_capable();
12871
12872         if (is_priv)
12873                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12874
12875         if (bpf_prog_is_dev_bound(env->prog->aux)) {
12876                 ret = bpf_prog_offload_verifier_prep(env->prog);
12877                 if (ret)
12878                         goto skip_full_check;
12879         }
12880
12881         env->explored_states = kvcalloc(state_htab_size(env),
12882                                        sizeof(struct bpf_verifier_state_list *),
12883                                        GFP_USER);
12884         ret = -ENOMEM;
12885         if (!env->explored_states)
12886                 goto skip_full_check;
12887
12888         ret = check_subprogs(env);
12889         if (ret < 0)
12890                 goto skip_full_check;
12891
12892         ret = check_btf_info(env, attr, uattr);
12893         if (ret < 0)
12894                 goto skip_full_check;
12895
12896         ret = check_attach_btf_id(env);
12897         if (ret)
12898                 goto skip_full_check;
12899
12900         ret = resolve_pseudo_ldimm64(env);
12901         if (ret < 0)
12902                 goto skip_full_check;
12903
12904         ret = check_cfg(env);
12905         if (ret < 0)
12906                 goto skip_full_check;
12907
12908         ret = do_check_subprogs(env);
12909         ret = ret ?: do_check_main(env);
12910
12911         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12912                 ret = bpf_prog_offload_finalize(env);
12913
12914 skip_full_check:
12915         kvfree(env->explored_states);
12916
12917         if (ret == 0)
12918                 ret = check_max_stack_depth(env);
12919
12920         /* instruction rewrites happen after this point */
12921         if (is_priv) {
12922                 if (ret == 0)
12923                         opt_hard_wire_dead_code_branches(env);
12924                 if (ret == 0)
12925                         ret = opt_remove_dead_code(env);
12926                 if (ret == 0)
12927                         ret = opt_remove_nops(env);
12928         } else {
12929                 if (ret == 0)
12930                         sanitize_dead_code(env);
12931         }
12932
12933         if (ret == 0)
12934                 /* program is valid, convert *(u32*)(ctx + off) accesses */
12935                 ret = convert_ctx_accesses(env);
12936
12937         if (ret == 0)
12938                 ret = do_misc_fixups(env);
12939
12940         /* do 32-bit optimization after insn patching has done so those patched
12941          * insns could be handled correctly.
12942          */
12943         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12944                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12945                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12946                                                                      : false;
12947         }
12948
12949         if (ret == 0)
12950                 ret = fixup_call_args(env);
12951
12952         env->verification_time = ktime_get_ns() - start_time;
12953         print_verification_stats(env);
12954
12955         if (log->level && bpf_verifier_log_full(log))
12956                 ret = -ENOSPC;
12957         if (log->level && !log->ubuf) {
12958                 ret = -EFAULT;
12959                 goto err_release_maps;
12960         }
12961
12962         if (ret)
12963                 goto err_release_maps;
12964
12965         if (env->used_map_cnt) {
12966                 /* if program passed verifier, update used_maps in bpf_prog_info */
12967                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12968                                                           sizeof(env->used_maps[0]),
12969                                                           GFP_KERNEL);
12970
12971                 if (!env->prog->aux->used_maps) {
12972                         ret = -ENOMEM;
12973                         goto err_release_maps;
12974                 }
12975
12976                 memcpy(env->prog->aux->used_maps, env->used_maps,
12977                        sizeof(env->used_maps[0]) * env->used_map_cnt);
12978                 env->prog->aux->used_map_cnt = env->used_map_cnt;
12979         }
12980         if (env->used_btf_cnt) {
12981                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
12982                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
12983                                                           sizeof(env->used_btfs[0]),
12984                                                           GFP_KERNEL);
12985                 if (!env->prog->aux->used_btfs) {
12986                         ret = -ENOMEM;
12987                         goto err_release_maps;
12988                 }
12989
12990                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
12991                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
12992                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
12993         }
12994         if (env->used_map_cnt || env->used_btf_cnt) {
12995                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12996                  * bpf_ld_imm64 instructions
12997                  */
12998                 convert_pseudo_ld_imm64(env);
12999         }
13000
13001         adjust_btf_func(env);
13002
13003 err_release_maps:
13004         if (!env->prog->aux->used_maps)
13005                 /* if we didn't copy map pointers into bpf_prog_info, release
13006                  * them now. Otherwise free_used_maps() will release them.
13007                  */
13008                 release_maps(env);
13009         if (!env->prog->aux->used_btfs)
13010                 release_btfs(env);
13011
13012         /* extension progs temporarily inherit the attach_type of their targets
13013            for verification purposes, so set it back to zero before returning
13014          */
13015         if (env->prog->type == BPF_PROG_TYPE_EXT)
13016                 env->prog->expected_attach_type = 0;
13017
13018         *prog = env->prog;
13019 err_unlock:
13020         if (!is_priv)
13021                 mutex_unlock(&bpf_verifier_lock);
13022         vfree(env->insn_aux_data);
13023 err_free_env:
13024         kfree(env);
13025         return ret;
13026 }