Merge tag 'asoc-fix-v5.13-rc4' of https://git.kernel.org/pub/scm/linux/kernel/git...
[linux-2.6-microblaze.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
25
26 #include "disasm.h"
27
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30         [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
34 #undef BPF_PROG_TYPE
35 #undef BPF_MAP_TYPE
36 #undef BPF_LINK_TYPE
37 };
38
39 /* bpf_check() is a static code analyzer that walks eBPF program
40  * instruction by instruction and updates register/stack state.
41  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42  *
43  * The first pass is depth-first-search to check that the program is a DAG.
44  * It rejects the following programs:
45  * - larger than BPF_MAXINSNS insns
46  * - if loop is present (detected via back-edge)
47  * - unreachable insns exist (shouldn't be a forest. program = one function)
48  * - out of bounds or malformed jumps
49  * The second pass is all possible path descent from the 1st insn.
50  * Since it's analyzing all 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 struct bpf_call_arg_meta {
238         struct bpf_map *map_ptr;
239         bool raw_mode;
240         bool pkt_access;
241         int regno;
242         int access_size;
243         int mem_size;
244         u64 msize_max_value;
245         int ref_obj_id;
246         int func_id;
247         struct btf *btf;
248         u32 btf_id;
249         struct btf *ret_btf;
250         u32 ret_btf_id;
251 };
252
253 struct btf *btf_vmlinux;
254
255 static DEFINE_MUTEX(bpf_verifier_lock);
256
257 static const struct bpf_line_info *
258 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
259 {
260         const struct bpf_line_info *linfo;
261         const struct bpf_prog *prog;
262         u32 i, nr_linfo;
263
264         prog = env->prog;
265         nr_linfo = prog->aux->nr_linfo;
266
267         if (!nr_linfo || insn_off >= prog->len)
268                 return NULL;
269
270         linfo = prog->aux->linfo;
271         for (i = 1; i < nr_linfo; i++)
272                 if (insn_off < linfo[i].insn_off)
273                         break;
274
275         return &linfo[i - 1];
276 }
277
278 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
279                        va_list args)
280 {
281         unsigned int n;
282
283         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
284
285         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
286                   "verifier log line truncated - local buffer too short\n");
287
288         n = min(log->len_total - log->len_used - 1, n);
289         log->kbuf[n] = '\0';
290
291         if (log->level == BPF_LOG_KERNEL) {
292                 pr_err("BPF:%s\n", log->kbuf);
293                 return;
294         }
295         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
296                 log->len_used += n;
297         else
298                 log->ubuf = NULL;
299 }
300
301 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
302 {
303         char zero = 0;
304
305         if (!bpf_verifier_log_needed(log))
306                 return;
307
308         log->len_used = new_pos;
309         if (put_user(zero, log->ubuf + new_pos))
310                 log->ubuf = NULL;
311 }
312
313 /* log_level controls verbosity level of eBPF verifier.
314  * bpf_verifier_log_write() is used to dump the verification trace to the log,
315  * so the user can figure out what's wrong with the program
316  */
317 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
318                                            const char *fmt, ...)
319 {
320         va_list args;
321
322         if (!bpf_verifier_log_needed(&env->log))
323                 return;
324
325         va_start(args, fmt);
326         bpf_verifier_vlog(&env->log, fmt, args);
327         va_end(args);
328 }
329 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
330
331 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
332 {
333         struct bpf_verifier_env *env = private_data;
334         va_list args;
335
336         if (!bpf_verifier_log_needed(&env->log))
337                 return;
338
339         va_start(args, fmt);
340         bpf_verifier_vlog(&env->log, fmt, args);
341         va_end(args);
342 }
343
344 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
345                             const char *fmt, ...)
346 {
347         va_list args;
348
349         if (!bpf_verifier_log_needed(log))
350                 return;
351
352         va_start(args, fmt);
353         bpf_verifier_vlog(log, fmt, args);
354         va_end(args);
355 }
356
357 static const char *ltrim(const char *s)
358 {
359         while (isspace(*s))
360                 s++;
361
362         return s;
363 }
364
365 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
366                                          u32 insn_off,
367                                          const char *prefix_fmt, ...)
368 {
369         const struct bpf_line_info *linfo;
370
371         if (!bpf_verifier_log_needed(&env->log))
372                 return;
373
374         linfo = find_linfo(env, insn_off);
375         if (!linfo || linfo == env->prev_linfo)
376                 return;
377
378         if (prefix_fmt) {
379                 va_list args;
380
381                 va_start(args, prefix_fmt);
382                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
383                 va_end(args);
384         }
385
386         verbose(env, "%s\n",
387                 ltrim(btf_name_by_offset(env->prog->aux->btf,
388                                          linfo->line_off)));
389
390         env->prev_linfo = linfo;
391 }
392
393 static bool type_is_pkt_pointer(enum bpf_reg_type type)
394 {
395         return type == PTR_TO_PACKET ||
396                type == PTR_TO_PACKET_META;
397 }
398
399 static bool type_is_sk_pointer(enum bpf_reg_type type)
400 {
401         return type == PTR_TO_SOCKET ||
402                 type == PTR_TO_SOCK_COMMON ||
403                 type == PTR_TO_TCP_SOCK ||
404                 type == PTR_TO_XDP_SOCK;
405 }
406
407 static bool reg_type_not_null(enum bpf_reg_type type)
408 {
409         return type == PTR_TO_SOCKET ||
410                 type == PTR_TO_TCP_SOCK ||
411                 type == PTR_TO_MAP_VALUE ||
412                 type == PTR_TO_SOCK_COMMON;
413 }
414
415 static bool reg_type_may_be_null(enum bpf_reg_type type)
416 {
417         return type == PTR_TO_MAP_VALUE_OR_NULL ||
418                type == PTR_TO_SOCKET_OR_NULL ||
419                type == PTR_TO_SOCK_COMMON_OR_NULL ||
420                type == PTR_TO_TCP_SOCK_OR_NULL ||
421                type == PTR_TO_BTF_ID_OR_NULL ||
422                type == PTR_TO_MEM_OR_NULL ||
423                type == PTR_TO_RDONLY_BUF_OR_NULL ||
424                type == PTR_TO_RDWR_BUF_OR_NULL;
425 }
426
427 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
428 {
429         return reg->type == PTR_TO_MAP_VALUE &&
430                 map_value_has_spin_lock(reg->map_ptr);
431 }
432
433 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
434 {
435         return type == PTR_TO_SOCKET ||
436                 type == PTR_TO_SOCKET_OR_NULL ||
437                 type == PTR_TO_TCP_SOCK ||
438                 type == PTR_TO_TCP_SOCK_OR_NULL ||
439                 type == PTR_TO_MEM ||
440                 type == PTR_TO_MEM_OR_NULL;
441 }
442
443 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
444 {
445         return type == ARG_PTR_TO_SOCK_COMMON;
446 }
447
448 static bool arg_type_may_be_null(enum bpf_arg_type type)
449 {
450         return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
451                type == ARG_PTR_TO_MEM_OR_NULL ||
452                type == ARG_PTR_TO_CTX_OR_NULL ||
453                type == ARG_PTR_TO_SOCKET_OR_NULL ||
454                type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
455 }
456
457 /* Determine whether the function releases some resources allocated by another
458  * function call. The first reference type argument will be assumed to be
459  * released by release_reference().
460  */
461 static bool is_release_function(enum bpf_func_id func_id)
462 {
463         return func_id == BPF_FUNC_sk_release ||
464                func_id == BPF_FUNC_ringbuf_submit ||
465                func_id == BPF_FUNC_ringbuf_discard;
466 }
467
468 static bool may_be_acquire_function(enum bpf_func_id func_id)
469 {
470         return func_id == BPF_FUNC_sk_lookup_tcp ||
471                 func_id == BPF_FUNC_sk_lookup_udp ||
472                 func_id == BPF_FUNC_skc_lookup_tcp ||
473                 func_id == BPF_FUNC_map_lookup_elem ||
474                 func_id == BPF_FUNC_ringbuf_reserve;
475 }
476
477 static bool is_acquire_function(enum bpf_func_id func_id,
478                                 const struct bpf_map *map)
479 {
480         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
481
482         if (func_id == BPF_FUNC_sk_lookup_tcp ||
483             func_id == BPF_FUNC_sk_lookup_udp ||
484             func_id == BPF_FUNC_skc_lookup_tcp ||
485             func_id == BPF_FUNC_ringbuf_reserve)
486                 return true;
487
488         if (func_id == BPF_FUNC_map_lookup_elem &&
489             (map_type == BPF_MAP_TYPE_SOCKMAP ||
490              map_type == BPF_MAP_TYPE_SOCKHASH))
491                 return true;
492
493         return false;
494 }
495
496 static bool is_ptr_cast_function(enum bpf_func_id func_id)
497 {
498         return func_id == BPF_FUNC_tcp_sock ||
499                 func_id == BPF_FUNC_sk_fullsock ||
500                 func_id == BPF_FUNC_skc_to_tcp_sock ||
501                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
502                 func_id == BPF_FUNC_skc_to_udp6_sock ||
503                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
504                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
505 }
506
507 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
508 {
509         return BPF_CLASS(insn->code) == BPF_STX &&
510                BPF_MODE(insn->code) == BPF_ATOMIC &&
511                insn->imm == BPF_CMPXCHG;
512 }
513
514 /* string representation of 'enum bpf_reg_type' */
515 static const char * const reg_type_str[] = {
516         [NOT_INIT]              = "?",
517         [SCALAR_VALUE]          = "inv",
518         [PTR_TO_CTX]            = "ctx",
519         [CONST_PTR_TO_MAP]      = "map_ptr",
520         [PTR_TO_MAP_VALUE]      = "map_value",
521         [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
522         [PTR_TO_STACK]          = "fp",
523         [PTR_TO_PACKET]         = "pkt",
524         [PTR_TO_PACKET_META]    = "pkt_meta",
525         [PTR_TO_PACKET_END]     = "pkt_end",
526         [PTR_TO_FLOW_KEYS]      = "flow_keys",
527         [PTR_TO_SOCKET]         = "sock",
528         [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
529         [PTR_TO_SOCK_COMMON]    = "sock_common",
530         [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
531         [PTR_TO_TCP_SOCK]       = "tcp_sock",
532         [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
533         [PTR_TO_TP_BUFFER]      = "tp_buffer",
534         [PTR_TO_XDP_SOCK]       = "xdp_sock",
535         [PTR_TO_BTF_ID]         = "ptr_",
536         [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
537         [PTR_TO_PERCPU_BTF_ID]  = "percpu_ptr_",
538         [PTR_TO_MEM]            = "mem",
539         [PTR_TO_MEM_OR_NULL]    = "mem_or_null",
540         [PTR_TO_RDONLY_BUF]     = "rdonly_buf",
541         [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
542         [PTR_TO_RDWR_BUF]       = "rdwr_buf",
543         [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
544 };
545
546 static char slot_type_char[] = {
547         [STACK_INVALID] = '?',
548         [STACK_SPILL]   = 'r',
549         [STACK_MISC]    = 'm',
550         [STACK_ZERO]    = '0',
551 };
552
553 static void print_liveness(struct bpf_verifier_env *env,
554                            enum bpf_reg_liveness live)
555 {
556         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
557             verbose(env, "_");
558         if (live & REG_LIVE_READ)
559                 verbose(env, "r");
560         if (live & REG_LIVE_WRITTEN)
561                 verbose(env, "w");
562         if (live & REG_LIVE_DONE)
563                 verbose(env, "D");
564 }
565
566 static struct bpf_func_state *func(struct bpf_verifier_env *env,
567                                    const struct bpf_reg_state *reg)
568 {
569         struct bpf_verifier_state *cur = env->cur_state;
570
571         return cur->frame[reg->frameno];
572 }
573
574 static const char *kernel_type_name(const struct btf* btf, u32 id)
575 {
576         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
577 }
578
579 static void print_verifier_state(struct bpf_verifier_env *env,
580                                  const struct bpf_func_state *state)
581 {
582         const struct bpf_reg_state *reg;
583         enum bpf_reg_type t;
584         int i;
585
586         if (state->frameno)
587                 verbose(env, " frame%d:", state->frameno);
588         for (i = 0; i < MAX_BPF_REG; i++) {
589                 reg = &state->regs[i];
590                 t = reg->type;
591                 if (t == NOT_INIT)
592                         continue;
593                 verbose(env, " R%d", i);
594                 print_liveness(env, reg->live);
595                 verbose(env, "=%s", reg_type_str[t]);
596                 if (t == SCALAR_VALUE && reg->precise)
597                         verbose(env, "P");
598                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
599                     tnum_is_const(reg->var_off)) {
600                         /* reg->off should be 0 for SCALAR_VALUE */
601                         verbose(env, "%lld", reg->var_off.value + reg->off);
602                 } else {
603                         if (t == PTR_TO_BTF_ID ||
604                             t == PTR_TO_BTF_ID_OR_NULL ||
605                             t == PTR_TO_PERCPU_BTF_ID)
606                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
607                         verbose(env, "(id=%d", reg->id);
608                         if (reg_type_may_be_refcounted_or_null(t))
609                                 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
610                         if (t != SCALAR_VALUE)
611                                 verbose(env, ",off=%d", reg->off);
612                         if (type_is_pkt_pointer(t))
613                                 verbose(env, ",r=%d", reg->range);
614                         else if (t == CONST_PTR_TO_MAP ||
615                                  t == PTR_TO_MAP_VALUE ||
616                                  t == PTR_TO_MAP_VALUE_OR_NULL)
617                                 verbose(env, ",ks=%d,vs=%d",
618                                         reg->map_ptr->key_size,
619                                         reg->map_ptr->value_size);
620                         if (tnum_is_const(reg->var_off)) {
621                                 /* Typically an immediate SCALAR_VALUE, but
622                                  * could be a pointer whose offset is too big
623                                  * for reg->off
624                                  */
625                                 verbose(env, ",imm=%llx", reg->var_off.value);
626                         } else {
627                                 if (reg->smin_value != reg->umin_value &&
628                                     reg->smin_value != S64_MIN)
629                                         verbose(env, ",smin_value=%lld",
630                                                 (long long)reg->smin_value);
631                                 if (reg->smax_value != reg->umax_value &&
632                                     reg->smax_value != S64_MAX)
633                                         verbose(env, ",smax_value=%lld",
634                                                 (long long)reg->smax_value);
635                                 if (reg->umin_value != 0)
636                                         verbose(env, ",umin_value=%llu",
637                                                 (unsigned long long)reg->umin_value);
638                                 if (reg->umax_value != U64_MAX)
639                                         verbose(env, ",umax_value=%llu",
640                                                 (unsigned long long)reg->umax_value);
641                                 if (!tnum_is_unknown(reg->var_off)) {
642                                         char tn_buf[48];
643
644                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
645                                         verbose(env, ",var_off=%s", tn_buf);
646                                 }
647                                 if (reg->s32_min_value != reg->smin_value &&
648                                     reg->s32_min_value != S32_MIN)
649                                         verbose(env, ",s32_min_value=%d",
650                                                 (int)(reg->s32_min_value));
651                                 if (reg->s32_max_value != reg->smax_value &&
652                                     reg->s32_max_value != S32_MAX)
653                                         verbose(env, ",s32_max_value=%d",
654                                                 (int)(reg->s32_max_value));
655                                 if (reg->u32_min_value != reg->umin_value &&
656                                     reg->u32_min_value != U32_MIN)
657                                         verbose(env, ",u32_min_value=%d",
658                                                 (int)(reg->u32_min_value));
659                                 if (reg->u32_max_value != reg->umax_value &&
660                                     reg->u32_max_value != U32_MAX)
661                                         verbose(env, ",u32_max_value=%d",
662                                                 (int)(reg->u32_max_value));
663                         }
664                         verbose(env, ")");
665                 }
666         }
667         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
668                 char types_buf[BPF_REG_SIZE + 1];
669                 bool valid = false;
670                 int j;
671
672                 for (j = 0; j < BPF_REG_SIZE; j++) {
673                         if (state->stack[i].slot_type[j] != STACK_INVALID)
674                                 valid = true;
675                         types_buf[j] = slot_type_char[
676                                         state->stack[i].slot_type[j]];
677                 }
678                 types_buf[BPF_REG_SIZE] = 0;
679                 if (!valid)
680                         continue;
681                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
682                 print_liveness(env, state->stack[i].spilled_ptr.live);
683                 if (state->stack[i].slot_type[0] == STACK_SPILL) {
684                         reg = &state->stack[i].spilled_ptr;
685                         t = reg->type;
686                         verbose(env, "=%s", reg_type_str[t]);
687                         if (t == SCALAR_VALUE && reg->precise)
688                                 verbose(env, "P");
689                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
690                                 verbose(env, "%lld", reg->var_off.value + reg->off);
691                 } else {
692                         verbose(env, "=%s", types_buf);
693                 }
694         }
695         if (state->acquired_refs && state->refs[0].id) {
696                 verbose(env, " refs=%d", state->refs[0].id);
697                 for (i = 1; i < state->acquired_refs; i++)
698                         if (state->refs[i].id)
699                                 verbose(env, ",%d", state->refs[i].id);
700         }
701         verbose(env, "\n");
702 }
703
704 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)                         \
705 static int copy_##NAME##_state(struct bpf_func_state *dst,              \
706                                const struct bpf_func_state *src)        \
707 {                                                                       \
708         if (!src->FIELD)                                                \
709                 return 0;                                               \
710         if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {                    \
711                 /* internal bug, make state invalid to reject the program */ \
712                 memset(dst, 0, sizeof(*dst));                           \
713                 return -EFAULT;                                         \
714         }                                                               \
715         memcpy(dst->FIELD, src->FIELD,                                  \
716                sizeof(*src->FIELD) * (src->COUNT / SIZE));              \
717         return 0;                                                       \
718 }
719 /* copy_reference_state() */
720 COPY_STATE_FN(reference, acquired_refs, refs, 1)
721 /* copy_stack_state() */
722 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
723 #undef COPY_STATE_FN
724
725 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)                      \
726 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
727                                   bool copy_old)                        \
728 {                                                                       \
729         u32 old_size = state->COUNT;                                    \
730         struct bpf_##NAME##_state *new_##FIELD;                         \
731         int slot = size / SIZE;                                         \
732                                                                         \
733         if (size <= old_size || !size) {                                \
734                 if (copy_old)                                           \
735                         return 0;                                       \
736                 state->COUNT = slot * SIZE;                             \
737                 if (!size && old_size) {                                \
738                         kfree(state->FIELD);                            \
739                         state->FIELD = NULL;                            \
740                 }                                                       \
741                 return 0;                                               \
742         }                                                               \
743         new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
744                                     GFP_KERNEL);                        \
745         if (!new_##FIELD)                                               \
746                 return -ENOMEM;                                         \
747         if (copy_old) {                                                 \
748                 if (state->FIELD)                                       \
749                         memcpy(new_##FIELD, state->FIELD,               \
750                                sizeof(*new_##FIELD) * (old_size / SIZE)); \
751                 memset(new_##FIELD + old_size / SIZE, 0,                \
752                        sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
753         }                                                               \
754         state->COUNT = slot * SIZE;                                     \
755         kfree(state->FIELD);                                            \
756         state->FIELD = new_##FIELD;                                     \
757         return 0;                                                       \
758 }
759 /* realloc_reference_state() */
760 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
761 /* realloc_stack_state() */
762 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
763 #undef REALLOC_STATE_FN
764
765 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
766  * make it consume minimal amount of memory. check_stack_write() access from
767  * the program calls into realloc_func_state() to grow the stack size.
768  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
769  * which realloc_stack_state() copies over. It points to previous
770  * bpf_verifier_state which is never reallocated.
771  */
772 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
773                               int refs_size, bool copy_old)
774 {
775         int err = realloc_reference_state(state, refs_size, copy_old);
776         if (err)
777                 return err;
778         return realloc_stack_state(state, stack_size, copy_old);
779 }
780
781 /* Acquire a pointer id from the env and update the state->refs to include
782  * this new pointer reference.
783  * On success, returns a valid pointer id to associate with the register
784  * On failure, returns a negative errno.
785  */
786 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
787 {
788         struct bpf_func_state *state = cur_func(env);
789         int new_ofs = state->acquired_refs;
790         int id, err;
791
792         err = realloc_reference_state(state, state->acquired_refs + 1, true);
793         if (err)
794                 return err;
795         id = ++env->id_gen;
796         state->refs[new_ofs].id = id;
797         state->refs[new_ofs].insn_idx = insn_idx;
798
799         return id;
800 }
801
802 /* release function corresponding to acquire_reference_state(). Idempotent. */
803 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
804 {
805         int i, last_idx;
806
807         last_idx = state->acquired_refs - 1;
808         for (i = 0; i < state->acquired_refs; i++) {
809                 if (state->refs[i].id == ptr_id) {
810                         if (last_idx && i != last_idx)
811                                 memcpy(&state->refs[i], &state->refs[last_idx],
812                                        sizeof(*state->refs));
813                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
814                         state->acquired_refs--;
815                         return 0;
816                 }
817         }
818         return -EINVAL;
819 }
820
821 static int transfer_reference_state(struct bpf_func_state *dst,
822                                     struct bpf_func_state *src)
823 {
824         int err = realloc_reference_state(dst, src->acquired_refs, false);
825         if (err)
826                 return err;
827         err = copy_reference_state(dst, src);
828         if (err)
829                 return err;
830         return 0;
831 }
832
833 static void free_func_state(struct bpf_func_state *state)
834 {
835         if (!state)
836                 return;
837         kfree(state->refs);
838         kfree(state->stack);
839         kfree(state);
840 }
841
842 static void clear_jmp_history(struct bpf_verifier_state *state)
843 {
844         kfree(state->jmp_history);
845         state->jmp_history = NULL;
846         state->jmp_history_cnt = 0;
847 }
848
849 static void free_verifier_state(struct bpf_verifier_state *state,
850                                 bool free_self)
851 {
852         int i;
853
854         for (i = 0; i <= state->curframe; i++) {
855                 free_func_state(state->frame[i]);
856                 state->frame[i] = NULL;
857         }
858         clear_jmp_history(state);
859         if (free_self)
860                 kfree(state);
861 }
862
863 /* copy verifier state from src to dst growing dst stack space
864  * when necessary to accommodate larger src stack
865  */
866 static int copy_func_state(struct bpf_func_state *dst,
867                            const struct bpf_func_state *src)
868 {
869         int err;
870
871         err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
872                                  false);
873         if (err)
874                 return err;
875         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
876         err = copy_reference_state(dst, src);
877         if (err)
878                 return err;
879         return copy_stack_state(dst, src);
880 }
881
882 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
883                                const struct bpf_verifier_state *src)
884 {
885         struct bpf_func_state *dst;
886         u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
887         int i, err;
888
889         if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
890                 kfree(dst_state->jmp_history);
891                 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
892                 if (!dst_state->jmp_history)
893                         return -ENOMEM;
894         }
895         memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
896         dst_state->jmp_history_cnt = src->jmp_history_cnt;
897
898         /* if dst has more stack frames then src frame, free them */
899         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
900                 free_func_state(dst_state->frame[i]);
901                 dst_state->frame[i] = NULL;
902         }
903         dst_state->speculative = src->speculative;
904         dst_state->curframe = src->curframe;
905         dst_state->active_spin_lock = src->active_spin_lock;
906         dst_state->branches = src->branches;
907         dst_state->parent = src->parent;
908         dst_state->first_insn_idx = src->first_insn_idx;
909         dst_state->last_insn_idx = src->last_insn_idx;
910         for (i = 0; i <= src->curframe; i++) {
911                 dst = dst_state->frame[i];
912                 if (!dst) {
913                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
914                         if (!dst)
915                                 return -ENOMEM;
916                         dst_state->frame[i] = dst;
917                 }
918                 err = copy_func_state(dst, src->frame[i]);
919                 if (err)
920                         return err;
921         }
922         return 0;
923 }
924
925 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
926 {
927         while (st) {
928                 u32 br = --st->branches;
929
930                 /* WARN_ON(br > 1) technically makes sense here,
931                  * but see comment in push_stack(), hence:
932                  */
933                 WARN_ONCE((int)br < 0,
934                           "BUG update_branch_counts:branches_to_explore=%d\n",
935                           br);
936                 if (br)
937                         break;
938                 st = st->parent;
939         }
940 }
941
942 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
943                      int *insn_idx, bool pop_log)
944 {
945         struct bpf_verifier_state *cur = env->cur_state;
946         struct bpf_verifier_stack_elem *elem, *head = env->head;
947         int err;
948
949         if (env->head == NULL)
950                 return -ENOENT;
951
952         if (cur) {
953                 err = copy_verifier_state(cur, &head->st);
954                 if (err)
955                         return err;
956         }
957         if (pop_log)
958                 bpf_vlog_reset(&env->log, head->log_pos);
959         if (insn_idx)
960                 *insn_idx = head->insn_idx;
961         if (prev_insn_idx)
962                 *prev_insn_idx = head->prev_insn_idx;
963         elem = head->next;
964         free_verifier_state(&head->st, false);
965         kfree(head);
966         env->head = elem;
967         env->stack_size--;
968         return 0;
969 }
970
971 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
972                                              int insn_idx, int prev_insn_idx,
973                                              bool speculative)
974 {
975         struct bpf_verifier_state *cur = env->cur_state;
976         struct bpf_verifier_stack_elem *elem;
977         int err;
978
979         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
980         if (!elem)
981                 goto err;
982
983         elem->insn_idx = insn_idx;
984         elem->prev_insn_idx = prev_insn_idx;
985         elem->next = env->head;
986         elem->log_pos = env->log.len_used;
987         env->head = elem;
988         env->stack_size++;
989         err = copy_verifier_state(&elem->st, cur);
990         if (err)
991                 goto err;
992         elem->st.speculative |= speculative;
993         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
994                 verbose(env, "The sequence of %d jumps is too complex.\n",
995                         env->stack_size);
996                 goto err;
997         }
998         if (elem->st.parent) {
999                 ++elem->st.parent->branches;
1000                 /* WARN_ON(branches > 2) technically makes sense here,
1001                  * but
1002                  * 1. speculative states will bump 'branches' for non-branch
1003                  * instructions
1004                  * 2. is_state_visited() heuristics may decide not to create
1005                  * a new state for a sequence of branches and all such current
1006                  * and cloned states will be pointing to a single parent state
1007                  * which might have large 'branches' count.
1008                  */
1009         }
1010         return &elem->st;
1011 err:
1012         free_verifier_state(env->cur_state, true);
1013         env->cur_state = NULL;
1014         /* pop all elements and return */
1015         while (!pop_stack(env, NULL, NULL, false));
1016         return NULL;
1017 }
1018
1019 #define CALLER_SAVED_REGS 6
1020 static const int caller_saved[CALLER_SAVED_REGS] = {
1021         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1022 };
1023
1024 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1025                                 struct bpf_reg_state *reg);
1026
1027 /* This helper doesn't clear reg->id */
1028 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1029 {
1030         reg->var_off = tnum_const(imm);
1031         reg->smin_value = (s64)imm;
1032         reg->smax_value = (s64)imm;
1033         reg->umin_value = imm;
1034         reg->umax_value = imm;
1035
1036         reg->s32_min_value = (s32)imm;
1037         reg->s32_max_value = (s32)imm;
1038         reg->u32_min_value = (u32)imm;
1039         reg->u32_max_value = (u32)imm;
1040 }
1041
1042 /* Mark the unknown part of a register (variable offset or scalar value) as
1043  * known to have the value @imm.
1044  */
1045 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1046 {
1047         /* Clear id, off, and union(map_ptr, range) */
1048         memset(((u8 *)reg) + sizeof(reg->type), 0,
1049                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1050         ___mark_reg_known(reg, imm);
1051 }
1052
1053 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1054 {
1055         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1056         reg->s32_min_value = (s32)imm;
1057         reg->s32_max_value = (s32)imm;
1058         reg->u32_min_value = (u32)imm;
1059         reg->u32_max_value = (u32)imm;
1060 }
1061
1062 /* Mark the 'variable offset' part of a register as zero.  This should be
1063  * used only on registers holding a pointer type.
1064  */
1065 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1066 {
1067         __mark_reg_known(reg, 0);
1068 }
1069
1070 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1071 {
1072         __mark_reg_known(reg, 0);
1073         reg->type = SCALAR_VALUE;
1074 }
1075
1076 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1077                                 struct bpf_reg_state *regs, u32 regno)
1078 {
1079         if (WARN_ON(regno >= MAX_BPF_REG)) {
1080                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1081                 /* Something bad happened, let's kill all regs */
1082                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1083                         __mark_reg_not_init(env, regs + regno);
1084                 return;
1085         }
1086         __mark_reg_known_zero(regs + regno);
1087 }
1088
1089 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1090 {
1091         switch (reg->type) {
1092         case PTR_TO_MAP_VALUE_OR_NULL: {
1093                 const struct bpf_map *map = reg->map_ptr;
1094
1095                 if (map->inner_map_meta) {
1096                         reg->type = CONST_PTR_TO_MAP;
1097                         reg->map_ptr = map->inner_map_meta;
1098                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1099                         reg->type = PTR_TO_XDP_SOCK;
1100                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1101                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1102                         reg->type = PTR_TO_SOCKET;
1103                 } else {
1104                         reg->type = PTR_TO_MAP_VALUE;
1105                 }
1106                 break;
1107         }
1108         case PTR_TO_SOCKET_OR_NULL:
1109                 reg->type = PTR_TO_SOCKET;
1110                 break;
1111         case PTR_TO_SOCK_COMMON_OR_NULL:
1112                 reg->type = PTR_TO_SOCK_COMMON;
1113                 break;
1114         case PTR_TO_TCP_SOCK_OR_NULL:
1115                 reg->type = PTR_TO_TCP_SOCK;
1116                 break;
1117         case PTR_TO_BTF_ID_OR_NULL:
1118                 reg->type = PTR_TO_BTF_ID;
1119                 break;
1120         case PTR_TO_MEM_OR_NULL:
1121                 reg->type = PTR_TO_MEM;
1122                 break;
1123         case PTR_TO_RDONLY_BUF_OR_NULL:
1124                 reg->type = PTR_TO_RDONLY_BUF;
1125                 break;
1126         case PTR_TO_RDWR_BUF_OR_NULL:
1127                 reg->type = PTR_TO_RDWR_BUF;
1128                 break;
1129         default:
1130                 WARN_ONCE(1, "unknown nullable register type");
1131         }
1132 }
1133
1134 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1135 {
1136         return type_is_pkt_pointer(reg->type);
1137 }
1138
1139 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1140 {
1141         return reg_is_pkt_pointer(reg) ||
1142                reg->type == PTR_TO_PACKET_END;
1143 }
1144
1145 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1146 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1147                                     enum bpf_reg_type which)
1148 {
1149         /* The register can already have a range from prior markings.
1150          * This is fine as long as it hasn't been advanced from its
1151          * origin.
1152          */
1153         return reg->type == which &&
1154                reg->id == 0 &&
1155                reg->off == 0 &&
1156                tnum_equals_const(reg->var_off, 0);
1157 }
1158
1159 /* Reset the min/max bounds of a register */
1160 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1161 {
1162         reg->smin_value = S64_MIN;
1163         reg->smax_value = S64_MAX;
1164         reg->umin_value = 0;
1165         reg->umax_value = U64_MAX;
1166
1167         reg->s32_min_value = S32_MIN;
1168         reg->s32_max_value = S32_MAX;
1169         reg->u32_min_value = 0;
1170         reg->u32_max_value = U32_MAX;
1171 }
1172
1173 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1174 {
1175         reg->smin_value = S64_MIN;
1176         reg->smax_value = S64_MAX;
1177         reg->umin_value = 0;
1178         reg->umax_value = U64_MAX;
1179 }
1180
1181 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1182 {
1183         reg->s32_min_value = S32_MIN;
1184         reg->s32_max_value = S32_MAX;
1185         reg->u32_min_value = 0;
1186         reg->u32_max_value = U32_MAX;
1187 }
1188
1189 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1190 {
1191         struct tnum var32_off = tnum_subreg(reg->var_off);
1192
1193         /* min signed is max(sign bit) | min(other bits) */
1194         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1195                         var32_off.value | (var32_off.mask & S32_MIN));
1196         /* max signed is min(sign bit) | max(other bits) */
1197         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1198                         var32_off.value | (var32_off.mask & S32_MAX));
1199         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1200         reg->u32_max_value = min(reg->u32_max_value,
1201                                  (u32)(var32_off.value | var32_off.mask));
1202 }
1203
1204 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1205 {
1206         /* min signed is max(sign bit) | min(other bits) */
1207         reg->smin_value = max_t(s64, reg->smin_value,
1208                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1209         /* max signed is min(sign bit) | max(other bits) */
1210         reg->smax_value = min_t(s64, reg->smax_value,
1211                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1212         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1213         reg->umax_value = min(reg->umax_value,
1214                               reg->var_off.value | reg->var_off.mask);
1215 }
1216
1217 static void __update_reg_bounds(struct bpf_reg_state *reg)
1218 {
1219         __update_reg32_bounds(reg);
1220         __update_reg64_bounds(reg);
1221 }
1222
1223 /* Uses signed min/max values to inform unsigned, and vice-versa */
1224 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1225 {
1226         /* Learn sign from signed bounds.
1227          * If we cannot cross the sign boundary, then signed and unsigned bounds
1228          * are the same, so combine.  This works even in the negative case, e.g.
1229          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1230          */
1231         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1232                 reg->s32_min_value = reg->u32_min_value =
1233                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1234                 reg->s32_max_value = reg->u32_max_value =
1235                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1236                 return;
1237         }
1238         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1239          * boundary, so we must be careful.
1240          */
1241         if ((s32)reg->u32_max_value >= 0) {
1242                 /* Positive.  We can't learn anything from the smin, but smax
1243                  * is positive, hence safe.
1244                  */
1245                 reg->s32_min_value = reg->u32_min_value;
1246                 reg->s32_max_value = reg->u32_max_value =
1247                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1248         } else if ((s32)reg->u32_min_value < 0) {
1249                 /* Negative.  We can't learn anything from the smax, but smin
1250                  * is negative, hence safe.
1251                  */
1252                 reg->s32_min_value = reg->u32_min_value =
1253                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1254                 reg->s32_max_value = reg->u32_max_value;
1255         }
1256 }
1257
1258 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1259 {
1260         /* Learn sign from signed bounds.
1261          * If we cannot cross the sign boundary, then signed and unsigned bounds
1262          * are the same, so combine.  This works even in the negative case, e.g.
1263          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1264          */
1265         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1266                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1267                                                           reg->umin_value);
1268                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1269                                                           reg->umax_value);
1270                 return;
1271         }
1272         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1273          * boundary, so we must be careful.
1274          */
1275         if ((s64)reg->umax_value >= 0) {
1276                 /* Positive.  We can't learn anything from the smin, but smax
1277                  * is positive, hence safe.
1278                  */
1279                 reg->smin_value = reg->umin_value;
1280                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1281                                                           reg->umax_value);
1282         } else if ((s64)reg->umin_value < 0) {
1283                 /* Negative.  We can't learn anything from the smax, but smin
1284                  * is negative, hence safe.
1285                  */
1286                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1287                                                           reg->umin_value);
1288                 reg->smax_value = reg->umax_value;
1289         }
1290 }
1291
1292 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1293 {
1294         __reg32_deduce_bounds(reg);
1295         __reg64_deduce_bounds(reg);
1296 }
1297
1298 /* Attempts to improve var_off based on unsigned min/max information */
1299 static void __reg_bound_offset(struct bpf_reg_state *reg)
1300 {
1301         struct tnum var64_off = tnum_intersect(reg->var_off,
1302                                                tnum_range(reg->umin_value,
1303                                                           reg->umax_value));
1304         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1305                                                 tnum_range(reg->u32_min_value,
1306                                                            reg->u32_max_value));
1307
1308         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1309 }
1310
1311 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1312 {
1313         reg->umin_value = reg->u32_min_value;
1314         reg->umax_value = reg->u32_max_value;
1315         /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1316          * but must be positive otherwise set to worse case bounds
1317          * and refine later from tnum.
1318          */
1319         if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1320                 reg->smax_value = reg->s32_max_value;
1321         else
1322                 reg->smax_value = U32_MAX;
1323         if (reg->s32_min_value >= 0)
1324                 reg->smin_value = reg->s32_min_value;
1325         else
1326                 reg->smin_value = 0;
1327 }
1328
1329 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1330 {
1331         /* special case when 64-bit register has upper 32-bit register
1332          * zeroed. Typically happens after zext or <<32, >>32 sequence
1333          * allowing us to use 32-bit bounds directly,
1334          */
1335         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1336                 __reg_assign_32_into_64(reg);
1337         } else {
1338                 /* Otherwise the best we can do is push lower 32bit known and
1339                  * unknown bits into register (var_off set from jmp logic)
1340                  * then learn as much as possible from the 64-bit tnum
1341                  * known and unknown bits. The previous smin/smax bounds are
1342                  * invalid here because of jmp32 compare so mark them unknown
1343                  * so they do not impact tnum bounds calculation.
1344                  */
1345                 __mark_reg64_unbounded(reg);
1346                 __update_reg_bounds(reg);
1347         }
1348
1349         /* Intersecting with the old var_off might have improved our bounds
1350          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1351          * then new var_off is (0; 0x7f...fc) which improves our umax.
1352          */
1353         __reg_deduce_bounds(reg);
1354         __reg_bound_offset(reg);
1355         __update_reg_bounds(reg);
1356 }
1357
1358 static bool __reg64_bound_s32(s64 a)
1359 {
1360         return a > S32_MIN && a < S32_MAX;
1361 }
1362
1363 static bool __reg64_bound_u32(u64 a)
1364 {
1365         if (a > U32_MIN && a < U32_MAX)
1366                 return true;
1367         return false;
1368 }
1369
1370 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1371 {
1372         __mark_reg32_unbounded(reg);
1373
1374         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1375                 reg->s32_min_value = (s32)reg->smin_value;
1376                 reg->s32_max_value = (s32)reg->smax_value;
1377         }
1378         if (__reg64_bound_u32(reg->umin_value))
1379                 reg->u32_min_value = (u32)reg->umin_value;
1380         if (__reg64_bound_u32(reg->umax_value))
1381                 reg->u32_max_value = (u32)reg->umax_value;
1382
1383         /* Intersecting with the old var_off might have improved our bounds
1384          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1385          * then new var_off is (0; 0x7f...fc) which improves our umax.
1386          */
1387         __reg_deduce_bounds(reg);
1388         __reg_bound_offset(reg);
1389         __update_reg_bounds(reg);
1390 }
1391
1392 /* Mark a register as having a completely unknown (scalar) value. */
1393 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1394                                struct bpf_reg_state *reg)
1395 {
1396         /*
1397          * Clear type, id, off, and union(map_ptr, range) and
1398          * padding between 'type' and union
1399          */
1400         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1401         reg->type = SCALAR_VALUE;
1402         reg->var_off = tnum_unknown;
1403         reg->frameno = 0;
1404         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1405         __mark_reg_unbounded(reg);
1406 }
1407
1408 static void mark_reg_unknown(struct bpf_verifier_env *env,
1409                              struct bpf_reg_state *regs, u32 regno)
1410 {
1411         if (WARN_ON(regno >= MAX_BPF_REG)) {
1412                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1413                 /* Something bad happened, let's kill all regs except FP */
1414                 for (regno = 0; regno < BPF_REG_FP; regno++)
1415                         __mark_reg_not_init(env, regs + regno);
1416                 return;
1417         }
1418         __mark_reg_unknown(env, regs + regno);
1419 }
1420
1421 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1422                                 struct bpf_reg_state *reg)
1423 {
1424         __mark_reg_unknown(env, reg);
1425         reg->type = NOT_INIT;
1426 }
1427
1428 static void mark_reg_not_init(struct bpf_verifier_env *env,
1429                               struct bpf_reg_state *regs, u32 regno)
1430 {
1431         if (WARN_ON(regno >= MAX_BPF_REG)) {
1432                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1433                 /* Something bad happened, let's kill all regs except FP */
1434                 for (regno = 0; regno < BPF_REG_FP; regno++)
1435                         __mark_reg_not_init(env, regs + regno);
1436                 return;
1437         }
1438         __mark_reg_not_init(env, regs + regno);
1439 }
1440
1441 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1442                             struct bpf_reg_state *regs, u32 regno,
1443                             enum bpf_reg_type reg_type,
1444                             struct btf *btf, u32 btf_id)
1445 {
1446         if (reg_type == SCALAR_VALUE) {
1447                 mark_reg_unknown(env, regs, regno);
1448                 return;
1449         }
1450         mark_reg_known_zero(env, regs, regno);
1451         regs[regno].type = PTR_TO_BTF_ID;
1452         regs[regno].btf = btf;
1453         regs[regno].btf_id = btf_id;
1454 }
1455
1456 #define DEF_NOT_SUBREG  (0)
1457 static void init_reg_state(struct bpf_verifier_env *env,
1458                            struct bpf_func_state *state)
1459 {
1460         struct bpf_reg_state *regs = state->regs;
1461         int i;
1462
1463         for (i = 0; i < MAX_BPF_REG; i++) {
1464                 mark_reg_not_init(env, regs, i);
1465                 regs[i].live = REG_LIVE_NONE;
1466                 regs[i].parent = NULL;
1467                 regs[i].subreg_def = DEF_NOT_SUBREG;
1468         }
1469
1470         /* frame pointer */
1471         regs[BPF_REG_FP].type = PTR_TO_STACK;
1472         mark_reg_known_zero(env, regs, BPF_REG_FP);
1473         regs[BPF_REG_FP].frameno = state->frameno;
1474 }
1475
1476 #define BPF_MAIN_FUNC (-1)
1477 static void init_func_state(struct bpf_verifier_env *env,
1478                             struct bpf_func_state *state,
1479                             int callsite, int frameno, int subprogno)
1480 {
1481         state->callsite = callsite;
1482         state->frameno = frameno;
1483         state->subprogno = subprogno;
1484         init_reg_state(env, state);
1485 }
1486
1487 enum reg_arg_type {
1488         SRC_OP,         /* register is used as source operand */
1489         DST_OP,         /* register is used as destination operand */
1490         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1491 };
1492
1493 static int cmp_subprogs(const void *a, const void *b)
1494 {
1495         return ((struct bpf_subprog_info *)a)->start -
1496                ((struct bpf_subprog_info *)b)->start;
1497 }
1498
1499 static int find_subprog(struct bpf_verifier_env *env, int off)
1500 {
1501         struct bpf_subprog_info *p;
1502
1503         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1504                     sizeof(env->subprog_info[0]), cmp_subprogs);
1505         if (!p)
1506                 return -ENOENT;
1507         return p - env->subprog_info;
1508
1509 }
1510
1511 static int add_subprog(struct bpf_verifier_env *env, int off)
1512 {
1513         int insn_cnt = env->prog->len;
1514         int ret;
1515
1516         if (off >= insn_cnt || off < 0) {
1517                 verbose(env, "call to invalid destination\n");
1518                 return -EINVAL;
1519         }
1520         ret = find_subprog(env, off);
1521         if (ret >= 0)
1522                 return 0;
1523         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1524                 verbose(env, "too many subprograms\n");
1525                 return -E2BIG;
1526         }
1527         env->subprog_info[env->subprog_cnt++].start = off;
1528         sort(env->subprog_info, env->subprog_cnt,
1529              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1530         return 0;
1531 }
1532
1533 static int check_subprogs(struct bpf_verifier_env *env)
1534 {
1535         int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1536         struct bpf_subprog_info *subprog = env->subprog_info;
1537         struct bpf_insn *insn = env->prog->insnsi;
1538         int insn_cnt = env->prog->len;
1539
1540         /* Add entry function. */
1541         ret = add_subprog(env, 0);
1542         if (ret < 0)
1543                 return ret;
1544
1545         /* determine subprog starts. The end is one before the next starts */
1546         for (i = 0; i < insn_cnt; i++) {
1547                 if (!bpf_pseudo_call(insn + i))
1548                         continue;
1549                 if (!env->bpf_capable) {
1550                         verbose(env,
1551                                 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1552                         return -EPERM;
1553                 }
1554                 ret = add_subprog(env, i + insn[i].imm + 1);
1555                 if (ret < 0)
1556                         return ret;
1557         }
1558
1559         /* Add a fake 'exit' subprog which could simplify subprog iteration
1560          * logic. 'subprog_cnt' should not be increased.
1561          */
1562         subprog[env->subprog_cnt].start = insn_cnt;
1563
1564         if (env->log.level & BPF_LOG_LEVEL2)
1565                 for (i = 0; i < env->subprog_cnt; i++)
1566                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
1567
1568         /* now check that all jumps are within the same subprog */
1569         subprog_start = subprog[cur_subprog].start;
1570         subprog_end = subprog[cur_subprog + 1].start;
1571         for (i = 0; i < insn_cnt; i++) {
1572                 u8 code = insn[i].code;
1573
1574                 if (code == (BPF_JMP | BPF_CALL) &&
1575                     insn[i].imm == BPF_FUNC_tail_call &&
1576                     insn[i].src_reg != BPF_PSEUDO_CALL)
1577                         subprog[cur_subprog].has_tail_call = true;
1578                 if (BPF_CLASS(code) == BPF_LD &&
1579                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1580                         subprog[cur_subprog].has_ld_abs = true;
1581                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1582                         goto next;
1583                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1584                         goto next;
1585                 off = i + insn[i].off + 1;
1586                 if (off < subprog_start || off >= subprog_end) {
1587                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
1588                         return -EINVAL;
1589                 }
1590 next:
1591                 if (i == subprog_end - 1) {
1592                         /* to avoid fall-through from one subprog into another
1593                          * the last insn of the subprog should be either exit
1594                          * or unconditional jump back
1595                          */
1596                         if (code != (BPF_JMP | BPF_EXIT) &&
1597                             code != (BPF_JMP | BPF_JA)) {
1598                                 verbose(env, "last insn is not an exit or jmp\n");
1599                                 return -EINVAL;
1600                         }
1601                         subprog_start = subprog_end;
1602                         cur_subprog++;
1603                         if (cur_subprog < env->subprog_cnt)
1604                                 subprog_end = subprog[cur_subprog + 1].start;
1605                 }
1606         }
1607         return 0;
1608 }
1609
1610 /* Parentage chain of this register (or stack slot) should take care of all
1611  * issues like callee-saved registers, stack slot allocation time, etc.
1612  */
1613 static int mark_reg_read(struct bpf_verifier_env *env,
1614                          const struct bpf_reg_state *state,
1615                          struct bpf_reg_state *parent, u8 flag)
1616 {
1617         bool writes = parent == state->parent; /* Observe write marks */
1618         int cnt = 0;
1619
1620         while (parent) {
1621                 /* if read wasn't screened by an earlier write ... */
1622                 if (writes && state->live & REG_LIVE_WRITTEN)
1623                         break;
1624                 if (parent->live & REG_LIVE_DONE) {
1625                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1626                                 reg_type_str[parent->type],
1627                                 parent->var_off.value, parent->off);
1628                         return -EFAULT;
1629                 }
1630                 /* The first condition is more likely to be true than the
1631                  * second, checked it first.
1632                  */
1633                 if ((parent->live & REG_LIVE_READ) == flag ||
1634                     parent->live & REG_LIVE_READ64)
1635                         /* The parentage chain never changes and
1636                          * this parent was already marked as LIVE_READ.
1637                          * There is no need to keep walking the chain again and
1638                          * keep re-marking all parents as LIVE_READ.
1639                          * This case happens when the same register is read
1640                          * multiple times without writes into it in-between.
1641                          * Also, if parent has the stronger REG_LIVE_READ64 set,
1642                          * then no need to set the weak REG_LIVE_READ32.
1643                          */
1644                         break;
1645                 /* ... then we depend on parent's value */
1646                 parent->live |= flag;
1647                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1648                 if (flag == REG_LIVE_READ64)
1649                         parent->live &= ~REG_LIVE_READ32;
1650                 state = parent;
1651                 parent = state->parent;
1652                 writes = true;
1653                 cnt++;
1654         }
1655
1656         if (env->longest_mark_read_walk < cnt)
1657                 env->longest_mark_read_walk = cnt;
1658         return 0;
1659 }
1660
1661 /* This function is supposed to be used by the following 32-bit optimization
1662  * code only. It returns TRUE if the source or destination register operates
1663  * on 64-bit, otherwise return FALSE.
1664  */
1665 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1666                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1667 {
1668         u8 code, class, op;
1669
1670         code = insn->code;
1671         class = BPF_CLASS(code);
1672         op = BPF_OP(code);
1673         if (class == BPF_JMP) {
1674                 /* BPF_EXIT for "main" will reach here. Return TRUE
1675                  * conservatively.
1676                  */
1677                 if (op == BPF_EXIT)
1678                         return true;
1679                 if (op == BPF_CALL) {
1680                         /* BPF to BPF call will reach here because of marking
1681                          * caller saved clobber with DST_OP_NO_MARK for which we
1682                          * don't care the register def because they are anyway
1683                          * marked as NOT_INIT already.
1684                          */
1685                         if (insn->src_reg == BPF_PSEUDO_CALL)
1686                                 return false;
1687                         /* Helper call will reach here because of arg type
1688                          * check, conservatively return TRUE.
1689                          */
1690                         if (t == SRC_OP)
1691                                 return true;
1692
1693                         return false;
1694                 }
1695         }
1696
1697         if (class == BPF_ALU64 || class == BPF_JMP ||
1698             /* BPF_END always use BPF_ALU class. */
1699             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1700                 return true;
1701
1702         if (class == BPF_ALU || class == BPF_JMP32)
1703                 return false;
1704
1705         if (class == BPF_LDX) {
1706                 if (t != SRC_OP)
1707                         return BPF_SIZE(code) == BPF_DW;
1708                 /* LDX source must be ptr. */
1709                 return true;
1710         }
1711
1712         if (class == BPF_STX) {
1713                 /* BPF_STX (including atomic variants) has multiple source
1714                  * operands, one of which is a ptr. Check whether the caller is
1715                  * asking about it.
1716                  */
1717                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
1718                         return true;
1719                 return BPF_SIZE(code) == BPF_DW;
1720         }
1721
1722         if (class == BPF_LD) {
1723                 u8 mode = BPF_MODE(code);
1724
1725                 /* LD_IMM64 */
1726                 if (mode == BPF_IMM)
1727                         return true;
1728
1729                 /* Both LD_IND and LD_ABS return 32-bit data. */
1730                 if (t != SRC_OP)
1731                         return  false;
1732
1733                 /* Implicit ctx ptr. */
1734                 if (regno == BPF_REG_6)
1735                         return true;
1736
1737                 /* Explicit source could be any width. */
1738                 return true;
1739         }
1740
1741         if (class == BPF_ST)
1742                 /* The only source register for BPF_ST is a ptr. */
1743                 return true;
1744
1745         /* Conservatively return true at default. */
1746         return true;
1747 }
1748
1749 /* Return the regno defined by the insn, or -1. */
1750 static int insn_def_regno(const struct bpf_insn *insn)
1751 {
1752         switch (BPF_CLASS(insn->code)) {
1753         case BPF_JMP:
1754         case BPF_JMP32:
1755         case BPF_ST:
1756                 return -1;
1757         case BPF_STX:
1758                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1759                     (insn->imm & BPF_FETCH)) {
1760                         if (insn->imm == BPF_CMPXCHG)
1761                                 return BPF_REG_0;
1762                         else
1763                                 return insn->src_reg;
1764                 } else {
1765                         return -1;
1766                 }
1767         default:
1768                 return insn->dst_reg;
1769         }
1770 }
1771
1772 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1773 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1774 {
1775         int dst_reg = insn_def_regno(insn);
1776
1777         if (dst_reg == -1)
1778                 return false;
1779
1780         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
1781 }
1782
1783 static void mark_insn_zext(struct bpf_verifier_env *env,
1784                            struct bpf_reg_state *reg)
1785 {
1786         s32 def_idx = reg->subreg_def;
1787
1788         if (def_idx == DEF_NOT_SUBREG)
1789                 return;
1790
1791         env->insn_aux_data[def_idx - 1].zext_dst = true;
1792         /* The dst will be zero extended, so won't be sub-register anymore. */
1793         reg->subreg_def = DEF_NOT_SUBREG;
1794 }
1795
1796 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1797                          enum reg_arg_type t)
1798 {
1799         struct bpf_verifier_state *vstate = env->cur_state;
1800         struct bpf_func_state *state = vstate->frame[vstate->curframe];
1801         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1802         struct bpf_reg_state *reg, *regs = state->regs;
1803         bool rw64;
1804
1805         if (regno >= MAX_BPF_REG) {
1806                 verbose(env, "R%d is invalid\n", regno);
1807                 return -EINVAL;
1808         }
1809
1810         reg = &regs[regno];
1811         rw64 = is_reg64(env, insn, regno, reg, t);
1812         if (t == SRC_OP) {
1813                 /* check whether register used as source operand can be read */
1814                 if (reg->type == NOT_INIT) {
1815                         verbose(env, "R%d !read_ok\n", regno);
1816                         return -EACCES;
1817                 }
1818                 /* We don't need to worry about FP liveness because it's read-only */
1819                 if (regno == BPF_REG_FP)
1820                         return 0;
1821
1822                 if (rw64)
1823                         mark_insn_zext(env, reg);
1824
1825                 return mark_reg_read(env, reg, reg->parent,
1826                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1827         } else {
1828                 /* check whether register used as dest operand can be written to */
1829                 if (regno == BPF_REG_FP) {
1830                         verbose(env, "frame pointer is read only\n");
1831                         return -EACCES;
1832                 }
1833                 reg->live |= REG_LIVE_WRITTEN;
1834                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1835                 if (t == DST_OP)
1836                         mark_reg_unknown(env, regs, regno);
1837         }
1838         return 0;
1839 }
1840
1841 /* for any branch, call, exit record the history of jmps in the given state */
1842 static int push_jmp_history(struct bpf_verifier_env *env,
1843                             struct bpf_verifier_state *cur)
1844 {
1845         u32 cnt = cur->jmp_history_cnt;
1846         struct bpf_idx_pair *p;
1847
1848         cnt++;
1849         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1850         if (!p)
1851                 return -ENOMEM;
1852         p[cnt - 1].idx = env->insn_idx;
1853         p[cnt - 1].prev_idx = env->prev_insn_idx;
1854         cur->jmp_history = p;
1855         cur->jmp_history_cnt = cnt;
1856         return 0;
1857 }
1858
1859 /* Backtrack one insn at a time. If idx is not at the top of recorded
1860  * history then previous instruction came from straight line execution.
1861  */
1862 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1863                              u32 *history)
1864 {
1865         u32 cnt = *history;
1866
1867         if (cnt && st->jmp_history[cnt - 1].idx == i) {
1868                 i = st->jmp_history[cnt - 1].prev_idx;
1869                 (*history)--;
1870         } else {
1871                 i--;
1872         }
1873         return i;
1874 }
1875
1876 /* For given verifier state backtrack_insn() is called from the last insn to
1877  * the first insn. Its purpose is to compute a bitmask of registers and
1878  * stack slots that needs precision in the parent verifier state.
1879  */
1880 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1881                           u32 *reg_mask, u64 *stack_mask)
1882 {
1883         const struct bpf_insn_cbs cbs = {
1884                 .cb_print       = verbose,
1885                 .private_data   = env,
1886         };
1887         struct bpf_insn *insn = env->prog->insnsi + idx;
1888         u8 class = BPF_CLASS(insn->code);
1889         u8 opcode = BPF_OP(insn->code);
1890         u8 mode = BPF_MODE(insn->code);
1891         u32 dreg = 1u << insn->dst_reg;
1892         u32 sreg = 1u << insn->src_reg;
1893         u32 spi;
1894
1895         if (insn->code == 0)
1896                 return 0;
1897         if (env->log.level & BPF_LOG_LEVEL) {
1898                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1899                 verbose(env, "%d: ", idx);
1900                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1901         }
1902
1903         if (class == BPF_ALU || class == BPF_ALU64) {
1904                 if (!(*reg_mask & dreg))
1905                         return 0;
1906                 if (opcode == BPF_MOV) {
1907                         if (BPF_SRC(insn->code) == BPF_X) {
1908                                 /* dreg = sreg
1909                                  * dreg needs precision after this insn
1910                                  * sreg needs precision before this insn
1911                                  */
1912                                 *reg_mask &= ~dreg;
1913                                 *reg_mask |= sreg;
1914                         } else {
1915                                 /* dreg = K
1916                                  * dreg needs precision after this insn.
1917                                  * Corresponding register is already marked
1918                                  * as precise=true in this verifier state.
1919                                  * No further markings in parent are necessary
1920                                  */
1921                                 *reg_mask &= ~dreg;
1922                         }
1923                 } else {
1924                         if (BPF_SRC(insn->code) == BPF_X) {
1925                                 /* dreg += sreg
1926                                  * both dreg and sreg need precision
1927                                  * before this insn
1928                                  */
1929                                 *reg_mask |= sreg;
1930                         } /* else dreg += K
1931                            * dreg still needs precision before this insn
1932                            */
1933                 }
1934         } else if (class == BPF_LDX) {
1935                 if (!(*reg_mask & dreg))
1936                         return 0;
1937                 *reg_mask &= ~dreg;
1938
1939                 /* scalars can only be spilled into stack w/o losing precision.
1940                  * Load from any other memory can be zero extended.
1941                  * The desire to keep that precision is already indicated
1942                  * by 'precise' mark in corresponding register of this state.
1943                  * No further tracking necessary.
1944                  */
1945                 if (insn->src_reg != BPF_REG_FP)
1946                         return 0;
1947                 if (BPF_SIZE(insn->code) != BPF_DW)
1948                         return 0;
1949
1950                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1951                  * that [fp - off] slot contains scalar that needs to be
1952                  * tracked with precision
1953                  */
1954                 spi = (-insn->off - 1) / BPF_REG_SIZE;
1955                 if (spi >= 64) {
1956                         verbose(env, "BUG spi %d\n", spi);
1957                         WARN_ONCE(1, "verifier backtracking bug");
1958                         return -EFAULT;
1959                 }
1960                 *stack_mask |= 1ull << spi;
1961         } else if (class == BPF_STX || class == BPF_ST) {
1962                 if (*reg_mask & dreg)
1963                         /* stx & st shouldn't be using _scalar_ dst_reg
1964                          * to access memory. It means backtracking
1965                          * encountered a case of pointer subtraction.
1966                          */
1967                         return -ENOTSUPP;
1968                 /* scalars can only be spilled into stack */
1969                 if (insn->dst_reg != BPF_REG_FP)
1970                         return 0;
1971                 if (BPF_SIZE(insn->code) != BPF_DW)
1972                         return 0;
1973                 spi = (-insn->off - 1) / BPF_REG_SIZE;
1974                 if (spi >= 64) {
1975                         verbose(env, "BUG spi %d\n", spi);
1976                         WARN_ONCE(1, "verifier backtracking bug");
1977                         return -EFAULT;
1978                 }
1979                 if (!(*stack_mask & (1ull << spi)))
1980                         return 0;
1981                 *stack_mask &= ~(1ull << spi);
1982                 if (class == BPF_STX)
1983                         *reg_mask |= sreg;
1984         } else if (class == BPF_JMP || class == BPF_JMP32) {
1985                 if (opcode == BPF_CALL) {
1986                         if (insn->src_reg == BPF_PSEUDO_CALL)
1987                                 return -ENOTSUPP;
1988                         /* regular helper call sets R0 */
1989                         *reg_mask &= ~1;
1990                         if (*reg_mask & 0x3f) {
1991                                 /* if backtracing was looking for registers R1-R5
1992                                  * they should have been found already.
1993                                  */
1994                                 verbose(env, "BUG regs %x\n", *reg_mask);
1995                                 WARN_ONCE(1, "verifier backtracking bug");
1996                                 return -EFAULT;
1997                         }
1998                 } else if (opcode == BPF_EXIT) {
1999                         return -ENOTSUPP;
2000                 }
2001         } else if (class == BPF_LD) {
2002                 if (!(*reg_mask & dreg))
2003                         return 0;
2004                 *reg_mask &= ~dreg;
2005                 /* It's ld_imm64 or ld_abs or ld_ind.
2006                  * For ld_imm64 no further tracking of precision
2007                  * into parent is necessary
2008                  */
2009                 if (mode == BPF_IND || mode == BPF_ABS)
2010                         /* to be analyzed */
2011                         return -ENOTSUPP;
2012         }
2013         return 0;
2014 }
2015
2016 /* the scalar precision tracking algorithm:
2017  * . at the start all registers have precise=false.
2018  * . scalar ranges are tracked as normal through alu and jmp insns.
2019  * . once precise value of the scalar register is used in:
2020  *   .  ptr + scalar alu
2021  *   . if (scalar cond K|scalar)
2022  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2023  *   backtrack through the verifier states and mark all registers and
2024  *   stack slots with spilled constants that these scalar regisers
2025  *   should be precise.
2026  * . during state pruning two registers (or spilled stack slots)
2027  *   are equivalent if both are not precise.
2028  *
2029  * Note the verifier cannot simply walk register parentage chain,
2030  * since many different registers and stack slots could have been
2031  * used to compute single precise scalar.
2032  *
2033  * The approach of starting with precise=true for all registers and then
2034  * backtrack to mark a register as not precise when the verifier detects
2035  * that program doesn't care about specific value (e.g., when helper
2036  * takes register as ARG_ANYTHING parameter) is not safe.
2037  *
2038  * It's ok to walk single parentage chain of the verifier states.
2039  * It's possible that this backtracking will go all the way till 1st insn.
2040  * All other branches will be explored for needing precision later.
2041  *
2042  * The backtracking needs to deal with cases like:
2043  *   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)
2044  * r9 -= r8
2045  * r5 = r9
2046  * if r5 > 0x79f goto pc+7
2047  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2048  * r5 += 1
2049  * ...
2050  * call bpf_perf_event_output#25
2051  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2052  *
2053  * and this case:
2054  * r6 = 1
2055  * call foo // uses callee's r6 inside to compute r0
2056  * r0 += r6
2057  * if r0 == 0 goto
2058  *
2059  * to track above reg_mask/stack_mask needs to be independent for each frame.
2060  *
2061  * Also if parent's curframe > frame where backtracking started,
2062  * the verifier need to mark registers in both frames, otherwise callees
2063  * may incorrectly prune callers. This is similar to
2064  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2065  *
2066  * For now backtracking falls back into conservative marking.
2067  */
2068 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2069                                      struct bpf_verifier_state *st)
2070 {
2071         struct bpf_func_state *func;
2072         struct bpf_reg_state *reg;
2073         int i, j;
2074
2075         /* big hammer: mark all scalars precise in this path.
2076          * pop_stack may still get !precise scalars.
2077          */
2078         for (; st; st = st->parent)
2079                 for (i = 0; i <= st->curframe; i++) {
2080                         func = st->frame[i];
2081                         for (j = 0; j < BPF_REG_FP; j++) {
2082                                 reg = &func->regs[j];
2083                                 if (reg->type != SCALAR_VALUE)
2084                                         continue;
2085                                 reg->precise = true;
2086                         }
2087                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2088                                 if (func->stack[j].slot_type[0] != STACK_SPILL)
2089                                         continue;
2090                                 reg = &func->stack[j].spilled_ptr;
2091                                 if (reg->type != SCALAR_VALUE)
2092                                         continue;
2093                                 reg->precise = true;
2094                         }
2095                 }
2096 }
2097
2098 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2099                                   int spi)
2100 {
2101         struct bpf_verifier_state *st = env->cur_state;
2102         int first_idx = st->first_insn_idx;
2103         int last_idx = env->insn_idx;
2104         struct bpf_func_state *func;
2105         struct bpf_reg_state *reg;
2106         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2107         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2108         bool skip_first = true;
2109         bool new_marks = false;
2110         int i, err;
2111
2112         if (!env->bpf_capable)
2113                 return 0;
2114
2115         func = st->frame[st->curframe];
2116         if (regno >= 0) {
2117                 reg = &func->regs[regno];
2118                 if (reg->type != SCALAR_VALUE) {
2119                         WARN_ONCE(1, "backtracing misuse");
2120                         return -EFAULT;
2121                 }
2122                 if (!reg->precise)
2123                         new_marks = true;
2124                 else
2125                         reg_mask = 0;
2126                 reg->precise = true;
2127         }
2128
2129         while (spi >= 0) {
2130                 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2131                         stack_mask = 0;
2132                         break;
2133                 }
2134                 reg = &func->stack[spi].spilled_ptr;
2135                 if (reg->type != SCALAR_VALUE) {
2136                         stack_mask = 0;
2137                         break;
2138                 }
2139                 if (!reg->precise)
2140                         new_marks = true;
2141                 else
2142                         stack_mask = 0;
2143                 reg->precise = true;
2144                 break;
2145         }
2146
2147         if (!new_marks)
2148                 return 0;
2149         if (!reg_mask && !stack_mask)
2150                 return 0;
2151         for (;;) {
2152                 DECLARE_BITMAP(mask, 64);
2153                 u32 history = st->jmp_history_cnt;
2154
2155                 if (env->log.level & BPF_LOG_LEVEL)
2156                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2157                 for (i = last_idx;;) {
2158                         if (skip_first) {
2159                                 err = 0;
2160                                 skip_first = false;
2161                         } else {
2162                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2163                         }
2164                         if (err == -ENOTSUPP) {
2165                                 mark_all_scalars_precise(env, st);
2166                                 return 0;
2167                         } else if (err) {
2168                                 return err;
2169                         }
2170                         if (!reg_mask && !stack_mask)
2171                                 /* Found assignment(s) into tracked register in this state.
2172                                  * Since this state is already marked, just return.
2173                                  * Nothing to be tracked further in the parent state.
2174                                  */
2175                                 return 0;
2176                         if (i == first_idx)
2177                                 break;
2178                         i = get_prev_insn_idx(st, i, &history);
2179                         if (i >= env->prog->len) {
2180                                 /* This can happen if backtracking reached insn 0
2181                                  * and there are still reg_mask or stack_mask
2182                                  * to backtrack.
2183                                  * It means the backtracking missed the spot where
2184                                  * particular register was initialized with a constant.
2185                                  */
2186                                 verbose(env, "BUG backtracking idx %d\n", i);
2187                                 WARN_ONCE(1, "verifier backtracking bug");
2188                                 return -EFAULT;
2189                         }
2190                 }
2191                 st = st->parent;
2192                 if (!st)
2193                         break;
2194
2195                 new_marks = false;
2196                 func = st->frame[st->curframe];
2197                 bitmap_from_u64(mask, reg_mask);
2198                 for_each_set_bit(i, mask, 32) {
2199                         reg = &func->regs[i];
2200                         if (reg->type != SCALAR_VALUE) {
2201                                 reg_mask &= ~(1u << i);
2202                                 continue;
2203                         }
2204                         if (!reg->precise)
2205                                 new_marks = true;
2206                         reg->precise = true;
2207                 }
2208
2209                 bitmap_from_u64(mask, stack_mask);
2210                 for_each_set_bit(i, mask, 64) {
2211                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2212                                 /* the sequence of instructions:
2213                                  * 2: (bf) r3 = r10
2214                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2215                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2216                                  * doesn't contain jmps. It's backtracked
2217                                  * as a single block.
2218                                  * During backtracking insn 3 is not recognized as
2219                                  * stack access, so at the end of backtracking
2220                                  * stack slot fp-8 is still marked in stack_mask.
2221                                  * However the parent state may not have accessed
2222                                  * fp-8 and it's "unallocated" stack space.
2223                                  * In such case fallback to conservative.
2224                                  */
2225                                 mark_all_scalars_precise(env, st);
2226                                 return 0;
2227                         }
2228
2229                         if (func->stack[i].slot_type[0] != STACK_SPILL) {
2230                                 stack_mask &= ~(1ull << i);
2231                                 continue;
2232                         }
2233                         reg = &func->stack[i].spilled_ptr;
2234                         if (reg->type != SCALAR_VALUE) {
2235                                 stack_mask &= ~(1ull << i);
2236                                 continue;
2237                         }
2238                         if (!reg->precise)
2239                                 new_marks = true;
2240                         reg->precise = true;
2241                 }
2242                 if (env->log.level & BPF_LOG_LEVEL) {
2243                         print_verifier_state(env, func);
2244                         verbose(env, "parent %s regs=%x stack=%llx marks\n",
2245                                 new_marks ? "didn't have" : "already had",
2246                                 reg_mask, stack_mask);
2247                 }
2248
2249                 if (!reg_mask && !stack_mask)
2250                         break;
2251                 if (!new_marks)
2252                         break;
2253
2254                 last_idx = st->last_insn_idx;
2255                 first_idx = st->first_insn_idx;
2256         }
2257         return 0;
2258 }
2259
2260 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2261 {
2262         return __mark_chain_precision(env, regno, -1);
2263 }
2264
2265 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2266 {
2267         return __mark_chain_precision(env, -1, spi);
2268 }
2269
2270 static bool is_spillable_regtype(enum bpf_reg_type type)
2271 {
2272         switch (type) {
2273         case PTR_TO_MAP_VALUE:
2274         case PTR_TO_MAP_VALUE_OR_NULL:
2275         case PTR_TO_STACK:
2276         case PTR_TO_CTX:
2277         case PTR_TO_PACKET:
2278         case PTR_TO_PACKET_META:
2279         case PTR_TO_PACKET_END:
2280         case PTR_TO_FLOW_KEYS:
2281         case CONST_PTR_TO_MAP:
2282         case PTR_TO_SOCKET:
2283         case PTR_TO_SOCKET_OR_NULL:
2284         case PTR_TO_SOCK_COMMON:
2285         case PTR_TO_SOCK_COMMON_OR_NULL:
2286         case PTR_TO_TCP_SOCK:
2287         case PTR_TO_TCP_SOCK_OR_NULL:
2288         case PTR_TO_XDP_SOCK:
2289         case PTR_TO_BTF_ID:
2290         case PTR_TO_BTF_ID_OR_NULL:
2291         case PTR_TO_RDONLY_BUF:
2292         case PTR_TO_RDONLY_BUF_OR_NULL:
2293         case PTR_TO_RDWR_BUF:
2294         case PTR_TO_RDWR_BUF_OR_NULL:
2295         case PTR_TO_PERCPU_BTF_ID:
2296         case PTR_TO_MEM:
2297         case PTR_TO_MEM_OR_NULL:
2298                 return true;
2299         default:
2300                 return false;
2301         }
2302 }
2303
2304 /* Does this register contain a constant zero? */
2305 static bool register_is_null(struct bpf_reg_state *reg)
2306 {
2307         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2308 }
2309
2310 static bool register_is_const(struct bpf_reg_state *reg)
2311 {
2312         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2313 }
2314
2315 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2316 {
2317         return tnum_is_unknown(reg->var_off) &&
2318                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2319                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2320                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2321                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2322 }
2323
2324 static bool register_is_bounded(struct bpf_reg_state *reg)
2325 {
2326         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2327 }
2328
2329 static bool __is_pointer_value(bool allow_ptr_leaks,
2330                                const struct bpf_reg_state *reg)
2331 {
2332         if (allow_ptr_leaks)
2333                 return false;
2334
2335         return reg->type != SCALAR_VALUE;
2336 }
2337
2338 static void save_register_state(struct bpf_func_state *state,
2339                                 int spi, struct bpf_reg_state *reg)
2340 {
2341         int i;
2342
2343         state->stack[spi].spilled_ptr = *reg;
2344         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2345
2346         for (i = 0; i < BPF_REG_SIZE; i++)
2347                 state->stack[spi].slot_type[i] = STACK_SPILL;
2348 }
2349
2350 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2351  * stack boundary and alignment are checked in check_mem_access()
2352  */
2353 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2354                                        /* stack frame we're writing to */
2355                                        struct bpf_func_state *state,
2356                                        int off, int size, int value_regno,
2357                                        int insn_idx)
2358 {
2359         struct bpf_func_state *cur; /* state of the current function */
2360         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2361         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2362         struct bpf_reg_state *reg = NULL;
2363
2364         err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2365                                  state->acquired_refs, true);
2366         if (err)
2367                 return err;
2368         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2369          * so it's aligned access and [off, off + size) are within stack limits
2370          */
2371         if (!env->allow_ptr_leaks &&
2372             state->stack[spi].slot_type[0] == STACK_SPILL &&
2373             size != BPF_REG_SIZE) {
2374                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2375                 return -EACCES;
2376         }
2377
2378         cur = env->cur_state->frame[env->cur_state->curframe];
2379         if (value_regno >= 0)
2380                 reg = &cur->regs[value_regno];
2381
2382         if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2383             !register_is_null(reg) && env->bpf_capable) {
2384                 if (dst_reg != BPF_REG_FP) {
2385                         /* The backtracking logic can only recognize explicit
2386                          * stack slot address like [fp - 8]. Other spill of
2387                          * scalar via different register has to be conervative.
2388                          * Backtrack from here and mark all registers as precise
2389                          * that contributed into 'reg' being a constant.
2390                          */
2391                         err = mark_chain_precision(env, value_regno);
2392                         if (err)
2393                                 return err;
2394                 }
2395                 save_register_state(state, spi, reg);
2396         } else if (reg && is_spillable_regtype(reg->type)) {
2397                 /* register containing pointer is being spilled into stack */
2398                 if (size != BPF_REG_SIZE) {
2399                         verbose_linfo(env, insn_idx, "; ");
2400                         verbose(env, "invalid size of register spill\n");
2401                         return -EACCES;
2402                 }
2403
2404                 if (state != cur && reg->type == PTR_TO_STACK) {
2405                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2406                         return -EINVAL;
2407                 }
2408
2409                 if (!env->bypass_spec_v4) {
2410                         bool sanitize = false;
2411
2412                         if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2413                             register_is_const(&state->stack[spi].spilled_ptr))
2414                                 sanitize = true;
2415                         for (i = 0; i < BPF_REG_SIZE; i++)
2416                                 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2417                                         sanitize = true;
2418                                         break;
2419                                 }
2420                         if (sanitize) {
2421                                 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2422                                 int soff = (-spi - 1) * BPF_REG_SIZE;
2423
2424                                 /* detected reuse of integer stack slot with a pointer
2425                                  * which means either llvm is reusing stack slot or
2426                                  * an attacker is trying to exploit CVE-2018-3639
2427                                  * (speculative store bypass)
2428                                  * Have to sanitize that slot with preemptive
2429                                  * store of zero.
2430                                  */
2431                                 if (*poff && *poff != soff) {
2432                                         /* disallow programs where single insn stores
2433                                          * into two different stack slots, since verifier
2434                                          * cannot sanitize them
2435                                          */
2436                                         verbose(env,
2437                                                 "insn %d cannot access two stack slots fp%d and fp%d",
2438                                                 insn_idx, *poff, soff);
2439                                         return -EINVAL;
2440                                 }
2441                                 *poff = soff;
2442                         }
2443                 }
2444                 save_register_state(state, spi, reg);
2445         } else {
2446                 u8 type = STACK_MISC;
2447
2448                 /* regular write of data into stack destroys any spilled ptr */
2449                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2450                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2451                 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2452                         for (i = 0; i < BPF_REG_SIZE; i++)
2453                                 state->stack[spi].slot_type[i] = STACK_MISC;
2454
2455                 /* only mark the slot as written if all 8 bytes were written
2456                  * otherwise read propagation may incorrectly stop too soon
2457                  * when stack slots are partially written.
2458                  * This heuristic means that read propagation will be
2459                  * conservative, since it will add reg_live_read marks
2460                  * to stack slots all the way to first state when programs
2461                  * writes+reads less than 8 bytes
2462                  */
2463                 if (size == BPF_REG_SIZE)
2464                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2465
2466                 /* when we zero initialize stack slots mark them as such */
2467                 if (reg && register_is_null(reg)) {
2468                         /* backtracking doesn't work for STACK_ZERO yet. */
2469                         err = mark_chain_precision(env, value_regno);
2470                         if (err)
2471                                 return err;
2472                         type = STACK_ZERO;
2473                 }
2474
2475                 /* Mark slots affected by this stack write. */
2476                 for (i = 0; i < size; i++)
2477                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2478                                 type;
2479         }
2480         return 0;
2481 }
2482
2483 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2484  * known to contain a variable offset.
2485  * This function checks whether the write is permitted and conservatively
2486  * tracks the effects of the write, considering that each stack slot in the
2487  * dynamic range is potentially written to.
2488  *
2489  * 'off' includes 'regno->off'.
2490  * 'value_regno' can be -1, meaning that an unknown value is being written to
2491  * the stack.
2492  *
2493  * Spilled pointers in range are not marked as written because we don't know
2494  * what's going to be actually written. This means that read propagation for
2495  * future reads cannot be terminated by this write.
2496  *
2497  * For privileged programs, uninitialized stack slots are considered
2498  * initialized by this write (even though we don't know exactly what offsets
2499  * are going to be written to). The idea is that we don't want the verifier to
2500  * reject future reads that access slots written to through variable offsets.
2501  */
2502 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2503                                      /* func where register points to */
2504                                      struct bpf_func_state *state,
2505                                      int ptr_regno, int off, int size,
2506                                      int value_regno, int insn_idx)
2507 {
2508         struct bpf_func_state *cur; /* state of the current function */
2509         int min_off, max_off;
2510         int i, err;
2511         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2512         bool writing_zero = false;
2513         /* set if the fact that we're writing a zero is used to let any
2514          * stack slots remain STACK_ZERO
2515          */
2516         bool zero_used = false;
2517
2518         cur = env->cur_state->frame[env->cur_state->curframe];
2519         ptr_reg = &cur->regs[ptr_regno];
2520         min_off = ptr_reg->smin_value + off;
2521         max_off = ptr_reg->smax_value + off + size;
2522         if (value_regno >= 0)
2523                 value_reg = &cur->regs[value_regno];
2524         if (value_reg && register_is_null(value_reg))
2525                 writing_zero = true;
2526
2527         err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2528                                  state->acquired_refs, true);
2529         if (err)
2530                 return err;
2531
2532
2533         /* Variable offset writes destroy any spilled pointers in range. */
2534         for (i = min_off; i < max_off; i++) {
2535                 u8 new_type, *stype;
2536                 int slot, spi;
2537
2538                 slot = -i - 1;
2539                 spi = slot / BPF_REG_SIZE;
2540                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2541
2542                 if (!env->allow_ptr_leaks
2543                                 && *stype != NOT_INIT
2544                                 && *stype != SCALAR_VALUE) {
2545                         /* Reject the write if there's are spilled pointers in
2546                          * range. If we didn't reject here, the ptr status
2547                          * would be erased below (even though not all slots are
2548                          * actually overwritten), possibly opening the door to
2549                          * leaks.
2550                          */
2551                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2552                                 insn_idx, i);
2553                         return -EINVAL;
2554                 }
2555
2556                 /* Erase all spilled pointers. */
2557                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2558
2559                 /* Update the slot type. */
2560                 new_type = STACK_MISC;
2561                 if (writing_zero && *stype == STACK_ZERO) {
2562                         new_type = STACK_ZERO;
2563                         zero_used = true;
2564                 }
2565                 /* If the slot is STACK_INVALID, we check whether it's OK to
2566                  * pretend that it will be initialized by this write. The slot
2567                  * might not actually be written to, and so if we mark it as
2568                  * initialized future reads might leak uninitialized memory.
2569                  * For privileged programs, we will accept such reads to slots
2570                  * that may or may not be written because, if we're reject
2571                  * them, the error would be too confusing.
2572                  */
2573                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2574                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2575                                         insn_idx, i);
2576                         return -EINVAL;
2577                 }
2578                 *stype = new_type;
2579         }
2580         if (zero_used) {
2581                 /* backtracking doesn't work for STACK_ZERO yet. */
2582                 err = mark_chain_precision(env, value_regno);
2583                 if (err)
2584                         return err;
2585         }
2586         return 0;
2587 }
2588
2589 /* When register 'dst_regno' is assigned some values from stack[min_off,
2590  * max_off), we set the register's type according to the types of the
2591  * respective stack slots. If all the stack values are known to be zeros, then
2592  * so is the destination reg. Otherwise, the register is considered to be
2593  * SCALAR. This function does not deal with register filling; the caller must
2594  * ensure that all spilled registers in the stack range have been marked as
2595  * read.
2596  */
2597 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2598                                 /* func where src register points to */
2599                                 struct bpf_func_state *ptr_state,
2600                                 int min_off, int max_off, int dst_regno)
2601 {
2602         struct bpf_verifier_state *vstate = env->cur_state;
2603         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2604         int i, slot, spi;
2605         u8 *stype;
2606         int zeros = 0;
2607
2608         for (i = min_off; i < max_off; i++) {
2609                 slot = -i - 1;
2610                 spi = slot / BPF_REG_SIZE;
2611                 stype = ptr_state->stack[spi].slot_type;
2612                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2613                         break;
2614                 zeros++;
2615         }
2616         if (zeros == max_off - min_off) {
2617                 /* any access_size read into register is zero extended,
2618                  * so the whole register == const_zero
2619                  */
2620                 __mark_reg_const_zero(&state->regs[dst_regno]);
2621                 /* backtracking doesn't support STACK_ZERO yet,
2622                  * so mark it precise here, so that later
2623                  * backtracking can stop here.
2624                  * Backtracking may not need this if this register
2625                  * doesn't participate in pointer adjustment.
2626                  * Forward propagation of precise flag is not
2627                  * necessary either. This mark is only to stop
2628                  * backtracking. Any register that contributed
2629                  * to const 0 was marked precise before spill.
2630                  */
2631                 state->regs[dst_regno].precise = true;
2632         } else {
2633                 /* have read misc data from the stack */
2634                 mark_reg_unknown(env, state->regs, dst_regno);
2635         }
2636         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2637 }
2638
2639 /* Read the stack at 'off' and put the results into the register indicated by
2640  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2641  * spilled reg.
2642  *
2643  * 'dst_regno' can be -1, meaning that the read value is not going to a
2644  * register.
2645  *
2646  * The access is assumed to be within the current stack bounds.
2647  */
2648 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2649                                       /* func where src register points to */
2650                                       struct bpf_func_state *reg_state,
2651                                       int off, int size, int dst_regno)
2652 {
2653         struct bpf_verifier_state *vstate = env->cur_state;
2654         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2655         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2656         struct bpf_reg_state *reg;
2657         u8 *stype;
2658
2659         stype = reg_state->stack[spi].slot_type;
2660         reg = &reg_state->stack[spi].spilled_ptr;
2661
2662         if (stype[0] == STACK_SPILL) {
2663                 if (size != BPF_REG_SIZE) {
2664                         if (reg->type != SCALAR_VALUE) {
2665                                 verbose_linfo(env, env->insn_idx, "; ");
2666                                 verbose(env, "invalid size of register fill\n");
2667                                 return -EACCES;
2668                         }
2669                         if (dst_regno >= 0) {
2670                                 mark_reg_unknown(env, state->regs, dst_regno);
2671                                 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2672                         }
2673                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2674                         return 0;
2675                 }
2676                 for (i = 1; i < BPF_REG_SIZE; i++) {
2677                         if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2678                                 verbose(env, "corrupted spill memory\n");
2679                                 return -EACCES;
2680                         }
2681                 }
2682
2683                 if (dst_regno >= 0) {
2684                         /* restore register state from stack */
2685                         state->regs[dst_regno] = *reg;
2686                         /* mark reg as written since spilled pointer state likely
2687                          * has its liveness marks cleared by is_state_visited()
2688                          * which resets stack/reg liveness for state transitions
2689                          */
2690                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2691                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2692                         /* If dst_regno==-1, the caller is asking us whether
2693                          * it is acceptable to use this value as a SCALAR_VALUE
2694                          * (e.g. for XADD).
2695                          * We must not allow unprivileged callers to do that
2696                          * with spilled pointers.
2697                          */
2698                         verbose(env, "leaking pointer from stack off %d\n",
2699                                 off);
2700                         return -EACCES;
2701                 }
2702                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2703         } else {
2704                 u8 type;
2705
2706                 for (i = 0; i < size; i++) {
2707                         type = stype[(slot - i) % BPF_REG_SIZE];
2708                         if (type == STACK_MISC)
2709                                 continue;
2710                         if (type == STACK_ZERO)
2711                                 continue;
2712                         verbose(env, "invalid read from stack off %d+%d size %d\n",
2713                                 off, i, size);
2714                         return -EACCES;
2715                 }
2716                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2717                 if (dst_regno >= 0)
2718                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2719         }
2720         return 0;
2721 }
2722
2723 enum stack_access_src {
2724         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2725         ACCESS_HELPER = 2,  /* the access is performed by a helper */
2726 };
2727
2728 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2729                                          int regno, int off, int access_size,
2730                                          bool zero_size_allowed,
2731                                          enum stack_access_src type,
2732                                          struct bpf_call_arg_meta *meta);
2733
2734 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2735 {
2736         return cur_regs(env) + regno;
2737 }
2738
2739 /* Read the stack at 'ptr_regno + off' and put the result into the register
2740  * 'dst_regno'.
2741  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2742  * but not its variable offset.
2743  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2744  *
2745  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2746  * filling registers (i.e. reads of spilled register cannot be detected when
2747  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2748  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2749  * offset; for a fixed offset check_stack_read_fixed_off should be used
2750  * instead.
2751  */
2752 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2753                                     int ptr_regno, int off, int size, int dst_regno)
2754 {
2755         /* The state of the source register. */
2756         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2757         struct bpf_func_state *ptr_state = func(env, reg);
2758         int err;
2759         int min_off, max_off;
2760
2761         /* Note that we pass a NULL meta, so raw access will not be permitted.
2762          */
2763         err = check_stack_range_initialized(env, ptr_regno, off, size,
2764                                             false, ACCESS_DIRECT, NULL);
2765         if (err)
2766                 return err;
2767
2768         min_off = reg->smin_value + off;
2769         max_off = reg->smax_value + off;
2770         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2771         return 0;
2772 }
2773
2774 /* check_stack_read dispatches to check_stack_read_fixed_off or
2775  * check_stack_read_var_off.
2776  *
2777  * The caller must ensure that the offset falls within the allocated stack
2778  * bounds.
2779  *
2780  * 'dst_regno' is a register which will receive the value from the stack. It
2781  * can be -1, meaning that the read value is not going to a register.
2782  */
2783 static int check_stack_read(struct bpf_verifier_env *env,
2784                             int ptr_regno, int off, int size,
2785                             int dst_regno)
2786 {
2787         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2788         struct bpf_func_state *state = func(env, reg);
2789         int err;
2790         /* Some accesses are only permitted with a static offset. */
2791         bool var_off = !tnum_is_const(reg->var_off);
2792
2793         /* The offset is required to be static when reads don't go to a
2794          * register, in order to not leak pointers (see
2795          * check_stack_read_fixed_off).
2796          */
2797         if (dst_regno < 0 && var_off) {
2798                 char tn_buf[48];
2799
2800                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2801                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2802                         tn_buf, off, size);
2803                 return -EACCES;
2804         }
2805         /* Variable offset is prohibited for unprivileged mode for simplicity
2806          * since it requires corresponding support in Spectre masking for stack
2807          * ALU. See also retrieve_ptr_limit().
2808          */
2809         if (!env->bypass_spec_v1 && var_off) {
2810                 char tn_buf[48];
2811
2812                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2813                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2814                                 ptr_regno, tn_buf);
2815                 return -EACCES;
2816         }
2817
2818         if (!var_off) {
2819                 off += reg->var_off.value;
2820                 err = check_stack_read_fixed_off(env, state, off, size,
2821                                                  dst_regno);
2822         } else {
2823                 /* Variable offset stack reads need more conservative handling
2824                  * than fixed offset ones. Note that dst_regno >= 0 on this
2825                  * branch.
2826                  */
2827                 err = check_stack_read_var_off(env, ptr_regno, off, size,
2828                                                dst_regno);
2829         }
2830         return err;
2831 }
2832
2833
2834 /* check_stack_write dispatches to check_stack_write_fixed_off or
2835  * check_stack_write_var_off.
2836  *
2837  * 'ptr_regno' is the register used as a pointer into the stack.
2838  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2839  * 'value_regno' is the register whose value we're writing to the stack. It can
2840  * be -1, meaning that we're not writing from a register.
2841  *
2842  * The caller must ensure that the offset falls within the maximum stack size.
2843  */
2844 static int check_stack_write(struct bpf_verifier_env *env,
2845                              int ptr_regno, int off, int size,
2846                              int value_regno, int insn_idx)
2847 {
2848         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2849         struct bpf_func_state *state = func(env, reg);
2850         int err;
2851
2852         if (tnum_is_const(reg->var_off)) {
2853                 off += reg->var_off.value;
2854                 err = check_stack_write_fixed_off(env, state, off, size,
2855                                                   value_regno, insn_idx);
2856         } else {
2857                 /* Variable offset stack reads need more conservative handling
2858                  * than fixed offset ones.
2859                  */
2860                 err = check_stack_write_var_off(env, state,
2861                                                 ptr_regno, off, size,
2862                                                 value_regno, insn_idx);
2863         }
2864         return err;
2865 }
2866
2867 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2868                                  int off, int size, enum bpf_access_type type)
2869 {
2870         struct bpf_reg_state *regs = cur_regs(env);
2871         struct bpf_map *map = regs[regno].map_ptr;
2872         u32 cap = bpf_map_flags_to_cap(map);
2873
2874         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2875                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2876                         map->value_size, off, size);
2877                 return -EACCES;
2878         }
2879
2880         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2881                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2882                         map->value_size, off, size);
2883                 return -EACCES;
2884         }
2885
2886         return 0;
2887 }
2888
2889 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2890 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2891                               int off, int size, u32 mem_size,
2892                               bool zero_size_allowed)
2893 {
2894         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2895         struct bpf_reg_state *reg;
2896
2897         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2898                 return 0;
2899
2900         reg = &cur_regs(env)[regno];
2901         switch (reg->type) {
2902         case PTR_TO_MAP_VALUE:
2903                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2904                         mem_size, off, size);
2905                 break;
2906         case PTR_TO_PACKET:
2907         case PTR_TO_PACKET_META:
2908         case PTR_TO_PACKET_END:
2909                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2910                         off, size, regno, reg->id, off, mem_size);
2911                 break;
2912         case PTR_TO_MEM:
2913         default:
2914                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2915                         mem_size, off, size);
2916         }
2917
2918         return -EACCES;
2919 }
2920
2921 /* check read/write into a memory region with possible variable offset */
2922 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2923                                    int off, int size, u32 mem_size,
2924                                    bool zero_size_allowed)
2925 {
2926         struct bpf_verifier_state *vstate = env->cur_state;
2927         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2928         struct bpf_reg_state *reg = &state->regs[regno];
2929         int err;
2930
2931         /* We may have adjusted the register pointing to memory region, so we
2932          * need to try adding each of min_value and max_value to off
2933          * to make sure our theoretical access will be safe.
2934          */
2935         if (env->log.level & BPF_LOG_LEVEL)
2936                 print_verifier_state(env, state);
2937
2938         /* The minimum value is only important with signed
2939          * comparisons where we can't assume the floor of a
2940          * value is 0.  If we are using signed variables for our
2941          * index'es we need to make sure that whatever we use
2942          * will have a set floor within our range.
2943          */
2944         if (reg->smin_value < 0 &&
2945             (reg->smin_value == S64_MIN ||
2946              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2947               reg->smin_value + off < 0)) {
2948                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2949                         regno);
2950                 return -EACCES;
2951         }
2952         err = __check_mem_access(env, regno, reg->smin_value + off, size,
2953                                  mem_size, zero_size_allowed);
2954         if (err) {
2955                 verbose(env, "R%d min value is outside of the allowed memory range\n",
2956                         regno);
2957                 return err;
2958         }
2959
2960         /* If we haven't set a max value then we need to bail since we can't be
2961          * sure we won't do bad things.
2962          * If reg->umax_value + off could overflow, treat that as unbounded too.
2963          */
2964         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2965                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
2966                         regno);
2967                 return -EACCES;
2968         }
2969         err = __check_mem_access(env, regno, reg->umax_value + off, size,
2970                                  mem_size, zero_size_allowed);
2971         if (err) {
2972                 verbose(env, "R%d max value is outside of the allowed memory range\n",
2973                         regno);
2974                 return err;
2975         }
2976
2977         return 0;
2978 }
2979
2980 /* check read/write into a map element with possible variable offset */
2981 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2982                             int off, int size, bool zero_size_allowed)
2983 {
2984         struct bpf_verifier_state *vstate = env->cur_state;
2985         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2986         struct bpf_reg_state *reg = &state->regs[regno];
2987         struct bpf_map *map = reg->map_ptr;
2988         int err;
2989
2990         err = check_mem_region_access(env, regno, off, size, map->value_size,
2991                                       zero_size_allowed);
2992         if (err)
2993                 return err;
2994
2995         if (map_value_has_spin_lock(map)) {
2996                 u32 lock = map->spin_lock_off;
2997
2998                 /* if any part of struct bpf_spin_lock can be touched by
2999                  * load/store reject this program.
3000                  * To check that [x1, x2) overlaps with [y1, y2)
3001                  * it is sufficient to check x1 < y2 && y1 < x2.
3002                  */
3003                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3004                      lock < reg->umax_value + off + size) {
3005                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3006                         return -EACCES;
3007                 }
3008         }
3009         return err;
3010 }
3011
3012 #define MAX_PACKET_OFF 0xffff
3013
3014 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3015 {
3016         return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3017 }
3018
3019 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3020                                        const struct bpf_call_arg_meta *meta,
3021                                        enum bpf_access_type t)
3022 {
3023         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3024
3025         switch (prog_type) {
3026         /* Program types only with direct read access go here! */
3027         case BPF_PROG_TYPE_LWT_IN:
3028         case BPF_PROG_TYPE_LWT_OUT:
3029         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3030         case BPF_PROG_TYPE_SK_REUSEPORT:
3031         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3032         case BPF_PROG_TYPE_CGROUP_SKB:
3033                 if (t == BPF_WRITE)
3034                         return false;
3035                 fallthrough;
3036
3037         /* Program types with direct read + write access go here! */
3038         case BPF_PROG_TYPE_SCHED_CLS:
3039         case BPF_PROG_TYPE_SCHED_ACT:
3040         case BPF_PROG_TYPE_XDP:
3041         case BPF_PROG_TYPE_LWT_XMIT:
3042         case BPF_PROG_TYPE_SK_SKB:
3043         case BPF_PROG_TYPE_SK_MSG:
3044                 if (meta)
3045                         return meta->pkt_access;
3046
3047                 env->seen_direct_write = true;
3048                 return true;
3049
3050         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3051                 if (t == BPF_WRITE)
3052                         env->seen_direct_write = true;
3053
3054                 return true;
3055
3056         default:
3057                 return false;
3058         }
3059 }
3060
3061 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3062                                int size, bool zero_size_allowed)
3063 {
3064         struct bpf_reg_state *regs = cur_regs(env);
3065         struct bpf_reg_state *reg = &regs[regno];
3066         int err;
3067
3068         /* We may have added a variable offset to the packet pointer; but any
3069          * reg->range we have comes after that.  We are only checking the fixed
3070          * offset.
3071          */
3072
3073         /* We don't allow negative numbers, because we aren't tracking enough
3074          * detail to prove they're safe.
3075          */
3076         if (reg->smin_value < 0) {
3077                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3078                         regno);
3079                 return -EACCES;
3080         }
3081
3082         err = reg->range < 0 ? -EINVAL :
3083               __check_mem_access(env, regno, off, size, reg->range,
3084                                  zero_size_allowed);
3085         if (err) {
3086                 verbose(env, "R%d offset is outside of the packet\n", regno);
3087                 return err;
3088         }
3089
3090         /* __check_mem_access has made sure "off + size - 1" is within u16.
3091          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3092          * otherwise find_good_pkt_pointers would have refused to set range info
3093          * that __check_mem_access would have rejected this pkt access.
3094          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3095          */
3096         env->prog->aux->max_pkt_offset =
3097                 max_t(u32, env->prog->aux->max_pkt_offset,
3098                       off + reg->umax_value + size - 1);
3099
3100         return err;
3101 }
3102
3103 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3104 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3105                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
3106                             struct btf **btf, u32 *btf_id)
3107 {
3108         struct bpf_insn_access_aux info = {
3109                 .reg_type = *reg_type,
3110                 .log = &env->log,
3111         };
3112
3113         if (env->ops->is_valid_access &&
3114             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3115                 /* A non zero info.ctx_field_size indicates that this field is a
3116                  * candidate for later verifier transformation to load the whole
3117                  * field and then apply a mask when accessed with a narrower
3118                  * access than actual ctx access size. A zero info.ctx_field_size
3119                  * will only allow for whole field access and rejects any other
3120                  * type of narrower access.
3121                  */
3122                 *reg_type = info.reg_type;
3123
3124                 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3125                         *btf = info.btf;
3126                         *btf_id = info.btf_id;
3127                 } else {
3128                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3129                 }
3130                 /* remember the offset of last byte accessed in ctx */
3131                 if (env->prog->aux->max_ctx_offset < off + size)
3132                         env->prog->aux->max_ctx_offset = off + size;
3133                 return 0;
3134         }
3135
3136         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3137         return -EACCES;
3138 }
3139
3140 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3141                                   int size)
3142 {
3143         if (size < 0 || off < 0 ||
3144             (u64)off + size > sizeof(struct bpf_flow_keys)) {
3145                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3146                         off, size);
3147                 return -EACCES;
3148         }
3149         return 0;
3150 }
3151
3152 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3153                              u32 regno, int off, int size,
3154                              enum bpf_access_type t)
3155 {
3156         struct bpf_reg_state *regs = cur_regs(env);
3157         struct bpf_reg_state *reg = &regs[regno];
3158         struct bpf_insn_access_aux info = {};
3159         bool valid;
3160
3161         if (reg->smin_value < 0) {
3162                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3163                         regno);
3164                 return -EACCES;
3165         }
3166
3167         switch (reg->type) {
3168         case PTR_TO_SOCK_COMMON:
3169                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3170                 break;
3171         case PTR_TO_SOCKET:
3172                 valid = bpf_sock_is_valid_access(off, size, t, &info);
3173                 break;
3174         case PTR_TO_TCP_SOCK:
3175                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3176                 break;
3177         case PTR_TO_XDP_SOCK:
3178                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3179                 break;
3180         default:
3181                 valid = false;
3182         }
3183
3184
3185         if (valid) {
3186                 env->insn_aux_data[insn_idx].ctx_field_size =
3187                         info.ctx_field_size;
3188                 return 0;
3189         }
3190
3191         verbose(env, "R%d invalid %s access off=%d size=%d\n",
3192                 regno, reg_type_str[reg->type], off, size);
3193
3194         return -EACCES;
3195 }
3196
3197 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3198 {
3199         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3200 }
3201
3202 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3203 {
3204         const struct bpf_reg_state *reg = reg_state(env, regno);
3205
3206         return reg->type == PTR_TO_CTX;
3207 }
3208
3209 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3210 {
3211         const struct bpf_reg_state *reg = reg_state(env, regno);
3212
3213         return type_is_sk_pointer(reg->type);
3214 }
3215
3216 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3217 {
3218         const struct bpf_reg_state *reg = reg_state(env, regno);
3219
3220         return type_is_pkt_pointer(reg->type);
3221 }
3222
3223 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3224 {
3225         const struct bpf_reg_state *reg = reg_state(env, regno);
3226
3227         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3228         return reg->type == PTR_TO_FLOW_KEYS;
3229 }
3230
3231 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3232                                    const struct bpf_reg_state *reg,
3233                                    int off, int size, bool strict)
3234 {
3235         struct tnum reg_off;
3236         int ip_align;
3237
3238         /* Byte size accesses are always allowed. */
3239         if (!strict || size == 1)
3240                 return 0;
3241
3242         /* For platforms that do not have a Kconfig enabling
3243          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3244          * NET_IP_ALIGN is universally set to '2'.  And on platforms
3245          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3246          * to this code only in strict mode where we want to emulate
3247          * the NET_IP_ALIGN==2 checking.  Therefore use an
3248          * unconditional IP align value of '2'.
3249          */
3250         ip_align = 2;
3251
3252         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3253         if (!tnum_is_aligned(reg_off, size)) {
3254                 char tn_buf[48];
3255
3256                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3257                 verbose(env,
3258                         "misaligned packet access off %d+%s+%d+%d size %d\n",
3259                         ip_align, tn_buf, reg->off, off, size);
3260                 return -EACCES;
3261         }
3262
3263         return 0;
3264 }
3265
3266 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3267                                        const struct bpf_reg_state *reg,
3268                                        const char *pointer_desc,
3269                                        int off, int size, bool strict)
3270 {
3271         struct tnum reg_off;
3272
3273         /* Byte size accesses are always allowed. */
3274         if (!strict || size == 1)
3275                 return 0;
3276
3277         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3278         if (!tnum_is_aligned(reg_off, size)) {
3279                 char tn_buf[48];
3280
3281                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3282                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3283                         pointer_desc, tn_buf, reg->off, off, size);
3284                 return -EACCES;
3285         }
3286
3287         return 0;
3288 }
3289
3290 static int check_ptr_alignment(struct bpf_verifier_env *env,
3291                                const struct bpf_reg_state *reg, int off,
3292                                int size, bool strict_alignment_once)
3293 {
3294         bool strict = env->strict_alignment || strict_alignment_once;
3295         const char *pointer_desc = "";
3296
3297         switch (reg->type) {
3298         case PTR_TO_PACKET:
3299         case PTR_TO_PACKET_META:
3300                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3301                  * right in front, treat it the very same way.
3302                  */
3303                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3304         case PTR_TO_FLOW_KEYS:
3305                 pointer_desc = "flow keys ";
3306                 break;
3307         case PTR_TO_MAP_VALUE:
3308                 pointer_desc = "value ";
3309                 break;
3310         case PTR_TO_CTX:
3311                 pointer_desc = "context ";
3312                 break;
3313         case PTR_TO_STACK:
3314                 pointer_desc = "stack ";
3315                 /* The stack spill tracking logic in check_stack_write_fixed_off()
3316                  * and check_stack_read_fixed_off() relies on stack accesses being
3317                  * aligned.
3318                  */
3319                 strict = true;
3320                 break;
3321         case PTR_TO_SOCKET:
3322                 pointer_desc = "sock ";
3323                 break;
3324         case PTR_TO_SOCK_COMMON:
3325                 pointer_desc = "sock_common ";
3326                 break;
3327         case PTR_TO_TCP_SOCK:
3328                 pointer_desc = "tcp_sock ";
3329                 break;
3330         case PTR_TO_XDP_SOCK:
3331                 pointer_desc = "xdp_sock ";
3332                 break;
3333         default:
3334                 break;
3335         }
3336         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3337                                            strict);
3338 }
3339
3340 static int update_stack_depth(struct bpf_verifier_env *env,
3341                               const struct bpf_func_state *func,
3342                               int off)
3343 {
3344         u16 stack = env->subprog_info[func->subprogno].stack_depth;
3345
3346         if (stack >= -off)
3347                 return 0;
3348
3349         /* update known max for given subprogram */
3350         env->subprog_info[func->subprogno].stack_depth = -off;
3351         return 0;
3352 }
3353
3354 /* starting from main bpf function walk all instructions of the function
3355  * and recursively walk all callees that given function can call.
3356  * Ignore jump and exit insns.
3357  * Since recursion is prevented by check_cfg() this algorithm
3358  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3359  */
3360 static int check_max_stack_depth(struct bpf_verifier_env *env)
3361 {
3362         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3363         struct bpf_subprog_info *subprog = env->subprog_info;
3364         struct bpf_insn *insn = env->prog->insnsi;
3365         bool tail_call_reachable = false;
3366         int ret_insn[MAX_CALL_FRAMES];
3367         int ret_prog[MAX_CALL_FRAMES];
3368         int j;
3369
3370 process_func:
3371         /* protect against potential stack overflow that might happen when
3372          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3373          * depth for such case down to 256 so that the worst case scenario
3374          * would result in 8k stack size (32 which is tailcall limit * 256 =
3375          * 8k).
3376          *
3377          * To get the idea what might happen, see an example:
3378          * func1 -> sub rsp, 128
3379          *  subfunc1 -> sub rsp, 256
3380          *  tailcall1 -> add rsp, 256
3381          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3382          *   subfunc2 -> sub rsp, 64
3383          *   subfunc22 -> sub rsp, 128
3384          *   tailcall2 -> add rsp, 128
3385          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3386          *
3387          * tailcall will unwind the current stack frame but it will not get rid
3388          * of caller's stack as shown on the example above.
3389          */
3390         if (idx && subprog[idx].has_tail_call && depth >= 256) {
3391                 verbose(env,
3392                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3393                         depth);
3394                 return -EACCES;
3395         }
3396         /* round up to 32-bytes, since this is granularity
3397          * of interpreter stack size
3398          */
3399         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3400         if (depth > MAX_BPF_STACK) {
3401                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3402                         frame + 1, depth);
3403                 return -EACCES;
3404         }
3405 continue_func:
3406         subprog_end = subprog[idx + 1].start;
3407         for (; i < subprog_end; i++) {
3408                 if (!bpf_pseudo_call(insn + i))
3409                         continue;
3410                 /* remember insn and function to return to */
3411                 ret_insn[frame] = i + 1;
3412                 ret_prog[frame] = idx;
3413
3414                 /* find the callee */
3415                 i = i + insn[i].imm + 1;
3416                 idx = find_subprog(env, i);
3417                 if (idx < 0) {
3418                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3419                                   i);
3420                         return -EFAULT;
3421                 }
3422
3423                 if (subprog[idx].has_tail_call)
3424                         tail_call_reachable = true;
3425
3426                 frame++;
3427                 if (frame >= MAX_CALL_FRAMES) {
3428                         verbose(env, "the call stack of %d frames is too deep !\n",
3429                                 frame);
3430                         return -E2BIG;
3431                 }
3432                 goto process_func;
3433         }
3434         /* if tail call got detected across bpf2bpf calls then mark each of the
3435          * currently present subprog frames as tail call reachable subprogs;
3436          * this info will be utilized by JIT so that we will be preserving the
3437          * tail call counter throughout bpf2bpf calls combined with tailcalls
3438          */
3439         if (tail_call_reachable)
3440                 for (j = 0; j < frame; j++)
3441                         subprog[ret_prog[j]].tail_call_reachable = true;
3442
3443         /* end of for() loop means the last insn of the 'subprog'
3444          * was reached. Doesn't matter whether it was JA or EXIT
3445          */
3446         if (frame == 0)
3447                 return 0;
3448         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3449         frame--;
3450         i = ret_insn[frame];
3451         idx = ret_prog[frame];
3452         goto continue_func;
3453 }
3454
3455 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3456 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3457                                   const struct bpf_insn *insn, int idx)
3458 {
3459         int start = idx + insn->imm + 1, subprog;
3460
3461         subprog = find_subprog(env, start);
3462         if (subprog < 0) {
3463                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3464                           start);
3465                 return -EFAULT;
3466         }
3467         return env->subprog_info[subprog].stack_depth;
3468 }
3469 #endif
3470
3471 int check_ctx_reg(struct bpf_verifier_env *env,
3472                   const struct bpf_reg_state *reg, int regno)
3473 {
3474         /* Access to ctx or passing it to a helper is only allowed in
3475          * its original, unmodified form.
3476          */
3477
3478         if (reg->off) {
3479                 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3480                         regno, reg->off);
3481                 return -EACCES;
3482         }
3483
3484         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3485                 char tn_buf[48];
3486
3487                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3488                 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3489                 return -EACCES;
3490         }
3491
3492         return 0;
3493 }
3494
3495 static int __check_buffer_access(struct bpf_verifier_env *env,
3496                                  const char *buf_info,
3497                                  const struct bpf_reg_state *reg,
3498                                  int regno, int off, int size)
3499 {
3500         if (off < 0) {
3501                 verbose(env,
3502                         "R%d invalid %s buffer access: off=%d, size=%d\n",
3503                         regno, buf_info, off, size);
3504                 return -EACCES;
3505         }
3506         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3507                 char tn_buf[48];
3508
3509                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3510                 verbose(env,
3511                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3512                         regno, off, tn_buf);
3513                 return -EACCES;
3514         }
3515
3516         return 0;
3517 }
3518
3519 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3520                                   const struct bpf_reg_state *reg,
3521                                   int regno, int off, int size)
3522 {
3523         int err;
3524
3525         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3526         if (err)
3527                 return err;
3528
3529         if (off + size > env->prog->aux->max_tp_access)
3530                 env->prog->aux->max_tp_access = off + size;
3531
3532         return 0;
3533 }
3534
3535 static int check_buffer_access(struct bpf_verifier_env *env,
3536                                const struct bpf_reg_state *reg,
3537                                int regno, int off, int size,
3538                                bool zero_size_allowed,
3539                                const char *buf_info,
3540                                u32 *max_access)
3541 {
3542         int err;
3543
3544         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3545         if (err)
3546                 return err;
3547
3548         if (off + size > *max_access)
3549                 *max_access = off + size;
3550
3551         return 0;
3552 }
3553
3554 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3555 static void zext_32_to_64(struct bpf_reg_state *reg)
3556 {
3557         reg->var_off = tnum_subreg(reg->var_off);
3558         __reg_assign_32_into_64(reg);
3559 }
3560
3561 /* truncate register to smaller size (in bytes)
3562  * must be called with size < BPF_REG_SIZE
3563  */
3564 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3565 {
3566         u64 mask;
3567
3568         /* clear high bits in bit representation */
3569         reg->var_off = tnum_cast(reg->var_off, size);
3570
3571         /* fix arithmetic bounds */
3572         mask = ((u64)1 << (size * 8)) - 1;
3573         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3574                 reg->umin_value &= mask;
3575                 reg->umax_value &= mask;
3576         } else {
3577                 reg->umin_value = 0;
3578                 reg->umax_value = mask;
3579         }
3580         reg->smin_value = reg->umin_value;
3581         reg->smax_value = reg->umax_value;
3582
3583         /* If size is smaller than 32bit register the 32bit register
3584          * values are also truncated so we push 64-bit bounds into
3585          * 32-bit bounds. Above were truncated < 32-bits already.
3586          */
3587         if (size >= 4)
3588                 return;
3589         __reg_combine_64_into_32(reg);
3590 }
3591
3592 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3593 {
3594         return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3595 }
3596
3597 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3598 {
3599         void *ptr;
3600         u64 addr;
3601         int err;
3602
3603         err = map->ops->map_direct_value_addr(map, &addr, off);
3604         if (err)
3605                 return err;
3606         ptr = (void *)(long)addr + off;
3607
3608         switch (size) {
3609         case sizeof(u8):
3610                 *val = (u64)*(u8 *)ptr;
3611                 break;
3612         case sizeof(u16):
3613                 *val = (u64)*(u16 *)ptr;
3614                 break;
3615         case sizeof(u32):
3616                 *val = (u64)*(u32 *)ptr;
3617                 break;
3618         case sizeof(u64):
3619                 *val = *(u64 *)ptr;
3620                 break;
3621         default:
3622                 return -EINVAL;
3623         }
3624         return 0;
3625 }
3626
3627 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3628                                    struct bpf_reg_state *regs,
3629                                    int regno, int off, int size,
3630                                    enum bpf_access_type atype,
3631                                    int value_regno)
3632 {
3633         struct bpf_reg_state *reg = regs + regno;
3634         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3635         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3636         u32 btf_id;
3637         int ret;
3638
3639         if (off < 0) {
3640                 verbose(env,
3641                         "R%d is ptr_%s invalid negative access: off=%d\n",
3642                         regno, tname, off);
3643                 return -EACCES;
3644         }
3645         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3646                 char tn_buf[48];
3647
3648                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3649                 verbose(env,
3650                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3651                         regno, tname, off, tn_buf);
3652                 return -EACCES;
3653         }
3654
3655         if (env->ops->btf_struct_access) {
3656                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3657                                                   off, size, atype, &btf_id);
3658         } else {
3659                 if (atype != BPF_READ) {
3660                         verbose(env, "only read is supported\n");
3661                         return -EACCES;
3662                 }
3663
3664                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3665                                         atype, &btf_id);
3666         }
3667
3668         if (ret < 0)
3669                 return ret;
3670
3671         if (atype == BPF_READ && value_regno >= 0)
3672                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3673
3674         return 0;
3675 }
3676
3677 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3678                                    struct bpf_reg_state *regs,
3679                                    int regno, int off, int size,
3680                                    enum bpf_access_type atype,
3681                                    int value_regno)
3682 {
3683         struct bpf_reg_state *reg = regs + regno;
3684         struct bpf_map *map = reg->map_ptr;
3685         const struct btf_type *t;
3686         const char *tname;
3687         u32 btf_id;
3688         int ret;
3689
3690         if (!btf_vmlinux) {
3691                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3692                 return -ENOTSUPP;
3693         }
3694
3695         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3696                 verbose(env, "map_ptr access not supported for map type %d\n",
3697                         map->map_type);
3698                 return -ENOTSUPP;
3699         }
3700
3701         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3702         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3703
3704         if (!env->allow_ptr_to_map_access) {
3705                 verbose(env,
3706                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3707                         tname);
3708                 return -EPERM;
3709         }
3710
3711         if (off < 0) {
3712                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3713                         regno, tname, off);
3714                 return -EACCES;
3715         }
3716
3717         if (atype != BPF_READ) {
3718                 verbose(env, "only read from %s is supported\n", tname);
3719                 return -EACCES;
3720         }
3721
3722         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
3723         if (ret < 0)
3724                 return ret;
3725
3726         if (value_regno >= 0)
3727                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
3728
3729         return 0;
3730 }
3731
3732 /* Check that the stack access at the given offset is within bounds. The
3733  * maximum valid offset is -1.
3734  *
3735  * The minimum valid offset is -MAX_BPF_STACK for writes, and
3736  * -state->allocated_stack for reads.
3737  */
3738 static int check_stack_slot_within_bounds(int off,
3739                                           struct bpf_func_state *state,
3740                                           enum bpf_access_type t)
3741 {
3742         int min_valid_off;
3743
3744         if (t == BPF_WRITE)
3745                 min_valid_off = -MAX_BPF_STACK;
3746         else
3747                 min_valid_off = -state->allocated_stack;
3748
3749         if (off < min_valid_off || off > -1)
3750                 return -EACCES;
3751         return 0;
3752 }
3753
3754 /* Check that the stack access at 'regno + off' falls within the maximum stack
3755  * bounds.
3756  *
3757  * 'off' includes `regno->offset`, but not its dynamic part (if any).
3758  */
3759 static int check_stack_access_within_bounds(
3760                 struct bpf_verifier_env *env,
3761                 int regno, int off, int access_size,
3762                 enum stack_access_src src, enum bpf_access_type type)
3763 {
3764         struct bpf_reg_state *regs = cur_regs(env);
3765         struct bpf_reg_state *reg = regs + regno;
3766         struct bpf_func_state *state = func(env, reg);
3767         int min_off, max_off;
3768         int err;
3769         char *err_extra;
3770
3771         if (src == ACCESS_HELPER)
3772                 /* We don't know if helpers are reading or writing (or both). */
3773                 err_extra = " indirect access to";
3774         else if (type == BPF_READ)
3775                 err_extra = " read from";
3776         else
3777                 err_extra = " write to";
3778
3779         if (tnum_is_const(reg->var_off)) {
3780                 min_off = reg->var_off.value + off;
3781                 if (access_size > 0)
3782                         max_off = min_off + access_size - 1;
3783                 else
3784                         max_off = min_off;
3785         } else {
3786                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3787                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
3788                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3789                                 err_extra, regno);
3790                         return -EACCES;
3791                 }
3792                 min_off = reg->smin_value + off;
3793                 if (access_size > 0)
3794                         max_off = reg->smax_value + off + access_size - 1;
3795                 else
3796                         max_off = min_off;
3797         }
3798
3799         err = check_stack_slot_within_bounds(min_off, state, type);
3800         if (!err)
3801                 err = check_stack_slot_within_bounds(max_off, state, type);
3802
3803         if (err) {
3804                 if (tnum_is_const(reg->var_off)) {
3805                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3806                                 err_extra, regno, off, access_size);
3807                 } else {
3808                         char tn_buf[48];
3809
3810                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3811                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3812                                 err_extra, regno, tn_buf, access_size);
3813                 }
3814         }
3815         return err;
3816 }
3817
3818 /* check whether memory at (regno + off) is accessible for t = (read | write)
3819  * if t==write, value_regno is a register which value is stored into memory
3820  * if t==read, value_regno is a register which will receive the value from memory
3821  * if t==write && value_regno==-1, some unknown value is stored into memory
3822  * if t==read && value_regno==-1, don't care what we read from memory
3823  */
3824 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3825                             int off, int bpf_size, enum bpf_access_type t,
3826                             int value_regno, bool strict_alignment_once)
3827 {
3828         struct bpf_reg_state *regs = cur_regs(env);
3829         struct bpf_reg_state *reg = regs + regno;
3830         struct bpf_func_state *state;
3831         int size, err = 0;
3832
3833         size = bpf_size_to_bytes(bpf_size);
3834         if (size < 0)
3835                 return size;
3836
3837         /* alignment checks will add in reg->off themselves */
3838         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3839         if (err)
3840                 return err;
3841
3842         /* for access checks, reg->off is just part of off */
3843         off += reg->off;
3844
3845         if (reg->type == PTR_TO_MAP_VALUE) {
3846                 if (t == BPF_WRITE && value_regno >= 0 &&
3847                     is_pointer_value(env, value_regno)) {
3848                         verbose(env, "R%d leaks addr into map\n", value_regno);
3849                         return -EACCES;
3850                 }
3851                 err = check_map_access_type(env, regno, off, size, t);
3852                 if (err)
3853                         return err;
3854                 err = check_map_access(env, regno, off, size, false);
3855                 if (!err && t == BPF_READ && value_regno >= 0) {
3856                         struct bpf_map *map = reg->map_ptr;
3857
3858                         /* if map is read-only, track its contents as scalars */
3859                         if (tnum_is_const(reg->var_off) &&
3860                             bpf_map_is_rdonly(map) &&
3861                             map->ops->map_direct_value_addr) {
3862                                 int map_off = off + reg->var_off.value;
3863                                 u64 val = 0;
3864
3865                                 err = bpf_map_direct_read(map, map_off, size,
3866                                                           &val);
3867                                 if (err)
3868                                         return err;
3869
3870                                 regs[value_regno].type = SCALAR_VALUE;
3871                                 __mark_reg_known(&regs[value_regno], val);
3872                         } else {
3873                                 mark_reg_unknown(env, regs, value_regno);
3874                         }
3875                 }
3876         } else if (reg->type == PTR_TO_MEM) {
3877                 if (t == BPF_WRITE && value_regno >= 0 &&
3878                     is_pointer_value(env, value_regno)) {
3879                         verbose(env, "R%d leaks addr into mem\n", value_regno);
3880                         return -EACCES;
3881                 }
3882                 err = check_mem_region_access(env, regno, off, size,
3883                                               reg->mem_size, false);
3884                 if (!err && t == BPF_READ && value_regno >= 0)
3885                         mark_reg_unknown(env, regs, value_regno);
3886         } else if (reg->type == PTR_TO_CTX) {
3887                 enum bpf_reg_type reg_type = SCALAR_VALUE;
3888                 struct btf *btf = NULL;
3889                 u32 btf_id = 0;
3890
3891                 if (t == BPF_WRITE && value_regno >= 0 &&
3892                     is_pointer_value(env, value_regno)) {
3893                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
3894                         return -EACCES;
3895                 }
3896
3897                 err = check_ctx_reg(env, reg, regno);
3898                 if (err < 0)
3899                         return err;
3900
3901                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
3902                 if (err)
3903                         verbose_linfo(env, insn_idx, "; ");
3904                 if (!err && t == BPF_READ && value_regno >= 0) {
3905                         /* ctx access returns either a scalar, or a
3906                          * PTR_TO_PACKET[_META,_END]. In the latter
3907                          * case, we know the offset is zero.
3908                          */
3909                         if (reg_type == SCALAR_VALUE) {
3910                                 mark_reg_unknown(env, regs, value_regno);
3911                         } else {
3912                                 mark_reg_known_zero(env, regs,
3913                                                     value_regno);
3914                                 if (reg_type_may_be_null(reg_type))
3915                                         regs[value_regno].id = ++env->id_gen;
3916                                 /* A load of ctx field could have different
3917                                  * actual load size with the one encoded in the
3918                                  * insn. When the dst is PTR, it is for sure not
3919                                  * a sub-register.
3920                                  */
3921                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3922                                 if (reg_type == PTR_TO_BTF_ID ||
3923                                     reg_type == PTR_TO_BTF_ID_OR_NULL) {
3924                                         regs[value_regno].btf = btf;
3925                                         regs[value_regno].btf_id = btf_id;
3926                                 }
3927                         }
3928                         regs[value_regno].type = reg_type;
3929                 }
3930
3931         } else if (reg->type == PTR_TO_STACK) {
3932                 /* Basic bounds checks. */
3933                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
3934                 if (err)
3935                         return err;
3936
3937                 state = func(env, reg);
3938                 err = update_stack_depth(env, state, off);
3939                 if (err)
3940                         return err;
3941
3942                 if (t == BPF_READ)
3943                         err = check_stack_read(env, regno, off, size,
3944                                                value_regno);
3945                 else
3946                         err = check_stack_write(env, regno, off, size,
3947                                                 value_regno, insn_idx);
3948         } else if (reg_is_pkt_pointer(reg)) {
3949                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
3950                         verbose(env, "cannot write into packet\n");
3951                         return -EACCES;
3952                 }
3953                 if (t == BPF_WRITE && value_regno >= 0 &&
3954                     is_pointer_value(env, value_regno)) {
3955                         verbose(env, "R%d leaks addr into packet\n",
3956                                 value_regno);
3957                         return -EACCES;
3958                 }
3959                 err = check_packet_access(env, regno, off, size, false);
3960                 if (!err && t == BPF_READ && value_regno >= 0)
3961                         mark_reg_unknown(env, regs, value_regno);
3962         } else if (reg->type == PTR_TO_FLOW_KEYS) {
3963                 if (t == BPF_WRITE && value_regno >= 0 &&
3964                     is_pointer_value(env, value_regno)) {
3965                         verbose(env, "R%d leaks addr into flow keys\n",
3966                                 value_regno);
3967                         return -EACCES;
3968                 }
3969
3970                 err = check_flow_keys_access(env, off, size);
3971                 if (!err && t == BPF_READ && value_regno >= 0)
3972                         mark_reg_unknown(env, regs, value_regno);
3973         } else if (type_is_sk_pointer(reg->type)) {
3974                 if (t == BPF_WRITE) {
3975                         verbose(env, "R%d cannot write into %s\n",
3976                                 regno, reg_type_str[reg->type]);
3977                         return -EACCES;
3978                 }
3979                 err = check_sock_access(env, insn_idx, regno, off, size, t);
3980                 if (!err && value_regno >= 0)
3981                         mark_reg_unknown(env, regs, value_regno);
3982         } else if (reg->type == PTR_TO_TP_BUFFER) {
3983                 err = check_tp_buffer_access(env, reg, regno, off, size);
3984                 if (!err && t == BPF_READ && value_regno >= 0)
3985                         mark_reg_unknown(env, regs, value_regno);
3986         } else if (reg->type == PTR_TO_BTF_ID) {
3987                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3988                                               value_regno);
3989         } else if (reg->type == CONST_PTR_TO_MAP) {
3990                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3991                                               value_regno);
3992         } else if (reg->type == PTR_TO_RDONLY_BUF) {
3993                 if (t == BPF_WRITE) {
3994                         verbose(env, "R%d cannot write into %s\n",
3995                                 regno, reg_type_str[reg->type]);
3996                         return -EACCES;
3997                 }
3998                 err = check_buffer_access(env, reg, regno, off, size, false,
3999                                           "rdonly",
4000                                           &env->prog->aux->max_rdonly_access);
4001                 if (!err && value_regno >= 0)
4002                         mark_reg_unknown(env, regs, value_regno);
4003         } else if (reg->type == PTR_TO_RDWR_BUF) {
4004                 err = check_buffer_access(env, reg, regno, off, size, false,
4005                                           "rdwr",
4006                                           &env->prog->aux->max_rdwr_access);
4007                 if (!err && t == BPF_READ && value_regno >= 0)
4008                         mark_reg_unknown(env, regs, value_regno);
4009         } else {
4010                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4011                         reg_type_str[reg->type]);
4012                 return -EACCES;
4013         }
4014
4015         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4016             regs[value_regno].type == SCALAR_VALUE) {
4017                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4018                 coerce_reg_to_size(&regs[value_regno], size);
4019         }
4020         return err;
4021 }
4022
4023 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4024 {
4025         int load_reg;
4026         int err;
4027
4028         switch (insn->imm) {
4029         case BPF_ADD:
4030         case BPF_ADD | BPF_FETCH:
4031         case BPF_AND:
4032         case BPF_AND | BPF_FETCH:
4033         case BPF_OR:
4034         case BPF_OR | BPF_FETCH:
4035         case BPF_XOR:
4036         case BPF_XOR | BPF_FETCH:
4037         case BPF_XCHG:
4038         case BPF_CMPXCHG:
4039                 break;
4040         default:
4041                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4042                 return -EINVAL;
4043         }
4044
4045         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4046                 verbose(env, "invalid atomic operand size\n");
4047                 return -EINVAL;
4048         }
4049
4050         /* check src1 operand */
4051         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4052         if (err)
4053                 return err;
4054
4055         /* check src2 operand */
4056         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4057         if (err)
4058                 return err;
4059
4060         if (insn->imm == BPF_CMPXCHG) {
4061                 /* Check comparison of R0 with memory location */
4062                 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4063                 if (err)
4064                         return err;
4065         }
4066
4067         if (is_pointer_value(env, insn->src_reg)) {
4068                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4069                 return -EACCES;
4070         }
4071
4072         if (is_ctx_reg(env, insn->dst_reg) ||
4073             is_pkt_reg(env, insn->dst_reg) ||
4074             is_flow_key_reg(env, insn->dst_reg) ||
4075             is_sk_reg(env, insn->dst_reg)) {
4076                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4077                         insn->dst_reg,
4078                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
4079                 return -EACCES;
4080         }
4081
4082         if (insn->imm & BPF_FETCH) {
4083                 if (insn->imm == BPF_CMPXCHG)
4084                         load_reg = BPF_REG_0;
4085                 else
4086                         load_reg = insn->src_reg;
4087
4088                 /* check and record load of old value */
4089                 err = check_reg_arg(env, load_reg, DST_OP);
4090                 if (err)
4091                         return err;
4092         } else {
4093                 /* This instruction accesses a memory location but doesn't
4094                  * actually load it into a register.
4095                  */
4096                 load_reg = -1;
4097         }
4098
4099         /* check whether we can read the memory */
4100         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4101                                BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4102         if (err)
4103                 return err;
4104
4105         /* check whether we can write into the same memory */
4106         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4107                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4108         if (err)
4109                 return err;
4110
4111         return 0;
4112 }
4113
4114 /* When register 'regno' is used to read the stack (either directly or through
4115  * a helper function) make sure that it's within stack boundary and, depending
4116  * on the access type, that all elements of the stack are initialized.
4117  *
4118  * 'off' includes 'regno->off', but not its dynamic part (if any).
4119  *
4120  * All registers that have been spilled on the stack in the slots within the
4121  * read offsets are marked as read.
4122  */
4123 static int check_stack_range_initialized(
4124                 struct bpf_verifier_env *env, int regno, int off,
4125                 int access_size, bool zero_size_allowed,
4126                 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4127 {
4128         struct bpf_reg_state *reg = reg_state(env, regno);
4129         struct bpf_func_state *state = func(env, reg);
4130         int err, min_off, max_off, i, j, slot, spi;
4131         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4132         enum bpf_access_type bounds_check_type;
4133         /* Some accesses can write anything into the stack, others are
4134          * read-only.
4135          */
4136         bool clobber = false;
4137
4138         if (access_size == 0 && !zero_size_allowed) {
4139                 verbose(env, "invalid zero-sized read\n");
4140                 return -EACCES;
4141         }
4142
4143         if (type == ACCESS_HELPER) {
4144                 /* The bounds checks for writes are more permissive than for
4145                  * reads. However, if raw_mode is not set, we'll do extra
4146                  * checks below.
4147                  */
4148                 bounds_check_type = BPF_WRITE;
4149                 clobber = true;
4150         } else {
4151                 bounds_check_type = BPF_READ;
4152         }
4153         err = check_stack_access_within_bounds(env, regno, off, access_size,
4154                                                type, bounds_check_type);
4155         if (err)
4156                 return err;
4157
4158
4159         if (tnum_is_const(reg->var_off)) {
4160                 min_off = max_off = reg->var_off.value + off;
4161         } else {
4162                 /* Variable offset is prohibited for unprivileged mode for
4163                  * simplicity since it requires corresponding support in
4164                  * Spectre masking for stack ALU.
4165                  * See also retrieve_ptr_limit().
4166                  */
4167                 if (!env->bypass_spec_v1) {
4168                         char tn_buf[48];
4169
4170                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4171                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4172                                 regno, err_extra, tn_buf);
4173                         return -EACCES;
4174                 }
4175                 /* Only initialized buffer on stack is allowed to be accessed
4176                  * with variable offset. With uninitialized buffer it's hard to
4177                  * guarantee that whole memory is marked as initialized on
4178                  * helper return since specific bounds are unknown what may
4179                  * cause uninitialized stack leaking.
4180                  */
4181                 if (meta && meta->raw_mode)
4182                         meta = NULL;
4183
4184                 min_off = reg->smin_value + off;
4185                 max_off = reg->smax_value + off;
4186         }
4187
4188         if (meta && meta->raw_mode) {
4189                 meta->access_size = access_size;
4190                 meta->regno = regno;
4191                 return 0;
4192         }
4193
4194         for (i = min_off; i < max_off + access_size; i++) {
4195                 u8 *stype;
4196
4197                 slot = -i - 1;
4198                 spi = slot / BPF_REG_SIZE;
4199                 if (state->allocated_stack <= slot)
4200                         goto err;
4201                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4202                 if (*stype == STACK_MISC)
4203                         goto mark;
4204                 if (*stype == STACK_ZERO) {
4205                         if (clobber) {
4206                                 /* helper can write anything into the stack */
4207                                 *stype = STACK_MISC;
4208                         }
4209                         goto mark;
4210                 }
4211
4212                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4213                     state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4214                         goto mark;
4215
4216                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4217                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4218                      env->allow_ptr_leaks)) {
4219                         if (clobber) {
4220                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4221                                 for (j = 0; j < BPF_REG_SIZE; j++)
4222                                         state->stack[spi].slot_type[j] = STACK_MISC;
4223                         }
4224                         goto mark;
4225                 }
4226
4227 err:
4228                 if (tnum_is_const(reg->var_off)) {
4229                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4230                                 err_extra, regno, min_off, i - min_off, access_size);
4231                 } else {
4232                         char tn_buf[48];
4233
4234                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4235                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4236                                 err_extra, regno, tn_buf, i - min_off, access_size);
4237                 }
4238                 return -EACCES;
4239 mark:
4240                 /* reading any byte out of 8-byte 'spill_slot' will cause
4241                  * the whole slot to be marked as 'read'
4242                  */
4243                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4244                               state->stack[spi].spilled_ptr.parent,
4245                               REG_LIVE_READ64);
4246         }
4247         return update_stack_depth(env, state, min_off);
4248 }
4249
4250 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4251                                    int access_size, bool zero_size_allowed,
4252                                    struct bpf_call_arg_meta *meta)
4253 {
4254         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4255
4256         switch (reg->type) {
4257         case PTR_TO_PACKET:
4258         case PTR_TO_PACKET_META:
4259                 return check_packet_access(env, regno, reg->off, access_size,
4260                                            zero_size_allowed);
4261         case PTR_TO_MAP_VALUE:
4262                 if (check_map_access_type(env, regno, reg->off, access_size,
4263                                           meta && meta->raw_mode ? BPF_WRITE :
4264                                           BPF_READ))
4265                         return -EACCES;
4266                 return check_map_access(env, regno, reg->off, access_size,
4267                                         zero_size_allowed);
4268         case PTR_TO_MEM:
4269                 return check_mem_region_access(env, regno, reg->off,
4270                                                access_size, reg->mem_size,
4271                                                zero_size_allowed);
4272         case PTR_TO_RDONLY_BUF:
4273                 if (meta && meta->raw_mode)
4274                         return -EACCES;
4275                 return check_buffer_access(env, reg, regno, reg->off,
4276                                            access_size, zero_size_allowed,
4277                                            "rdonly",
4278                                            &env->prog->aux->max_rdonly_access);
4279         case PTR_TO_RDWR_BUF:
4280                 return check_buffer_access(env, reg, regno, reg->off,
4281                                            access_size, zero_size_allowed,
4282                                            "rdwr",
4283                                            &env->prog->aux->max_rdwr_access);
4284         case PTR_TO_STACK:
4285                 return check_stack_range_initialized(
4286                                 env,
4287                                 regno, reg->off, access_size,
4288                                 zero_size_allowed, ACCESS_HELPER, meta);
4289         default: /* scalar_value or invalid ptr */
4290                 /* Allow zero-byte read from NULL, regardless of pointer type */
4291                 if (zero_size_allowed && access_size == 0 &&
4292                     register_is_null(reg))
4293                         return 0;
4294
4295                 verbose(env, "R%d type=%s expected=%s\n", regno,
4296                         reg_type_str[reg->type],
4297                         reg_type_str[PTR_TO_STACK]);
4298                 return -EACCES;
4299         }
4300 }
4301
4302 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4303                    u32 regno, u32 mem_size)
4304 {
4305         if (register_is_null(reg))
4306                 return 0;
4307
4308         if (reg_type_may_be_null(reg->type)) {
4309                 /* Assuming that the register contains a value check if the memory
4310                  * access is safe. Temporarily save and restore the register's state as
4311                  * the conversion shouldn't be visible to a caller.
4312                  */
4313                 const struct bpf_reg_state saved_reg = *reg;
4314                 int rv;
4315
4316                 mark_ptr_not_null_reg(reg);
4317                 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4318                 *reg = saved_reg;
4319                 return rv;
4320         }
4321
4322         return check_helper_mem_access(env, regno, mem_size, true, NULL);
4323 }
4324
4325 /* Implementation details:
4326  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4327  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4328  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4329  * value_or_null->value transition, since the verifier only cares about
4330  * the range of access to valid map value pointer and doesn't care about actual
4331  * address of the map element.
4332  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4333  * reg->id > 0 after value_or_null->value transition. By doing so
4334  * two bpf_map_lookups will be considered two different pointers that
4335  * point to different bpf_spin_locks.
4336  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4337  * dead-locks.
4338  * Since only one bpf_spin_lock is allowed the checks are simpler than
4339  * reg_is_refcounted() logic. The verifier needs to remember only
4340  * one spin_lock instead of array of acquired_refs.
4341  * cur_state->active_spin_lock remembers which map value element got locked
4342  * and clears it after bpf_spin_unlock.
4343  */
4344 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4345                              bool is_lock)
4346 {
4347         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4348         struct bpf_verifier_state *cur = env->cur_state;
4349         bool is_const = tnum_is_const(reg->var_off);
4350         struct bpf_map *map = reg->map_ptr;
4351         u64 val = reg->var_off.value;
4352
4353         if (!is_const) {
4354                 verbose(env,
4355                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4356                         regno);
4357                 return -EINVAL;
4358         }
4359         if (!map->btf) {
4360                 verbose(env,
4361                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4362                         map->name);
4363                 return -EINVAL;
4364         }
4365         if (!map_value_has_spin_lock(map)) {
4366                 if (map->spin_lock_off == -E2BIG)
4367                         verbose(env,
4368                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4369                                 map->name);
4370                 else if (map->spin_lock_off == -ENOENT)
4371                         verbose(env,
4372                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4373                                 map->name);
4374                 else
4375                         verbose(env,
4376                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4377                                 map->name);
4378                 return -EINVAL;
4379         }
4380         if (map->spin_lock_off != val + reg->off) {
4381                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4382                         val + reg->off);
4383                 return -EINVAL;
4384         }
4385         if (is_lock) {
4386                 if (cur->active_spin_lock) {
4387                         verbose(env,
4388                                 "Locking two bpf_spin_locks are not allowed\n");
4389                         return -EINVAL;
4390                 }
4391                 cur->active_spin_lock = reg->id;
4392         } else {
4393                 if (!cur->active_spin_lock) {
4394                         verbose(env, "bpf_spin_unlock without taking a lock\n");
4395                         return -EINVAL;
4396                 }
4397                 if (cur->active_spin_lock != reg->id) {
4398                         verbose(env, "bpf_spin_unlock of different lock\n");
4399                         return -EINVAL;
4400                 }
4401                 cur->active_spin_lock = 0;
4402         }
4403         return 0;
4404 }
4405
4406 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4407 {
4408         return type == ARG_PTR_TO_MEM ||
4409                type == ARG_PTR_TO_MEM_OR_NULL ||
4410                type == ARG_PTR_TO_UNINIT_MEM;
4411 }
4412
4413 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4414 {
4415         return type == ARG_CONST_SIZE ||
4416                type == ARG_CONST_SIZE_OR_ZERO;
4417 }
4418
4419 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4420 {
4421         return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4422 }
4423
4424 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4425 {
4426         return type == ARG_PTR_TO_INT ||
4427                type == ARG_PTR_TO_LONG;
4428 }
4429
4430 static int int_ptr_type_to_size(enum bpf_arg_type type)
4431 {
4432         if (type == ARG_PTR_TO_INT)
4433                 return sizeof(u32);
4434         else if (type == ARG_PTR_TO_LONG)
4435                 return sizeof(u64);
4436
4437         return -EINVAL;
4438 }
4439
4440 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4441                                  const struct bpf_call_arg_meta *meta,
4442                                  enum bpf_arg_type *arg_type)
4443 {
4444         if (!meta->map_ptr) {
4445                 /* kernel subsystem misconfigured verifier */
4446                 verbose(env, "invalid map_ptr to access map->type\n");
4447                 return -EACCES;
4448         }
4449
4450         switch (meta->map_ptr->map_type) {
4451         case BPF_MAP_TYPE_SOCKMAP:
4452         case BPF_MAP_TYPE_SOCKHASH:
4453                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4454                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4455                 } else {
4456                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
4457                         return -EINVAL;
4458                 }
4459                 break;
4460
4461         default:
4462                 break;
4463         }
4464         return 0;
4465 }
4466
4467 struct bpf_reg_types {
4468         const enum bpf_reg_type types[10];
4469         u32 *btf_id;
4470 };
4471
4472 static const struct bpf_reg_types map_key_value_types = {
4473         .types = {
4474                 PTR_TO_STACK,
4475                 PTR_TO_PACKET,
4476                 PTR_TO_PACKET_META,
4477                 PTR_TO_MAP_VALUE,
4478         },
4479 };
4480
4481 static const struct bpf_reg_types sock_types = {
4482         .types = {
4483                 PTR_TO_SOCK_COMMON,
4484                 PTR_TO_SOCKET,
4485                 PTR_TO_TCP_SOCK,
4486                 PTR_TO_XDP_SOCK,
4487         },
4488 };
4489
4490 #ifdef CONFIG_NET
4491 static const struct bpf_reg_types btf_id_sock_common_types = {
4492         .types = {
4493                 PTR_TO_SOCK_COMMON,
4494                 PTR_TO_SOCKET,
4495                 PTR_TO_TCP_SOCK,
4496                 PTR_TO_XDP_SOCK,
4497                 PTR_TO_BTF_ID,
4498         },
4499         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4500 };
4501 #endif
4502
4503 static const struct bpf_reg_types mem_types = {
4504         .types = {
4505                 PTR_TO_STACK,
4506                 PTR_TO_PACKET,
4507                 PTR_TO_PACKET_META,
4508                 PTR_TO_MAP_VALUE,
4509                 PTR_TO_MEM,
4510                 PTR_TO_RDONLY_BUF,
4511                 PTR_TO_RDWR_BUF,
4512         },
4513 };
4514
4515 static const struct bpf_reg_types int_ptr_types = {
4516         .types = {
4517                 PTR_TO_STACK,
4518                 PTR_TO_PACKET,
4519                 PTR_TO_PACKET_META,
4520                 PTR_TO_MAP_VALUE,
4521         },
4522 };
4523
4524 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4525 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4526 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4527 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4528 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4529 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4530 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4531 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4532
4533 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4534         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
4535         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
4536         [ARG_PTR_TO_UNINIT_MAP_VALUE]   = &map_key_value_types,
4537         [ARG_PTR_TO_MAP_VALUE_OR_NULL]  = &map_key_value_types,
4538         [ARG_CONST_SIZE]                = &scalar_types,
4539         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
4540         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
4541         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
4542         [ARG_PTR_TO_CTX]                = &context_types,
4543         [ARG_PTR_TO_CTX_OR_NULL]        = &context_types,
4544         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
4545 #ifdef CONFIG_NET
4546         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4547 #endif
4548         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
4549         [ARG_PTR_TO_SOCKET_OR_NULL]     = &fullsock_types,
4550         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
4551         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
4552         [ARG_PTR_TO_MEM]                = &mem_types,
4553         [ARG_PTR_TO_MEM_OR_NULL]        = &mem_types,
4554         [ARG_PTR_TO_UNINIT_MEM]         = &mem_types,
4555         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
4556         [ARG_PTR_TO_ALLOC_MEM_OR_NULL]  = &alloc_mem_types,
4557         [ARG_PTR_TO_INT]                = &int_ptr_types,
4558         [ARG_PTR_TO_LONG]               = &int_ptr_types,
4559         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
4560 };
4561
4562 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4563                           enum bpf_arg_type arg_type,
4564                           const u32 *arg_btf_id)
4565 {
4566         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4567         enum bpf_reg_type expected, type = reg->type;
4568         const struct bpf_reg_types *compatible;
4569         int i, j;
4570
4571         compatible = compatible_reg_types[arg_type];
4572         if (!compatible) {
4573                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4574                 return -EFAULT;
4575         }
4576
4577         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4578                 expected = compatible->types[i];
4579                 if (expected == NOT_INIT)
4580                         break;
4581
4582                 if (type == expected)
4583                         goto found;
4584         }
4585
4586         verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4587         for (j = 0; j + 1 < i; j++)
4588                 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4589         verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4590         return -EACCES;
4591
4592 found:
4593         if (type == PTR_TO_BTF_ID) {
4594                 if (!arg_btf_id) {
4595                         if (!compatible->btf_id) {
4596                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4597                                 return -EFAULT;
4598                         }
4599                         arg_btf_id = compatible->btf_id;
4600                 }
4601
4602                 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4603                                           btf_vmlinux, *arg_btf_id)) {
4604                         verbose(env, "R%d is of type %s but %s is expected\n",
4605                                 regno, kernel_type_name(reg->btf, reg->btf_id),
4606                                 kernel_type_name(btf_vmlinux, *arg_btf_id));
4607                         return -EACCES;
4608                 }
4609
4610                 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4611                         verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4612                                 regno);
4613                         return -EACCES;
4614                 }
4615         }
4616
4617         return 0;
4618 }
4619
4620 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4621                           struct bpf_call_arg_meta *meta,
4622                           const struct bpf_func_proto *fn)
4623 {
4624         u32 regno = BPF_REG_1 + arg;
4625         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4626         enum bpf_arg_type arg_type = fn->arg_type[arg];
4627         enum bpf_reg_type type = reg->type;
4628         int err = 0;
4629
4630         if (arg_type == ARG_DONTCARE)
4631                 return 0;
4632
4633         err = check_reg_arg(env, regno, SRC_OP);
4634         if (err)
4635                 return err;
4636
4637         if (arg_type == ARG_ANYTHING) {
4638                 if (is_pointer_value(env, regno)) {
4639                         verbose(env, "R%d leaks addr into helper function\n",
4640                                 regno);
4641                         return -EACCES;
4642                 }
4643                 return 0;
4644         }
4645
4646         if (type_is_pkt_pointer(type) &&
4647             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4648                 verbose(env, "helper access to the packet is not allowed\n");
4649                 return -EACCES;
4650         }
4651
4652         if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4653             arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4654             arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4655                 err = resolve_map_arg_type(env, meta, &arg_type);
4656                 if (err)
4657                         return err;
4658         }
4659
4660         if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4661                 /* A NULL register has a SCALAR_VALUE type, so skip
4662                  * type checking.
4663                  */
4664                 goto skip_type_check;
4665
4666         err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4667         if (err)
4668                 return err;
4669
4670         if (type == PTR_TO_CTX) {
4671                 err = check_ctx_reg(env, reg, regno);
4672                 if (err < 0)
4673                         return err;
4674         }
4675
4676 skip_type_check:
4677         if (reg->ref_obj_id) {
4678                 if (meta->ref_obj_id) {
4679                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4680                                 regno, reg->ref_obj_id,
4681                                 meta->ref_obj_id);
4682                         return -EFAULT;
4683                 }
4684                 meta->ref_obj_id = reg->ref_obj_id;
4685         }
4686
4687         if (arg_type == ARG_CONST_MAP_PTR) {
4688                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4689                 meta->map_ptr = reg->map_ptr;
4690         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4691                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4692                  * check that [key, key + map->key_size) are within
4693                  * stack limits and initialized
4694                  */
4695                 if (!meta->map_ptr) {
4696                         /* in function declaration map_ptr must come before
4697                          * map_key, so that it's verified and known before
4698                          * we have to check map_key here. Otherwise it means
4699                          * that kernel subsystem misconfigured verifier
4700                          */
4701                         verbose(env, "invalid map_ptr to access map->key\n");
4702                         return -EACCES;
4703                 }
4704                 err = check_helper_mem_access(env, regno,
4705                                               meta->map_ptr->key_size, false,
4706                                               NULL);
4707         } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4708                    (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4709                     !register_is_null(reg)) ||
4710                    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4711                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4712                  * check [value, value + map->value_size) validity
4713                  */
4714                 if (!meta->map_ptr) {
4715                         /* kernel subsystem misconfigured verifier */
4716                         verbose(env, "invalid map_ptr to access map->value\n");
4717                         return -EACCES;
4718                 }
4719                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4720                 err = check_helper_mem_access(env, regno,
4721                                               meta->map_ptr->value_size, false,
4722                                               meta);
4723         } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4724                 if (!reg->btf_id) {
4725                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4726                         return -EACCES;
4727                 }
4728                 meta->ret_btf = reg->btf;
4729                 meta->ret_btf_id = reg->btf_id;
4730         } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4731                 if (meta->func_id == BPF_FUNC_spin_lock) {
4732                         if (process_spin_lock(env, regno, true))
4733                                 return -EACCES;
4734                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4735                         if (process_spin_lock(env, regno, false))
4736                                 return -EACCES;
4737                 } else {
4738                         verbose(env, "verifier internal error\n");
4739                         return -EFAULT;
4740                 }
4741         } else if (arg_type_is_mem_ptr(arg_type)) {
4742                 /* The access to this pointer is only checked when we hit the
4743                  * next is_mem_size argument below.
4744                  */
4745                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4746         } else if (arg_type_is_mem_size(arg_type)) {
4747                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4748
4749                 /* This is used to refine r0 return value bounds for helpers
4750                  * that enforce this value as an upper bound on return values.
4751                  * See do_refine_retval_range() for helpers that can refine
4752                  * the return value. C type of helper is u32 so we pull register
4753                  * bound from umax_value however, if negative verifier errors
4754                  * out. Only upper bounds can be learned because retval is an
4755                  * int type and negative retvals are allowed.
4756                  */
4757                 meta->msize_max_value = reg->umax_value;
4758
4759                 /* The register is SCALAR_VALUE; the access check
4760                  * happens using its boundaries.
4761                  */
4762                 if (!tnum_is_const(reg->var_off))
4763                         /* For unprivileged variable accesses, disable raw
4764                          * mode so that the program is required to
4765                          * initialize all the memory that the helper could
4766                          * just partially fill up.
4767                          */
4768                         meta = NULL;
4769
4770                 if (reg->smin_value < 0) {
4771                         verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4772                                 regno);
4773                         return -EACCES;
4774                 }
4775
4776                 if (reg->umin_value == 0) {
4777                         err = check_helper_mem_access(env, regno - 1, 0,
4778                                                       zero_size_allowed,
4779                                                       meta);
4780                         if (err)
4781                                 return err;
4782                 }
4783
4784                 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4785                         verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4786                                 regno);
4787                         return -EACCES;
4788                 }
4789                 err = check_helper_mem_access(env, regno - 1,
4790                                               reg->umax_value,
4791                                               zero_size_allowed, meta);
4792                 if (!err)
4793                         err = mark_chain_precision(env, regno);
4794         } else if (arg_type_is_alloc_size(arg_type)) {
4795                 if (!tnum_is_const(reg->var_off)) {
4796                         verbose(env, "R%d is not a known constant'\n",
4797                                 regno);
4798                         return -EACCES;
4799                 }
4800                 meta->mem_size = reg->var_off.value;
4801         } else if (arg_type_is_int_ptr(arg_type)) {
4802                 int size = int_ptr_type_to_size(arg_type);
4803
4804                 err = check_helper_mem_access(env, regno, size, false, meta);
4805                 if (err)
4806                         return err;
4807                 err = check_ptr_alignment(env, reg, 0, size, true);
4808         }
4809
4810         return err;
4811 }
4812
4813 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4814 {
4815         enum bpf_attach_type eatype = env->prog->expected_attach_type;
4816         enum bpf_prog_type type = resolve_prog_type(env->prog);
4817
4818         if (func_id != BPF_FUNC_map_update_elem)
4819                 return false;
4820
4821         /* It's not possible to get access to a locked struct sock in these
4822          * contexts, so updating is safe.
4823          */
4824         switch (type) {
4825         case BPF_PROG_TYPE_TRACING:
4826                 if (eatype == BPF_TRACE_ITER)
4827                         return true;
4828                 break;
4829         case BPF_PROG_TYPE_SOCKET_FILTER:
4830         case BPF_PROG_TYPE_SCHED_CLS:
4831         case BPF_PROG_TYPE_SCHED_ACT:
4832         case BPF_PROG_TYPE_XDP:
4833         case BPF_PROG_TYPE_SK_REUSEPORT:
4834         case BPF_PROG_TYPE_FLOW_DISSECTOR:
4835         case BPF_PROG_TYPE_SK_LOOKUP:
4836                 return true;
4837         default:
4838                 break;
4839         }
4840
4841         verbose(env, "cannot update sockmap in this context\n");
4842         return false;
4843 }
4844
4845 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4846 {
4847         return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4848 }
4849
4850 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4851                                         struct bpf_map *map, int func_id)
4852 {
4853         if (!map)
4854                 return 0;
4855
4856         /* We need a two way check, first is from map perspective ... */
4857         switch (map->map_type) {
4858         case BPF_MAP_TYPE_PROG_ARRAY:
4859                 if (func_id != BPF_FUNC_tail_call)
4860                         goto error;
4861                 break;
4862         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4863                 if (func_id != BPF_FUNC_perf_event_read &&
4864                     func_id != BPF_FUNC_perf_event_output &&
4865                     func_id != BPF_FUNC_skb_output &&
4866                     func_id != BPF_FUNC_perf_event_read_value &&
4867                     func_id != BPF_FUNC_xdp_output)
4868                         goto error;
4869                 break;
4870         case BPF_MAP_TYPE_RINGBUF:
4871                 if (func_id != BPF_FUNC_ringbuf_output &&
4872                     func_id != BPF_FUNC_ringbuf_reserve &&
4873                     func_id != BPF_FUNC_ringbuf_submit &&
4874                     func_id != BPF_FUNC_ringbuf_discard &&
4875                     func_id != BPF_FUNC_ringbuf_query)
4876                         goto error;
4877                 break;
4878         case BPF_MAP_TYPE_STACK_TRACE:
4879                 if (func_id != BPF_FUNC_get_stackid)
4880                         goto error;
4881                 break;
4882         case BPF_MAP_TYPE_CGROUP_ARRAY:
4883                 if (func_id != BPF_FUNC_skb_under_cgroup &&
4884                     func_id != BPF_FUNC_current_task_under_cgroup)
4885                         goto error;
4886                 break;
4887         case BPF_MAP_TYPE_CGROUP_STORAGE:
4888         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4889                 if (func_id != BPF_FUNC_get_local_storage)
4890                         goto error;
4891                 break;
4892         case BPF_MAP_TYPE_DEVMAP:
4893         case BPF_MAP_TYPE_DEVMAP_HASH:
4894                 if (func_id != BPF_FUNC_redirect_map &&
4895                     func_id != BPF_FUNC_map_lookup_elem)
4896                         goto error;
4897                 break;
4898         /* Restrict bpf side of cpumap and xskmap, open when use-cases
4899          * appear.
4900          */
4901         case BPF_MAP_TYPE_CPUMAP:
4902                 if (func_id != BPF_FUNC_redirect_map)
4903                         goto error;
4904                 break;
4905         case BPF_MAP_TYPE_XSKMAP:
4906                 if (func_id != BPF_FUNC_redirect_map &&
4907                     func_id != BPF_FUNC_map_lookup_elem)
4908                         goto error;
4909                 break;
4910         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4911         case BPF_MAP_TYPE_HASH_OF_MAPS:
4912                 if (func_id != BPF_FUNC_map_lookup_elem)
4913                         goto error;
4914                 break;
4915         case BPF_MAP_TYPE_SOCKMAP:
4916                 if (func_id != BPF_FUNC_sk_redirect_map &&
4917                     func_id != BPF_FUNC_sock_map_update &&
4918                     func_id != BPF_FUNC_map_delete_elem &&
4919                     func_id != BPF_FUNC_msg_redirect_map &&
4920                     func_id != BPF_FUNC_sk_select_reuseport &&
4921                     func_id != BPF_FUNC_map_lookup_elem &&
4922                     !may_update_sockmap(env, func_id))
4923                         goto error;
4924                 break;
4925         case BPF_MAP_TYPE_SOCKHASH:
4926                 if (func_id != BPF_FUNC_sk_redirect_hash &&
4927                     func_id != BPF_FUNC_sock_hash_update &&
4928                     func_id != BPF_FUNC_map_delete_elem &&
4929                     func_id != BPF_FUNC_msg_redirect_hash &&
4930                     func_id != BPF_FUNC_sk_select_reuseport &&
4931                     func_id != BPF_FUNC_map_lookup_elem &&
4932                     !may_update_sockmap(env, func_id))
4933                         goto error;
4934                 break;
4935         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4936                 if (func_id != BPF_FUNC_sk_select_reuseport)
4937                         goto error;
4938                 break;
4939         case BPF_MAP_TYPE_QUEUE:
4940         case BPF_MAP_TYPE_STACK:
4941                 if (func_id != BPF_FUNC_map_peek_elem &&
4942                     func_id != BPF_FUNC_map_pop_elem &&
4943                     func_id != BPF_FUNC_map_push_elem)
4944                         goto error;
4945                 break;
4946         case BPF_MAP_TYPE_SK_STORAGE:
4947                 if (func_id != BPF_FUNC_sk_storage_get &&
4948                     func_id != BPF_FUNC_sk_storage_delete)
4949                         goto error;
4950                 break;
4951         case BPF_MAP_TYPE_INODE_STORAGE:
4952                 if (func_id != BPF_FUNC_inode_storage_get &&
4953                     func_id != BPF_FUNC_inode_storage_delete)
4954                         goto error;
4955                 break;
4956         case BPF_MAP_TYPE_TASK_STORAGE:
4957                 if (func_id != BPF_FUNC_task_storage_get &&
4958                     func_id != BPF_FUNC_task_storage_delete)
4959                         goto error;
4960                 break;
4961         default:
4962                 break;
4963         }
4964
4965         /* ... and second from the function itself. */
4966         switch (func_id) {
4967         case BPF_FUNC_tail_call:
4968                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4969                         goto error;
4970                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4971                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
4972                         return -EINVAL;
4973                 }
4974                 break;
4975         case BPF_FUNC_perf_event_read:
4976         case BPF_FUNC_perf_event_output:
4977         case BPF_FUNC_perf_event_read_value:
4978         case BPF_FUNC_skb_output:
4979         case BPF_FUNC_xdp_output:
4980                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4981                         goto error;
4982                 break;
4983         case BPF_FUNC_get_stackid:
4984                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4985                         goto error;
4986                 break;
4987         case BPF_FUNC_current_task_under_cgroup:
4988         case BPF_FUNC_skb_under_cgroup:
4989                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4990                         goto error;
4991                 break;
4992         case BPF_FUNC_redirect_map:
4993                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
4994                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
4995                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
4996                     map->map_type != BPF_MAP_TYPE_XSKMAP)
4997                         goto error;
4998                 break;
4999         case BPF_FUNC_sk_redirect_map:
5000         case BPF_FUNC_msg_redirect_map:
5001         case BPF_FUNC_sock_map_update:
5002                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5003                         goto error;
5004                 break;
5005         case BPF_FUNC_sk_redirect_hash:
5006         case BPF_FUNC_msg_redirect_hash:
5007         case BPF_FUNC_sock_hash_update:
5008                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5009                         goto error;
5010                 break;
5011         case BPF_FUNC_get_local_storage:
5012                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5013                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5014                         goto error;
5015                 break;
5016         case BPF_FUNC_sk_select_reuseport:
5017                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5018                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5019                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
5020                         goto error;
5021                 break;
5022         case BPF_FUNC_map_peek_elem:
5023         case BPF_FUNC_map_pop_elem:
5024         case BPF_FUNC_map_push_elem:
5025                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5026                     map->map_type != BPF_MAP_TYPE_STACK)
5027                         goto error;
5028                 break;
5029         case BPF_FUNC_sk_storage_get:
5030         case BPF_FUNC_sk_storage_delete:
5031                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5032                         goto error;
5033                 break;
5034         case BPF_FUNC_inode_storage_get:
5035         case BPF_FUNC_inode_storage_delete:
5036                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5037                         goto error;
5038                 break;
5039         case BPF_FUNC_task_storage_get:
5040         case BPF_FUNC_task_storage_delete:
5041                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5042                         goto error;
5043                 break;
5044         default:
5045                 break;
5046         }
5047
5048         return 0;
5049 error:
5050         verbose(env, "cannot pass map_type %d into func %s#%d\n",
5051                 map->map_type, func_id_name(func_id), func_id);
5052         return -EINVAL;
5053 }
5054
5055 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5056 {
5057         int count = 0;
5058
5059         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5060                 count++;
5061         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5062                 count++;
5063         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5064                 count++;
5065         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5066                 count++;
5067         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5068                 count++;
5069
5070         /* We only support one arg being in raw mode at the moment,
5071          * which is sufficient for the helper functions we have
5072          * right now.
5073          */
5074         return count <= 1;
5075 }
5076
5077 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5078                                     enum bpf_arg_type arg_next)
5079 {
5080         return (arg_type_is_mem_ptr(arg_curr) &&
5081                 !arg_type_is_mem_size(arg_next)) ||
5082                (!arg_type_is_mem_ptr(arg_curr) &&
5083                 arg_type_is_mem_size(arg_next));
5084 }
5085
5086 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5087 {
5088         /* bpf_xxx(..., buf, len) call will access 'len'
5089          * bytes from memory 'buf'. Both arg types need
5090          * to be paired, so make sure there's no buggy
5091          * helper function specification.
5092          */
5093         if (arg_type_is_mem_size(fn->arg1_type) ||
5094             arg_type_is_mem_ptr(fn->arg5_type)  ||
5095             check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5096             check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5097             check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5098             check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5099                 return false;
5100
5101         return true;
5102 }
5103
5104 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5105 {
5106         int count = 0;
5107
5108         if (arg_type_may_be_refcounted(fn->arg1_type))
5109                 count++;
5110         if (arg_type_may_be_refcounted(fn->arg2_type))
5111                 count++;
5112         if (arg_type_may_be_refcounted(fn->arg3_type))
5113                 count++;
5114         if (arg_type_may_be_refcounted(fn->arg4_type))
5115                 count++;
5116         if (arg_type_may_be_refcounted(fn->arg5_type))
5117                 count++;
5118
5119         /* A reference acquiring function cannot acquire
5120          * another refcounted ptr.
5121          */
5122         if (may_be_acquire_function(func_id) && count)
5123                 return false;
5124
5125         /* We only support one arg being unreferenced at the moment,
5126          * which is sufficient for the helper functions we have right now.
5127          */
5128         return count <= 1;
5129 }
5130
5131 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5132 {
5133         int i;
5134
5135         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5136                 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5137                         return false;
5138
5139                 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5140                         return false;
5141         }
5142
5143         return true;
5144 }
5145
5146 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5147 {
5148         return check_raw_mode_ok(fn) &&
5149                check_arg_pair_ok(fn) &&
5150                check_btf_id_ok(fn) &&
5151                check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5152 }
5153
5154 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5155  * are now invalid, so turn them into unknown SCALAR_VALUE.
5156  */
5157 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5158                                      struct bpf_func_state *state)
5159 {
5160         struct bpf_reg_state *regs = state->regs, *reg;
5161         int i;
5162
5163         for (i = 0; i < MAX_BPF_REG; i++)
5164                 if (reg_is_pkt_pointer_any(&regs[i]))
5165                         mark_reg_unknown(env, regs, i);
5166
5167         bpf_for_each_spilled_reg(i, state, reg) {
5168                 if (!reg)
5169                         continue;
5170                 if (reg_is_pkt_pointer_any(reg))
5171                         __mark_reg_unknown(env, reg);
5172         }
5173 }
5174
5175 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5176 {
5177         struct bpf_verifier_state *vstate = env->cur_state;
5178         int i;
5179
5180         for (i = 0; i <= vstate->curframe; i++)
5181                 __clear_all_pkt_pointers(env, vstate->frame[i]);
5182 }
5183
5184 enum {
5185         AT_PKT_END = -1,
5186         BEYOND_PKT_END = -2,
5187 };
5188
5189 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5190 {
5191         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5192         struct bpf_reg_state *reg = &state->regs[regn];
5193
5194         if (reg->type != PTR_TO_PACKET)
5195                 /* PTR_TO_PACKET_META is not supported yet */
5196                 return;
5197
5198         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5199          * How far beyond pkt_end it goes is unknown.
5200          * if (!range_open) it's the case of pkt >= pkt_end
5201          * if (range_open) it's the case of pkt > pkt_end
5202          * hence this pointer is at least 1 byte bigger than pkt_end
5203          */
5204         if (range_open)
5205                 reg->range = BEYOND_PKT_END;
5206         else
5207                 reg->range = AT_PKT_END;
5208 }
5209
5210 static void release_reg_references(struct bpf_verifier_env *env,
5211                                    struct bpf_func_state *state,
5212                                    int ref_obj_id)
5213 {
5214         struct bpf_reg_state *regs = state->regs, *reg;
5215         int i;
5216
5217         for (i = 0; i < MAX_BPF_REG; i++)
5218                 if (regs[i].ref_obj_id == ref_obj_id)
5219                         mark_reg_unknown(env, regs, i);
5220
5221         bpf_for_each_spilled_reg(i, state, reg) {
5222                 if (!reg)
5223                         continue;
5224                 if (reg->ref_obj_id == ref_obj_id)
5225                         __mark_reg_unknown(env, reg);
5226         }
5227 }
5228
5229 /* The pointer with the specified id has released its reference to kernel
5230  * resources. Identify all copies of the same pointer and clear the reference.
5231  */
5232 static int release_reference(struct bpf_verifier_env *env,
5233                              int ref_obj_id)
5234 {
5235         struct bpf_verifier_state *vstate = env->cur_state;
5236         int err;
5237         int i;
5238
5239         err = release_reference_state(cur_func(env), ref_obj_id);
5240         if (err)
5241                 return err;
5242
5243         for (i = 0; i <= vstate->curframe; i++)
5244                 release_reg_references(env, vstate->frame[i], ref_obj_id);
5245
5246         return 0;
5247 }
5248
5249 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5250                                     struct bpf_reg_state *regs)
5251 {
5252         int i;
5253
5254         /* after the call registers r0 - r5 were scratched */
5255         for (i = 0; i < CALLER_SAVED_REGS; i++) {
5256                 mark_reg_not_init(env, regs, caller_saved[i]);
5257                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5258         }
5259 }
5260
5261 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5262                            int *insn_idx)
5263 {
5264         struct bpf_verifier_state *state = env->cur_state;
5265         struct bpf_func_info_aux *func_info_aux;
5266         struct bpf_func_state *caller, *callee;
5267         int i, err, subprog, target_insn;
5268         bool is_global = false;
5269
5270         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5271                 verbose(env, "the call stack of %d frames is too deep\n",
5272                         state->curframe + 2);
5273                 return -E2BIG;
5274         }
5275
5276         target_insn = *insn_idx + insn->imm;
5277         subprog = find_subprog(env, target_insn + 1);
5278         if (subprog < 0) {
5279                 verbose(env, "verifier bug. No program starts at insn %d\n",
5280                         target_insn + 1);
5281                 return -EFAULT;
5282         }
5283
5284         caller = state->frame[state->curframe];
5285         if (state->frame[state->curframe + 1]) {
5286                 verbose(env, "verifier bug. Frame %d already allocated\n",
5287                         state->curframe + 1);
5288                 return -EFAULT;
5289         }
5290
5291         func_info_aux = env->prog->aux->func_info_aux;
5292         if (func_info_aux)
5293                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5294         err = btf_check_func_arg_match(env, subprog, caller->regs);
5295         if (err == -EFAULT)
5296                 return err;
5297         if (is_global) {
5298                 if (err) {
5299                         verbose(env, "Caller passes invalid args into func#%d\n",
5300                                 subprog);
5301                         return err;
5302                 } else {
5303                         if (env->log.level & BPF_LOG_LEVEL)
5304                                 verbose(env,
5305                                         "Func#%d is global and valid. Skipping.\n",
5306                                         subprog);
5307                         clear_caller_saved_regs(env, caller->regs);
5308
5309                         /* All global functions return a 64-bit SCALAR_VALUE */
5310                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
5311                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5312
5313                         /* continue with next insn after call */
5314                         return 0;
5315                 }
5316         }
5317
5318         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5319         if (!callee)
5320                 return -ENOMEM;
5321         state->frame[state->curframe + 1] = callee;
5322
5323         /* callee cannot access r0, r6 - r9 for reading and has to write
5324          * into its own stack before reading from it.
5325          * callee can read/write into caller's stack
5326          */
5327         init_func_state(env, callee,
5328                         /* remember the callsite, it will be used by bpf_exit */
5329                         *insn_idx /* callsite */,
5330                         state->curframe + 1 /* frameno within this callchain */,
5331                         subprog /* subprog number within this prog */);
5332
5333         /* Transfer references to the callee */
5334         err = transfer_reference_state(callee, caller);
5335         if (err)
5336                 return err;
5337
5338         /* copy r1 - r5 args that callee can access.  The copy includes parent
5339          * pointers, which connects us up to the liveness chain
5340          */
5341         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5342                 callee->regs[i] = caller->regs[i];
5343
5344         clear_caller_saved_regs(env, caller->regs);
5345
5346         /* only increment it after check_reg_arg() finished */
5347         state->curframe++;
5348
5349         /* and go analyze first insn of the callee */
5350         *insn_idx = target_insn;
5351
5352         if (env->log.level & BPF_LOG_LEVEL) {
5353                 verbose(env, "caller:\n");
5354                 print_verifier_state(env, caller);
5355                 verbose(env, "callee:\n");
5356                 print_verifier_state(env, callee);
5357         }
5358         return 0;
5359 }
5360
5361 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5362 {
5363         struct bpf_verifier_state *state = env->cur_state;
5364         struct bpf_func_state *caller, *callee;
5365         struct bpf_reg_state *r0;
5366         int err;
5367
5368         callee = state->frame[state->curframe];
5369         r0 = &callee->regs[BPF_REG_0];
5370         if (r0->type == PTR_TO_STACK) {
5371                 /* technically it's ok to return caller's stack pointer
5372                  * (or caller's caller's pointer) back to the caller,
5373                  * since these pointers are valid. Only current stack
5374                  * pointer will be invalid as soon as function exits,
5375                  * but let's be conservative
5376                  */
5377                 verbose(env, "cannot return stack pointer to the caller\n");
5378                 return -EINVAL;
5379         }
5380
5381         state->curframe--;
5382         caller = state->frame[state->curframe];
5383         /* return to the caller whatever r0 had in the callee */
5384         caller->regs[BPF_REG_0] = *r0;
5385
5386         /* Transfer references to the caller */
5387         err = transfer_reference_state(caller, callee);
5388         if (err)
5389                 return err;
5390
5391         *insn_idx = callee->callsite + 1;
5392         if (env->log.level & BPF_LOG_LEVEL) {
5393                 verbose(env, "returning from callee:\n");
5394                 print_verifier_state(env, callee);
5395                 verbose(env, "to caller at %d:\n", *insn_idx);
5396                 print_verifier_state(env, caller);
5397         }
5398         /* clear everything in the callee */
5399         free_func_state(callee);
5400         state->frame[state->curframe + 1] = NULL;
5401         return 0;
5402 }
5403
5404 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5405                                    int func_id,
5406                                    struct bpf_call_arg_meta *meta)
5407 {
5408         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5409
5410         if (ret_type != RET_INTEGER ||
5411             (func_id != BPF_FUNC_get_stack &&
5412              func_id != BPF_FUNC_probe_read_str &&
5413              func_id != BPF_FUNC_probe_read_kernel_str &&
5414              func_id != BPF_FUNC_probe_read_user_str))
5415                 return;
5416
5417         ret_reg->smax_value = meta->msize_max_value;
5418         ret_reg->s32_max_value = meta->msize_max_value;
5419         ret_reg->smin_value = -MAX_ERRNO;
5420         ret_reg->s32_min_value = -MAX_ERRNO;
5421         __reg_deduce_bounds(ret_reg);
5422         __reg_bound_offset(ret_reg);
5423         __update_reg_bounds(ret_reg);
5424 }
5425
5426 static int
5427 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5428                 int func_id, int insn_idx)
5429 {
5430         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5431         struct bpf_map *map = meta->map_ptr;
5432
5433         if (func_id != BPF_FUNC_tail_call &&
5434             func_id != BPF_FUNC_map_lookup_elem &&
5435             func_id != BPF_FUNC_map_update_elem &&
5436             func_id != BPF_FUNC_map_delete_elem &&
5437             func_id != BPF_FUNC_map_push_elem &&
5438             func_id != BPF_FUNC_map_pop_elem &&
5439             func_id != BPF_FUNC_map_peek_elem)
5440                 return 0;
5441
5442         if (map == NULL) {
5443                 verbose(env, "kernel subsystem misconfigured verifier\n");
5444                 return -EINVAL;
5445         }
5446
5447         /* In case of read-only, some additional restrictions
5448          * need to be applied in order to prevent altering the
5449          * state of the map from program side.
5450          */
5451         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5452             (func_id == BPF_FUNC_map_delete_elem ||
5453              func_id == BPF_FUNC_map_update_elem ||
5454              func_id == BPF_FUNC_map_push_elem ||
5455              func_id == BPF_FUNC_map_pop_elem)) {
5456                 verbose(env, "write into map forbidden\n");
5457                 return -EACCES;
5458         }
5459
5460         if (!BPF_MAP_PTR(aux->map_ptr_state))
5461                 bpf_map_ptr_store(aux, meta->map_ptr,
5462                                   !meta->map_ptr->bypass_spec_v1);
5463         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5464                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5465                                   !meta->map_ptr->bypass_spec_v1);
5466         return 0;
5467 }
5468
5469 static int
5470 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5471                 int func_id, int insn_idx)
5472 {
5473         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5474         struct bpf_reg_state *regs = cur_regs(env), *reg;
5475         struct bpf_map *map = meta->map_ptr;
5476         struct tnum range;
5477         u64 val;
5478         int err;
5479
5480         if (func_id != BPF_FUNC_tail_call)
5481                 return 0;
5482         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5483                 verbose(env, "kernel subsystem misconfigured verifier\n");
5484                 return -EINVAL;
5485         }
5486
5487         range = tnum_range(0, map->max_entries - 1);
5488         reg = &regs[BPF_REG_3];
5489
5490         if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5491                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5492                 return 0;
5493         }
5494
5495         err = mark_chain_precision(env, BPF_REG_3);
5496         if (err)
5497                 return err;
5498
5499         val = reg->var_off.value;
5500         if (bpf_map_key_unseen(aux))
5501                 bpf_map_key_store(aux, val);
5502         else if (!bpf_map_key_poisoned(aux) &&
5503                   bpf_map_key_immediate(aux) != val)
5504                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5505         return 0;
5506 }
5507
5508 static int check_reference_leak(struct bpf_verifier_env *env)
5509 {
5510         struct bpf_func_state *state = cur_func(env);
5511         int i;
5512
5513         for (i = 0; i < state->acquired_refs; i++) {
5514                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5515                         state->refs[i].id, state->refs[i].insn_idx);
5516         }
5517         return state->acquired_refs ? -EINVAL : 0;
5518 }
5519
5520 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5521 {
5522         const struct bpf_func_proto *fn = NULL;
5523         struct bpf_reg_state *regs;
5524         struct bpf_call_arg_meta meta;
5525         bool changes_data;
5526         int i, err;
5527
5528         /* find function prototype */
5529         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5530                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5531                         func_id);
5532                 return -EINVAL;
5533         }
5534
5535         if (env->ops->get_func_proto)
5536                 fn = env->ops->get_func_proto(func_id, env->prog);
5537         if (!fn) {
5538                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5539                         func_id);
5540                 return -EINVAL;
5541         }
5542
5543         /* eBPF programs must be GPL compatible to use GPL-ed functions */
5544         if (!env->prog->gpl_compatible && fn->gpl_only) {
5545                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5546                 return -EINVAL;
5547         }
5548
5549         if (fn->allowed && !fn->allowed(env->prog)) {
5550                 verbose(env, "helper call is not allowed in probe\n");
5551                 return -EINVAL;
5552         }
5553
5554         /* With LD_ABS/IND some JITs save/restore skb from r1. */
5555         changes_data = bpf_helper_changes_pkt_data(fn->func);
5556         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5557                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5558                         func_id_name(func_id), func_id);
5559                 return -EINVAL;
5560         }
5561
5562         memset(&meta, 0, sizeof(meta));
5563         meta.pkt_access = fn->pkt_access;
5564
5565         err = check_func_proto(fn, func_id);
5566         if (err) {
5567                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5568                         func_id_name(func_id), func_id);
5569                 return err;
5570         }
5571
5572         meta.func_id = func_id;
5573         /* check args */
5574         for (i = 0; i < 5; i++) {
5575                 err = check_func_arg(env, i, &meta, fn);
5576                 if (err)
5577                         return err;
5578         }
5579
5580         err = record_func_map(env, &meta, func_id, insn_idx);
5581         if (err)
5582                 return err;
5583
5584         err = record_func_key(env, &meta, func_id, insn_idx);
5585         if (err)
5586                 return err;
5587
5588         /* Mark slots with STACK_MISC in case of raw mode, stack offset
5589          * is inferred from register state.
5590          */
5591         for (i = 0; i < meta.access_size; i++) {
5592                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5593                                        BPF_WRITE, -1, false);
5594                 if (err)
5595                         return err;
5596         }
5597
5598         if (func_id == BPF_FUNC_tail_call) {
5599                 err = check_reference_leak(env);
5600                 if (err) {
5601                         verbose(env, "tail_call would lead to reference leak\n");
5602                         return err;
5603                 }
5604         } else if (is_release_function(func_id)) {
5605                 err = release_reference(env, meta.ref_obj_id);
5606                 if (err) {
5607                         verbose(env, "func %s#%d reference has not been acquired before\n",
5608                                 func_id_name(func_id), func_id);
5609                         return err;
5610                 }
5611         }
5612
5613         regs = cur_regs(env);
5614
5615         /* check that flags argument in get_local_storage(map, flags) is 0,
5616          * this is required because get_local_storage() can't return an error.
5617          */
5618         if (func_id == BPF_FUNC_get_local_storage &&
5619             !register_is_null(&regs[BPF_REG_2])) {
5620                 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5621                 return -EINVAL;
5622         }
5623
5624         /* reset caller saved regs */
5625         for (i = 0; i < CALLER_SAVED_REGS; i++) {
5626                 mark_reg_not_init(env, regs, caller_saved[i]);
5627                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5628         }
5629
5630         /* helper call returns 64-bit value. */
5631         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5632
5633         /* update return register (already marked as written above) */
5634         if (fn->ret_type == RET_INTEGER) {
5635                 /* sets type to SCALAR_VALUE */
5636                 mark_reg_unknown(env, regs, BPF_REG_0);
5637         } else if (fn->ret_type == RET_VOID) {
5638                 regs[BPF_REG_0].type = NOT_INIT;
5639         } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5640                    fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5641                 /* There is no offset yet applied, variable or fixed */
5642                 mark_reg_known_zero(env, regs, BPF_REG_0);
5643                 /* remember map_ptr, so that check_map_access()
5644                  * can check 'value_size' boundary of memory access
5645                  * to map element returned from bpf_map_lookup_elem()
5646                  */
5647                 if (meta.map_ptr == NULL) {
5648                         verbose(env,
5649                                 "kernel subsystem misconfigured verifier\n");
5650                         return -EINVAL;
5651                 }
5652                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
5653                 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5654                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
5655                         if (map_value_has_spin_lock(meta.map_ptr))
5656                                 regs[BPF_REG_0].id = ++env->id_gen;
5657                 } else {
5658                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5659                 }
5660         } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5661                 mark_reg_known_zero(env, regs, BPF_REG_0);
5662                 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
5663         } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5664                 mark_reg_known_zero(env, regs, BPF_REG_0);
5665                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5666         } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5667                 mark_reg_known_zero(env, regs, BPF_REG_0);
5668                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5669         } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5670                 mark_reg_known_zero(env, regs, BPF_REG_0);
5671                 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5672                 regs[BPF_REG_0].mem_size = meta.mem_size;
5673         } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5674                    fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
5675                 const struct btf_type *t;
5676
5677                 mark_reg_known_zero(env, regs, BPF_REG_0);
5678                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
5679                 if (!btf_type_is_struct(t)) {
5680                         u32 tsize;
5681                         const struct btf_type *ret;
5682                         const char *tname;
5683
5684                         /* resolve the type size of ksym. */
5685                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
5686                         if (IS_ERR(ret)) {
5687                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
5688                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5689                                         tname, PTR_ERR(ret));
5690                                 return -EINVAL;
5691                         }
5692                         regs[BPF_REG_0].type =
5693                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5694                                 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
5695                         regs[BPF_REG_0].mem_size = tsize;
5696                 } else {
5697                         regs[BPF_REG_0].type =
5698                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5699                                 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
5700                         regs[BPF_REG_0].btf = meta.ret_btf;
5701                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5702                 }
5703         } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5704                    fn->ret_type == RET_PTR_TO_BTF_ID) {
5705                 int ret_btf_id;
5706
5707                 mark_reg_known_zero(env, regs, BPF_REG_0);
5708                 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5709                                                      PTR_TO_BTF_ID :
5710                                                      PTR_TO_BTF_ID_OR_NULL;
5711                 ret_btf_id = *fn->ret_btf_id;
5712                 if (ret_btf_id == 0) {
5713                         verbose(env, "invalid return type %d of func %s#%d\n",
5714                                 fn->ret_type, func_id_name(func_id), func_id);
5715                         return -EINVAL;
5716                 }
5717                 /* current BPF helper definitions are only coming from
5718                  * built-in code with type IDs from  vmlinux BTF
5719                  */
5720                 regs[BPF_REG_0].btf = btf_vmlinux;
5721                 regs[BPF_REG_0].btf_id = ret_btf_id;
5722         } else {
5723                 verbose(env, "unknown return type %d of func %s#%d\n",
5724                         fn->ret_type, func_id_name(func_id), func_id);
5725                 return -EINVAL;
5726         }
5727
5728         if (reg_type_may_be_null(regs[BPF_REG_0].type))
5729                 regs[BPF_REG_0].id = ++env->id_gen;
5730
5731         if (is_ptr_cast_function(func_id)) {
5732                 /* For release_reference() */
5733                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5734         } else if (is_acquire_function(func_id, meta.map_ptr)) {
5735                 int id = acquire_reference_state(env, insn_idx);
5736
5737                 if (id < 0)
5738                         return id;
5739                 /* For mark_ptr_or_null_reg() */
5740                 regs[BPF_REG_0].id = id;
5741                 /* For release_reference() */
5742                 regs[BPF_REG_0].ref_obj_id = id;
5743         }
5744
5745         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5746
5747         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5748         if (err)
5749                 return err;
5750
5751         if ((func_id == BPF_FUNC_get_stack ||
5752              func_id == BPF_FUNC_get_task_stack) &&
5753             !env->prog->has_callchain_buf) {
5754                 const char *err_str;
5755
5756 #ifdef CONFIG_PERF_EVENTS
5757                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5758                 err_str = "cannot get callchain buffer for func %s#%d\n";
5759 #else
5760                 err = -ENOTSUPP;
5761                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5762 #endif
5763                 if (err) {
5764                         verbose(env, err_str, func_id_name(func_id), func_id);
5765                         return err;
5766                 }
5767
5768                 env->prog->has_callchain_buf = true;
5769         }
5770
5771         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5772                 env->prog->call_get_stack = true;
5773
5774         if (changes_data)
5775                 clear_all_pkt_pointers(env);
5776         return 0;
5777 }
5778
5779 static bool signed_add_overflows(s64 a, s64 b)
5780 {
5781         /* Do the add in u64, where overflow is well-defined */
5782         s64 res = (s64)((u64)a + (u64)b);
5783
5784         if (b < 0)
5785                 return res > a;
5786         return res < a;
5787 }
5788
5789 static bool signed_add32_overflows(s32 a, s32 b)
5790 {
5791         /* Do the add in u32, where overflow is well-defined */
5792         s32 res = (s32)((u32)a + (u32)b);
5793
5794         if (b < 0)
5795                 return res > a;
5796         return res < a;
5797 }
5798
5799 static bool signed_sub_overflows(s64 a, s64 b)
5800 {
5801         /* Do the sub in u64, where overflow is well-defined */
5802         s64 res = (s64)((u64)a - (u64)b);
5803
5804         if (b < 0)
5805                 return res < a;
5806         return res > a;
5807 }
5808
5809 static bool signed_sub32_overflows(s32 a, s32 b)
5810 {
5811         /* Do the sub in u32, where overflow is well-defined */
5812         s32 res = (s32)((u32)a - (u32)b);
5813
5814         if (b < 0)
5815                 return res < a;
5816         return res > a;
5817 }
5818
5819 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5820                                   const struct bpf_reg_state *reg,
5821                                   enum bpf_reg_type type)
5822 {
5823         bool known = tnum_is_const(reg->var_off);
5824         s64 val = reg->var_off.value;
5825         s64 smin = reg->smin_value;
5826
5827         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5828                 verbose(env, "math between %s pointer and %lld is not allowed\n",
5829                         reg_type_str[type], val);
5830                 return false;
5831         }
5832
5833         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5834                 verbose(env, "%s pointer offset %d is not allowed\n",
5835                         reg_type_str[type], reg->off);
5836                 return false;
5837         }
5838
5839         if (smin == S64_MIN) {
5840                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5841                         reg_type_str[type]);
5842                 return false;
5843         }
5844
5845         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5846                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5847                         smin, reg_type_str[type]);
5848                 return false;
5849         }
5850
5851         return true;
5852 }
5853
5854 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5855 {
5856         return &env->insn_aux_data[env->insn_idx];
5857 }
5858
5859 enum {
5860         REASON_BOUNDS   = -1,
5861         REASON_TYPE     = -2,
5862         REASON_PATHS    = -3,
5863         REASON_LIMIT    = -4,
5864         REASON_STACK    = -5,
5865 };
5866
5867 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5868                               const struct bpf_reg_state *off_reg,
5869                               u32 *alu_limit, u8 opcode)
5870 {
5871         bool off_is_neg = off_reg->smin_value < 0;
5872         bool mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
5873                             (opcode == BPF_SUB && !off_is_neg);
5874         u32 max = 0, ptr_limit = 0;
5875
5876         if (!tnum_is_const(off_reg->var_off) &&
5877             (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
5878                 return REASON_BOUNDS;
5879
5880         switch (ptr_reg->type) {
5881         case PTR_TO_STACK:
5882                 /* Offset 0 is out-of-bounds, but acceptable start for the
5883                  * left direction, see BPF_REG_FP. Also, unknown scalar
5884                  * offset where we would need to deal with min/max bounds is
5885                  * currently prohibited for unprivileged.
5886                  */
5887                 max = MAX_BPF_STACK + mask_to_left;
5888                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
5889                 break;
5890         case PTR_TO_MAP_VALUE:
5891                 max = ptr_reg->map_ptr->value_size;
5892                 ptr_limit = (mask_to_left ?
5893                              ptr_reg->smin_value :
5894                              ptr_reg->umax_value) + ptr_reg->off;
5895                 break;
5896         default:
5897                 return REASON_TYPE;
5898         }
5899
5900         if (ptr_limit >= max)
5901                 return REASON_LIMIT;
5902         *alu_limit = ptr_limit;
5903         return 0;
5904 }
5905
5906 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5907                                     const struct bpf_insn *insn)
5908 {
5909         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5910 }
5911
5912 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5913                                        u32 alu_state, u32 alu_limit)
5914 {
5915         /* If we arrived here from different branches with different
5916          * state or limits to sanitize, then this won't work.
5917          */
5918         if (aux->alu_state &&
5919             (aux->alu_state != alu_state ||
5920              aux->alu_limit != alu_limit))
5921                 return REASON_PATHS;
5922
5923         /* Corresponding fixup done in fixup_bpf_calls(). */
5924         aux->alu_state = alu_state;
5925         aux->alu_limit = alu_limit;
5926         return 0;
5927 }
5928
5929 static int sanitize_val_alu(struct bpf_verifier_env *env,
5930                             struct bpf_insn *insn)
5931 {
5932         struct bpf_insn_aux_data *aux = cur_aux(env);
5933
5934         if (can_skip_alu_sanitation(env, insn))
5935                 return 0;
5936
5937         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5938 }
5939
5940 static bool sanitize_needed(u8 opcode)
5941 {
5942         return opcode == BPF_ADD || opcode == BPF_SUB;
5943 }
5944
5945 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5946                             struct bpf_insn *insn,
5947                             const struct bpf_reg_state *ptr_reg,
5948                             const struct bpf_reg_state *off_reg,
5949                             struct bpf_reg_state *dst_reg,
5950                             struct bpf_insn_aux_data *tmp_aux,
5951                             const bool commit_window)
5952 {
5953         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : tmp_aux;
5954         struct bpf_verifier_state *vstate = env->cur_state;
5955         bool off_is_neg = off_reg->smin_value < 0;
5956         bool ptr_is_dst_reg = ptr_reg == dst_reg;
5957         u8 opcode = BPF_OP(insn->code);
5958         u32 alu_state, alu_limit;
5959         struct bpf_reg_state tmp;
5960         bool ret;
5961         int err;
5962
5963         if (can_skip_alu_sanitation(env, insn))
5964                 return 0;
5965
5966         /* We already marked aux for masking from non-speculative
5967          * paths, thus we got here in the first place. We only care
5968          * to explore bad access from here.
5969          */
5970         if (vstate->speculative)
5971                 goto do_sim;
5972
5973         err = retrieve_ptr_limit(ptr_reg, off_reg, &alu_limit, opcode);
5974         if (err < 0)
5975                 return err;
5976
5977         if (commit_window) {
5978                 /* In commit phase we narrow the masking window based on
5979                  * the observed pointer move after the simulated operation.
5980                  */
5981                 alu_state = tmp_aux->alu_state;
5982                 alu_limit = abs(tmp_aux->alu_limit - alu_limit);
5983         } else {
5984                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5985                 alu_state |= ptr_is_dst_reg ?
5986                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5987         }
5988
5989         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
5990         if (err < 0)
5991                 return err;
5992 do_sim:
5993         /* If we're in commit phase, we're done here given we already
5994          * pushed the truncated dst_reg into the speculative verification
5995          * stack.
5996          */
5997         if (commit_window)
5998                 return 0;
5999
6000         /* Simulate and find potential out-of-bounds access under
6001          * speculative execution from truncation as a result of
6002          * masking when off was not within expected range. If off
6003          * sits in dst, then we temporarily need to move ptr there
6004          * to simulate dst (== 0) +/-= ptr. Needed, for example,
6005          * for cases where we use K-based arithmetic in one direction
6006          * and truncated reg-based in the other in order to explore
6007          * bad access.
6008          */
6009         if (!ptr_is_dst_reg) {
6010                 tmp = *dst_reg;
6011                 *dst_reg = *ptr_reg;
6012         }
6013         ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
6014         if (!ptr_is_dst_reg && ret)
6015                 *dst_reg = tmp;
6016         return !ret ? REASON_STACK : 0;
6017 }
6018
6019 static int sanitize_err(struct bpf_verifier_env *env,
6020                         const struct bpf_insn *insn, int reason,
6021                         const struct bpf_reg_state *off_reg,
6022                         const struct bpf_reg_state *dst_reg)
6023 {
6024         static const char *err = "pointer arithmetic with it prohibited for !root";
6025         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6026         u32 dst = insn->dst_reg, src = insn->src_reg;
6027
6028         switch (reason) {
6029         case REASON_BOUNDS:
6030                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6031                         off_reg == dst_reg ? dst : src, err);
6032                 break;
6033         case REASON_TYPE:
6034                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6035                         off_reg == dst_reg ? src : dst, err);
6036                 break;
6037         case REASON_PATHS:
6038                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6039                         dst, op, err);
6040                 break;
6041         case REASON_LIMIT:
6042                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6043                         dst, op, err);
6044                 break;
6045         case REASON_STACK:
6046                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6047                         dst, err);
6048                 break;
6049         default:
6050                 verbose(env, "verifier internal error: unknown reason (%d)\n",
6051                         reason);
6052                 break;
6053         }
6054
6055         return -EACCES;
6056 }
6057
6058 /* check that stack access falls within stack limits and that 'reg' doesn't
6059  * have a variable offset.
6060  *
6061  * Variable offset is prohibited for unprivileged mode for simplicity since it
6062  * requires corresponding support in Spectre masking for stack ALU.  See also
6063  * retrieve_ptr_limit().
6064  *
6065  *
6066  * 'off' includes 'reg->off'.
6067  */
6068 static int check_stack_access_for_ptr_arithmetic(
6069                                 struct bpf_verifier_env *env,
6070                                 int regno,
6071                                 const struct bpf_reg_state *reg,
6072                                 int off)
6073 {
6074         if (!tnum_is_const(reg->var_off)) {
6075                 char tn_buf[48];
6076
6077                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6078                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6079                         regno, tn_buf, off);
6080                 return -EACCES;
6081         }
6082
6083         if (off >= 0 || off < -MAX_BPF_STACK) {
6084                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6085                         "prohibited for !root; off=%d\n", regno, off);
6086                 return -EACCES;
6087         }
6088
6089         return 0;
6090 }
6091
6092 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6093                                  const struct bpf_insn *insn,
6094                                  const struct bpf_reg_state *dst_reg)
6095 {
6096         u32 dst = insn->dst_reg;
6097
6098         /* For unprivileged we require that resulting offset must be in bounds
6099          * in order to be able to sanitize access later on.
6100          */
6101         if (env->bypass_spec_v1)
6102                 return 0;
6103
6104         switch (dst_reg->type) {
6105         case PTR_TO_STACK:
6106                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6107                                         dst_reg->off + dst_reg->var_off.value))
6108                         return -EACCES;
6109                 break;
6110         case PTR_TO_MAP_VALUE:
6111                 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6112                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6113                                 "prohibited for !root\n", dst);
6114                         return -EACCES;
6115                 }
6116                 break;
6117         default:
6118                 break;
6119         }
6120
6121         return 0;
6122 }
6123
6124 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6125  * Caller should also handle BPF_MOV case separately.
6126  * If we return -EACCES, caller may want to try again treating pointer as a
6127  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6128  */
6129 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6130                                    struct bpf_insn *insn,
6131                                    const struct bpf_reg_state *ptr_reg,
6132                                    const struct bpf_reg_state *off_reg)
6133 {
6134         struct bpf_verifier_state *vstate = env->cur_state;
6135         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6136         struct bpf_reg_state *regs = state->regs, *dst_reg;
6137         bool known = tnum_is_const(off_reg->var_off);
6138         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6139             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6140         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6141             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6142         struct bpf_insn_aux_data tmp_aux = {};
6143         u8 opcode = BPF_OP(insn->code);
6144         u32 dst = insn->dst_reg;
6145         int ret;
6146
6147         dst_reg = &regs[dst];
6148
6149         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6150             smin_val > smax_val || umin_val > umax_val) {
6151                 /* Taint dst register if offset had invalid bounds derived from
6152                  * e.g. dead branches.
6153                  */
6154                 __mark_reg_unknown(env, dst_reg);
6155                 return 0;
6156         }
6157
6158         if (BPF_CLASS(insn->code) != BPF_ALU64) {
6159                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6160                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6161                         __mark_reg_unknown(env, dst_reg);
6162                         return 0;
6163                 }
6164
6165                 verbose(env,
6166                         "R%d 32-bit pointer arithmetic prohibited\n",
6167                         dst);
6168                 return -EACCES;
6169         }
6170
6171         switch (ptr_reg->type) {
6172         case PTR_TO_MAP_VALUE_OR_NULL:
6173                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6174                         dst, reg_type_str[ptr_reg->type]);
6175                 return -EACCES;
6176         case CONST_PTR_TO_MAP:
6177                 /* smin_val represents the known value */
6178                 if (known && smin_val == 0 && opcode == BPF_ADD)
6179                         break;
6180                 fallthrough;
6181         case PTR_TO_PACKET_END:
6182         case PTR_TO_SOCKET:
6183         case PTR_TO_SOCKET_OR_NULL:
6184         case PTR_TO_SOCK_COMMON:
6185         case PTR_TO_SOCK_COMMON_OR_NULL:
6186         case PTR_TO_TCP_SOCK:
6187         case PTR_TO_TCP_SOCK_OR_NULL:
6188         case PTR_TO_XDP_SOCK:
6189                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6190                         dst, reg_type_str[ptr_reg->type]);
6191                 return -EACCES;
6192         default:
6193                 break;
6194         }
6195
6196         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6197          * The id may be overwritten later if we create a new variable offset.
6198          */
6199         dst_reg->type = ptr_reg->type;
6200         dst_reg->id = ptr_reg->id;
6201
6202         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6203             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6204                 return -EINVAL;
6205
6206         /* pointer types do not carry 32-bit bounds at the moment. */
6207         __mark_reg32_unbounded(dst_reg);
6208
6209         if (sanitize_needed(opcode)) {
6210                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6211                                        &tmp_aux, false);
6212                 if (ret < 0)
6213                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
6214         }
6215
6216         switch (opcode) {
6217         case BPF_ADD:
6218                 /* We can take a fixed offset as long as it doesn't overflow
6219                  * the s32 'off' field
6220                  */
6221                 if (known && (ptr_reg->off + smin_val ==
6222                               (s64)(s32)(ptr_reg->off + smin_val))) {
6223                         /* pointer += K.  Accumulate it into fixed offset */
6224                         dst_reg->smin_value = smin_ptr;
6225                         dst_reg->smax_value = smax_ptr;
6226                         dst_reg->umin_value = umin_ptr;
6227                         dst_reg->umax_value = umax_ptr;
6228                         dst_reg->var_off = ptr_reg->var_off;
6229                         dst_reg->off = ptr_reg->off + smin_val;
6230                         dst_reg->raw = ptr_reg->raw;
6231                         break;
6232                 }
6233                 /* A new variable offset is created.  Note that off_reg->off
6234                  * == 0, since it's a scalar.
6235                  * dst_reg gets the pointer type and since some positive
6236                  * integer value was added to the pointer, give it a new 'id'
6237                  * if it's a PTR_TO_PACKET.
6238                  * this creates a new 'base' pointer, off_reg (variable) gets
6239                  * added into the variable offset, and we copy the fixed offset
6240                  * from ptr_reg.
6241                  */
6242                 if (signed_add_overflows(smin_ptr, smin_val) ||
6243                     signed_add_overflows(smax_ptr, smax_val)) {
6244                         dst_reg->smin_value = S64_MIN;
6245                         dst_reg->smax_value = S64_MAX;
6246                 } else {
6247                         dst_reg->smin_value = smin_ptr + smin_val;
6248                         dst_reg->smax_value = smax_ptr + smax_val;
6249                 }
6250                 if (umin_ptr + umin_val < umin_ptr ||
6251                     umax_ptr + umax_val < umax_ptr) {
6252                         dst_reg->umin_value = 0;
6253                         dst_reg->umax_value = U64_MAX;
6254                 } else {
6255                         dst_reg->umin_value = umin_ptr + umin_val;
6256                         dst_reg->umax_value = umax_ptr + umax_val;
6257                 }
6258                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6259                 dst_reg->off = ptr_reg->off;
6260                 dst_reg->raw = ptr_reg->raw;
6261                 if (reg_is_pkt_pointer(ptr_reg)) {
6262                         dst_reg->id = ++env->id_gen;
6263                         /* something was added to pkt_ptr, set range to zero */
6264                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6265                 }
6266                 break;
6267         case BPF_SUB:
6268                 if (dst_reg == off_reg) {
6269                         /* scalar -= pointer.  Creates an unknown scalar */
6270                         verbose(env, "R%d tried to subtract pointer from scalar\n",
6271                                 dst);
6272                         return -EACCES;
6273                 }
6274                 /* We don't allow subtraction from FP, because (according to
6275                  * test_verifier.c test "invalid fp arithmetic", JITs might not
6276                  * be able to deal with it.
6277                  */
6278                 if (ptr_reg->type == PTR_TO_STACK) {
6279                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
6280                                 dst);
6281                         return -EACCES;
6282                 }
6283                 if (known && (ptr_reg->off - smin_val ==
6284                               (s64)(s32)(ptr_reg->off - smin_val))) {
6285                         /* pointer -= K.  Subtract it from fixed offset */
6286                         dst_reg->smin_value = smin_ptr;
6287                         dst_reg->smax_value = smax_ptr;
6288                         dst_reg->umin_value = umin_ptr;
6289                         dst_reg->umax_value = umax_ptr;
6290                         dst_reg->var_off = ptr_reg->var_off;
6291                         dst_reg->id = ptr_reg->id;
6292                         dst_reg->off = ptr_reg->off - smin_val;
6293                         dst_reg->raw = ptr_reg->raw;
6294                         break;
6295                 }
6296                 /* A new variable offset is created.  If the subtrahend is known
6297                  * nonnegative, then any reg->range we had before is still good.
6298                  */
6299                 if (signed_sub_overflows(smin_ptr, smax_val) ||
6300                     signed_sub_overflows(smax_ptr, smin_val)) {
6301                         /* Overflow possible, we know nothing */
6302                         dst_reg->smin_value = S64_MIN;
6303                         dst_reg->smax_value = S64_MAX;
6304                 } else {
6305                         dst_reg->smin_value = smin_ptr - smax_val;
6306                         dst_reg->smax_value = smax_ptr - smin_val;
6307                 }
6308                 if (umin_ptr < umax_val) {
6309                         /* Overflow possible, we know nothing */
6310                         dst_reg->umin_value = 0;
6311                         dst_reg->umax_value = U64_MAX;
6312                 } else {
6313                         /* Cannot overflow (as long as bounds are consistent) */
6314                         dst_reg->umin_value = umin_ptr - umax_val;
6315                         dst_reg->umax_value = umax_ptr - umin_val;
6316                 }
6317                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6318                 dst_reg->off = ptr_reg->off;
6319                 dst_reg->raw = ptr_reg->raw;
6320                 if (reg_is_pkt_pointer(ptr_reg)) {
6321                         dst_reg->id = ++env->id_gen;
6322                         /* something was added to pkt_ptr, set range to zero */
6323                         if (smin_val < 0)
6324                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6325                 }
6326                 break;
6327         case BPF_AND:
6328         case BPF_OR:
6329         case BPF_XOR:
6330                 /* bitwise ops on pointers are troublesome, prohibit. */
6331                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6332                         dst, bpf_alu_string[opcode >> 4]);
6333                 return -EACCES;
6334         default:
6335                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6336                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6337                         dst, bpf_alu_string[opcode >> 4]);
6338                 return -EACCES;
6339         }
6340
6341         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6342                 return -EINVAL;
6343
6344         __update_reg_bounds(dst_reg);
6345         __reg_deduce_bounds(dst_reg);
6346         __reg_bound_offset(dst_reg);
6347
6348         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6349                 return -EACCES;
6350         if (sanitize_needed(opcode)) {
6351                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6352                                        &tmp_aux, true);
6353                 if (ret < 0)
6354                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
6355         }
6356
6357         return 0;
6358 }
6359
6360 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6361                                  struct bpf_reg_state *src_reg)
6362 {
6363         s32 smin_val = src_reg->s32_min_value;
6364         s32 smax_val = src_reg->s32_max_value;
6365         u32 umin_val = src_reg->u32_min_value;
6366         u32 umax_val = src_reg->u32_max_value;
6367
6368         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6369             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6370                 dst_reg->s32_min_value = S32_MIN;
6371                 dst_reg->s32_max_value = S32_MAX;
6372         } else {
6373                 dst_reg->s32_min_value += smin_val;
6374                 dst_reg->s32_max_value += smax_val;
6375         }
6376         if (dst_reg->u32_min_value + umin_val < umin_val ||
6377             dst_reg->u32_max_value + umax_val < umax_val) {
6378                 dst_reg->u32_min_value = 0;
6379                 dst_reg->u32_max_value = U32_MAX;
6380         } else {
6381                 dst_reg->u32_min_value += umin_val;
6382                 dst_reg->u32_max_value += umax_val;
6383         }
6384 }
6385
6386 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6387                                struct bpf_reg_state *src_reg)
6388 {
6389         s64 smin_val = src_reg->smin_value;
6390         s64 smax_val = src_reg->smax_value;
6391         u64 umin_val = src_reg->umin_value;
6392         u64 umax_val = src_reg->umax_value;
6393
6394         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6395             signed_add_overflows(dst_reg->smax_value, smax_val)) {
6396                 dst_reg->smin_value = S64_MIN;
6397                 dst_reg->smax_value = S64_MAX;
6398         } else {
6399                 dst_reg->smin_value += smin_val;
6400                 dst_reg->smax_value += smax_val;
6401         }
6402         if (dst_reg->umin_value + umin_val < umin_val ||
6403             dst_reg->umax_value + umax_val < umax_val) {
6404                 dst_reg->umin_value = 0;
6405                 dst_reg->umax_value = U64_MAX;
6406         } else {
6407                 dst_reg->umin_value += umin_val;
6408                 dst_reg->umax_value += umax_val;
6409         }
6410 }
6411
6412 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6413                                  struct bpf_reg_state *src_reg)
6414 {
6415         s32 smin_val = src_reg->s32_min_value;
6416         s32 smax_val = src_reg->s32_max_value;
6417         u32 umin_val = src_reg->u32_min_value;
6418         u32 umax_val = src_reg->u32_max_value;
6419
6420         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6421             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6422                 /* Overflow possible, we know nothing */
6423                 dst_reg->s32_min_value = S32_MIN;
6424                 dst_reg->s32_max_value = S32_MAX;
6425         } else {
6426                 dst_reg->s32_min_value -= smax_val;
6427                 dst_reg->s32_max_value -= smin_val;
6428         }
6429         if (dst_reg->u32_min_value < umax_val) {
6430                 /* Overflow possible, we know nothing */
6431                 dst_reg->u32_min_value = 0;
6432                 dst_reg->u32_max_value = U32_MAX;
6433         } else {
6434                 /* Cannot overflow (as long as bounds are consistent) */
6435                 dst_reg->u32_min_value -= umax_val;
6436                 dst_reg->u32_max_value -= umin_val;
6437         }
6438 }
6439
6440 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6441                                struct bpf_reg_state *src_reg)
6442 {
6443         s64 smin_val = src_reg->smin_value;
6444         s64 smax_val = src_reg->smax_value;
6445         u64 umin_val = src_reg->umin_value;
6446         u64 umax_val = src_reg->umax_value;
6447
6448         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6449             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6450                 /* Overflow possible, we know nothing */
6451                 dst_reg->smin_value = S64_MIN;
6452                 dst_reg->smax_value = S64_MAX;
6453         } else {
6454                 dst_reg->smin_value -= smax_val;
6455                 dst_reg->smax_value -= smin_val;
6456         }
6457         if (dst_reg->umin_value < umax_val) {
6458                 /* Overflow possible, we know nothing */
6459                 dst_reg->umin_value = 0;
6460                 dst_reg->umax_value = U64_MAX;
6461         } else {
6462                 /* Cannot overflow (as long as bounds are consistent) */
6463                 dst_reg->umin_value -= umax_val;
6464                 dst_reg->umax_value -= umin_val;
6465         }
6466 }
6467
6468 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6469                                  struct bpf_reg_state *src_reg)
6470 {
6471         s32 smin_val = src_reg->s32_min_value;
6472         u32 umin_val = src_reg->u32_min_value;
6473         u32 umax_val = src_reg->u32_max_value;
6474
6475         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6476                 /* Ain't nobody got time to multiply that sign */
6477                 __mark_reg32_unbounded(dst_reg);
6478                 return;
6479         }
6480         /* Both values are positive, so we can work with unsigned and
6481          * copy the result to signed (unless it exceeds S32_MAX).
6482          */
6483         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6484                 /* Potential overflow, we know nothing */
6485                 __mark_reg32_unbounded(dst_reg);
6486                 return;
6487         }
6488         dst_reg->u32_min_value *= umin_val;
6489         dst_reg->u32_max_value *= umax_val;
6490         if (dst_reg->u32_max_value > S32_MAX) {
6491                 /* Overflow possible, we know nothing */
6492                 dst_reg->s32_min_value = S32_MIN;
6493                 dst_reg->s32_max_value = S32_MAX;
6494         } else {
6495                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6496                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6497         }
6498 }
6499
6500 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6501                                struct bpf_reg_state *src_reg)
6502 {
6503         s64 smin_val = src_reg->smin_value;
6504         u64 umin_val = src_reg->umin_value;
6505         u64 umax_val = src_reg->umax_value;
6506
6507         if (smin_val < 0 || dst_reg->smin_value < 0) {
6508                 /* Ain't nobody got time to multiply that sign */
6509                 __mark_reg64_unbounded(dst_reg);
6510                 return;
6511         }
6512         /* Both values are positive, so we can work with unsigned and
6513          * copy the result to signed (unless it exceeds S64_MAX).
6514          */
6515         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6516                 /* Potential overflow, we know nothing */
6517                 __mark_reg64_unbounded(dst_reg);
6518                 return;
6519         }
6520         dst_reg->umin_value *= umin_val;
6521         dst_reg->umax_value *= umax_val;
6522         if (dst_reg->umax_value > S64_MAX) {
6523                 /* Overflow possible, we know nothing */
6524                 dst_reg->smin_value = S64_MIN;
6525                 dst_reg->smax_value = S64_MAX;
6526         } else {
6527                 dst_reg->smin_value = dst_reg->umin_value;
6528                 dst_reg->smax_value = dst_reg->umax_value;
6529         }
6530 }
6531
6532 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6533                                  struct bpf_reg_state *src_reg)
6534 {
6535         bool src_known = tnum_subreg_is_const(src_reg->var_off);
6536         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6537         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6538         s32 smin_val = src_reg->s32_min_value;
6539         u32 umax_val = src_reg->u32_max_value;
6540
6541         /* Assuming scalar64_min_max_and will be called so its safe
6542          * to skip updating register for known 32-bit case.
6543          */
6544         if (src_known && dst_known)
6545                 return;
6546
6547         /* We get our minimum from the var_off, since that's inherently
6548          * bitwise.  Our maximum is the minimum of the operands' maxima.
6549          */
6550         dst_reg->u32_min_value = var32_off.value;
6551         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6552         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6553                 /* Lose signed bounds when ANDing negative numbers,
6554                  * ain't nobody got time for that.
6555                  */
6556                 dst_reg->s32_min_value = S32_MIN;
6557                 dst_reg->s32_max_value = S32_MAX;
6558         } else {
6559                 /* ANDing two positives gives a positive, so safe to
6560                  * cast result into s64.
6561                  */
6562                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6563                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6564         }
6565
6566 }
6567
6568 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6569                                struct bpf_reg_state *src_reg)
6570 {
6571         bool src_known = tnum_is_const(src_reg->var_off);
6572         bool dst_known = tnum_is_const(dst_reg->var_off);
6573         s64 smin_val = src_reg->smin_value;
6574         u64 umax_val = src_reg->umax_value;
6575
6576         if (src_known && dst_known) {
6577                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6578                 return;
6579         }
6580
6581         /* We get our minimum from the var_off, since that's inherently
6582          * bitwise.  Our maximum is the minimum of the operands' maxima.
6583          */
6584         dst_reg->umin_value = dst_reg->var_off.value;
6585         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6586         if (dst_reg->smin_value < 0 || smin_val < 0) {
6587                 /* Lose signed bounds when ANDing negative numbers,
6588                  * ain't nobody got time for that.
6589                  */
6590                 dst_reg->smin_value = S64_MIN;
6591                 dst_reg->smax_value = S64_MAX;
6592         } else {
6593                 /* ANDing two positives gives a positive, so safe to
6594                  * cast result into s64.
6595                  */
6596                 dst_reg->smin_value = dst_reg->umin_value;
6597                 dst_reg->smax_value = dst_reg->umax_value;
6598         }
6599         /* We may learn something more from the var_off */
6600         __update_reg_bounds(dst_reg);
6601 }
6602
6603 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6604                                 struct bpf_reg_state *src_reg)
6605 {
6606         bool src_known = tnum_subreg_is_const(src_reg->var_off);
6607         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6608         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6609         s32 smin_val = src_reg->s32_min_value;
6610         u32 umin_val = src_reg->u32_min_value;
6611
6612         /* Assuming scalar64_min_max_or will be called so it is safe
6613          * to skip updating register for known case.
6614          */
6615         if (src_known && dst_known)
6616                 return;
6617
6618         /* We get our maximum from the var_off, and our minimum is the
6619          * maximum of the operands' minima
6620          */
6621         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6622         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6623         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6624                 /* Lose signed bounds when ORing negative numbers,
6625                  * ain't nobody got time for that.
6626                  */
6627                 dst_reg->s32_min_value = S32_MIN;
6628                 dst_reg->s32_max_value = S32_MAX;
6629         } else {
6630                 /* ORing two positives gives a positive, so safe to
6631                  * cast result into s64.
6632                  */
6633                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6634                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6635         }
6636 }
6637
6638 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6639                               struct bpf_reg_state *src_reg)
6640 {
6641         bool src_known = tnum_is_const(src_reg->var_off);
6642         bool dst_known = tnum_is_const(dst_reg->var_off);
6643         s64 smin_val = src_reg->smin_value;
6644         u64 umin_val = src_reg->umin_value;
6645
6646         if (src_known && dst_known) {
6647                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6648                 return;
6649         }
6650
6651         /* We get our maximum from the var_off, and our minimum is the
6652          * maximum of the operands' minima
6653          */
6654         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6655         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6656         if (dst_reg->smin_value < 0 || smin_val < 0) {
6657                 /* Lose signed bounds when ORing negative numbers,
6658                  * ain't nobody got time for that.
6659                  */
6660                 dst_reg->smin_value = S64_MIN;
6661                 dst_reg->smax_value = S64_MAX;
6662         } else {
6663                 /* ORing two positives gives a positive, so safe to
6664                  * cast result into s64.
6665                  */
6666                 dst_reg->smin_value = dst_reg->umin_value;
6667                 dst_reg->smax_value = dst_reg->umax_value;
6668         }
6669         /* We may learn something more from the var_off */
6670         __update_reg_bounds(dst_reg);
6671 }
6672
6673 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6674                                  struct bpf_reg_state *src_reg)
6675 {
6676         bool src_known = tnum_subreg_is_const(src_reg->var_off);
6677         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6678         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6679         s32 smin_val = src_reg->s32_min_value;
6680
6681         /* Assuming scalar64_min_max_xor will be called so it is safe
6682          * to skip updating register for known case.
6683          */
6684         if (src_known && dst_known)
6685                 return;
6686
6687         /* We get both minimum and maximum from the var32_off. */
6688         dst_reg->u32_min_value = var32_off.value;
6689         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6690
6691         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6692                 /* XORing two positive sign numbers gives a positive,
6693                  * so safe to cast u32 result into s32.
6694                  */
6695                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6696                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6697         } else {
6698                 dst_reg->s32_min_value = S32_MIN;
6699                 dst_reg->s32_max_value = S32_MAX;
6700         }
6701 }
6702
6703 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6704                                struct bpf_reg_state *src_reg)
6705 {
6706         bool src_known = tnum_is_const(src_reg->var_off);
6707         bool dst_known = tnum_is_const(dst_reg->var_off);
6708         s64 smin_val = src_reg->smin_value;
6709
6710         if (src_known && dst_known) {
6711                 /* dst_reg->var_off.value has been updated earlier */
6712                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6713                 return;
6714         }
6715
6716         /* We get both minimum and maximum from the var_off. */
6717         dst_reg->umin_value = dst_reg->var_off.value;
6718         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6719
6720         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6721                 /* XORing two positive sign numbers gives a positive,
6722                  * so safe to cast u64 result into s64.
6723                  */
6724                 dst_reg->smin_value = dst_reg->umin_value;
6725                 dst_reg->smax_value = dst_reg->umax_value;
6726         } else {
6727                 dst_reg->smin_value = S64_MIN;
6728                 dst_reg->smax_value = S64_MAX;
6729         }
6730
6731         __update_reg_bounds(dst_reg);
6732 }
6733
6734 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6735                                    u64 umin_val, u64 umax_val)
6736 {
6737         /* We lose all sign bit information (except what we can pick
6738          * up from var_off)
6739          */
6740         dst_reg->s32_min_value = S32_MIN;
6741         dst_reg->s32_max_value = S32_MAX;
6742         /* If we might shift our top bit out, then we know nothing */
6743         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6744                 dst_reg->u32_min_value = 0;
6745                 dst_reg->u32_max_value = U32_MAX;
6746         } else {
6747                 dst_reg->u32_min_value <<= umin_val;
6748                 dst_reg->u32_max_value <<= umax_val;
6749         }
6750 }
6751
6752 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6753                                  struct bpf_reg_state *src_reg)
6754 {
6755         u32 umax_val = src_reg->u32_max_value;
6756         u32 umin_val = src_reg->u32_min_value;
6757         /* u32 alu operation will zext upper bits */
6758         struct tnum subreg = tnum_subreg(dst_reg->var_off);
6759
6760         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6761         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6762         /* Not required but being careful mark reg64 bounds as unknown so
6763          * that we are forced to pick them up from tnum and zext later and
6764          * if some path skips this step we are still safe.
6765          */
6766         __mark_reg64_unbounded(dst_reg);
6767         __update_reg32_bounds(dst_reg);
6768 }
6769
6770 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6771                                    u64 umin_val, u64 umax_val)
6772 {
6773         /* Special case <<32 because it is a common compiler pattern to sign
6774          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6775          * positive we know this shift will also be positive so we can track
6776          * bounds correctly. Otherwise we lose all sign bit information except
6777          * what we can pick up from var_off. Perhaps we can generalize this
6778          * later to shifts of any length.
6779          */
6780         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6781                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6782         else
6783                 dst_reg->smax_value = S64_MAX;
6784
6785         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6786                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6787         else
6788                 dst_reg->smin_value = S64_MIN;
6789
6790         /* If we might shift our top bit out, then we know nothing */
6791         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6792                 dst_reg->umin_value = 0;
6793                 dst_reg->umax_value = U64_MAX;
6794         } else {
6795                 dst_reg->umin_value <<= umin_val;
6796                 dst_reg->umax_value <<= umax_val;
6797         }
6798 }
6799
6800 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6801                                struct bpf_reg_state *src_reg)
6802 {
6803         u64 umax_val = src_reg->umax_value;
6804         u64 umin_val = src_reg->umin_value;
6805
6806         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6807         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6808         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6809
6810         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6811         /* We may learn something more from the var_off */
6812         __update_reg_bounds(dst_reg);
6813 }
6814
6815 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6816                                  struct bpf_reg_state *src_reg)
6817 {
6818         struct tnum subreg = tnum_subreg(dst_reg->var_off);
6819         u32 umax_val = src_reg->u32_max_value;
6820         u32 umin_val = src_reg->u32_min_value;
6821
6822         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6823          * be negative, then either:
6824          * 1) src_reg might be zero, so the sign bit of the result is
6825          *    unknown, so we lose our signed bounds
6826          * 2) it's known negative, thus the unsigned bounds capture the
6827          *    signed bounds
6828          * 3) the signed bounds cross zero, so they tell us nothing
6829          *    about the result
6830          * If the value in dst_reg is known nonnegative, then again the
6831          * unsigned bounds capture the signed bounds.
6832          * Thus, in all cases it suffices to blow away our signed bounds
6833          * and rely on inferring new ones from the unsigned bounds and
6834          * var_off of the result.
6835          */
6836         dst_reg->s32_min_value = S32_MIN;
6837         dst_reg->s32_max_value = S32_MAX;
6838
6839         dst_reg->var_off = tnum_rshift(subreg, umin_val);
6840         dst_reg->u32_min_value >>= umax_val;
6841         dst_reg->u32_max_value >>= umin_val;
6842
6843         __mark_reg64_unbounded(dst_reg);
6844         __update_reg32_bounds(dst_reg);
6845 }
6846
6847 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6848                                struct bpf_reg_state *src_reg)
6849 {
6850         u64 umax_val = src_reg->umax_value;
6851         u64 umin_val = src_reg->umin_value;
6852
6853         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6854          * be negative, then either:
6855          * 1) src_reg might be zero, so the sign bit of the result is
6856          *    unknown, so we lose our signed bounds
6857          * 2) it's known negative, thus the unsigned bounds capture the
6858          *    signed bounds
6859          * 3) the signed bounds cross zero, so they tell us nothing
6860          *    about the result
6861          * If the value in dst_reg is known nonnegative, then again the
6862          * unsigned bounds capture the signed bounds.
6863          * Thus, in all cases it suffices to blow away our signed bounds
6864          * and rely on inferring new ones from the unsigned bounds and
6865          * var_off of the result.
6866          */
6867         dst_reg->smin_value = S64_MIN;
6868         dst_reg->smax_value = S64_MAX;
6869         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6870         dst_reg->umin_value >>= umax_val;
6871         dst_reg->umax_value >>= umin_val;
6872
6873         /* Its not easy to operate on alu32 bounds here because it depends
6874          * on bits being shifted in. Take easy way out and mark unbounded
6875          * so we can recalculate later from tnum.
6876          */
6877         __mark_reg32_unbounded(dst_reg);
6878         __update_reg_bounds(dst_reg);
6879 }
6880
6881 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6882                                   struct bpf_reg_state *src_reg)
6883 {
6884         u64 umin_val = src_reg->u32_min_value;
6885
6886         /* Upon reaching here, src_known is true and
6887          * umax_val is equal to umin_val.
6888          */
6889         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6890         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6891
6892         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6893
6894         /* blow away the dst_reg umin_value/umax_value and rely on
6895          * dst_reg var_off to refine the result.
6896          */
6897         dst_reg->u32_min_value = 0;
6898         dst_reg->u32_max_value = U32_MAX;
6899
6900         __mark_reg64_unbounded(dst_reg);
6901         __update_reg32_bounds(dst_reg);
6902 }
6903
6904 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6905                                 struct bpf_reg_state *src_reg)
6906 {
6907         u64 umin_val = src_reg->umin_value;
6908
6909         /* Upon reaching here, src_known is true and umax_val is equal
6910          * to umin_val.
6911          */
6912         dst_reg->smin_value >>= umin_val;
6913         dst_reg->smax_value >>= umin_val;
6914
6915         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
6916
6917         /* blow away the dst_reg umin_value/umax_value and rely on
6918          * dst_reg var_off to refine the result.
6919          */
6920         dst_reg->umin_value = 0;
6921         dst_reg->umax_value = U64_MAX;
6922
6923         /* Its not easy to operate on alu32 bounds here because it depends
6924          * on bits being shifted in from upper 32-bits. Take easy way out
6925          * and mark unbounded so we can recalculate later from tnum.
6926          */
6927         __mark_reg32_unbounded(dst_reg);
6928         __update_reg_bounds(dst_reg);
6929 }
6930
6931 /* WARNING: This function does calculations on 64-bit values, but the actual
6932  * execution may occur on 32-bit values. Therefore, things like bitshifts
6933  * need extra checks in the 32-bit case.
6934  */
6935 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6936                                       struct bpf_insn *insn,
6937                                       struct bpf_reg_state *dst_reg,
6938                                       struct bpf_reg_state src_reg)
6939 {
6940         struct bpf_reg_state *regs = cur_regs(env);
6941         u8 opcode = BPF_OP(insn->code);
6942         bool src_known;
6943         s64 smin_val, smax_val;
6944         u64 umin_val, umax_val;
6945         s32 s32_min_val, s32_max_val;
6946         u32 u32_min_val, u32_max_val;
6947         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
6948         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
6949         int ret;
6950
6951         smin_val = src_reg.smin_value;
6952         smax_val = src_reg.smax_value;
6953         umin_val = src_reg.umin_value;
6954         umax_val = src_reg.umax_value;
6955
6956         s32_min_val = src_reg.s32_min_value;
6957         s32_max_val = src_reg.s32_max_value;
6958         u32_min_val = src_reg.u32_min_value;
6959         u32_max_val = src_reg.u32_max_value;
6960
6961         if (alu32) {
6962                 src_known = tnum_subreg_is_const(src_reg.var_off);
6963                 if ((src_known &&
6964                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6965                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6966                         /* Taint dst register if offset had invalid bounds
6967                          * derived from e.g. dead branches.
6968                          */
6969                         __mark_reg_unknown(env, dst_reg);
6970                         return 0;
6971                 }
6972         } else {
6973                 src_known = tnum_is_const(src_reg.var_off);
6974                 if ((src_known &&
6975                      (smin_val != smax_val || umin_val != umax_val)) ||
6976                     smin_val > smax_val || umin_val > umax_val) {
6977                         /* Taint dst register if offset had invalid bounds
6978                          * derived from e.g. dead branches.
6979                          */
6980                         __mark_reg_unknown(env, dst_reg);
6981                         return 0;
6982                 }
6983         }
6984
6985         if (!src_known &&
6986             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
6987                 __mark_reg_unknown(env, dst_reg);
6988                 return 0;
6989         }
6990
6991         if (sanitize_needed(opcode)) {
6992                 ret = sanitize_val_alu(env, insn);
6993                 if (ret < 0)
6994                         return sanitize_err(env, insn, ret, NULL, NULL);
6995         }
6996
6997         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6998          * There are two classes of instructions: The first class we track both
6999          * alu32 and alu64 sign/unsigned bounds independently this provides the
7000          * greatest amount of precision when alu operations are mixed with jmp32
7001          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7002          * and BPF_OR. This is possible because these ops have fairly easy to
7003          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7004          * See alu32 verifier tests for examples. The second class of
7005          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7006          * with regards to tracking sign/unsigned bounds because the bits may
7007          * cross subreg boundaries in the alu64 case. When this happens we mark
7008          * the reg unbounded in the subreg bound space and use the resulting
7009          * tnum to calculate an approximation of the sign/unsigned bounds.
7010          */
7011         switch (opcode) {
7012         case BPF_ADD:
7013                 scalar32_min_max_add(dst_reg, &src_reg);
7014                 scalar_min_max_add(dst_reg, &src_reg);
7015                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7016                 break;
7017         case BPF_SUB:
7018                 scalar32_min_max_sub(dst_reg, &src_reg);
7019                 scalar_min_max_sub(dst_reg, &src_reg);
7020                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7021                 break;
7022         case BPF_MUL:
7023                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7024                 scalar32_min_max_mul(dst_reg, &src_reg);
7025                 scalar_min_max_mul(dst_reg, &src_reg);
7026                 break;
7027         case BPF_AND:
7028                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7029                 scalar32_min_max_and(dst_reg, &src_reg);
7030                 scalar_min_max_and(dst_reg, &src_reg);
7031                 break;
7032         case BPF_OR:
7033                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7034                 scalar32_min_max_or(dst_reg, &src_reg);
7035                 scalar_min_max_or(dst_reg, &src_reg);
7036                 break;
7037         case BPF_XOR:
7038                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7039                 scalar32_min_max_xor(dst_reg, &src_reg);
7040                 scalar_min_max_xor(dst_reg, &src_reg);
7041                 break;
7042         case BPF_LSH:
7043                 if (umax_val >= insn_bitness) {
7044                         /* Shifts greater than 31 or 63 are undefined.
7045                          * This includes shifts by a negative number.
7046                          */
7047                         mark_reg_unknown(env, regs, insn->dst_reg);
7048                         break;
7049                 }
7050                 if (alu32)
7051                         scalar32_min_max_lsh(dst_reg, &src_reg);
7052                 else
7053                         scalar_min_max_lsh(dst_reg, &src_reg);
7054                 break;
7055         case BPF_RSH:
7056                 if (umax_val >= insn_bitness) {
7057                         /* Shifts greater than 31 or 63 are undefined.
7058                          * This includes shifts by a negative number.
7059                          */
7060                         mark_reg_unknown(env, regs, insn->dst_reg);
7061                         break;
7062                 }
7063                 if (alu32)
7064                         scalar32_min_max_rsh(dst_reg, &src_reg);
7065                 else
7066                         scalar_min_max_rsh(dst_reg, &src_reg);
7067                 break;
7068         case BPF_ARSH:
7069                 if (umax_val >= insn_bitness) {
7070                         /* Shifts greater than 31 or 63 are undefined.
7071                          * This includes shifts by a negative number.
7072                          */
7073                         mark_reg_unknown(env, regs, insn->dst_reg);
7074                         break;
7075                 }
7076                 if (alu32)
7077                         scalar32_min_max_arsh(dst_reg, &src_reg);
7078                 else
7079                         scalar_min_max_arsh(dst_reg, &src_reg);
7080                 break;
7081         default:
7082                 mark_reg_unknown(env, regs, insn->dst_reg);
7083                 break;
7084         }
7085
7086         /* ALU32 ops are zero extended into 64bit register */
7087         if (alu32)
7088                 zext_32_to_64(dst_reg);
7089
7090         __update_reg_bounds(dst_reg);
7091         __reg_deduce_bounds(dst_reg);
7092         __reg_bound_offset(dst_reg);
7093         return 0;
7094 }
7095
7096 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7097  * and var_off.
7098  */
7099 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7100                                    struct bpf_insn *insn)
7101 {
7102         struct bpf_verifier_state *vstate = env->cur_state;
7103         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7104         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7105         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7106         u8 opcode = BPF_OP(insn->code);
7107         int err;
7108
7109         dst_reg = &regs[insn->dst_reg];
7110         src_reg = NULL;
7111         if (dst_reg->type != SCALAR_VALUE)
7112                 ptr_reg = dst_reg;
7113         else
7114                 /* Make sure ID is cleared otherwise dst_reg min/max could be
7115                  * incorrectly propagated into other registers by find_equal_scalars()
7116                  */
7117                 dst_reg->id = 0;
7118         if (BPF_SRC(insn->code) == BPF_X) {
7119                 src_reg = &regs[insn->src_reg];
7120                 if (src_reg->type != SCALAR_VALUE) {
7121                         if (dst_reg->type != SCALAR_VALUE) {
7122                                 /* Combining two pointers by any ALU op yields
7123                                  * an arbitrary scalar. Disallow all math except
7124                                  * pointer subtraction
7125                                  */
7126                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7127                                         mark_reg_unknown(env, regs, insn->dst_reg);
7128                                         return 0;
7129                                 }
7130                                 verbose(env, "R%d pointer %s pointer prohibited\n",
7131                                         insn->dst_reg,
7132                                         bpf_alu_string[opcode >> 4]);
7133                                 return -EACCES;
7134                         } else {
7135                                 /* scalar += pointer
7136                                  * This is legal, but we have to reverse our
7137                                  * src/dest handling in computing the range
7138                                  */
7139                                 err = mark_chain_precision(env, insn->dst_reg);
7140                                 if (err)
7141                                         return err;
7142                                 return adjust_ptr_min_max_vals(env, insn,
7143                                                                src_reg, dst_reg);
7144                         }
7145                 } else if (ptr_reg) {
7146                         /* pointer += scalar */
7147                         err = mark_chain_precision(env, insn->src_reg);
7148                         if (err)
7149                                 return err;
7150                         return adjust_ptr_min_max_vals(env, insn,
7151                                                        dst_reg, src_reg);
7152                 }
7153         } else {
7154                 /* Pretend the src is a reg with a known value, since we only
7155                  * need to be able to read from this state.
7156                  */
7157                 off_reg.type = SCALAR_VALUE;
7158                 __mark_reg_known(&off_reg, insn->imm);
7159                 src_reg = &off_reg;
7160                 if (ptr_reg) /* pointer += K */
7161                         return adjust_ptr_min_max_vals(env, insn,
7162                                                        ptr_reg, src_reg);
7163         }
7164
7165         /* Got here implies adding two SCALAR_VALUEs */
7166         if (WARN_ON_ONCE(ptr_reg)) {
7167                 print_verifier_state(env, state);
7168                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7169                 return -EINVAL;
7170         }
7171         if (WARN_ON(!src_reg)) {
7172                 print_verifier_state(env, state);
7173                 verbose(env, "verifier internal error: no src_reg\n");
7174                 return -EINVAL;
7175         }
7176         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7177 }
7178
7179 /* check validity of 32-bit and 64-bit arithmetic operations */
7180 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7181 {
7182         struct bpf_reg_state *regs = cur_regs(env);
7183         u8 opcode = BPF_OP(insn->code);
7184         int err;
7185
7186         if (opcode == BPF_END || opcode == BPF_NEG) {
7187                 if (opcode == BPF_NEG) {
7188                         if (BPF_SRC(insn->code) != 0 ||
7189                             insn->src_reg != BPF_REG_0 ||
7190                             insn->off != 0 || insn->imm != 0) {
7191                                 verbose(env, "BPF_NEG uses reserved fields\n");
7192                                 return -EINVAL;
7193                         }
7194                 } else {
7195                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7196                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7197                             BPF_CLASS(insn->code) == BPF_ALU64) {
7198                                 verbose(env, "BPF_END uses reserved fields\n");
7199                                 return -EINVAL;
7200                         }
7201                 }
7202
7203                 /* check src operand */
7204                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7205                 if (err)
7206                         return err;
7207
7208                 if (is_pointer_value(env, insn->dst_reg)) {
7209                         verbose(env, "R%d pointer arithmetic prohibited\n",
7210                                 insn->dst_reg);
7211                         return -EACCES;
7212                 }
7213
7214                 /* check dest operand */
7215                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7216                 if (err)
7217                         return err;
7218
7219         } else if (opcode == BPF_MOV) {
7220
7221                 if (BPF_SRC(insn->code) == BPF_X) {
7222                         if (insn->imm != 0 || insn->off != 0) {
7223                                 verbose(env, "BPF_MOV uses reserved fields\n");
7224                                 return -EINVAL;
7225                         }
7226
7227                         /* check src operand */
7228                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
7229                         if (err)
7230                                 return err;
7231                 } else {
7232                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7233                                 verbose(env, "BPF_MOV uses reserved fields\n");
7234                                 return -EINVAL;
7235                         }
7236                 }
7237
7238                 /* check dest operand, mark as required later */
7239                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7240                 if (err)
7241                         return err;
7242
7243                 if (BPF_SRC(insn->code) == BPF_X) {
7244                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
7245                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7246
7247                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
7248                                 /* case: R1 = R2
7249                                  * copy register state to dest reg
7250                                  */
7251                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7252                                         /* Assign src and dst registers the same ID
7253                                          * that will be used by find_equal_scalars()
7254                                          * to propagate min/max range.
7255                                          */
7256                                         src_reg->id = ++env->id_gen;
7257                                 *dst_reg = *src_reg;
7258                                 dst_reg->live |= REG_LIVE_WRITTEN;
7259                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
7260                         } else {
7261                                 /* R1 = (u32) R2 */
7262                                 if (is_pointer_value(env, insn->src_reg)) {
7263                                         verbose(env,
7264                                                 "R%d partial copy of pointer\n",
7265                                                 insn->src_reg);
7266                                         return -EACCES;
7267                                 } else if (src_reg->type == SCALAR_VALUE) {
7268                                         *dst_reg = *src_reg;
7269                                         /* Make sure ID is cleared otherwise
7270                                          * dst_reg min/max could be incorrectly
7271                                          * propagated into src_reg by find_equal_scalars()
7272                                          */
7273                                         dst_reg->id = 0;
7274                                         dst_reg->live |= REG_LIVE_WRITTEN;
7275                                         dst_reg->subreg_def = env->insn_idx + 1;
7276                                 } else {
7277                                         mark_reg_unknown(env, regs,
7278                                                          insn->dst_reg);
7279                                 }
7280                                 zext_32_to_64(dst_reg);
7281                         }
7282                 } else {
7283                         /* case: R = imm
7284                          * remember the value we stored into this reg
7285                          */
7286                         /* clear any state __mark_reg_known doesn't set */
7287                         mark_reg_unknown(env, regs, insn->dst_reg);
7288                         regs[insn->dst_reg].type = SCALAR_VALUE;
7289                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
7290                                 __mark_reg_known(regs + insn->dst_reg,
7291                                                  insn->imm);
7292                         } else {
7293                                 __mark_reg_known(regs + insn->dst_reg,
7294                                                  (u32)insn->imm);
7295                         }
7296                 }
7297
7298         } else if (opcode > BPF_END) {
7299                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7300                 return -EINVAL;
7301
7302         } else {        /* all other ALU ops: and, sub, xor, add, ... */
7303
7304                 if (BPF_SRC(insn->code) == BPF_X) {
7305                         if (insn->imm != 0 || insn->off != 0) {
7306                                 verbose(env, "BPF_ALU uses reserved fields\n");
7307                                 return -EINVAL;
7308                         }
7309                         /* check src1 operand */
7310                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
7311                         if (err)
7312                                 return err;
7313                 } else {
7314                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7315                                 verbose(env, "BPF_ALU uses reserved fields\n");
7316                                 return -EINVAL;
7317                         }
7318                 }
7319
7320                 /* check src2 operand */
7321                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7322                 if (err)
7323                         return err;
7324
7325                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7326                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7327                         verbose(env, "div by zero\n");
7328                         return -EINVAL;
7329                 }
7330
7331                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7332                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7333                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7334
7335                         if (insn->imm < 0 || insn->imm >= size) {
7336                                 verbose(env, "invalid shift %d\n", insn->imm);
7337                                 return -EINVAL;
7338                         }
7339                 }
7340
7341                 /* check dest operand */
7342                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7343                 if (err)
7344                         return err;
7345
7346                 return adjust_reg_min_max_vals(env, insn);
7347         }
7348
7349         return 0;
7350 }
7351
7352 static void __find_good_pkt_pointers(struct bpf_func_state *state,
7353                                      struct bpf_reg_state *dst_reg,
7354                                      enum bpf_reg_type type, int new_range)
7355 {
7356         struct bpf_reg_state *reg;
7357         int i;
7358
7359         for (i = 0; i < MAX_BPF_REG; i++) {
7360                 reg = &state->regs[i];
7361                 if (reg->type == type && reg->id == dst_reg->id)
7362                         /* keep the maximum range already checked */
7363                         reg->range = max(reg->range, new_range);
7364         }
7365
7366         bpf_for_each_spilled_reg(i, state, reg) {
7367                 if (!reg)
7368                         continue;
7369                 if (reg->type == type && reg->id == dst_reg->id)
7370                         reg->range = max(reg->range, new_range);
7371         }
7372 }
7373
7374 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7375                                    struct bpf_reg_state *dst_reg,
7376                                    enum bpf_reg_type type,
7377                                    bool range_right_open)
7378 {
7379         int new_range, i;
7380
7381         if (dst_reg->off < 0 ||
7382             (dst_reg->off == 0 && range_right_open))
7383                 /* This doesn't give us any range */
7384                 return;
7385
7386         if (dst_reg->umax_value > MAX_PACKET_OFF ||
7387             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7388                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
7389                  * than pkt_end, but that's because it's also less than pkt.
7390                  */
7391                 return;
7392
7393         new_range = dst_reg->off;
7394         if (range_right_open)
7395                 new_range--;
7396
7397         /* Examples for register markings:
7398          *
7399          * pkt_data in dst register:
7400          *
7401          *   r2 = r3;
7402          *   r2 += 8;
7403          *   if (r2 > pkt_end) goto <handle exception>
7404          *   <access okay>
7405          *
7406          *   r2 = r3;
7407          *   r2 += 8;
7408          *   if (r2 < pkt_end) goto <access okay>
7409          *   <handle exception>
7410          *
7411          *   Where:
7412          *     r2 == dst_reg, pkt_end == src_reg
7413          *     r2=pkt(id=n,off=8,r=0)
7414          *     r3=pkt(id=n,off=0,r=0)
7415          *
7416          * pkt_data in src register:
7417          *
7418          *   r2 = r3;
7419          *   r2 += 8;
7420          *   if (pkt_end >= r2) goto <access okay>
7421          *   <handle exception>
7422          *
7423          *   r2 = r3;
7424          *   r2 += 8;
7425          *   if (pkt_end <= r2) goto <handle exception>
7426          *   <access okay>
7427          *
7428          *   Where:
7429          *     pkt_end == dst_reg, r2 == src_reg
7430          *     r2=pkt(id=n,off=8,r=0)
7431          *     r3=pkt(id=n,off=0,r=0)
7432          *
7433          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7434          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7435          * and [r3, r3 + 8-1) respectively is safe to access depending on
7436          * the check.
7437          */
7438
7439         /* If our ids match, then we must have the same max_value.  And we
7440          * don't care about the other reg's fixed offset, since if it's too big
7441          * the range won't allow anything.
7442          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7443          */
7444         for (i = 0; i <= vstate->curframe; i++)
7445                 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7446                                          new_range);
7447 }
7448
7449 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7450 {
7451         struct tnum subreg = tnum_subreg(reg->var_off);
7452         s32 sval = (s32)val;
7453
7454         switch (opcode) {
7455         case BPF_JEQ:
7456                 if (tnum_is_const(subreg))
7457                         return !!tnum_equals_const(subreg, val);
7458                 break;
7459         case BPF_JNE:
7460                 if (tnum_is_const(subreg))
7461                         return !tnum_equals_const(subreg, val);
7462                 break;
7463         case BPF_JSET:
7464                 if ((~subreg.mask & subreg.value) & val)
7465                         return 1;
7466                 if (!((subreg.mask | subreg.value) & val))
7467                         return 0;
7468                 break;
7469         case BPF_JGT:
7470                 if (reg->u32_min_value > val)
7471                         return 1;
7472                 else if (reg->u32_max_value <= val)
7473                         return 0;
7474                 break;
7475         case BPF_JSGT:
7476                 if (reg->s32_min_value > sval)
7477                         return 1;
7478                 else if (reg->s32_max_value <= sval)
7479                         return 0;
7480                 break;
7481         case BPF_JLT:
7482                 if (reg->u32_max_value < val)
7483                         return 1;
7484                 else if (reg->u32_min_value >= val)
7485                         return 0;
7486                 break;
7487         case BPF_JSLT:
7488                 if (reg->s32_max_value < sval)
7489                         return 1;
7490                 else if (reg->s32_min_value >= sval)
7491                         return 0;
7492                 break;
7493         case BPF_JGE:
7494                 if (reg->u32_min_value >= val)
7495                         return 1;
7496                 else if (reg->u32_max_value < val)
7497                         return 0;
7498                 break;
7499         case BPF_JSGE:
7500                 if (reg->s32_min_value >= sval)
7501                         return 1;
7502                 else if (reg->s32_max_value < sval)
7503                         return 0;
7504                 break;
7505         case BPF_JLE:
7506                 if (reg->u32_max_value <= val)
7507                         return 1;
7508                 else if (reg->u32_min_value > val)
7509                         return 0;
7510                 break;
7511         case BPF_JSLE:
7512                 if (reg->s32_max_value <= sval)
7513                         return 1;
7514                 else if (reg->s32_min_value > sval)
7515                         return 0;
7516                 break;
7517         }
7518
7519         return -1;
7520 }
7521
7522
7523 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7524 {
7525         s64 sval = (s64)val;
7526
7527         switch (opcode) {
7528         case BPF_JEQ:
7529                 if (tnum_is_const(reg->var_off))
7530                         return !!tnum_equals_const(reg->var_off, val);
7531                 break;
7532         case BPF_JNE:
7533                 if (tnum_is_const(reg->var_off))
7534                         return !tnum_equals_const(reg->var_off, val);
7535                 break;
7536         case BPF_JSET:
7537                 if ((~reg->var_off.mask & reg->var_off.value) & val)
7538                         return 1;
7539                 if (!((reg->var_off.mask | reg->var_off.value) & val))
7540                         return 0;
7541                 break;
7542         case BPF_JGT:
7543                 if (reg->umin_value > val)
7544                         return 1;
7545                 else if (reg->umax_value <= val)
7546                         return 0;
7547                 break;
7548         case BPF_JSGT:
7549                 if (reg->smin_value > sval)
7550                         return 1;
7551                 else if (reg->smax_value <= sval)
7552                         return 0;
7553                 break;
7554         case BPF_JLT:
7555                 if (reg->umax_value < val)
7556                         return 1;
7557                 else if (reg->umin_value >= val)
7558                         return 0;
7559                 break;
7560         case BPF_JSLT:
7561                 if (reg->smax_value < sval)
7562                         return 1;
7563                 else if (reg->smin_value >= sval)
7564                         return 0;
7565                 break;
7566         case BPF_JGE:
7567                 if (reg->umin_value >= val)
7568                         return 1;
7569                 else if (reg->umax_value < val)
7570                         return 0;
7571                 break;
7572         case BPF_JSGE:
7573                 if (reg->smin_value >= sval)
7574                         return 1;
7575                 else if (reg->smax_value < sval)
7576                         return 0;
7577                 break;
7578         case BPF_JLE:
7579                 if (reg->umax_value <= val)
7580                         return 1;
7581                 else if (reg->umin_value > val)
7582                         return 0;
7583                 break;
7584         case BPF_JSLE:
7585                 if (reg->smax_value <= sval)
7586                         return 1;
7587                 else if (reg->smin_value > sval)
7588                         return 0;
7589                 break;
7590         }
7591
7592         return -1;
7593 }
7594
7595 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7596  * and return:
7597  *  1 - branch will be taken and "goto target" will be executed
7598  *  0 - branch will not be taken and fall-through to next insn
7599  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7600  *      range [0,10]
7601  */
7602 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7603                            bool is_jmp32)
7604 {
7605         if (__is_pointer_value(false, reg)) {
7606                 if (!reg_type_not_null(reg->type))
7607                         return -1;
7608
7609                 /* If pointer is valid tests against zero will fail so we can
7610                  * use this to direct branch taken.
7611                  */
7612                 if (val != 0)
7613                         return -1;
7614
7615                 switch (opcode) {
7616                 case BPF_JEQ:
7617                         return 0;
7618                 case BPF_JNE:
7619                         return 1;
7620                 default:
7621                         return -1;
7622                 }
7623         }
7624
7625         if (is_jmp32)
7626                 return is_branch32_taken(reg, val, opcode);
7627         return is_branch64_taken(reg, val, opcode);
7628 }
7629
7630 static int flip_opcode(u32 opcode)
7631 {
7632         /* How can we transform "a <op> b" into "b <op> a"? */
7633         static const u8 opcode_flip[16] = {
7634                 /* these stay the same */
7635                 [BPF_JEQ  >> 4] = BPF_JEQ,
7636                 [BPF_JNE  >> 4] = BPF_JNE,
7637                 [BPF_JSET >> 4] = BPF_JSET,
7638                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7639                 [BPF_JGE  >> 4] = BPF_JLE,
7640                 [BPF_JGT  >> 4] = BPF_JLT,
7641                 [BPF_JLE  >> 4] = BPF_JGE,
7642                 [BPF_JLT  >> 4] = BPF_JGT,
7643                 [BPF_JSGE >> 4] = BPF_JSLE,
7644                 [BPF_JSGT >> 4] = BPF_JSLT,
7645                 [BPF_JSLE >> 4] = BPF_JSGE,
7646                 [BPF_JSLT >> 4] = BPF_JSGT
7647         };
7648         return opcode_flip[opcode >> 4];
7649 }
7650
7651 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7652                                    struct bpf_reg_state *src_reg,
7653                                    u8 opcode)
7654 {
7655         struct bpf_reg_state *pkt;
7656
7657         if (src_reg->type == PTR_TO_PACKET_END) {
7658                 pkt = dst_reg;
7659         } else if (dst_reg->type == PTR_TO_PACKET_END) {
7660                 pkt = src_reg;
7661                 opcode = flip_opcode(opcode);
7662         } else {
7663                 return -1;
7664         }
7665
7666         if (pkt->range >= 0)
7667                 return -1;
7668
7669         switch (opcode) {
7670         case BPF_JLE:
7671                 /* pkt <= pkt_end */
7672                 fallthrough;
7673         case BPF_JGT:
7674                 /* pkt > pkt_end */
7675                 if (pkt->range == BEYOND_PKT_END)
7676                         /* pkt has at last one extra byte beyond pkt_end */
7677                         return opcode == BPF_JGT;
7678                 break;
7679         case BPF_JLT:
7680                 /* pkt < pkt_end */
7681                 fallthrough;
7682         case BPF_JGE:
7683                 /* pkt >= pkt_end */
7684                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7685                         return opcode == BPF_JGE;
7686                 break;
7687         }
7688         return -1;
7689 }
7690
7691 /* Adjusts the register min/max values in the case that the dst_reg is the
7692  * variable register that we are working on, and src_reg is a constant or we're
7693  * simply doing a BPF_K check.
7694  * In JEQ/JNE cases we also adjust the var_off values.
7695  */
7696 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7697                             struct bpf_reg_state *false_reg,
7698                             u64 val, u32 val32,
7699                             u8 opcode, bool is_jmp32)
7700 {
7701         struct tnum false_32off = tnum_subreg(false_reg->var_off);
7702         struct tnum false_64off = false_reg->var_off;
7703         struct tnum true_32off = tnum_subreg(true_reg->var_off);
7704         struct tnum true_64off = true_reg->var_off;
7705         s64 sval = (s64)val;
7706         s32 sval32 = (s32)val32;
7707
7708         /* If the dst_reg is a pointer, we can't learn anything about its
7709          * variable offset from the compare (unless src_reg were a pointer into
7710          * the same object, but we don't bother with that.
7711          * Since false_reg and true_reg have the same type by construction, we
7712          * only need to check one of them for pointerness.
7713          */
7714         if (__is_pointer_value(false, false_reg))
7715                 return;
7716
7717         switch (opcode) {
7718         case BPF_JEQ:
7719         case BPF_JNE:
7720         {
7721                 struct bpf_reg_state *reg =
7722                         opcode == BPF_JEQ ? true_reg : false_reg;
7723
7724                 /* JEQ/JNE comparison doesn't change the register equivalence.
7725                  * r1 = r2;
7726                  * if (r1 == 42) goto label;
7727                  * ...
7728                  * label: // here both r1 and r2 are known to be 42.
7729                  *
7730                  * Hence when marking register as known preserve it's ID.
7731                  */
7732                 if (is_jmp32)
7733                         __mark_reg32_known(reg, val32);
7734                 else
7735                         ___mark_reg_known(reg, val);
7736                 break;
7737         }
7738         case BPF_JSET:
7739                 if (is_jmp32) {
7740                         false_32off = tnum_and(false_32off, tnum_const(~val32));
7741                         if (is_power_of_2(val32))
7742                                 true_32off = tnum_or(true_32off,
7743                                                      tnum_const(val32));
7744                 } else {
7745                         false_64off = tnum_and(false_64off, tnum_const(~val));
7746                         if (is_power_of_2(val))
7747                                 true_64off = tnum_or(true_64off,
7748                                                      tnum_const(val));
7749                 }
7750                 break;
7751         case BPF_JGE:
7752         case BPF_JGT:
7753         {
7754                 if (is_jmp32) {
7755                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
7756                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7757
7758                         false_reg->u32_max_value = min(false_reg->u32_max_value,
7759                                                        false_umax);
7760                         true_reg->u32_min_value = max(true_reg->u32_min_value,
7761                                                       true_umin);
7762                 } else {
7763                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
7764                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7765
7766                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
7767                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
7768                 }
7769                 break;
7770         }
7771         case BPF_JSGE:
7772         case BPF_JSGT:
7773         {
7774                 if (is_jmp32) {
7775                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
7776                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7777
7778                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7779                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7780                 } else {
7781                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
7782                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7783
7784                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
7785                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
7786                 }
7787                 break;
7788         }
7789         case BPF_JLE:
7790         case BPF_JLT:
7791         {
7792                 if (is_jmp32) {
7793                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
7794                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7795
7796                         false_reg->u32_min_value = max(false_reg->u32_min_value,
7797                                                        false_umin);
7798                         true_reg->u32_max_value = min(true_reg->u32_max_value,
7799                                                       true_umax);
7800                 } else {
7801                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
7802                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7803
7804                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
7805                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
7806                 }
7807                 break;
7808         }
7809         case BPF_JSLE:
7810         case BPF_JSLT:
7811         {
7812                 if (is_jmp32) {
7813                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
7814                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7815
7816                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7817                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7818                 } else {
7819                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
7820                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7821
7822                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
7823                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
7824                 }
7825                 break;
7826         }
7827         default:
7828                 return;
7829         }
7830
7831         if (is_jmp32) {
7832                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7833                                              tnum_subreg(false_32off));
7834                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7835                                             tnum_subreg(true_32off));
7836                 __reg_combine_32_into_64(false_reg);
7837                 __reg_combine_32_into_64(true_reg);
7838         } else {
7839                 false_reg->var_off = false_64off;
7840                 true_reg->var_off = true_64off;
7841                 __reg_combine_64_into_32(false_reg);
7842                 __reg_combine_64_into_32(true_reg);
7843         }
7844 }
7845
7846 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7847  * the variable reg.
7848  */
7849 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7850                                 struct bpf_reg_state *false_reg,
7851                                 u64 val, u32 val32,
7852                                 u8 opcode, bool is_jmp32)
7853 {
7854         opcode = flip_opcode(opcode);
7855         /* This uses zero as "not present in table"; luckily the zero opcode,
7856          * BPF_JA, can't get here.
7857          */
7858         if (opcode)
7859                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7860 }
7861
7862 /* Regs are known to be equal, so intersect their min/max/var_off */
7863 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7864                                   struct bpf_reg_state *dst_reg)
7865 {
7866         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7867                                                         dst_reg->umin_value);
7868         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7869                                                         dst_reg->umax_value);
7870         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7871                                                         dst_reg->smin_value);
7872         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7873                                                         dst_reg->smax_value);
7874         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7875                                                              dst_reg->var_off);
7876         /* We might have learned new bounds from the var_off. */
7877         __update_reg_bounds(src_reg);
7878         __update_reg_bounds(dst_reg);
7879         /* We might have learned something about the sign bit. */
7880         __reg_deduce_bounds(src_reg);
7881         __reg_deduce_bounds(dst_reg);
7882         /* We might have learned some bits from the bounds. */
7883         __reg_bound_offset(src_reg);
7884         __reg_bound_offset(dst_reg);
7885         /* Intersecting with the old var_off might have improved our bounds
7886          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7887          * then new var_off is (0; 0x7f...fc) which improves our umax.
7888          */
7889         __update_reg_bounds(src_reg);
7890         __update_reg_bounds(dst_reg);
7891 }
7892
7893 static void reg_combine_min_max(struct bpf_reg_state *true_src,
7894                                 struct bpf_reg_state *true_dst,
7895                                 struct bpf_reg_state *false_src,
7896                                 struct bpf_reg_state *false_dst,
7897                                 u8 opcode)
7898 {
7899         switch (opcode) {
7900         case BPF_JEQ:
7901                 __reg_combine_min_max(true_src, true_dst);
7902                 break;
7903         case BPF_JNE:
7904                 __reg_combine_min_max(false_src, false_dst);
7905                 break;
7906         }
7907 }
7908
7909 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7910                                  struct bpf_reg_state *reg, u32 id,
7911                                  bool is_null)
7912 {
7913         if (reg_type_may_be_null(reg->type) && reg->id == id &&
7914             !WARN_ON_ONCE(!reg->id)) {
7915                 /* Old offset (both fixed and variable parts) should
7916                  * have been known-zero, because we don't allow pointer
7917                  * arithmetic on pointers that might be NULL.
7918                  */
7919                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7920                                  !tnum_equals_const(reg->var_off, 0) ||
7921                                  reg->off)) {
7922                         __mark_reg_known_zero(reg);
7923                         reg->off = 0;
7924                 }
7925                 if (is_null) {
7926                         reg->type = SCALAR_VALUE;
7927                         /* We don't need id and ref_obj_id from this point
7928                          * onwards anymore, thus we should better reset it,
7929                          * so that state pruning has chances to take effect.
7930                          */
7931                         reg->id = 0;
7932                         reg->ref_obj_id = 0;
7933
7934                         return;
7935                 }
7936
7937                 mark_ptr_not_null_reg(reg);
7938
7939                 if (!reg_may_point_to_spin_lock(reg)) {
7940                         /* For not-NULL ptr, reg->ref_obj_id will be reset
7941                          * in release_reg_references().
7942                          *
7943                          * reg->id is still used by spin_lock ptr. Other
7944                          * than spin_lock ptr type, reg->id can be reset.
7945                          */
7946                         reg->id = 0;
7947                 }
7948         }
7949 }
7950
7951 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7952                                     bool is_null)
7953 {
7954         struct bpf_reg_state *reg;
7955         int i;
7956
7957         for (i = 0; i < MAX_BPF_REG; i++)
7958                 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7959
7960         bpf_for_each_spilled_reg(i, state, reg) {
7961                 if (!reg)
7962                         continue;
7963                 mark_ptr_or_null_reg(state, reg, id, is_null);
7964         }
7965 }
7966
7967 /* The logic is similar to find_good_pkt_pointers(), both could eventually
7968  * be folded together at some point.
7969  */
7970 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7971                                   bool is_null)
7972 {
7973         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7974         struct bpf_reg_state *regs = state->regs;
7975         u32 ref_obj_id = regs[regno].ref_obj_id;
7976         u32 id = regs[regno].id;
7977         int i;
7978
7979         if (ref_obj_id && ref_obj_id == id && is_null)
7980                 /* regs[regno] is in the " == NULL" branch.
7981                  * No one could have freed the reference state before
7982                  * doing the NULL check.
7983                  */
7984                 WARN_ON_ONCE(release_reference_state(state, id));
7985
7986         for (i = 0; i <= vstate->curframe; i++)
7987                 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
7988 }
7989
7990 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7991                                    struct bpf_reg_state *dst_reg,
7992                                    struct bpf_reg_state *src_reg,
7993                                    struct bpf_verifier_state *this_branch,
7994                                    struct bpf_verifier_state *other_branch)
7995 {
7996         if (BPF_SRC(insn->code) != BPF_X)
7997                 return false;
7998
7999         /* Pointers are always 64-bit. */
8000         if (BPF_CLASS(insn->code) == BPF_JMP32)
8001                 return false;
8002
8003         switch (BPF_OP(insn->code)) {
8004         case BPF_JGT:
8005                 if ((dst_reg->type == PTR_TO_PACKET &&
8006                      src_reg->type == PTR_TO_PACKET_END) ||
8007                     (dst_reg->type == PTR_TO_PACKET_META &&
8008                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8009                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8010                         find_good_pkt_pointers(this_branch, dst_reg,
8011                                                dst_reg->type, false);
8012                         mark_pkt_end(other_branch, insn->dst_reg, true);
8013                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8014                             src_reg->type == PTR_TO_PACKET) ||
8015                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8016                             src_reg->type == PTR_TO_PACKET_META)) {
8017                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8018                         find_good_pkt_pointers(other_branch, src_reg,
8019                                                src_reg->type, true);
8020                         mark_pkt_end(this_branch, insn->src_reg, false);
8021                 } else {
8022                         return false;
8023                 }
8024                 break;
8025         case BPF_JLT:
8026                 if ((dst_reg->type == PTR_TO_PACKET &&
8027                      src_reg->type == PTR_TO_PACKET_END) ||
8028                     (dst_reg->type == PTR_TO_PACKET_META &&
8029                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8030                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8031                         find_good_pkt_pointers(other_branch, dst_reg,
8032                                                dst_reg->type, true);
8033                         mark_pkt_end(this_branch, insn->dst_reg, false);
8034                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8035                             src_reg->type == PTR_TO_PACKET) ||
8036                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8037                             src_reg->type == PTR_TO_PACKET_META)) {
8038                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8039                         find_good_pkt_pointers(this_branch, src_reg,
8040                                                src_reg->type, false);
8041                         mark_pkt_end(other_branch, insn->src_reg, true);
8042                 } else {
8043                         return false;
8044                 }
8045                 break;
8046         case BPF_JGE:
8047                 if ((dst_reg->type == PTR_TO_PACKET &&
8048                      src_reg->type == PTR_TO_PACKET_END) ||
8049                     (dst_reg->type == PTR_TO_PACKET_META &&
8050                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8051                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8052                         find_good_pkt_pointers(this_branch, dst_reg,
8053                                                dst_reg->type, true);
8054                         mark_pkt_end(other_branch, insn->dst_reg, false);
8055                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8056                             src_reg->type == PTR_TO_PACKET) ||
8057                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8058                             src_reg->type == PTR_TO_PACKET_META)) {
8059                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8060                         find_good_pkt_pointers(other_branch, src_reg,
8061                                                src_reg->type, false);
8062                         mark_pkt_end(this_branch, insn->src_reg, true);
8063                 } else {
8064                         return false;
8065                 }
8066                 break;
8067         case BPF_JLE:
8068                 if ((dst_reg->type == PTR_TO_PACKET &&
8069                      src_reg->type == PTR_TO_PACKET_END) ||
8070                     (dst_reg->type == PTR_TO_PACKET_META &&
8071                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8072                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8073                         find_good_pkt_pointers(other_branch, dst_reg,
8074                                                dst_reg->type, false);
8075                         mark_pkt_end(this_branch, insn->dst_reg, true);
8076                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8077                             src_reg->type == PTR_TO_PACKET) ||
8078                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8079                             src_reg->type == PTR_TO_PACKET_META)) {
8080                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8081                         find_good_pkt_pointers(this_branch, src_reg,
8082                                                src_reg->type, true);
8083                         mark_pkt_end(other_branch, insn->src_reg, false);
8084                 } else {
8085                         return false;
8086                 }
8087                 break;
8088         default:
8089                 return false;
8090         }
8091
8092         return true;
8093 }
8094
8095 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8096                                struct bpf_reg_state *known_reg)
8097 {
8098         struct bpf_func_state *state;
8099         struct bpf_reg_state *reg;
8100         int i, j;
8101
8102         for (i = 0; i <= vstate->curframe; i++) {
8103                 state = vstate->frame[i];
8104                 for (j = 0; j < MAX_BPF_REG; j++) {
8105                         reg = &state->regs[j];
8106                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8107                                 *reg = *known_reg;
8108                 }
8109
8110                 bpf_for_each_spilled_reg(j, state, reg) {
8111                         if (!reg)
8112                                 continue;
8113                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8114                                 *reg = *known_reg;
8115                 }
8116         }
8117 }
8118
8119 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8120                              struct bpf_insn *insn, int *insn_idx)
8121 {
8122         struct bpf_verifier_state *this_branch = env->cur_state;
8123         struct bpf_verifier_state *other_branch;
8124         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8125         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8126         u8 opcode = BPF_OP(insn->code);
8127         bool is_jmp32;
8128         int pred = -1;
8129         int err;
8130
8131         /* Only conditional jumps are expected to reach here. */
8132         if (opcode == BPF_JA || opcode > BPF_JSLE) {
8133                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8134                 return -EINVAL;
8135         }
8136
8137         if (BPF_SRC(insn->code) == BPF_X) {
8138                 if (insn->imm != 0) {
8139                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8140                         return -EINVAL;
8141                 }
8142
8143                 /* check src1 operand */
8144                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8145                 if (err)
8146                         return err;
8147
8148                 if (is_pointer_value(env, insn->src_reg)) {
8149                         verbose(env, "R%d pointer comparison prohibited\n",
8150                                 insn->src_reg);
8151                         return -EACCES;
8152                 }
8153                 src_reg = &regs[insn->src_reg];
8154         } else {
8155                 if (insn->src_reg != BPF_REG_0) {
8156                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8157                         return -EINVAL;
8158                 }
8159         }
8160
8161         /* check src2 operand */
8162         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8163         if (err)
8164                 return err;
8165
8166         dst_reg = &regs[insn->dst_reg];
8167         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8168
8169         if (BPF_SRC(insn->code) == BPF_K) {
8170                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8171         } else if (src_reg->type == SCALAR_VALUE &&
8172                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8173                 pred = is_branch_taken(dst_reg,
8174                                        tnum_subreg(src_reg->var_off).value,
8175                                        opcode,
8176                                        is_jmp32);
8177         } else if (src_reg->type == SCALAR_VALUE &&
8178                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8179                 pred = is_branch_taken(dst_reg,
8180                                        src_reg->var_off.value,
8181                                        opcode,
8182                                        is_jmp32);
8183         } else if (reg_is_pkt_pointer_any(dst_reg) &&
8184                    reg_is_pkt_pointer_any(src_reg) &&
8185                    !is_jmp32) {
8186                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8187         }
8188
8189         if (pred >= 0) {
8190                 /* If we get here with a dst_reg pointer type it is because
8191                  * above is_branch_taken() special cased the 0 comparison.
8192                  */
8193                 if (!__is_pointer_value(false, dst_reg))
8194                         err = mark_chain_precision(env, insn->dst_reg);
8195                 if (BPF_SRC(insn->code) == BPF_X && !err &&
8196                     !__is_pointer_value(false, src_reg))
8197                         err = mark_chain_precision(env, insn->src_reg);
8198                 if (err)
8199                         return err;
8200         }
8201         if (pred == 1) {
8202                 /* only follow the goto, ignore fall-through */
8203                 *insn_idx += insn->off;
8204                 return 0;
8205         } else if (pred == 0) {
8206                 /* only follow fall-through branch, since
8207                  * that's where the program will go
8208                  */
8209                 return 0;
8210         }
8211
8212         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8213                                   false);
8214         if (!other_branch)
8215                 return -EFAULT;
8216         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8217
8218         /* detect if we are comparing against a constant value so we can adjust
8219          * our min/max values for our dst register.
8220          * this is only legit if both are scalars (or pointers to the same
8221          * object, I suppose, but we don't support that right now), because
8222          * otherwise the different base pointers mean the offsets aren't
8223          * comparable.
8224          */
8225         if (BPF_SRC(insn->code) == BPF_X) {
8226                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8227
8228                 if (dst_reg->type == SCALAR_VALUE &&
8229                     src_reg->type == SCALAR_VALUE) {
8230                         if (tnum_is_const(src_reg->var_off) ||
8231                             (is_jmp32 &&
8232                              tnum_is_const(tnum_subreg(src_reg->var_off))))
8233                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8234                                                 dst_reg,
8235                                                 src_reg->var_off.value,
8236                                                 tnum_subreg(src_reg->var_off).value,
8237                                                 opcode, is_jmp32);
8238                         else if (tnum_is_const(dst_reg->var_off) ||
8239                                  (is_jmp32 &&
8240                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
8241                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8242                                                     src_reg,
8243                                                     dst_reg->var_off.value,
8244                                                     tnum_subreg(dst_reg->var_off).value,
8245                                                     opcode, is_jmp32);
8246                         else if (!is_jmp32 &&
8247                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
8248                                 /* Comparing for equality, we can combine knowledge */
8249                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8250                                                     &other_branch_regs[insn->dst_reg],
8251                                                     src_reg, dst_reg, opcode);
8252                         if (src_reg->id &&
8253                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8254                                 find_equal_scalars(this_branch, src_reg);
8255                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8256                         }
8257
8258                 }
8259         } else if (dst_reg->type == SCALAR_VALUE) {
8260                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8261                                         dst_reg, insn->imm, (u32)insn->imm,
8262                                         opcode, is_jmp32);
8263         }
8264
8265         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8266             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8267                 find_equal_scalars(this_branch, dst_reg);
8268                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8269         }
8270
8271         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8272          * NOTE: these optimizations below are related with pointer comparison
8273          *       which will never be JMP32.
8274          */
8275         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8276             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8277             reg_type_may_be_null(dst_reg->type)) {
8278                 /* Mark all identical registers in each branch as either
8279                  * safe or unknown depending R == 0 or R != 0 conditional.
8280                  */
8281                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8282                                       opcode == BPF_JNE);
8283                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8284                                       opcode == BPF_JEQ);
8285         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8286                                            this_branch, other_branch) &&
8287                    is_pointer_value(env, insn->dst_reg)) {
8288                 verbose(env, "R%d pointer comparison prohibited\n",
8289                         insn->dst_reg);
8290                 return -EACCES;
8291         }
8292         if (env->log.level & BPF_LOG_LEVEL)
8293                 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8294         return 0;
8295 }
8296
8297 /* verify BPF_LD_IMM64 instruction */
8298 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8299 {
8300         struct bpf_insn_aux_data *aux = cur_aux(env);
8301         struct bpf_reg_state *regs = cur_regs(env);
8302         struct bpf_reg_state *dst_reg;
8303         struct bpf_map *map;
8304         int err;
8305
8306         if (BPF_SIZE(insn->code) != BPF_DW) {
8307                 verbose(env, "invalid BPF_LD_IMM insn\n");
8308                 return -EINVAL;
8309         }
8310         if (insn->off != 0) {
8311                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8312                 return -EINVAL;
8313         }
8314
8315         err = check_reg_arg(env, insn->dst_reg, DST_OP);
8316         if (err)
8317                 return err;
8318
8319         dst_reg = &regs[insn->dst_reg];
8320         if (insn->src_reg == 0) {
8321                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8322
8323                 dst_reg->type = SCALAR_VALUE;
8324                 __mark_reg_known(&regs[insn->dst_reg], imm);
8325                 return 0;
8326         }
8327
8328         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8329                 mark_reg_known_zero(env, regs, insn->dst_reg);
8330
8331                 dst_reg->type = aux->btf_var.reg_type;
8332                 switch (dst_reg->type) {
8333                 case PTR_TO_MEM:
8334                         dst_reg->mem_size = aux->btf_var.mem_size;
8335                         break;
8336                 case PTR_TO_BTF_ID:
8337                 case PTR_TO_PERCPU_BTF_ID:
8338                         dst_reg->btf = aux->btf_var.btf;
8339                         dst_reg->btf_id = aux->btf_var.btf_id;
8340                         break;
8341                 default:
8342                         verbose(env, "bpf verifier is misconfigured\n");
8343                         return -EFAULT;
8344                 }
8345                 return 0;
8346         }
8347
8348         map = env->used_maps[aux->map_index];
8349         mark_reg_known_zero(env, regs, insn->dst_reg);
8350         dst_reg->map_ptr = map;
8351
8352         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8353                 dst_reg->type = PTR_TO_MAP_VALUE;
8354                 dst_reg->off = aux->map_off;
8355                 if (map_value_has_spin_lock(map))
8356                         dst_reg->id = ++env->id_gen;
8357         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8358                 dst_reg->type = CONST_PTR_TO_MAP;
8359         } else {
8360                 verbose(env, "bpf verifier is misconfigured\n");
8361                 return -EINVAL;
8362         }
8363
8364         return 0;
8365 }
8366
8367 static bool may_access_skb(enum bpf_prog_type type)
8368 {
8369         switch (type) {
8370         case BPF_PROG_TYPE_SOCKET_FILTER:
8371         case BPF_PROG_TYPE_SCHED_CLS:
8372         case BPF_PROG_TYPE_SCHED_ACT:
8373                 return true;
8374         default:
8375                 return false;
8376         }
8377 }
8378
8379 /* verify safety of LD_ABS|LD_IND instructions:
8380  * - they can only appear in the programs where ctx == skb
8381  * - since they are wrappers of function calls, they scratch R1-R5 registers,
8382  *   preserve R6-R9, and store return value into R0
8383  *
8384  * Implicit input:
8385  *   ctx == skb == R6 == CTX
8386  *
8387  * Explicit input:
8388  *   SRC == any register
8389  *   IMM == 32-bit immediate
8390  *
8391  * Output:
8392  *   R0 - 8/16/32-bit skb data converted to cpu endianness
8393  */
8394 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8395 {
8396         struct bpf_reg_state *regs = cur_regs(env);
8397         static const int ctx_reg = BPF_REG_6;
8398         u8 mode = BPF_MODE(insn->code);
8399         int i, err;
8400
8401         if (!may_access_skb(resolve_prog_type(env->prog))) {
8402                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8403                 return -EINVAL;
8404         }
8405
8406         if (!env->ops->gen_ld_abs) {
8407                 verbose(env, "bpf verifier is misconfigured\n");
8408                 return -EINVAL;
8409         }
8410
8411         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8412             BPF_SIZE(insn->code) == BPF_DW ||
8413             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8414                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8415                 return -EINVAL;
8416         }
8417
8418         /* check whether implicit source operand (register R6) is readable */
8419         err = check_reg_arg(env, ctx_reg, SRC_OP);
8420         if (err)
8421                 return err;
8422
8423         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8424          * gen_ld_abs() may terminate the program at runtime, leading to
8425          * reference leak.
8426          */
8427         err = check_reference_leak(env);
8428         if (err) {
8429                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8430                 return err;
8431         }
8432
8433         if (env->cur_state->active_spin_lock) {
8434                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8435                 return -EINVAL;
8436         }
8437
8438         if (regs[ctx_reg].type != PTR_TO_CTX) {
8439                 verbose(env,
8440                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8441                 return -EINVAL;
8442         }
8443
8444         if (mode == BPF_IND) {
8445                 /* check explicit source operand */
8446                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8447                 if (err)
8448                         return err;
8449         }
8450
8451         err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8452         if (err < 0)
8453                 return err;
8454
8455         /* reset caller saved regs to unreadable */
8456         for (i = 0; i < CALLER_SAVED_REGS; i++) {
8457                 mark_reg_not_init(env, regs, caller_saved[i]);
8458                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8459         }
8460
8461         /* mark destination R0 register as readable, since it contains
8462          * the value fetched from the packet.
8463          * Already marked as written above.
8464          */
8465         mark_reg_unknown(env, regs, BPF_REG_0);
8466         /* ld_abs load up to 32-bit skb data. */
8467         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8468         return 0;
8469 }
8470
8471 static int check_return_code(struct bpf_verifier_env *env)
8472 {
8473         struct tnum enforce_attach_type_range = tnum_unknown;
8474         const struct bpf_prog *prog = env->prog;
8475         struct bpf_reg_state *reg;
8476         struct tnum range = tnum_range(0, 1);
8477         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8478         int err;
8479         const bool is_subprog = env->cur_state->frame[0]->subprogno;
8480
8481         /* LSM and struct_ops func-ptr's return type could be "void" */
8482         if (!is_subprog &&
8483             (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8484              prog_type == BPF_PROG_TYPE_LSM) &&
8485             !prog->aux->attach_func_proto->type)
8486                 return 0;
8487
8488         /* eBPF calling convetion is such that R0 is used
8489          * to return the value from eBPF program.
8490          * Make sure that it's readable at this time
8491          * of bpf_exit, which means that program wrote
8492          * something into it earlier
8493          */
8494         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8495         if (err)
8496                 return err;
8497
8498         if (is_pointer_value(env, BPF_REG_0)) {
8499                 verbose(env, "R0 leaks addr as return value\n");
8500                 return -EACCES;
8501         }
8502
8503         reg = cur_regs(env) + BPF_REG_0;
8504         if (is_subprog) {
8505                 if (reg->type != SCALAR_VALUE) {
8506                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8507                                 reg_type_str[reg->type]);
8508                         return -EINVAL;
8509                 }
8510                 return 0;
8511         }
8512
8513         switch (prog_type) {
8514         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8515                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8516                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8517                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8518                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8519                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8520                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8521                         range = tnum_range(1, 1);
8522                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
8523                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
8524                         range = tnum_range(0, 3);
8525                 break;
8526         case BPF_PROG_TYPE_CGROUP_SKB:
8527                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8528                         range = tnum_range(0, 3);
8529                         enforce_attach_type_range = tnum_range(2, 3);
8530                 }
8531                 break;
8532         case BPF_PROG_TYPE_CGROUP_SOCK:
8533         case BPF_PROG_TYPE_SOCK_OPS:
8534         case BPF_PROG_TYPE_CGROUP_DEVICE:
8535         case BPF_PROG_TYPE_CGROUP_SYSCTL:
8536         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8537                 break;
8538         case BPF_PROG_TYPE_RAW_TRACEPOINT:
8539                 if (!env->prog->aux->attach_btf_id)
8540                         return 0;
8541                 range = tnum_const(0);
8542                 break;
8543         case BPF_PROG_TYPE_TRACING:
8544                 switch (env->prog->expected_attach_type) {
8545                 case BPF_TRACE_FENTRY:
8546                 case BPF_TRACE_FEXIT:
8547                         range = tnum_const(0);
8548                         break;
8549                 case BPF_TRACE_RAW_TP:
8550                 case BPF_MODIFY_RETURN:
8551                         return 0;
8552                 case BPF_TRACE_ITER:
8553                         break;
8554                 default:
8555                         return -ENOTSUPP;
8556                 }
8557                 break;
8558         case BPF_PROG_TYPE_SK_LOOKUP:
8559                 range = tnum_range(SK_DROP, SK_PASS);
8560                 break;
8561         case BPF_PROG_TYPE_EXT:
8562                 /* freplace program can return anything as its return value
8563                  * depends on the to-be-replaced kernel func or bpf program.
8564                  */
8565         default:
8566                 return 0;
8567         }
8568
8569         if (reg->type != SCALAR_VALUE) {
8570                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8571                         reg_type_str[reg->type]);
8572                 return -EINVAL;
8573         }
8574
8575         if (!tnum_in(range, reg->var_off)) {
8576                 char tn_buf[48];
8577
8578                 verbose(env, "At program exit the register R0 ");
8579                 if (!tnum_is_unknown(reg->var_off)) {
8580                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8581                         verbose(env, "has value %s", tn_buf);
8582                 } else {
8583                         verbose(env, "has unknown scalar value");
8584                 }
8585                 tnum_strn(tn_buf, sizeof(tn_buf), range);
8586                 verbose(env, " should have been in %s\n", tn_buf);
8587                 return -EINVAL;
8588         }
8589
8590         if (!tnum_is_unknown(enforce_attach_type_range) &&
8591             tnum_in(enforce_attach_type_range, reg->var_off))
8592                 env->prog->enforce_expected_attach_type = 1;
8593         return 0;
8594 }
8595
8596 /* non-recursive DFS pseudo code
8597  * 1  procedure DFS-iterative(G,v):
8598  * 2      label v as discovered
8599  * 3      let S be a stack
8600  * 4      S.push(v)
8601  * 5      while S is not empty
8602  * 6            t <- S.pop()
8603  * 7            if t is what we're looking for:
8604  * 8                return t
8605  * 9            for all edges e in G.adjacentEdges(t) do
8606  * 10               if edge e is already labelled
8607  * 11                   continue with the next edge
8608  * 12               w <- G.adjacentVertex(t,e)
8609  * 13               if vertex w is not discovered and not explored
8610  * 14                   label e as tree-edge
8611  * 15                   label w as discovered
8612  * 16                   S.push(w)
8613  * 17                   continue at 5
8614  * 18               else if vertex w is discovered
8615  * 19                   label e as back-edge
8616  * 20               else
8617  * 21                   // vertex w is explored
8618  * 22                   label e as forward- or cross-edge
8619  * 23           label t as explored
8620  * 24           S.pop()
8621  *
8622  * convention:
8623  * 0x10 - discovered
8624  * 0x11 - discovered and fall-through edge labelled
8625  * 0x12 - discovered and fall-through and branch edges labelled
8626  * 0x20 - explored
8627  */
8628
8629 enum {
8630         DISCOVERED = 0x10,
8631         EXPLORED = 0x20,
8632         FALLTHROUGH = 1,
8633         BRANCH = 2,
8634 };
8635
8636 static u32 state_htab_size(struct bpf_verifier_env *env)
8637 {
8638         return env->prog->len;
8639 }
8640
8641 static struct bpf_verifier_state_list **explored_state(
8642                                         struct bpf_verifier_env *env,
8643                                         int idx)
8644 {
8645         struct bpf_verifier_state *cur = env->cur_state;
8646         struct bpf_func_state *state = cur->frame[cur->curframe];
8647
8648         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8649 }
8650
8651 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8652 {
8653         env->insn_aux_data[idx].prune_point = true;
8654 }
8655
8656 enum {
8657         DONE_EXPLORING = 0,
8658         KEEP_EXPLORING = 1,
8659 };
8660
8661 /* t, w, e - match pseudo-code above:
8662  * t - index of current instruction
8663  * w - next instruction
8664  * e - edge
8665  */
8666 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8667                      bool loop_ok)
8668 {
8669         int *insn_stack = env->cfg.insn_stack;
8670         int *insn_state = env->cfg.insn_state;
8671
8672         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8673                 return DONE_EXPLORING;
8674
8675         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8676                 return DONE_EXPLORING;
8677
8678         if (w < 0 || w >= env->prog->len) {
8679                 verbose_linfo(env, t, "%d: ", t);
8680                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
8681                 return -EINVAL;
8682         }
8683
8684         if (e == BRANCH)
8685                 /* mark branch target for state pruning */
8686                 init_explored_state(env, w);
8687
8688         if (insn_state[w] == 0) {
8689                 /* tree-edge */
8690                 insn_state[t] = DISCOVERED | e;
8691                 insn_state[w] = DISCOVERED;
8692                 if (env->cfg.cur_stack >= env->prog->len)
8693                         return -E2BIG;
8694                 insn_stack[env->cfg.cur_stack++] = w;
8695                 return KEEP_EXPLORING;
8696         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8697                 if (loop_ok && env->bpf_capable)
8698                         return DONE_EXPLORING;
8699                 verbose_linfo(env, t, "%d: ", t);
8700                 verbose_linfo(env, w, "%d: ", w);
8701                 verbose(env, "back-edge from insn %d to %d\n", t, w);
8702                 return -EINVAL;
8703         } else if (insn_state[w] == EXPLORED) {
8704                 /* forward- or cross-edge */
8705                 insn_state[t] = DISCOVERED | e;
8706         } else {
8707                 verbose(env, "insn state internal bug\n");
8708                 return -EFAULT;
8709         }
8710         return DONE_EXPLORING;
8711 }
8712
8713 /* Visits the instruction at index t and returns one of the following:
8714  *  < 0 - an error occurred
8715  *  DONE_EXPLORING - the instruction was fully explored
8716  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
8717  */
8718 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8719 {
8720         struct bpf_insn *insns = env->prog->insnsi;
8721         int ret;
8722
8723         /* All non-branch instructions have a single fall-through edge. */
8724         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8725             BPF_CLASS(insns[t].code) != BPF_JMP32)
8726                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
8727
8728         switch (BPF_OP(insns[t].code)) {
8729         case BPF_EXIT:
8730                 return DONE_EXPLORING;
8731
8732         case BPF_CALL:
8733                 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8734                 if (ret)
8735                         return ret;
8736
8737                 if (t + 1 < insn_cnt)
8738                         init_explored_state(env, t + 1);
8739                 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8740                         init_explored_state(env, t);
8741                         ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8742                                         env, false);
8743                 }
8744                 return ret;
8745
8746         case BPF_JA:
8747                 if (BPF_SRC(insns[t].code) != BPF_K)
8748                         return -EINVAL;
8749
8750                 /* unconditional jump with single edge */
8751                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8752                                 true);
8753                 if (ret)
8754                         return ret;
8755
8756                 /* unconditional jmp is not a good pruning point,
8757                  * but it's marked, since backtracking needs
8758                  * to record jmp history in is_state_visited().
8759                  */
8760                 init_explored_state(env, t + insns[t].off + 1);
8761                 /* tell verifier to check for equivalent states
8762                  * after every call and jump
8763                  */
8764                 if (t + 1 < insn_cnt)
8765                         init_explored_state(env, t + 1);
8766
8767                 return ret;
8768
8769         default:
8770                 /* conditional jump with two edges */
8771                 init_explored_state(env, t);
8772                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8773                 if (ret)
8774                         return ret;
8775
8776                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8777         }
8778 }
8779
8780 /* non-recursive depth-first-search to detect loops in BPF program
8781  * loop == back-edge in directed graph
8782  */
8783 static int check_cfg(struct bpf_verifier_env *env)
8784 {
8785         int insn_cnt = env->prog->len;
8786         int *insn_stack, *insn_state;
8787         int ret = 0;
8788         int i;
8789
8790         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8791         if (!insn_state)
8792                 return -ENOMEM;
8793
8794         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8795         if (!insn_stack) {
8796                 kvfree(insn_state);
8797                 return -ENOMEM;
8798         }
8799
8800         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8801         insn_stack[0] = 0; /* 0 is the first instruction */
8802         env->cfg.cur_stack = 1;
8803
8804         while (env->cfg.cur_stack > 0) {
8805                 int t = insn_stack[env->cfg.cur_stack - 1];
8806
8807                 ret = visit_insn(t, insn_cnt, env);
8808                 switch (ret) {
8809                 case DONE_EXPLORING:
8810                         insn_state[t] = EXPLORED;
8811                         env->cfg.cur_stack--;
8812                         break;
8813                 case KEEP_EXPLORING:
8814                         break;
8815                 default:
8816                         if (ret > 0) {
8817                                 verbose(env, "visit_insn internal bug\n");
8818                                 ret = -EFAULT;
8819                         }
8820                         goto err_free;
8821                 }
8822         }
8823
8824         if (env->cfg.cur_stack < 0) {
8825                 verbose(env, "pop stack internal bug\n");
8826                 ret = -EFAULT;
8827                 goto err_free;
8828         }
8829
8830         for (i = 0; i < insn_cnt; i++) {
8831                 if (insn_state[i] != EXPLORED) {
8832                         verbose(env, "unreachable insn %d\n", i);
8833                         ret = -EINVAL;
8834                         goto err_free;
8835                 }
8836         }
8837         ret = 0; /* cfg looks good */
8838
8839 err_free:
8840         kvfree(insn_state);
8841         kvfree(insn_stack);
8842         env->cfg.insn_state = env->cfg.insn_stack = NULL;
8843         return ret;
8844 }
8845
8846 static int check_abnormal_return(struct bpf_verifier_env *env)
8847 {
8848         int i;
8849
8850         for (i = 1; i < env->subprog_cnt; i++) {
8851                 if (env->subprog_info[i].has_ld_abs) {
8852                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8853                         return -EINVAL;
8854                 }
8855                 if (env->subprog_info[i].has_tail_call) {
8856                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8857                         return -EINVAL;
8858                 }
8859         }
8860         return 0;
8861 }
8862
8863 /* The minimum supported BTF func info size */
8864 #define MIN_BPF_FUNCINFO_SIZE   8
8865 #define MAX_FUNCINFO_REC_SIZE   252
8866
8867 static int check_btf_func(struct bpf_verifier_env *env,
8868                           const union bpf_attr *attr,
8869                           union bpf_attr __user *uattr)
8870 {
8871         const struct btf_type *type, *func_proto, *ret_type;
8872         u32 i, nfuncs, urec_size, min_size;
8873         u32 krec_size = sizeof(struct bpf_func_info);
8874         struct bpf_func_info *krecord;
8875         struct bpf_func_info_aux *info_aux = NULL;
8876         struct bpf_prog *prog;
8877         const struct btf *btf;
8878         void __user *urecord;
8879         u32 prev_offset = 0;
8880         bool scalar_return;
8881         int ret = -ENOMEM;
8882
8883         nfuncs = attr->func_info_cnt;
8884         if (!nfuncs) {
8885                 if (check_abnormal_return(env))
8886                         return -EINVAL;
8887                 return 0;
8888         }
8889
8890         if (nfuncs != env->subprog_cnt) {
8891                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8892                 return -EINVAL;
8893         }
8894
8895         urec_size = attr->func_info_rec_size;
8896         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8897             urec_size > MAX_FUNCINFO_REC_SIZE ||
8898             urec_size % sizeof(u32)) {
8899                 verbose(env, "invalid func info rec size %u\n", urec_size);
8900                 return -EINVAL;
8901         }
8902
8903         prog = env->prog;
8904         btf = prog->aux->btf;
8905
8906         urecord = u64_to_user_ptr(attr->func_info);
8907         min_size = min_t(u32, krec_size, urec_size);
8908
8909         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
8910         if (!krecord)
8911                 return -ENOMEM;
8912         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8913         if (!info_aux)
8914                 goto err_free;
8915
8916         for (i = 0; i < nfuncs; i++) {
8917                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8918                 if (ret) {
8919                         if (ret == -E2BIG) {
8920                                 verbose(env, "nonzero tailing record in func info");
8921                                 /* set the size kernel expects so loader can zero
8922                                  * out the rest of the record.
8923                                  */
8924                                 if (put_user(min_size, &uattr->func_info_rec_size))
8925                                         ret = -EFAULT;
8926                         }
8927                         goto err_free;
8928                 }
8929
8930                 if (copy_from_user(&krecord[i], urecord, min_size)) {
8931                         ret = -EFAULT;
8932                         goto err_free;
8933                 }
8934
8935                 /* check insn_off */
8936                 ret = -EINVAL;
8937                 if (i == 0) {
8938                         if (krecord[i].insn_off) {
8939                                 verbose(env,
8940                                         "nonzero insn_off %u for the first func info record",
8941                                         krecord[i].insn_off);
8942                                 goto err_free;
8943                         }
8944                 } else if (krecord[i].insn_off <= prev_offset) {
8945                         verbose(env,
8946                                 "same or smaller insn offset (%u) than previous func info record (%u)",
8947                                 krecord[i].insn_off, prev_offset);
8948                         goto err_free;
8949                 }
8950
8951                 if (env->subprog_info[i].start != krecord[i].insn_off) {
8952                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
8953                         goto err_free;
8954                 }
8955
8956                 /* check type_id */
8957                 type = btf_type_by_id(btf, krecord[i].type_id);
8958                 if (!type || !btf_type_is_func(type)) {
8959                         verbose(env, "invalid type id %d in func info",
8960                                 krecord[i].type_id);
8961                         goto err_free;
8962                 }
8963                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
8964
8965                 func_proto = btf_type_by_id(btf, type->type);
8966                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8967                         /* btf_func_check() already verified it during BTF load */
8968                         goto err_free;
8969                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8970                 scalar_return =
8971                         btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8972                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8973                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8974                         goto err_free;
8975                 }
8976                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8977                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8978                         goto err_free;
8979                 }
8980
8981                 prev_offset = krecord[i].insn_off;
8982                 urecord += urec_size;
8983         }
8984
8985         prog->aux->func_info = krecord;
8986         prog->aux->func_info_cnt = nfuncs;
8987         prog->aux->func_info_aux = info_aux;
8988         return 0;
8989
8990 err_free:
8991         kvfree(krecord);
8992         kfree(info_aux);
8993         return ret;
8994 }
8995
8996 static void adjust_btf_func(struct bpf_verifier_env *env)
8997 {
8998         struct bpf_prog_aux *aux = env->prog->aux;
8999         int i;
9000
9001         if (!aux->func_info)
9002                 return;
9003
9004         for (i = 0; i < env->subprog_cnt; i++)
9005                 aux->func_info[i].insn_off = env->subprog_info[i].start;
9006 }
9007
9008 #define MIN_BPF_LINEINFO_SIZE   (offsetof(struct bpf_line_info, line_col) + \
9009                 sizeof(((struct bpf_line_info *)(0))->line_col))
9010 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
9011
9012 static int check_btf_line(struct bpf_verifier_env *env,
9013                           const union bpf_attr *attr,
9014                           union bpf_attr __user *uattr)
9015 {
9016         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9017         struct bpf_subprog_info *sub;
9018         struct bpf_line_info *linfo;
9019         struct bpf_prog *prog;
9020         const struct btf *btf;
9021         void __user *ulinfo;
9022         int err;
9023
9024         nr_linfo = attr->line_info_cnt;
9025         if (!nr_linfo)
9026                 return 0;
9027
9028         rec_size = attr->line_info_rec_size;
9029         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9030             rec_size > MAX_LINEINFO_REC_SIZE ||
9031             rec_size & (sizeof(u32) - 1))
9032                 return -EINVAL;
9033
9034         /* Need to zero it in case the userspace may
9035          * pass in a smaller bpf_line_info object.
9036          */
9037         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9038                          GFP_KERNEL | __GFP_NOWARN);
9039         if (!linfo)
9040                 return -ENOMEM;
9041
9042         prog = env->prog;
9043         btf = prog->aux->btf;
9044
9045         s = 0;
9046         sub = env->subprog_info;
9047         ulinfo = u64_to_user_ptr(attr->line_info);
9048         expected_size = sizeof(struct bpf_line_info);
9049         ncopy = min_t(u32, expected_size, rec_size);
9050         for (i = 0; i < nr_linfo; i++) {
9051                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9052                 if (err) {
9053                         if (err == -E2BIG) {
9054                                 verbose(env, "nonzero tailing record in line_info");
9055                                 if (put_user(expected_size,
9056                                              &uattr->line_info_rec_size))
9057                                         err = -EFAULT;
9058                         }
9059                         goto err_free;
9060                 }
9061
9062                 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9063                         err = -EFAULT;
9064                         goto err_free;
9065                 }
9066
9067                 /*
9068                  * Check insn_off to ensure
9069                  * 1) strictly increasing AND
9070                  * 2) bounded by prog->len
9071                  *
9072                  * The linfo[0].insn_off == 0 check logically falls into
9073                  * the later "missing bpf_line_info for func..." case
9074                  * because the first linfo[0].insn_off must be the
9075                  * first sub also and the first sub must have
9076                  * subprog_info[0].start == 0.
9077                  */
9078                 if ((i && linfo[i].insn_off <= prev_offset) ||
9079                     linfo[i].insn_off >= prog->len) {
9080                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9081                                 i, linfo[i].insn_off, prev_offset,
9082                                 prog->len);
9083                         err = -EINVAL;
9084                         goto err_free;
9085                 }
9086
9087                 if (!prog->insnsi[linfo[i].insn_off].code) {
9088                         verbose(env,
9089                                 "Invalid insn code at line_info[%u].insn_off\n",
9090                                 i);
9091                         err = -EINVAL;
9092                         goto err_free;
9093                 }
9094
9095                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9096                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9097                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9098                         err = -EINVAL;
9099                         goto err_free;
9100                 }
9101
9102                 if (s != env->subprog_cnt) {
9103                         if (linfo[i].insn_off == sub[s].start) {
9104                                 sub[s].linfo_idx = i;
9105                                 s++;
9106                         } else if (sub[s].start < linfo[i].insn_off) {
9107                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
9108                                 err = -EINVAL;
9109                                 goto err_free;
9110                         }
9111                 }
9112
9113                 prev_offset = linfo[i].insn_off;
9114                 ulinfo += rec_size;
9115         }
9116
9117         if (s != env->subprog_cnt) {
9118                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9119                         env->subprog_cnt - s, s);
9120                 err = -EINVAL;
9121                 goto err_free;
9122         }
9123
9124         prog->aux->linfo = linfo;
9125         prog->aux->nr_linfo = nr_linfo;
9126
9127         return 0;
9128
9129 err_free:
9130         kvfree(linfo);
9131         return err;
9132 }
9133
9134 static int check_btf_info(struct bpf_verifier_env *env,
9135                           const union bpf_attr *attr,
9136                           union bpf_attr __user *uattr)
9137 {
9138         struct btf *btf;
9139         int err;
9140
9141         if (!attr->func_info_cnt && !attr->line_info_cnt) {
9142                 if (check_abnormal_return(env))
9143                         return -EINVAL;
9144                 return 0;
9145         }
9146
9147         btf = btf_get_by_fd(attr->prog_btf_fd);
9148         if (IS_ERR(btf))
9149                 return PTR_ERR(btf);
9150         if (btf_is_kernel(btf)) {
9151                 btf_put(btf);
9152                 return -EACCES;
9153         }
9154         env->prog->aux->btf = btf;
9155
9156         err = check_btf_func(env, attr, uattr);
9157         if (err)
9158                 return err;
9159
9160         err = check_btf_line(env, attr, uattr);
9161         if (err)
9162                 return err;
9163
9164         return 0;
9165 }
9166
9167 /* check %cur's range satisfies %old's */
9168 static bool range_within(struct bpf_reg_state *old,
9169                          struct bpf_reg_state *cur)
9170 {
9171         return old->umin_value <= cur->umin_value &&
9172                old->umax_value >= cur->umax_value &&
9173                old->smin_value <= cur->smin_value &&
9174                old->smax_value >= cur->smax_value &&
9175                old->u32_min_value <= cur->u32_min_value &&
9176                old->u32_max_value >= cur->u32_max_value &&
9177                old->s32_min_value <= cur->s32_min_value &&
9178                old->s32_max_value >= cur->s32_max_value;
9179 }
9180
9181 /* Maximum number of register states that can exist at once */
9182 #define ID_MAP_SIZE     (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9183 struct idpair {
9184         u32 old;
9185         u32 cur;
9186 };
9187
9188 /* If in the old state two registers had the same id, then they need to have
9189  * the same id in the new state as well.  But that id could be different from
9190  * the old state, so we need to track the mapping from old to new ids.
9191  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9192  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9193  * regs with a different old id could still have new id 9, we don't care about
9194  * that.
9195  * So we look through our idmap to see if this old id has been seen before.  If
9196  * so, we require the new id to match; otherwise, we add the id pair to the map.
9197  */
9198 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9199 {
9200         unsigned int i;
9201
9202         for (i = 0; i < ID_MAP_SIZE; i++) {
9203                 if (!idmap[i].old) {
9204                         /* Reached an empty slot; haven't seen this id before */
9205                         idmap[i].old = old_id;
9206                         idmap[i].cur = cur_id;
9207                         return true;
9208                 }
9209                 if (idmap[i].old == old_id)
9210                         return idmap[i].cur == cur_id;
9211         }
9212         /* We ran out of idmap slots, which should be impossible */
9213         WARN_ON_ONCE(1);
9214         return false;
9215 }
9216
9217 static void clean_func_state(struct bpf_verifier_env *env,
9218                              struct bpf_func_state *st)
9219 {
9220         enum bpf_reg_liveness live;
9221         int i, j;
9222
9223         for (i = 0; i < BPF_REG_FP; i++) {
9224                 live = st->regs[i].live;
9225                 /* liveness must not touch this register anymore */
9226                 st->regs[i].live |= REG_LIVE_DONE;
9227                 if (!(live & REG_LIVE_READ))
9228                         /* since the register is unused, clear its state
9229                          * to make further comparison simpler
9230                          */
9231                         __mark_reg_not_init(env, &st->regs[i]);
9232         }
9233
9234         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9235                 live = st->stack[i].spilled_ptr.live;
9236                 /* liveness must not touch this stack slot anymore */
9237                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9238                 if (!(live & REG_LIVE_READ)) {
9239                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9240                         for (j = 0; j < BPF_REG_SIZE; j++)
9241                                 st->stack[i].slot_type[j] = STACK_INVALID;
9242                 }
9243         }
9244 }
9245
9246 static void clean_verifier_state(struct bpf_verifier_env *env,
9247                                  struct bpf_verifier_state *st)
9248 {
9249         int i;
9250
9251         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9252                 /* all regs in this state in all frames were already marked */
9253                 return;
9254
9255         for (i = 0; i <= st->curframe; i++)
9256                 clean_func_state(env, st->frame[i]);
9257 }
9258
9259 /* the parentage chains form a tree.
9260  * the verifier states are added to state lists at given insn and
9261  * pushed into state stack for future exploration.
9262  * when the verifier reaches bpf_exit insn some of the verifer states
9263  * stored in the state lists have their final liveness state already,
9264  * but a lot of states will get revised from liveness point of view when
9265  * the verifier explores other branches.
9266  * Example:
9267  * 1: r0 = 1
9268  * 2: if r1 == 100 goto pc+1
9269  * 3: r0 = 2
9270  * 4: exit
9271  * when the verifier reaches exit insn the register r0 in the state list of
9272  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9273  * of insn 2 and goes exploring further. At the insn 4 it will walk the
9274  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9275  *
9276  * Since the verifier pushes the branch states as it sees them while exploring
9277  * the program the condition of walking the branch instruction for the second
9278  * time means that all states below this branch were already explored and
9279  * their final liveness markes are already propagated.
9280  * Hence when the verifier completes the search of state list in is_state_visited()
9281  * we can call this clean_live_states() function to mark all liveness states
9282  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9283  * will not be used.
9284  * This function also clears the registers and stack for states that !READ
9285  * to simplify state merging.
9286  *
9287  * Important note here that walking the same branch instruction in the callee
9288  * doesn't meant that the states are DONE. The verifier has to compare
9289  * the callsites
9290  */
9291 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9292                               struct bpf_verifier_state *cur)
9293 {
9294         struct bpf_verifier_state_list *sl;
9295         int i;
9296
9297         sl = *explored_state(env, insn);
9298         while (sl) {
9299                 if (sl->state.branches)
9300                         goto next;
9301                 if (sl->state.insn_idx != insn ||
9302                     sl->state.curframe != cur->curframe)
9303                         goto next;
9304                 for (i = 0; i <= cur->curframe; i++)
9305                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9306                                 goto next;
9307                 clean_verifier_state(env, &sl->state);
9308 next:
9309                 sl = sl->next;
9310         }
9311 }
9312
9313 /* Returns true if (rold safe implies rcur safe) */
9314 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9315                     struct idpair *idmap)
9316 {
9317         bool equal;
9318
9319         if (!(rold->live & REG_LIVE_READ))
9320                 /* explored state didn't use this */
9321                 return true;
9322
9323         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9324
9325         if (rold->type == PTR_TO_STACK)
9326                 /* two stack pointers are equal only if they're pointing to
9327                  * the same stack frame, since fp-8 in foo != fp-8 in bar
9328                  */
9329                 return equal && rold->frameno == rcur->frameno;
9330
9331         if (equal)
9332                 return true;
9333
9334         if (rold->type == NOT_INIT)
9335                 /* explored state can't have used this */
9336                 return true;
9337         if (rcur->type == NOT_INIT)
9338                 return false;
9339         switch (rold->type) {
9340         case SCALAR_VALUE:
9341                 if (rcur->type == SCALAR_VALUE) {
9342                         if (!rold->precise && !rcur->precise)
9343                                 return true;
9344                         /* new val must satisfy old val knowledge */
9345                         return range_within(rold, rcur) &&
9346                                tnum_in(rold->var_off, rcur->var_off);
9347                 } else {
9348                         /* We're trying to use a pointer in place of a scalar.
9349                          * Even if the scalar was unbounded, this could lead to
9350                          * pointer leaks because scalars are allowed to leak
9351                          * while pointers are not. We could make this safe in
9352                          * special cases if root is calling us, but it's
9353                          * probably not worth the hassle.
9354                          */
9355                         return false;
9356                 }
9357         case PTR_TO_MAP_VALUE:
9358                 /* If the new min/max/var_off satisfy the old ones and
9359                  * everything else matches, we are OK.
9360                  * 'id' is not compared, since it's only used for maps with
9361                  * bpf_spin_lock inside map element and in such cases if
9362                  * the rest of the prog is valid for one map element then
9363                  * it's valid for all map elements regardless of the key
9364                  * used in bpf_map_lookup()
9365                  */
9366                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9367                        range_within(rold, rcur) &&
9368                        tnum_in(rold->var_off, rcur->var_off);
9369         case PTR_TO_MAP_VALUE_OR_NULL:
9370                 /* a PTR_TO_MAP_VALUE could be safe to use as a
9371                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9372                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9373                  * checked, doing so could have affected others with the same
9374                  * id, and we can't check for that because we lost the id when
9375                  * we converted to a PTR_TO_MAP_VALUE.
9376                  */
9377                 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9378                         return false;
9379                 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9380                         return false;
9381                 /* Check our ids match any regs they're supposed to */
9382                 return check_ids(rold->id, rcur->id, idmap);
9383         case PTR_TO_PACKET_META:
9384         case PTR_TO_PACKET:
9385                 if (rcur->type != rold->type)
9386                         return false;
9387                 /* We must have at least as much range as the old ptr
9388                  * did, so that any accesses which were safe before are
9389                  * still safe.  This is true even if old range < old off,
9390                  * since someone could have accessed through (ptr - k), or
9391                  * even done ptr -= k in a register, to get a safe access.
9392                  */
9393                 if (rold->range > rcur->range)
9394                         return false;
9395                 /* If the offsets don't match, we can't trust our alignment;
9396                  * nor can we be sure that we won't fall out of range.
9397                  */
9398                 if (rold->off != rcur->off)
9399                         return false;
9400                 /* id relations must be preserved */
9401                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9402                         return false;
9403                 /* new val must satisfy old val knowledge */
9404                 return range_within(rold, rcur) &&
9405                        tnum_in(rold->var_off, rcur->var_off);
9406         case PTR_TO_CTX:
9407         case CONST_PTR_TO_MAP:
9408         case PTR_TO_PACKET_END:
9409         case PTR_TO_FLOW_KEYS:
9410         case PTR_TO_SOCKET:
9411         case PTR_TO_SOCKET_OR_NULL:
9412         case PTR_TO_SOCK_COMMON:
9413         case PTR_TO_SOCK_COMMON_OR_NULL:
9414         case PTR_TO_TCP_SOCK:
9415         case PTR_TO_TCP_SOCK_OR_NULL:
9416         case PTR_TO_XDP_SOCK:
9417                 /* Only valid matches are exact, which memcmp() above
9418                  * would have accepted
9419                  */
9420         default:
9421                 /* Don't know what's going on, just say it's not safe */
9422                 return false;
9423         }
9424
9425         /* Shouldn't get here; if we do, say it's not safe */
9426         WARN_ON_ONCE(1);
9427         return false;
9428 }
9429
9430 static bool stacksafe(struct bpf_func_state *old,
9431                       struct bpf_func_state *cur,
9432                       struct idpair *idmap)
9433 {
9434         int i, spi;
9435
9436         /* walk slots of the explored stack and ignore any additional
9437          * slots in the current stack, since explored(safe) state
9438          * didn't use them
9439          */
9440         for (i = 0; i < old->allocated_stack; i++) {
9441                 spi = i / BPF_REG_SIZE;
9442
9443                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9444                         i += BPF_REG_SIZE - 1;
9445                         /* explored state didn't use this */
9446                         continue;
9447                 }
9448
9449                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9450                         continue;
9451
9452                 /* explored stack has more populated slots than current stack
9453                  * and these slots were used
9454                  */
9455                 if (i >= cur->allocated_stack)
9456                         return false;
9457
9458                 /* if old state was safe with misc data in the stack
9459                  * it will be safe with zero-initialized stack.
9460                  * The opposite is not true
9461                  */
9462                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9463                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9464                         continue;
9465                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9466                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9467                         /* Ex: old explored (safe) state has STACK_SPILL in
9468                          * this stack slot, but current has STACK_MISC ->
9469                          * this verifier states are not equivalent,
9470                          * return false to continue verification of this path
9471                          */
9472                         return false;
9473                 if (i % BPF_REG_SIZE)
9474                         continue;
9475                 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9476                         continue;
9477                 if (!regsafe(&old->stack[spi].spilled_ptr,
9478                              &cur->stack[spi].spilled_ptr,
9479                              idmap))
9480                         /* when explored and current stack slot are both storing
9481                          * spilled registers, check that stored pointers types
9482                          * are the same as well.
9483                          * Ex: explored safe path could have stored
9484                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9485                          * but current path has stored:
9486                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9487                          * such verifier states are not equivalent.
9488                          * return false to continue verification of this path
9489                          */
9490                         return false;
9491         }
9492         return true;
9493 }
9494
9495 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9496 {
9497         if (old->acquired_refs != cur->acquired_refs)
9498                 return false;
9499         return !memcmp(old->refs, cur->refs,
9500                        sizeof(*old->refs) * old->acquired_refs);
9501 }
9502
9503 /* compare two verifier states
9504  *
9505  * all states stored in state_list are known to be valid, since
9506  * verifier reached 'bpf_exit' instruction through them
9507  *
9508  * this function is called when verifier exploring different branches of
9509  * execution popped from the state stack. If it sees an old state that has
9510  * more strict register state and more strict stack state then this execution
9511  * branch doesn't need to be explored further, since verifier already
9512  * concluded that more strict state leads to valid finish.
9513  *
9514  * Therefore two states are equivalent if register state is more conservative
9515  * and explored stack state is more conservative than the current one.
9516  * Example:
9517  *       explored                   current
9518  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9519  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9520  *
9521  * In other words if current stack state (one being explored) has more
9522  * valid slots than old one that already passed validation, it means
9523  * the verifier can stop exploring and conclude that current state is valid too
9524  *
9525  * Similarly with registers. If explored state has register type as invalid
9526  * whereas register type in current state is meaningful, it means that
9527  * the current state will reach 'bpf_exit' instruction safely
9528  */
9529 static bool func_states_equal(struct bpf_func_state *old,
9530                               struct bpf_func_state *cur)
9531 {
9532         struct idpair *idmap;
9533         bool ret = false;
9534         int i;
9535
9536         idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9537         /* If we failed to allocate the idmap, just say it's not safe */
9538         if (!idmap)
9539                 return false;
9540
9541         for (i = 0; i < MAX_BPF_REG; i++) {
9542                 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
9543                         goto out_free;
9544         }
9545
9546         if (!stacksafe(old, cur, idmap))
9547                 goto out_free;
9548
9549         if (!refsafe(old, cur))
9550                 goto out_free;
9551         ret = true;
9552 out_free:
9553         kfree(idmap);
9554         return ret;
9555 }
9556
9557 static bool states_equal(struct bpf_verifier_env *env,
9558                          struct bpf_verifier_state *old,
9559                          struct bpf_verifier_state *cur)
9560 {
9561         int i;
9562
9563         if (old->curframe != cur->curframe)
9564                 return false;
9565
9566         /* Verification state from speculative execution simulation
9567          * must never prune a non-speculative execution one.
9568          */
9569         if (old->speculative && !cur->speculative)
9570                 return false;
9571
9572         if (old->active_spin_lock != cur->active_spin_lock)
9573                 return false;
9574
9575         /* for states to be equal callsites have to be the same
9576          * and all frame states need to be equivalent
9577          */
9578         for (i = 0; i <= old->curframe; i++) {
9579                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9580                         return false;
9581                 if (!func_states_equal(old->frame[i], cur->frame[i]))
9582                         return false;
9583         }
9584         return true;
9585 }
9586
9587 /* Return 0 if no propagation happened. Return negative error code if error
9588  * happened. Otherwise, return the propagated bit.
9589  */
9590 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9591                                   struct bpf_reg_state *reg,
9592                                   struct bpf_reg_state *parent_reg)
9593 {
9594         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9595         u8 flag = reg->live & REG_LIVE_READ;
9596         int err;
9597
9598         /* When comes here, read flags of PARENT_REG or REG could be any of
9599          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9600          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9601          */
9602         if (parent_flag == REG_LIVE_READ64 ||
9603             /* Or if there is no read flag from REG. */
9604             !flag ||
9605             /* Or if the read flag from REG is the same as PARENT_REG. */
9606             parent_flag == flag)
9607                 return 0;
9608
9609         err = mark_reg_read(env, reg, parent_reg, flag);
9610         if (err)
9611                 return err;
9612
9613         return flag;
9614 }
9615
9616 /* A write screens off any subsequent reads; but write marks come from the
9617  * straight-line code between a state and its parent.  When we arrive at an
9618  * equivalent state (jump target or such) we didn't arrive by the straight-line
9619  * code, so read marks in the state must propagate to the parent regardless
9620  * of the state's write marks. That's what 'parent == state->parent' comparison
9621  * in mark_reg_read() is for.
9622  */
9623 static int propagate_liveness(struct bpf_verifier_env *env,
9624                               const struct bpf_verifier_state *vstate,
9625                               struct bpf_verifier_state *vparent)
9626 {
9627         struct bpf_reg_state *state_reg, *parent_reg;
9628         struct bpf_func_state *state, *parent;
9629         int i, frame, err = 0;
9630
9631         if (vparent->curframe != vstate->curframe) {
9632                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9633                      vparent->curframe, vstate->curframe);
9634                 return -EFAULT;
9635         }
9636         /* Propagate read liveness of registers... */
9637         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9638         for (frame = 0; frame <= vstate->curframe; frame++) {
9639                 parent = vparent->frame[frame];
9640                 state = vstate->frame[frame];
9641                 parent_reg = parent->regs;
9642                 state_reg = state->regs;
9643                 /* We don't need to worry about FP liveness, it's read-only */
9644                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9645                         err = propagate_liveness_reg(env, &state_reg[i],
9646                                                      &parent_reg[i]);
9647                         if (err < 0)
9648                                 return err;
9649                         if (err == REG_LIVE_READ64)
9650                                 mark_insn_zext(env, &parent_reg[i]);
9651                 }
9652
9653                 /* Propagate stack slots. */
9654                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9655                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9656                         parent_reg = &parent->stack[i].spilled_ptr;
9657                         state_reg = &state->stack[i].spilled_ptr;
9658                         err = propagate_liveness_reg(env, state_reg,
9659                                                      parent_reg);
9660                         if (err < 0)
9661                                 return err;
9662                 }
9663         }
9664         return 0;
9665 }
9666
9667 /* find precise scalars in the previous equivalent state and
9668  * propagate them into the current state
9669  */
9670 static int propagate_precision(struct bpf_verifier_env *env,
9671                                const struct bpf_verifier_state *old)
9672 {
9673         struct bpf_reg_state *state_reg;
9674         struct bpf_func_state *state;
9675         int i, err = 0;
9676
9677         state = old->frame[old->curframe];
9678         state_reg = state->regs;
9679         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9680                 if (state_reg->type != SCALAR_VALUE ||
9681                     !state_reg->precise)
9682                         continue;
9683                 if (env->log.level & BPF_LOG_LEVEL2)
9684                         verbose(env, "propagating r%d\n", i);
9685                 err = mark_chain_precision(env, i);
9686                 if (err < 0)
9687                         return err;
9688         }
9689
9690         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9691                 if (state->stack[i].slot_type[0] != STACK_SPILL)
9692                         continue;
9693                 state_reg = &state->stack[i].spilled_ptr;
9694                 if (state_reg->type != SCALAR_VALUE ||
9695                     !state_reg->precise)
9696                         continue;
9697                 if (env->log.level & BPF_LOG_LEVEL2)
9698                         verbose(env, "propagating fp%d\n",
9699                                 (-i - 1) * BPF_REG_SIZE);
9700                 err = mark_chain_precision_stack(env, i);
9701                 if (err < 0)
9702                         return err;
9703         }
9704         return 0;
9705 }
9706
9707 static bool states_maybe_looping(struct bpf_verifier_state *old,
9708                                  struct bpf_verifier_state *cur)
9709 {
9710         struct bpf_func_state *fold, *fcur;
9711         int i, fr = cur->curframe;
9712
9713         if (old->curframe != fr)
9714                 return false;
9715
9716         fold = old->frame[fr];
9717         fcur = cur->frame[fr];
9718         for (i = 0; i < MAX_BPF_REG; i++)
9719                 if (memcmp(&fold->regs[i], &fcur->regs[i],
9720                            offsetof(struct bpf_reg_state, parent)))
9721                         return false;
9722         return true;
9723 }
9724
9725
9726 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9727 {
9728         struct bpf_verifier_state_list *new_sl;
9729         struct bpf_verifier_state_list *sl, **pprev;
9730         struct bpf_verifier_state *cur = env->cur_state, *new;
9731         int i, j, err, states_cnt = 0;
9732         bool add_new_state = env->test_state_freq ? true : false;
9733
9734         cur->last_insn_idx = env->prev_insn_idx;
9735         if (!env->insn_aux_data[insn_idx].prune_point)
9736                 /* this 'insn_idx' instruction wasn't marked, so we will not
9737                  * be doing state search here
9738                  */
9739                 return 0;
9740
9741         /* bpf progs typically have pruning point every 4 instructions
9742          * http://vger.kernel.org/bpfconf2019.html#session-1
9743          * Do not add new state for future pruning if the verifier hasn't seen
9744          * at least 2 jumps and at least 8 instructions.
9745          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9746          * In tests that amounts to up to 50% reduction into total verifier
9747          * memory consumption and 20% verifier time speedup.
9748          */
9749         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9750             env->insn_processed - env->prev_insn_processed >= 8)
9751                 add_new_state = true;
9752
9753         pprev = explored_state(env, insn_idx);
9754         sl = *pprev;
9755
9756         clean_live_states(env, insn_idx, cur);
9757
9758         while (sl) {
9759                 states_cnt++;
9760                 if (sl->state.insn_idx != insn_idx)
9761                         goto next;
9762                 if (sl->state.branches) {
9763                         if (states_maybe_looping(&sl->state, cur) &&
9764                             states_equal(env, &sl->state, cur)) {
9765                                 verbose_linfo(env, insn_idx, "; ");
9766                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9767                                 return -EINVAL;
9768                         }
9769                         /* if the verifier is processing a loop, avoid adding new state
9770                          * too often, since different loop iterations have distinct
9771                          * states and may not help future pruning.
9772                          * This threshold shouldn't be too low to make sure that
9773                          * a loop with large bound will be rejected quickly.
9774                          * The most abusive loop will be:
9775                          * r1 += 1
9776                          * if r1 < 1000000 goto pc-2
9777                          * 1M insn_procssed limit / 100 == 10k peak states.
9778                          * This threshold shouldn't be too high either, since states
9779                          * at the end of the loop are likely to be useful in pruning.
9780                          */
9781                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9782                             env->insn_processed - env->prev_insn_processed < 100)
9783                                 add_new_state = false;
9784                         goto miss;
9785                 }
9786                 if (states_equal(env, &sl->state, cur)) {
9787                         sl->hit_cnt++;
9788                         /* reached equivalent register/stack state,
9789                          * prune the search.
9790                          * Registers read by the continuation are read by us.
9791                          * If we have any write marks in env->cur_state, they
9792                          * will prevent corresponding reads in the continuation
9793                          * from reaching our parent (an explored_state).  Our
9794                          * own state will get the read marks recorded, but
9795                          * they'll be immediately forgotten as we're pruning
9796                          * this state and will pop a new one.
9797                          */
9798                         err = propagate_liveness(env, &sl->state, cur);
9799
9800                         /* if previous state reached the exit with precision and
9801                          * current state is equivalent to it (except precsion marks)
9802                          * the precision needs to be propagated back in
9803                          * the current state.
9804                          */
9805                         err = err ? : push_jmp_history(env, cur);
9806                         err = err ? : propagate_precision(env, &sl->state);
9807                         if (err)
9808                                 return err;
9809                         return 1;
9810                 }
9811 miss:
9812                 /* when new state is not going to be added do not increase miss count.
9813                  * Otherwise several loop iterations will remove the state
9814                  * recorded earlier. The goal of these heuristics is to have
9815                  * states from some iterations of the loop (some in the beginning
9816                  * and some at the end) to help pruning.
9817                  */
9818                 if (add_new_state)
9819                         sl->miss_cnt++;
9820                 /* heuristic to determine whether this state is beneficial
9821                  * to keep checking from state equivalence point of view.
9822                  * Higher numbers increase max_states_per_insn and verification time,
9823                  * but do not meaningfully decrease insn_processed.
9824                  */
9825                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9826                         /* the state is unlikely to be useful. Remove it to
9827                          * speed up verification
9828                          */
9829                         *pprev = sl->next;
9830                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9831                                 u32 br = sl->state.branches;
9832
9833                                 WARN_ONCE(br,
9834                                           "BUG live_done but branches_to_explore %d\n",
9835                                           br);
9836                                 free_verifier_state(&sl->state, false);
9837                                 kfree(sl);
9838                                 env->peak_states--;
9839                         } else {
9840                                 /* cannot free this state, since parentage chain may
9841                                  * walk it later. Add it for free_list instead to
9842                                  * be freed at the end of verification
9843                                  */
9844                                 sl->next = env->free_list;
9845                                 env->free_list = sl;
9846                         }
9847                         sl = *pprev;
9848                         continue;
9849                 }
9850 next:
9851                 pprev = &sl->next;
9852                 sl = *pprev;
9853         }
9854
9855         if (env->max_states_per_insn < states_cnt)
9856                 env->max_states_per_insn = states_cnt;
9857
9858         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9859                 return push_jmp_history(env, cur);
9860
9861         if (!add_new_state)
9862                 return push_jmp_history(env, cur);
9863
9864         /* There were no equivalent states, remember the current one.
9865          * Technically the current state is not proven to be safe yet,
9866          * but it will either reach outer most bpf_exit (which means it's safe)
9867          * or it will be rejected. When there are no loops the verifier won't be
9868          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9869          * again on the way to bpf_exit.
9870          * When looping the sl->state.branches will be > 0 and this state
9871          * will not be considered for equivalence until branches == 0.
9872          */
9873         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9874         if (!new_sl)
9875                 return -ENOMEM;
9876         env->total_states++;
9877         env->peak_states++;
9878         env->prev_jmps_processed = env->jmps_processed;
9879         env->prev_insn_processed = env->insn_processed;
9880
9881         /* add new state to the head of linked list */
9882         new = &new_sl->state;
9883         err = copy_verifier_state(new, cur);
9884         if (err) {
9885                 free_verifier_state(new, false);
9886                 kfree(new_sl);
9887                 return err;
9888         }
9889         new->insn_idx = insn_idx;
9890         WARN_ONCE(new->branches != 1,
9891                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9892
9893         cur->parent = new;
9894         cur->first_insn_idx = insn_idx;
9895         clear_jmp_history(cur);
9896         new_sl->next = *explored_state(env, insn_idx);
9897         *explored_state(env, insn_idx) = new_sl;
9898         /* connect new state to parentage chain. Current frame needs all
9899          * registers connected. Only r6 - r9 of the callers are alive (pushed
9900          * to the stack implicitly by JITs) so in callers' frames connect just
9901          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9902          * the state of the call instruction (with WRITTEN set), and r0 comes
9903          * from callee with its full parentage chain, anyway.
9904          */
9905         /* clear write marks in current state: the writes we did are not writes
9906          * our child did, so they don't screen off its reads from us.
9907          * (There are no read marks in current state, because reads always mark
9908          * their parent and current state never has children yet.  Only
9909          * explored_states can get read marks.)
9910          */
9911         for (j = 0; j <= cur->curframe; j++) {
9912                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9913                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9914                 for (i = 0; i < BPF_REG_FP; i++)
9915                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9916         }
9917
9918         /* all stack frames are accessible from callee, clear them all */
9919         for (j = 0; j <= cur->curframe; j++) {
9920                 struct bpf_func_state *frame = cur->frame[j];
9921                 struct bpf_func_state *newframe = new->frame[j];
9922
9923                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
9924                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
9925                         frame->stack[i].spilled_ptr.parent =
9926                                                 &newframe->stack[i].spilled_ptr;
9927                 }
9928         }
9929         return 0;
9930 }
9931
9932 /* Return true if it's OK to have the same insn return a different type. */
9933 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9934 {
9935         switch (type) {
9936         case PTR_TO_CTX:
9937         case PTR_TO_SOCKET:
9938         case PTR_TO_SOCKET_OR_NULL:
9939         case PTR_TO_SOCK_COMMON:
9940         case PTR_TO_SOCK_COMMON_OR_NULL:
9941         case PTR_TO_TCP_SOCK:
9942         case PTR_TO_TCP_SOCK_OR_NULL:
9943         case PTR_TO_XDP_SOCK:
9944         case PTR_TO_BTF_ID:
9945         case PTR_TO_BTF_ID_OR_NULL:
9946                 return false;
9947         default:
9948                 return true;
9949         }
9950 }
9951
9952 /* If an instruction was previously used with particular pointer types, then we
9953  * need to be careful to avoid cases such as the below, where it may be ok
9954  * for one branch accessing the pointer, but not ok for the other branch:
9955  *
9956  * R1 = sock_ptr
9957  * goto X;
9958  * ...
9959  * R1 = some_other_valid_ptr;
9960  * goto X;
9961  * ...
9962  * R2 = *(u32 *)(R1 + 0);
9963  */
9964 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9965 {
9966         return src != prev && (!reg_type_mismatch_ok(src) ||
9967                                !reg_type_mismatch_ok(prev));
9968 }
9969
9970 static int do_check(struct bpf_verifier_env *env)
9971 {
9972         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
9973         struct bpf_verifier_state *state = env->cur_state;
9974         struct bpf_insn *insns = env->prog->insnsi;
9975         struct bpf_reg_state *regs;
9976         int insn_cnt = env->prog->len;
9977         bool do_print_state = false;
9978         int prev_insn_idx = -1;
9979
9980         for (;;) {
9981                 struct bpf_insn *insn;
9982                 u8 class;
9983                 int err;
9984
9985                 env->prev_insn_idx = prev_insn_idx;
9986                 if (env->insn_idx >= insn_cnt) {
9987                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
9988                                 env->insn_idx, insn_cnt);
9989                         return -EFAULT;
9990                 }
9991
9992                 insn = &insns[env->insn_idx];
9993                 class = BPF_CLASS(insn->code);
9994
9995                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
9996                         verbose(env,
9997                                 "BPF program is too large. Processed %d insn\n",
9998                                 env->insn_processed);
9999                         return -E2BIG;
10000                 }
10001
10002                 err = is_state_visited(env, env->insn_idx);
10003                 if (err < 0)
10004                         return err;
10005                 if (err == 1) {
10006                         /* found equivalent state, can prune the search */
10007                         if (env->log.level & BPF_LOG_LEVEL) {
10008                                 if (do_print_state)
10009                                         verbose(env, "\nfrom %d to %d%s: safe\n",
10010                                                 env->prev_insn_idx, env->insn_idx,
10011                                                 env->cur_state->speculative ?
10012                                                 " (speculative execution)" : "");
10013                                 else
10014                                         verbose(env, "%d: safe\n", env->insn_idx);
10015                         }
10016                         goto process_bpf_exit;
10017                 }
10018
10019                 if (signal_pending(current))
10020                         return -EAGAIN;
10021
10022                 if (need_resched())
10023                         cond_resched();
10024
10025                 if (env->log.level & BPF_LOG_LEVEL2 ||
10026                     (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10027                         if (env->log.level & BPF_LOG_LEVEL2)
10028                                 verbose(env, "%d:", env->insn_idx);
10029                         else
10030                                 verbose(env, "\nfrom %d to %d%s:",
10031                                         env->prev_insn_idx, env->insn_idx,
10032                                         env->cur_state->speculative ?
10033                                         " (speculative execution)" : "");
10034                         print_verifier_state(env, state->frame[state->curframe]);
10035                         do_print_state = false;
10036                 }
10037
10038                 if (env->log.level & BPF_LOG_LEVEL) {
10039                         const struct bpf_insn_cbs cbs = {
10040                                 .cb_print       = verbose,
10041                                 .private_data   = env,
10042                         };
10043
10044                         verbose_linfo(env, env->insn_idx, "; ");
10045                         verbose(env, "%d: ", env->insn_idx);
10046                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10047                 }
10048
10049                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10050                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10051                                                            env->prev_insn_idx);
10052                         if (err)
10053                                 return err;
10054                 }
10055
10056                 regs = cur_regs(env);
10057                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10058                 prev_insn_idx = env->insn_idx;
10059
10060                 if (class == BPF_ALU || class == BPF_ALU64) {
10061                         err = check_alu_op(env, insn);
10062                         if (err)
10063                                 return err;
10064
10065                 } else if (class == BPF_LDX) {
10066                         enum bpf_reg_type *prev_src_type, src_reg_type;
10067
10068                         /* check for reserved fields is already done */
10069
10070                         /* check src operand */
10071                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10072                         if (err)
10073                                 return err;
10074
10075                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10076                         if (err)
10077                                 return err;
10078
10079                         src_reg_type = regs[insn->src_reg].type;
10080
10081                         /* check that memory (src_reg + off) is readable,
10082                          * the state of dst_reg will be updated by this func
10083                          */
10084                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
10085                                                insn->off, BPF_SIZE(insn->code),
10086                                                BPF_READ, insn->dst_reg, false);
10087                         if (err)
10088                                 return err;
10089
10090                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10091
10092                         if (*prev_src_type == NOT_INIT) {
10093                                 /* saw a valid insn
10094                                  * dst_reg = *(u32 *)(src_reg + off)
10095                                  * save type to validate intersecting paths
10096                                  */
10097                                 *prev_src_type = src_reg_type;
10098
10099                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10100                                 /* ABuser program is trying to use the same insn
10101                                  * dst_reg = *(u32*) (src_reg + off)
10102                                  * with different pointer types:
10103                                  * src_reg == ctx in one branch and
10104                                  * src_reg == stack|map in some other branch.
10105                                  * Reject it.
10106                                  */
10107                                 verbose(env, "same insn cannot be used with different pointers\n");
10108                                 return -EINVAL;
10109                         }
10110
10111                 } else if (class == BPF_STX) {
10112                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
10113
10114                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10115                                 err = check_atomic(env, env->insn_idx, insn);
10116                                 if (err)
10117                                         return err;
10118                                 env->insn_idx++;
10119                                 continue;
10120                         }
10121
10122                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10123                                 verbose(env, "BPF_STX uses reserved fields\n");
10124                                 return -EINVAL;
10125                         }
10126
10127                         /* check src1 operand */
10128                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10129                         if (err)
10130                                 return err;
10131                         /* check src2 operand */
10132                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10133                         if (err)
10134                                 return err;
10135
10136                         dst_reg_type = regs[insn->dst_reg].type;
10137
10138                         /* check that memory (dst_reg + off) is writeable */
10139                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10140                                                insn->off, BPF_SIZE(insn->code),
10141                                                BPF_WRITE, insn->src_reg, false);
10142                         if (err)
10143                                 return err;
10144
10145                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10146
10147                         if (*prev_dst_type == NOT_INIT) {
10148                                 *prev_dst_type = dst_reg_type;
10149                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10150                                 verbose(env, "same insn cannot be used with different pointers\n");
10151                                 return -EINVAL;
10152                         }
10153
10154                 } else if (class == BPF_ST) {
10155                         if (BPF_MODE(insn->code) != BPF_MEM ||
10156                             insn->src_reg != BPF_REG_0) {
10157                                 verbose(env, "BPF_ST uses reserved fields\n");
10158                                 return -EINVAL;
10159                         }
10160                         /* check src operand */
10161                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10162                         if (err)
10163                                 return err;
10164
10165                         if (is_ctx_reg(env, insn->dst_reg)) {
10166                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10167                                         insn->dst_reg,
10168                                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
10169                                 return -EACCES;
10170                         }
10171
10172                         /* check that memory (dst_reg + off) is writeable */
10173                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10174                                                insn->off, BPF_SIZE(insn->code),
10175                                                BPF_WRITE, -1, false);
10176                         if (err)
10177                                 return err;
10178
10179                 } else if (class == BPF_JMP || class == BPF_JMP32) {
10180                         u8 opcode = BPF_OP(insn->code);
10181
10182                         env->jmps_processed++;
10183                         if (opcode == BPF_CALL) {
10184                                 if (BPF_SRC(insn->code) != BPF_K ||
10185                                     insn->off != 0 ||
10186                                     (insn->src_reg != BPF_REG_0 &&
10187                                      insn->src_reg != BPF_PSEUDO_CALL) ||
10188                                     insn->dst_reg != BPF_REG_0 ||
10189                                     class == BPF_JMP32) {
10190                                         verbose(env, "BPF_CALL uses reserved fields\n");
10191                                         return -EINVAL;
10192                                 }
10193
10194                                 if (env->cur_state->active_spin_lock &&
10195                                     (insn->src_reg == BPF_PSEUDO_CALL ||
10196                                      insn->imm != BPF_FUNC_spin_unlock)) {
10197                                         verbose(env, "function calls are not allowed while holding a lock\n");
10198                                         return -EINVAL;
10199                                 }
10200                                 if (insn->src_reg == BPF_PSEUDO_CALL)
10201                                         err = check_func_call(env, insn, &env->insn_idx);
10202                                 else
10203                                         err = check_helper_call(env, insn->imm, env->insn_idx);
10204                                 if (err)
10205                                         return err;
10206
10207                         } else if (opcode == BPF_JA) {
10208                                 if (BPF_SRC(insn->code) != BPF_K ||
10209                                     insn->imm != 0 ||
10210                                     insn->src_reg != BPF_REG_0 ||
10211                                     insn->dst_reg != BPF_REG_0 ||
10212                                     class == BPF_JMP32) {
10213                                         verbose(env, "BPF_JA uses reserved fields\n");
10214                                         return -EINVAL;
10215                                 }
10216
10217                                 env->insn_idx += insn->off + 1;
10218                                 continue;
10219
10220                         } else if (opcode == BPF_EXIT) {
10221                                 if (BPF_SRC(insn->code) != BPF_K ||
10222                                     insn->imm != 0 ||
10223                                     insn->src_reg != BPF_REG_0 ||
10224                                     insn->dst_reg != BPF_REG_0 ||
10225                                     class == BPF_JMP32) {
10226                                         verbose(env, "BPF_EXIT uses reserved fields\n");
10227                                         return -EINVAL;
10228                                 }
10229
10230                                 if (env->cur_state->active_spin_lock) {
10231                                         verbose(env, "bpf_spin_unlock is missing\n");
10232                                         return -EINVAL;
10233                                 }
10234
10235                                 if (state->curframe) {
10236                                         /* exit from nested function */
10237                                         err = prepare_func_exit(env, &env->insn_idx);
10238                                         if (err)
10239                                                 return err;
10240                                         do_print_state = true;
10241                                         continue;
10242                                 }
10243
10244                                 err = check_reference_leak(env);
10245                                 if (err)
10246                                         return err;
10247
10248                                 err = check_return_code(env);
10249                                 if (err)
10250                                         return err;
10251 process_bpf_exit:
10252                                 update_branch_counts(env, env->cur_state);
10253                                 err = pop_stack(env, &prev_insn_idx,
10254                                                 &env->insn_idx, pop_log);
10255                                 if (err < 0) {
10256                                         if (err != -ENOENT)
10257                                                 return err;
10258                                         break;
10259                                 } else {
10260                                         do_print_state = true;
10261                                         continue;
10262                                 }
10263                         } else {
10264                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
10265                                 if (err)
10266                                         return err;
10267                         }
10268                 } else if (class == BPF_LD) {
10269                         u8 mode = BPF_MODE(insn->code);
10270
10271                         if (mode == BPF_ABS || mode == BPF_IND) {
10272                                 err = check_ld_abs(env, insn);
10273                                 if (err)
10274                                         return err;
10275
10276                         } else if (mode == BPF_IMM) {
10277                                 err = check_ld_imm(env, insn);
10278                                 if (err)
10279                                         return err;
10280
10281                                 env->insn_idx++;
10282                                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10283                         } else {
10284                                 verbose(env, "invalid BPF_LD mode\n");
10285                                 return -EINVAL;
10286                         }
10287                 } else {
10288                         verbose(env, "unknown insn class %d\n", class);
10289                         return -EINVAL;
10290                 }
10291
10292                 env->insn_idx++;
10293         }
10294
10295         return 0;
10296 }
10297
10298 static int find_btf_percpu_datasec(struct btf *btf)
10299 {
10300         const struct btf_type *t;
10301         const char *tname;
10302         int i, n;
10303
10304         /*
10305          * Both vmlinux and module each have their own ".data..percpu"
10306          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10307          * types to look at only module's own BTF types.
10308          */
10309         n = btf_nr_types(btf);
10310         if (btf_is_module(btf))
10311                 i = btf_nr_types(btf_vmlinux);
10312         else
10313                 i = 1;
10314
10315         for(; i < n; i++) {
10316                 t = btf_type_by_id(btf, i);
10317                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10318                         continue;
10319
10320                 tname = btf_name_by_offset(btf, t->name_off);
10321                 if (!strcmp(tname, ".data..percpu"))
10322                         return i;
10323         }
10324
10325         return -ENOENT;
10326 }
10327
10328 /* replace pseudo btf_id with kernel symbol address */
10329 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10330                                struct bpf_insn *insn,
10331                                struct bpf_insn_aux_data *aux)
10332 {
10333         const struct btf_var_secinfo *vsi;
10334         const struct btf_type *datasec;
10335         struct btf_mod_pair *btf_mod;
10336         const struct btf_type *t;
10337         const char *sym_name;
10338         bool percpu = false;
10339         u32 type, id = insn->imm;
10340         struct btf *btf;
10341         s32 datasec_id;
10342         u64 addr;
10343         int i, btf_fd, err;
10344
10345         btf_fd = insn[1].imm;
10346         if (btf_fd) {
10347                 btf = btf_get_by_fd(btf_fd);
10348                 if (IS_ERR(btf)) {
10349                         verbose(env, "invalid module BTF object FD specified.\n");
10350                         return -EINVAL;
10351                 }
10352         } else {
10353                 if (!btf_vmlinux) {
10354                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10355                         return -EINVAL;
10356                 }
10357                 btf = btf_vmlinux;
10358                 btf_get(btf);
10359         }
10360
10361         t = btf_type_by_id(btf, id);
10362         if (!t) {
10363                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10364                 err = -ENOENT;
10365                 goto err_put;
10366         }
10367
10368         if (!btf_type_is_var(t)) {
10369                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10370                 err = -EINVAL;
10371                 goto err_put;
10372         }
10373
10374         sym_name = btf_name_by_offset(btf, t->name_off);
10375         addr = kallsyms_lookup_name(sym_name);
10376         if (!addr) {
10377                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10378                         sym_name);
10379                 err = -ENOENT;
10380                 goto err_put;
10381         }
10382
10383         datasec_id = find_btf_percpu_datasec(btf);
10384         if (datasec_id > 0) {
10385                 datasec = btf_type_by_id(btf, datasec_id);
10386                 for_each_vsi(i, datasec, vsi) {
10387                         if (vsi->type == id) {
10388                                 percpu = true;
10389                                 break;
10390                         }
10391                 }
10392         }
10393
10394         insn[0].imm = (u32)addr;
10395         insn[1].imm = addr >> 32;
10396
10397         type = t->type;
10398         t = btf_type_skip_modifiers(btf, type, NULL);
10399         if (percpu) {
10400                 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10401                 aux->btf_var.btf = btf;
10402                 aux->btf_var.btf_id = type;
10403         } else if (!btf_type_is_struct(t)) {
10404                 const struct btf_type *ret;
10405                 const char *tname;
10406                 u32 tsize;
10407
10408                 /* resolve the type size of ksym. */
10409                 ret = btf_resolve_size(btf, t, &tsize);
10410                 if (IS_ERR(ret)) {
10411                         tname = btf_name_by_offset(btf, t->name_off);
10412                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10413                                 tname, PTR_ERR(ret));
10414                         err = -EINVAL;
10415                         goto err_put;
10416                 }
10417                 aux->btf_var.reg_type = PTR_TO_MEM;
10418                 aux->btf_var.mem_size = tsize;
10419         } else {
10420                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
10421                 aux->btf_var.btf = btf;
10422                 aux->btf_var.btf_id = type;
10423         }
10424
10425         /* check whether we recorded this BTF (and maybe module) already */
10426         for (i = 0; i < env->used_btf_cnt; i++) {
10427                 if (env->used_btfs[i].btf == btf) {
10428                         btf_put(btf);
10429                         return 0;
10430                 }
10431         }
10432
10433         if (env->used_btf_cnt >= MAX_USED_BTFS) {
10434                 err = -E2BIG;
10435                 goto err_put;
10436         }
10437
10438         btf_mod = &env->used_btfs[env->used_btf_cnt];
10439         btf_mod->btf = btf;
10440         btf_mod->module = NULL;
10441
10442         /* if we reference variables from kernel module, bump its refcount */
10443         if (btf_is_module(btf)) {
10444                 btf_mod->module = btf_try_get_module(btf);
10445                 if (!btf_mod->module) {
10446                         err = -ENXIO;
10447                         goto err_put;
10448                 }
10449         }
10450
10451         env->used_btf_cnt++;
10452
10453         return 0;
10454 err_put:
10455         btf_put(btf);
10456         return err;
10457 }
10458
10459 static int check_map_prealloc(struct bpf_map *map)
10460 {
10461         return (map->map_type != BPF_MAP_TYPE_HASH &&
10462                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10463                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10464                 !(map->map_flags & BPF_F_NO_PREALLOC);
10465 }
10466
10467 static bool is_tracing_prog_type(enum bpf_prog_type type)
10468 {
10469         switch (type) {
10470         case BPF_PROG_TYPE_KPROBE:
10471         case BPF_PROG_TYPE_TRACEPOINT:
10472         case BPF_PROG_TYPE_PERF_EVENT:
10473         case BPF_PROG_TYPE_RAW_TRACEPOINT:
10474                 return true;
10475         default:
10476                 return false;
10477         }
10478 }
10479
10480 static bool is_preallocated_map(struct bpf_map *map)
10481 {
10482         if (!check_map_prealloc(map))
10483                 return false;
10484         if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10485                 return false;
10486         return true;
10487 }
10488
10489 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10490                                         struct bpf_map *map,
10491                                         struct bpf_prog *prog)
10492
10493 {
10494         enum bpf_prog_type prog_type = resolve_prog_type(prog);
10495         /*
10496          * Validate that trace type programs use preallocated hash maps.
10497          *
10498          * For programs attached to PERF events this is mandatory as the
10499          * perf NMI can hit any arbitrary code sequence.
10500          *
10501          * All other trace types using preallocated hash maps are unsafe as
10502          * well because tracepoint or kprobes can be inside locked regions
10503          * of the memory allocator or at a place where a recursion into the
10504          * memory allocator would see inconsistent state.
10505          *
10506          * On RT enabled kernels run-time allocation of all trace type
10507          * programs is strictly prohibited due to lock type constraints. On
10508          * !RT kernels it is allowed for backwards compatibility reasons for
10509          * now, but warnings are emitted so developers are made aware of
10510          * the unsafety and can fix their programs before this is enforced.
10511          */
10512         if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10513                 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10514                         verbose(env, "perf_event programs can only use preallocated hash map\n");
10515                         return -EINVAL;
10516                 }
10517                 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10518                         verbose(env, "trace type programs can only use preallocated hash map\n");
10519                         return -EINVAL;
10520                 }
10521                 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10522                 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10523         }
10524
10525         if (map_value_has_spin_lock(map)) {
10526                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10527                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10528                         return -EINVAL;
10529                 }
10530
10531                 if (is_tracing_prog_type(prog_type)) {
10532                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10533                         return -EINVAL;
10534                 }
10535
10536                 if (prog->aux->sleepable) {
10537                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10538                         return -EINVAL;
10539                 }
10540         }
10541
10542         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10543             !bpf_offload_prog_map_match(prog, map)) {
10544                 verbose(env, "offload device mismatch between prog and map\n");
10545                 return -EINVAL;
10546         }
10547
10548         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10549                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10550                 return -EINVAL;
10551         }
10552
10553         if (prog->aux->sleepable)
10554                 switch (map->map_type) {
10555                 case BPF_MAP_TYPE_HASH:
10556                 case BPF_MAP_TYPE_LRU_HASH:
10557                 case BPF_MAP_TYPE_ARRAY:
10558                 case BPF_MAP_TYPE_PERCPU_HASH:
10559                 case BPF_MAP_TYPE_PERCPU_ARRAY:
10560                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10561                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10562                 case BPF_MAP_TYPE_HASH_OF_MAPS:
10563                         if (!is_preallocated_map(map)) {
10564                                 verbose(env,
10565                                         "Sleepable programs can only use preallocated maps\n");
10566                                 return -EINVAL;
10567                         }
10568                         break;
10569                 case BPF_MAP_TYPE_RINGBUF:
10570                         break;
10571                 default:
10572                         verbose(env,
10573                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
10574                         return -EINVAL;
10575                 }
10576
10577         return 0;
10578 }
10579
10580 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10581 {
10582         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10583                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10584 }
10585
10586 /* find and rewrite pseudo imm in ld_imm64 instructions:
10587  *
10588  * 1. if it accesses map FD, replace it with actual map pointer.
10589  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10590  *
10591  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10592  */
10593 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10594 {
10595         struct bpf_insn *insn = env->prog->insnsi;
10596         int insn_cnt = env->prog->len;
10597         int i, j, err;
10598
10599         err = bpf_prog_calc_tag(env->prog);
10600         if (err)
10601                 return err;
10602
10603         for (i = 0; i < insn_cnt; i++, insn++) {
10604                 if (BPF_CLASS(insn->code) == BPF_LDX &&
10605                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10606                         verbose(env, "BPF_LDX uses reserved fields\n");
10607                         return -EINVAL;
10608                 }
10609
10610                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10611                         struct bpf_insn_aux_data *aux;
10612                         struct bpf_map *map;
10613                         struct fd f;
10614                         u64 addr;
10615
10616                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
10617                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10618                             insn[1].off != 0) {
10619                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
10620                                 return -EINVAL;
10621                         }
10622
10623                         if (insn[0].src_reg == 0)
10624                                 /* valid generic load 64-bit imm */
10625                                 goto next_insn;
10626
10627                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10628                                 aux = &env->insn_aux_data[i];
10629                                 err = check_pseudo_btf_id(env, insn, aux);
10630                                 if (err)
10631                                         return err;
10632                                 goto next_insn;
10633                         }
10634
10635                         /* In final convert_pseudo_ld_imm64() step, this is
10636                          * converted into regular 64-bit imm load insn.
10637                          */
10638                         if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10639                              insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10640                             (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10641                              insn[1].imm != 0)) {
10642                                 verbose(env,
10643                                         "unrecognized bpf_ld_imm64 insn\n");
10644                                 return -EINVAL;
10645                         }
10646
10647                         f = fdget(insn[0].imm);
10648                         map = __bpf_map_get(f);
10649                         if (IS_ERR(map)) {
10650                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
10651                                         insn[0].imm);
10652                                 return PTR_ERR(map);
10653                         }
10654
10655                         err = check_map_prog_compatibility(env, map, env->prog);
10656                         if (err) {
10657                                 fdput(f);
10658                                 return err;
10659                         }
10660
10661                         aux = &env->insn_aux_data[i];
10662                         if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10663                                 addr = (unsigned long)map;
10664                         } else {
10665                                 u32 off = insn[1].imm;
10666
10667                                 if (off >= BPF_MAX_VAR_OFF) {
10668                                         verbose(env, "direct value offset of %u is not allowed\n", off);
10669                                         fdput(f);
10670                                         return -EINVAL;
10671                                 }
10672
10673                                 if (!map->ops->map_direct_value_addr) {
10674                                         verbose(env, "no direct value access support for this map type\n");
10675                                         fdput(f);
10676                                         return -EINVAL;
10677                                 }
10678
10679                                 err = map->ops->map_direct_value_addr(map, &addr, off);
10680                                 if (err) {
10681                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10682                                                 map->value_size, off);
10683                                         fdput(f);
10684                                         return err;
10685                                 }
10686
10687                                 aux->map_off = off;
10688                                 addr += off;
10689                         }
10690
10691                         insn[0].imm = (u32)addr;
10692                         insn[1].imm = addr >> 32;
10693
10694                         /* check whether we recorded this map already */
10695                         for (j = 0; j < env->used_map_cnt; j++) {
10696                                 if (env->used_maps[j] == map) {
10697                                         aux->map_index = j;
10698                                         fdput(f);
10699                                         goto next_insn;
10700                                 }
10701                         }
10702
10703                         if (env->used_map_cnt >= MAX_USED_MAPS) {
10704                                 fdput(f);
10705                                 return -E2BIG;
10706                         }
10707
10708                         /* hold the map. If the program is rejected by verifier,
10709                          * the map will be released by release_maps() or it
10710                          * will be used by the valid program until it's unloaded
10711                          * and all maps are released in free_used_maps()
10712                          */
10713                         bpf_map_inc(map);
10714
10715                         aux->map_index = env->used_map_cnt;
10716                         env->used_maps[env->used_map_cnt++] = map;
10717
10718                         if (bpf_map_is_cgroup_storage(map) &&
10719                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
10720                                 verbose(env, "only one cgroup storage of each type is allowed\n");
10721                                 fdput(f);
10722                                 return -EBUSY;
10723                         }
10724
10725                         fdput(f);
10726 next_insn:
10727                         insn++;
10728                         i++;
10729                         continue;
10730                 }
10731
10732                 /* Basic sanity check before we invest more work here. */
10733                 if (!bpf_opcode_in_insntable(insn->code)) {
10734                         verbose(env, "unknown opcode %02x\n", insn->code);
10735                         return -EINVAL;
10736                 }
10737         }
10738
10739         /* now all pseudo BPF_LD_IMM64 instructions load valid
10740          * 'struct bpf_map *' into a register instead of user map_fd.
10741          * These pointers will be used later by verifier to validate map access.
10742          */
10743         return 0;
10744 }
10745
10746 /* drop refcnt of maps used by the rejected program */
10747 static void release_maps(struct bpf_verifier_env *env)
10748 {
10749         __bpf_free_used_maps(env->prog->aux, env->used_maps,
10750                              env->used_map_cnt);
10751 }
10752
10753 /* drop refcnt of maps used by the rejected program */
10754 static void release_btfs(struct bpf_verifier_env *env)
10755 {
10756         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
10757                              env->used_btf_cnt);
10758 }
10759
10760 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10761 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10762 {
10763         struct bpf_insn *insn = env->prog->insnsi;
10764         int insn_cnt = env->prog->len;
10765         int i;
10766
10767         for (i = 0; i < insn_cnt; i++, insn++)
10768                 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10769                         insn->src_reg = 0;
10770 }
10771
10772 /* single env->prog->insni[off] instruction was replaced with the range
10773  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
10774  * [0, off) and [off, end) to new locations, so the patched range stays zero
10775  */
10776 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10777                                 struct bpf_prog *new_prog, u32 off, u32 cnt)
10778 {
10779         struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
10780         struct bpf_insn *insn = new_prog->insnsi;
10781         u32 prog_len;
10782         int i;
10783
10784         /* aux info at OFF always needs adjustment, no matter fast path
10785          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10786          * original insn at old prog.
10787          */
10788         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10789
10790         if (cnt == 1)
10791                 return 0;
10792         prog_len = new_prog->len;
10793         new_data = vzalloc(array_size(prog_len,
10794                                       sizeof(struct bpf_insn_aux_data)));
10795         if (!new_data)
10796                 return -ENOMEM;
10797         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10798         memcpy(new_data + off + cnt - 1, old_data + off,
10799                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10800         for (i = off; i < off + cnt - 1; i++) {
10801                 new_data[i].seen = env->pass_cnt;
10802                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10803         }
10804         env->insn_aux_data = new_data;
10805         vfree(old_data);
10806         return 0;
10807 }
10808
10809 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10810 {
10811         int i;
10812
10813         if (len == 1)
10814                 return;
10815         /* NOTE: fake 'exit' subprog should be updated as well. */
10816         for (i = 0; i <= env->subprog_cnt; i++) {
10817                 if (env->subprog_info[i].start <= off)
10818                         continue;
10819                 env->subprog_info[i].start += len - 1;
10820         }
10821 }
10822
10823 static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10824 {
10825         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10826         int i, sz = prog->aux->size_poke_tab;
10827         struct bpf_jit_poke_descriptor *desc;
10828
10829         for (i = 0; i < sz; i++) {
10830                 desc = &tab[i];
10831                 desc->insn_idx += len - 1;
10832         }
10833 }
10834
10835 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10836                                             const struct bpf_insn *patch, u32 len)
10837 {
10838         struct bpf_prog *new_prog;
10839
10840         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10841         if (IS_ERR(new_prog)) {
10842                 if (PTR_ERR(new_prog) == -ERANGE)
10843                         verbose(env,
10844                                 "insn %d cannot be patched due to 16-bit range\n",
10845                                 env->insn_aux_data[off].orig_idx);
10846                 return NULL;
10847         }
10848         if (adjust_insn_aux_data(env, new_prog, off, len))
10849                 return NULL;
10850         adjust_subprog_starts(env, off, len);
10851         adjust_poke_descs(new_prog, len);
10852         return new_prog;
10853 }
10854
10855 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10856                                               u32 off, u32 cnt)
10857 {
10858         int i, j;
10859
10860         /* find first prog starting at or after off (first to remove) */
10861         for (i = 0; i < env->subprog_cnt; i++)
10862                 if (env->subprog_info[i].start >= off)
10863                         break;
10864         /* find first prog starting at or after off + cnt (first to stay) */
10865         for (j = i; j < env->subprog_cnt; j++)
10866                 if (env->subprog_info[j].start >= off + cnt)
10867                         break;
10868         /* if j doesn't start exactly at off + cnt, we are just removing
10869          * the front of previous prog
10870          */
10871         if (env->subprog_info[j].start != off + cnt)
10872                 j--;
10873
10874         if (j > i) {
10875                 struct bpf_prog_aux *aux = env->prog->aux;
10876                 int move;
10877
10878                 /* move fake 'exit' subprog as well */
10879                 move = env->subprog_cnt + 1 - j;
10880
10881                 memmove(env->subprog_info + i,
10882                         env->subprog_info + j,
10883                         sizeof(*env->subprog_info) * move);
10884                 env->subprog_cnt -= j - i;
10885
10886                 /* remove func_info */
10887                 if (aux->func_info) {
10888                         move = aux->func_info_cnt - j;
10889
10890                         memmove(aux->func_info + i,
10891                                 aux->func_info + j,
10892                                 sizeof(*aux->func_info) * move);
10893                         aux->func_info_cnt -= j - i;
10894                         /* func_info->insn_off is set after all code rewrites,
10895                          * in adjust_btf_func() - no need to adjust
10896                          */
10897                 }
10898         } else {
10899                 /* convert i from "first prog to remove" to "first to adjust" */
10900                 if (env->subprog_info[i].start == off)
10901                         i++;
10902         }
10903
10904         /* update fake 'exit' subprog as well */
10905         for (; i <= env->subprog_cnt; i++)
10906                 env->subprog_info[i].start -= cnt;
10907
10908         return 0;
10909 }
10910
10911 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10912                                       u32 cnt)
10913 {
10914         struct bpf_prog *prog = env->prog;
10915         u32 i, l_off, l_cnt, nr_linfo;
10916         struct bpf_line_info *linfo;
10917
10918         nr_linfo = prog->aux->nr_linfo;
10919         if (!nr_linfo)
10920                 return 0;
10921
10922         linfo = prog->aux->linfo;
10923
10924         /* find first line info to remove, count lines to be removed */
10925         for (i = 0; i < nr_linfo; i++)
10926                 if (linfo[i].insn_off >= off)
10927                         break;
10928
10929         l_off = i;
10930         l_cnt = 0;
10931         for (; i < nr_linfo; i++)
10932                 if (linfo[i].insn_off < off + cnt)
10933                         l_cnt++;
10934                 else
10935                         break;
10936
10937         /* First live insn doesn't match first live linfo, it needs to "inherit"
10938          * last removed linfo.  prog is already modified, so prog->len == off
10939          * means no live instructions after (tail of the program was removed).
10940          */
10941         if (prog->len != off && l_cnt &&
10942             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10943                 l_cnt--;
10944                 linfo[--i].insn_off = off + cnt;
10945         }
10946
10947         /* remove the line info which refer to the removed instructions */
10948         if (l_cnt) {
10949                 memmove(linfo + l_off, linfo + i,
10950                         sizeof(*linfo) * (nr_linfo - i));
10951
10952                 prog->aux->nr_linfo -= l_cnt;
10953                 nr_linfo = prog->aux->nr_linfo;
10954         }
10955
10956         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10957         for (i = l_off; i < nr_linfo; i++)
10958                 linfo[i].insn_off -= cnt;
10959
10960         /* fix up all subprogs (incl. 'exit') which start >= off */
10961         for (i = 0; i <= env->subprog_cnt; i++)
10962                 if (env->subprog_info[i].linfo_idx > l_off) {
10963                         /* program may have started in the removed region but
10964                          * may not be fully removed
10965                          */
10966                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10967                                 env->subprog_info[i].linfo_idx -= l_cnt;
10968                         else
10969                                 env->subprog_info[i].linfo_idx = l_off;
10970                 }
10971
10972         return 0;
10973 }
10974
10975 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10976 {
10977         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10978         unsigned int orig_prog_len = env->prog->len;
10979         int err;
10980
10981         if (bpf_prog_is_dev_bound(env->prog->aux))
10982                 bpf_prog_offload_remove_insns(env, off, cnt);
10983
10984         err = bpf_remove_insns(env->prog, off, cnt);
10985         if (err)
10986                 return err;
10987
10988         err = adjust_subprog_starts_after_remove(env, off, cnt);
10989         if (err)
10990                 return err;
10991
10992         err = bpf_adj_linfo_after_remove(env, off, cnt);
10993         if (err)
10994                 return err;
10995
10996         memmove(aux_data + off, aux_data + off + cnt,
10997                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10998
10999         return 0;
11000 }
11001
11002 /* The verifier does more data flow analysis than llvm and will not
11003  * explore branches that are dead at run time. Malicious programs can
11004  * have dead code too. Therefore replace all dead at-run-time code
11005  * with 'ja -1'.
11006  *
11007  * Just nops are not optimal, e.g. if they would sit at the end of the
11008  * program and through another bug we would manage to jump there, then
11009  * we'd execute beyond program memory otherwise. Returning exception
11010  * code also wouldn't work since we can have subprogs where the dead
11011  * code could be located.
11012  */
11013 static void sanitize_dead_code(struct bpf_verifier_env *env)
11014 {
11015         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11016         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11017         struct bpf_insn *insn = env->prog->insnsi;
11018         const int insn_cnt = env->prog->len;
11019         int i;
11020
11021         for (i = 0; i < insn_cnt; i++) {
11022                 if (aux_data[i].seen)
11023                         continue;
11024                 memcpy(insn + i, &trap, sizeof(trap));
11025         }
11026 }
11027
11028 static bool insn_is_cond_jump(u8 code)
11029 {
11030         u8 op;
11031
11032         if (BPF_CLASS(code) == BPF_JMP32)
11033                 return true;
11034
11035         if (BPF_CLASS(code) != BPF_JMP)
11036                 return false;
11037
11038         op = BPF_OP(code);
11039         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11040 }
11041
11042 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11043 {
11044         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11045         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11046         struct bpf_insn *insn = env->prog->insnsi;
11047         const int insn_cnt = env->prog->len;
11048         int i;
11049
11050         for (i = 0; i < insn_cnt; i++, insn++) {
11051                 if (!insn_is_cond_jump(insn->code))
11052                         continue;
11053
11054                 if (!aux_data[i + 1].seen)
11055                         ja.off = insn->off;
11056                 else if (!aux_data[i + 1 + insn->off].seen)
11057                         ja.off = 0;
11058                 else
11059                         continue;
11060
11061                 if (bpf_prog_is_dev_bound(env->prog->aux))
11062                         bpf_prog_offload_replace_insn(env, i, &ja);
11063
11064                 memcpy(insn, &ja, sizeof(ja));
11065         }
11066 }
11067
11068 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11069 {
11070         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11071         int insn_cnt = env->prog->len;
11072         int i, err;
11073
11074         for (i = 0; i < insn_cnt; i++) {
11075                 int j;
11076
11077                 j = 0;
11078                 while (i + j < insn_cnt && !aux_data[i + j].seen)
11079                         j++;
11080                 if (!j)
11081                         continue;
11082
11083                 err = verifier_remove_insns(env, i, j);
11084                 if (err)
11085                         return err;
11086                 insn_cnt = env->prog->len;
11087         }
11088
11089         return 0;
11090 }
11091
11092 static int opt_remove_nops(struct bpf_verifier_env *env)
11093 {
11094         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11095         struct bpf_insn *insn = env->prog->insnsi;
11096         int insn_cnt = env->prog->len;
11097         int i, err;
11098
11099         for (i = 0; i < insn_cnt; i++) {
11100                 if (memcmp(&insn[i], &ja, sizeof(ja)))
11101                         continue;
11102
11103                 err = verifier_remove_insns(env, i, 1);
11104                 if (err)
11105                         return err;
11106                 insn_cnt--;
11107                 i--;
11108         }
11109
11110         return 0;
11111 }
11112
11113 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11114                                          const union bpf_attr *attr)
11115 {
11116         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11117         struct bpf_insn_aux_data *aux = env->insn_aux_data;
11118         int i, patch_len, delta = 0, len = env->prog->len;
11119         struct bpf_insn *insns = env->prog->insnsi;
11120         struct bpf_prog *new_prog;
11121         bool rnd_hi32;
11122
11123         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11124         zext_patch[1] = BPF_ZEXT_REG(0);
11125         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11126         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11127         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11128         for (i = 0; i < len; i++) {
11129                 int adj_idx = i + delta;
11130                 struct bpf_insn insn;
11131                 int load_reg;
11132
11133                 insn = insns[adj_idx];
11134                 load_reg = insn_def_regno(&insn);
11135                 if (!aux[adj_idx].zext_dst) {
11136                         u8 code, class;
11137                         u32 imm_rnd;
11138
11139                         if (!rnd_hi32)
11140                                 continue;
11141
11142                         code = insn.code;
11143                         class = BPF_CLASS(code);
11144                         if (load_reg == -1)
11145                                 continue;
11146
11147                         /* NOTE: arg "reg" (the fourth one) is only used for
11148                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
11149                          *       here.
11150                          */
11151                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
11152                                 if (class == BPF_LD &&
11153                                     BPF_MODE(code) == BPF_IMM)
11154                                         i++;
11155                                 continue;
11156                         }
11157
11158                         /* ctx load could be transformed into wider load. */
11159                         if (class == BPF_LDX &&
11160                             aux[adj_idx].ptr_type == PTR_TO_CTX)
11161                                 continue;
11162
11163                         imm_rnd = get_random_int();
11164                         rnd_hi32_patch[0] = insn;
11165                         rnd_hi32_patch[1].imm = imm_rnd;
11166                         rnd_hi32_patch[3].dst_reg = load_reg;
11167                         patch = rnd_hi32_patch;
11168                         patch_len = 4;
11169                         goto apply_patch_buffer;
11170                 }
11171
11172                 /* Add in an zero-extend instruction if a) the JIT has requested
11173                  * it or b) it's a CMPXCHG.
11174                  *
11175                  * The latter is because: BPF_CMPXCHG always loads a value into
11176                  * R0, therefore always zero-extends. However some archs'
11177                  * equivalent instruction only does this load when the
11178                  * comparison is successful. This detail of CMPXCHG is
11179                  * orthogonal to the general zero-extension behaviour of the
11180                  * CPU, so it's treated independently of bpf_jit_needs_zext.
11181                  */
11182                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
11183                         continue;
11184
11185                 if (WARN_ON(load_reg == -1)) {
11186                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11187                         return -EFAULT;
11188                 }
11189
11190                 zext_patch[0] = insn;
11191                 zext_patch[1].dst_reg = load_reg;
11192                 zext_patch[1].src_reg = load_reg;
11193                 patch = zext_patch;
11194                 patch_len = 2;
11195 apply_patch_buffer:
11196                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11197                 if (!new_prog)
11198                         return -ENOMEM;
11199                 env->prog = new_prog;
11200                 insns = new_prog->insnsi;
11201                 aux = env->insn_aux_data;
11202                 delta += patch_len - 1;
11203         }
11204
11205         return 0;
11206 }
11207
11208 /* convert load instructions that access fields of a context type into a
11209  * sequence of instructions that access fields of the underlying structure:
11210  *     struct __sk_buff    -> struct sk_buff
11211  *     struct bpf_sock_ops -> struct sock
11212  */
11213 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11214 {
11215         const struct bpf_verifier_ops *ops = env->ops;
11216         int i, cnt, size, ctx_field_size, delta = 0;
11217         const int insn_cnt = env->prog->len;
11218         struct bpf_insn insn_buf[16], *insn;
11219         u32 target_size, size_default, off;
11220         struct bpf_prog *new_prog;
11221         enum bpf_access_type type;
11222         bool is_narrower_load;
11223
11224         if (ops->gen_prologue || env->seen_direct_write) {
11225                 if (!ops->gen_prologue) {
11226                         verbose(env, "bpf verifier is misconfigured\n");
11227                         return -EINVAL;
11228                 }
11229                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11230                                         env->prog);
11231                 if (cnt >= ARRAY_SIZE(insn_buf)) {
11232                         verbose(env, "bpf verifier is misconfigured\n");
11233                         return -EINVAL;
11234                 } else if (cnt) {
11235                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11236                         if (!new_prog)
11237                                 return -ENOMEM;
11238
11239                         env->prog = new_prog;
11240                         delta += cnt - 1;
11241                 }
11242         }
11243
11244         if (bpf_prog_is_dev_bound(env->prog->aux))
11245                 return 0;
11246
11247         insn = env->prog->insnsi + delta;
11248
11249         for (i = 0; i < insn_cnt; i++, insn++) {
11250                 bpf_convert_ctx_access_t convert_ctx_access;
11251
11252                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11253                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11254                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11255                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
11256                         type = BPF_READ;
11257                 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11258                          insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11259                          insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11260                          insn->code == (BPF_STX | BPF_MEM | BPF_DW))
11261                         type = BPF_WRITE;
11262                 else
11263                         continue;
11264
11265                 if (type == BPF_WRITE &&
11266                     env->insn_aux_data[i + delta].sanitize_stack_off) {
11267                         struct bpf_insn patch[] = {
11268                                 /* Sanitize suspicious stack slot with zero.
11269                                  * There are no memory dependencies for this store,
11270                                  * since it's only using frame pointer and immediate
11271                                  * constant of zero
11272                                  */
11273                                 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11274                                            env->insn_aux_data[i + delta].sanitize_stack_off,
11275                                            0),
11276                                 /* the original STX instruction will immediately
11277                                  * overwrite the same stack slot with appropriate value
11278                                  */
11279                                 *insn,
11280                         };
11281
11282                         cnt = ARRAY_SIZE(patch);
11283                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11284                         if (!new_prog)
11285                                 return -ENOMEM;
11286
11287                         delta    += cnt - 1;
11288                         env->prog = new_prog;
11289                         insn      = new_prog->insnsi + i + delta;
11290                         continue;
11291                 }
11292
11293                 switch (env->insn_aux_data[i + delta].ptr_type) {
11294                 case PTR_TO_CTX:
11295                         if (!ops->convert_ctx_access)
11296                                 continue;
11297                         convert_ctx_access = ops->convert_ctx_access;
11298                         break;
11299                 case PTR_TO_SOCKET:
11300                 case PTR_TO_SOCK_COMMON:
11301                         convert_ctx_access = bpf_sock_convert_ctx_access;
11302                         break;
11303                 case PTR_TO_TCP_SOCK:
11304                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11305                         break;
11306                 case PTR_TO_XDP_SOCK:
11307                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11308                         break;
11309                 case PTR_TO_BTF_ID:
11310                         if (type == BPF_READ) {
11311                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
11312                                         BPF_SIZE((insn)->code);
11313                                 env->prog->aux->num_exentries++;
11314                         } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11315                                 verbose(env, "Writes through BTF pointers are not allowed\n");
11316                                 return -EINVAL;
11317                         }
11318                         continue;
11319                 default:
11320                         continue;
11321                 }
11322
11323                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11324                 size = BPF_LDST_BYTES(insn);
11325
11326                 /* If the read access is a narrower load of the field,
11327                  * convert to a 4/8-byte load, to minimum program type specific
11328                  * convert_ctx_access changes. If conversion is successful,
11329                  * we will apply proper mask to the result.
11330                  */
11331                 is_narrower_load = size < ctx_field_size;
11332                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11333                 off = insn->off;
11334                 if (is_narrower_load) {
11335                         u8 size_code;
11336
11337                         if (type == BPF_WRITE) {
11338                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11339                                 return -EINVAL;
11340                         }
11341
11342                         size_code = BPF_H;
11343                         if (ctx_field_size == 4)
11344                                 size_code = BPF_W;
11345                         else if (ctx_field_size == 8)
11346                                 size_code = BPF_DW;
11347
11348                         insn->off = off & ~(size_default - 1);
11349                         insn->code = BPF_LDX | BPF_MEM | size_code;
11350                 }
11351
11352                 target_size = 0;
11353                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11354                                          &target_size);
11355                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11356                     (ctx_field_size && !target_size)) {
11357                         verbose(env, "bpf verifier is misconfigured\n");
11358                         return -EINVAL;
11359                 }
11360
11361                 if (is_narrower_load && size < target_size) {
11362                         u8 shift = bpf_ctx_narrow_access_offset(
11363                                 off, size, size_default) * 8;
11364                         if (ctx_field_size <= 4) {
11365                                 if (shift)
11366                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11367                                                                         insn->dst_reg,
11368                                                                         shift);
11369                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11370                                                                 (1 << size * 8) - 1);
11371                         } else {
11372                                 if (shift)
11373                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11374                                                                         insn->dst_reg,
11375                                                                         shift);
11376                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
11377                                                                 (1ULL << size * 8) - 1);
11378                         }
11379                 }
11380
11381                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11382                 if (!new_prog)
11383                         return -ENOMEM;
11384
11385                 delta += cnt - 1;
11386
11387                 /* keep walking new program and skip insns we just inserted */
11388                 env->prog = new_prog;
11389                 insn      = new_prog->insnsi + i + delta;
11390         }
11391
11392         return 0;
11393 }
11394
11395 static int jit_subprogs(struct bpf_verifier_env *env)
11396 {
11397         struct bpf_prog *prog = env->prog, **func, *tmp;
11398         int i, j, subprog_start, subprog_end = 0, len, subprog;
11399         struct bpf_map *map_ptr;
11400         struct bpf_insn *insn;
11401         void *old_bpf_func;
11402         int err, num_exentries;
11403
11404         if (env->subprog_cnt <= 1)
11405                 return 0;
11406
11407         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11408                 if (!bpf_pseudo_call(insn))
11409                         continue;
11410                 /* Upon error here we cannot fall back to interpreter but
11411                  * need a hard reject of the program. Thus -EFAULT is
11412                  * propagated in any case.
11413                  */
11414                 subprog = find_subprog(env, i + insn->imm + 1);
11415                 if (subprog < 0) {
11416                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11417                                   i + insn->imm + 1);
11418                         return -EFAULT;
11419                 }
11420                 /* temporarily remember subprog id inside insn instead of
11421                  * aux_data, since next loop will split up all insns into funcs
11422                  */
11423                 insn->off = subprog;
11424                 /* remember original imm in case JIT fails and fallback
11425                  * to interpreter will be needed
11426                  */
11427                 env->insn_aux_data[i].call_imm = insn->imm;
11428                 /* point imm to __bpf_call_base+1 from JITs point of view */
11429                 insn->imm = 1;
11430         }
11431
11432         err = bpf_prog_alloc_jited_linfo(prog);
11433         if (err)
11434                 goto out_undo_insn;
11435
11436         err = -ENOMEM;
11437         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11438         if (!func)
11439                 goto out_undo_insn;
11440
11441         for (i = 0; i < env->subprog_cnt; i++) {
11442                 subprog_start = subprog_end;
11443                 subprog_end = env->subprog_info[i + 1].start;
11444
11445                 len = subprog_end - subprog_start;
11446                 /* BPF_PROG_RUN doesn't call subprogs directly,
11447                  * hence main prog stats include the runtime of subprogs.
11448                  * subprogs don't have IDs and not reachable via prog_get_next_id
11449                  * func[i]->stats will never be accessed and stays NULL
11450                  */
11451                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11452                 if (!func[i])
11453                         goto out_free;
11454                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11455                        len * sizeof(struct bpf_insn));
11456                 func[i]->type = prog->type;
11457                 func[i]->len = len;
11458                 if (bpf_prog_calc_tag(func[i]))
11459                         goto out_free;
11460                 func[i]->is_func = 1;
11461                 func[i]->aux->func_idx = i;
11462                 /* the btf and func_info will be freed only at prog->aux */
11463                 func[i]->aux->btf = prog->aux->btf;
11464                 func[i]->aux->func_info = prog->aux->func_info;
11465
11466                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11467                         u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11468                         int ret;
11469
11470                         if (!(insn_idx >= subprog_start &&
11471                               insn_idx <= subprog_end))
11472                                 continue;
11473
11474                         ret = bpf_jit_add_poke_descriptor(func[i],
11475                                                           &prog->aux->poke_tab[j]);
11476                         if (ret < 0) {
11477                                 verbose(env, "adding tail call poke descriptor failed\n");
11478                                 goto out_free;
11479                         }
11480
11481                         func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11482
11483                         map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11484                         ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11485                         if (ret < 0) {
11486                                 verbose(env, "tracking tail call prog failed\n");
11487                                 goto out_free;
11488                         }
11489                 }
11490
11491                 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11492                  * Long term would need debug info to populate names
11493                  */
11494                 func[i]->aux->name[0] = 'F';
11495                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11496                 func[i]->jit_requested = 1;
11497                 func[i]->aux->linfo = prog->aux->linfo;
11498                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11499                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11500                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11501                 num_exentries = 0;
11502                 insn = func[i]->insnsi;
11503                 for (j = 0; j < func[i]->len; j++, insn++) {
11504                         if (BPF_CLASS(insn->code) == BPF_LDX &&
11505                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
11506                                 num_exentries++;
11507                 }
11508                 func[i]->aux->num_exentries = num_exentries;
11509                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11510                 func[i] = bpf_int_jit_compile(func[i]);
11511                 if (!func[i]->jited) {
11512                         err = -ENOTSUPP;
11513                         goto out_free;
11514                 }
11515                 cond_resched();
11516         }
11517
11518         /* Untrack main program's aux structs so that during map_poke_run()
11519          * we will not stumble upon the unfilled poke descriptors; each
11520          * of the main program's poke descs got distributed across subprogs
11521          * and got tracked onto map, so we are sure that none of them will
11522          * be missed after the operation below
11523          */
11524         for (i = 0; i < prog->aux->size_poke_tab; i++) {
11525                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11526
11527                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11528         }
11529
11530         /* at this point all bpf functions were successfully JITed
11531          * now populate all bpf_calls with correct addresses and
11532          * run last pass of JIT
11533          */
11534         for (i = 0; i < env->subprog_cnt; i++) {
11535                 insn = func[i]->insnsi;
11536                 for (j = 0; j < func[i]->len; j++, insn++) {
11537                         if (!bpf_pseudo_call(insn))
11538                                 continue;
11539                         subprog = insn->off;
11540                         insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11541                                     __bpf_call_base;
11542                 }
11543
11544                 /* we use the aux data to keep a list of the start addresses
11545                  * of the JITed images for each function in the program
11546                  *
11547                  * for some architectures, such as powerpc64, the imm field
11548                  * might not be large enough to hold the offset of the start
11549                  * address of the callee's JITed image from __bpf_call_base
11550                  *
11551                  * in such cases, we can lookup the start address of a callee
11552                  * by using its subprog id, available from the off field of
11553                  * the call instruction, as an index for this list
11554                  */
11555                 func[i]->aux->func = func;
11556                 func[i]->aux->func_cnt = env->subprog_cnt;
11557         }
11558         for (i = 0; i < env->subprog_cnt; i++) {
11559                 old_bpf_func = func[i]->bpf_func;
11560                 tmp = bpf_int_jit_compile(func[i]);
11561                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11562                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11563                         err = -ENOTSUPP;
11564                         goto out_free;
11565                 }
11566                 cond_resched();
11567         }
11568
11569         /* finally lock prog and jit images for all functions and
11570          * populate kallsysm
11571          */
11572         for (i = 0; i < env->subprog_cnt; i++) {
11573                 bpf_prog_lock_ro(func[i]);
11574                 bpf_prog_kallsyms_add(func[i]);
11575         }
11576
11577         /* Last step: make now unused interpreter insns from main
11578          * prog consistent for later dump requests, so they can
11579          * later look the same as if they were interpreted only.
11580          */
11581         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11582                 if (!bpf_pseudo_call(insn))
11583                         continue;
11584                 insn->off = env->insn_aux_data[i].call_imm;
11585                 subprog = find_subprog(env, i + insn->off + 1);
11586                 insn->imm = subprog;
11587         }
11588
11589         prog->jited = 1;
11590         prog->bpf_func = func[0]->bpf_func;
11591         prog->aux->func = func;
11592         prog->aux->func_cnt = env->subprog_cnt;
11593         bpf_prog_free_unused_jited_linfo(prog);
11594         return 0;
11595 out_free:
11596         for (i = 0; i < env->subprog_cnt; i++) {
11597                 if (!func[i])
11598                         continue;
11599
11600                 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11601                         map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11602                         map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11603                 }
11604                 bpf_jit_free(func[i]);
11605         }
11606         kfree(func);
11607 out_undo_insn:
11608         /* cleanup main prog to be interpreted */
11609         prog->jit_requested = 0;
11610         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11611                 if (!bpf_pseudo_call(insn))
11612                         continue;
11613                 insn->off = 0;
11614                 insn->imm = env->insn_aux_data[i].call_imm;
11615         }
11616         bpf_prog_free_jited_linfo(prog);
11617         return err;
11618 }
11619
11620 static int fixup_call_args(struct bpf_verifier_env *env)
11621 {
11622 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11623         struct bpf_prog *prog = env->prog;
11624         struct bpf_insn *insn = prog->insnsi;
11625         int i, depth;
11626 #endif
11627         int err = 0;
11628
11629         if (env->prog->jit_requested &&
11630             !bpf_prog_is_dev_bound(env->prog->aux)) {
11631                 err = jit_subprogs(env);
11632                 if (err == 0)
11633                         return 0;
11634                 if (err == -EFAULT)
11635                         return err;
11636         }
11637 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11638         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11639                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11640                  * have to be rejected, since interpreter doesn't support them yet.
11641                  */
11642                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11643                 return -EINVAL;
11644         }
11645         for (i = 0; i < prog->len; i++, insn++) {
11646                 if (!bpf_pseudo_call(insn))
11647                         continue;
11648                 depth = get_callee_stack_depth(env, insn, i);
11649                 if (depth < 0)
11650                         return depth;
11651                 bpf_patch_call_args(insn, depth);
11652         }
11653         err = 0;
11654 #endif
11655         return err;
11656 }
11657
11658 /* fixup insn->imm field of bpf_call instructions
11659  * and inline eligible helpers as explicit sequence of BPF instructions
11660  *
11661  * this function is called after eBPF program passed verification
11662  */
11663 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11664 {
11665         struct bpf_prog *prog = env->prog;
11666         bool expect_blinding = bpf_jit_blinding_enabled(prog);
11667         struct bpf_insn *insn = prog->insnsi;
11668         const struct bpf_func_proto *fn;
11669         const int insn_cnt = prog->len;
11670         const struct bpf_map_ops *ops;
11671         struct bpf_insn_aux_data *aux;
11672         struct bpf_insn insn_buf[16];
11673         struct bpf_prog *new_prog;
11674         struct bpf_map *map_ptr;
11675         int i, ret, cnt, delta = 0;
11676
11677         for (i = 0; i < insn_cnt; i++, insn++) {
11678                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11679                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11680                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11681                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11682                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11683                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11684                         struct bpf_insn *patchlet;
11685                         struct bpf_insn chk_and_div[] = {
11686                                 /* [R,W]x div 0 -> 0 */
11687                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11688                                              BPF_JNE | BPF_K, insn->src_reg,
11689                                              0, 2, 0),
11690                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11691                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11692                                 *insn,
11693                         };
11694                         struct bpf_insn chk_and_mod[] = {
11695                                 /* [R,W]x mod 0 -> [R,W]x */
11696                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11697                                              BPF_JEQ | BPF_K, insn->src_reg,
11698                                              0, 1 + (is64 ? 0 : 1), 0),
11699                                 *insn,
11700                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11701                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11702                         };
11703
11704                         patchlet = isdiv ? chk_and_div : chk_and_mod;
11705                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11706                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11707
11708                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11709                         if (!new_prog)
11710                                 return -ENOMEM;
11711
11712                         delta    += cnt - 1;
11713                         env->prog = prog = new_prog;
11714                         insn      = new_prog->insnsi + i + delta;
11715                         continue;
11716                 }
11717
11718                 if (BPF_CLASS(insn->code) == BPF_LD &&
11719                     (BPF_MODE(insn->code) == BPF_ABS ||
11720                      BPF_MODE(insn->code) == BPF_IND)) {
11721                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
11722                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11723                                 verbose(env, "bpf verifier is misconfigured\n");
11724                                 return -EINVAL;
11725                         }
11726
11727                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11728                         if (!new_prog)
11729                                 return -ENOMEM;
11730
11731                         delta    += cnt - 1;
11732                         env->prog = prog = new_prog;
11733                         insn      = new_prog->insnsi + i + delta;
11734                         continue;
11735                 }
11736
11737                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11738                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11739                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11740                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11741                         struct bpf_insn insn_buf[16];
11742                         struct bpf_insn *patch = &insn_buf[0];
11743                         bool issrc, isneg;
11744                         u32 off_reg;
11745
11746                         aux = &env->insn_aux_data[i + delta];
11747                         if (!aux->alu_state ||
11748                             aux->alu_state == BPF_ALU_NON_POINTER)
11749                                 continue;
11750
11751                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11752                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11753                                 BPF_ALU_SANITIZE_SRC;
11754
11755                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
11756                         if (isneg)
11757                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11758                         *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11759                         *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11760                         *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11761                         *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11762                         *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11763                         if (issrc) {
11764                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
11765                                                          off_reg);
11766                                 insn->src_reg = BPF_REG_AX;
11767                         } else {
11768                                 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
11769                                                          BPF_REG_AX);
11770                         }
11771                         if (isneg)
11772                                 insn->code = insn->code == code_add ?
11773                                              code_sub : code_add;
11774                         *patch++ = *insn;
11775                         if (issrc && isneg)
11776                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11777                         cnt = patch - insn_buf;
11778
11779                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11780                         if (!new_prog)
11781                                 return -ENOMEM;
11782
11783                         delta    += cnt - 1;
11784                         env->prog = prog = new_prog;
11785                         insn      = new_prog->insnsi + i + delta;
11786                         continue;
11787                 }
11788
11789                 if (insn->code != (BPF_JMP | BPF_CALL))
11790                         continue;
11791                 if (insn->src_reg == BPF_PSEUDO_CALL)
11792                         continue;
11793
11794                 if (insn->imm == BPF_FUNC_get_route_realm)
11795                         prog->dst_needed = 1;
11796                 if (insn->imm == BPF_FUNC_get_prandom_u32)
11797                         bpf_user_rnd_init_once();
11798                 if (insn->imm == BPF_FUNC_override_return)
11799                         prog->kprobe_override = 1;
11800                 if (insn->imm == BPF_FUNC_tail_call) {
11801                         /* If we tail call into other programs, we
11802                          * cannot make any assumptions since they can
11803                          * be replaced dynamically during runtime in
11804                          * the program array.
11805                          */
11806                         prog->cb_access = 1;
11807                         if (!allow_tail_call_in_subprogs(env))
11808                                 prog->aux->stack_depth = MAX_BPF_STACK;
11809                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11810
11811                         /* mark bpf_tail_call as different opcode to avoid
11812                          * conditional branch in the interpeter for every normal
11813                          * call and to prevent accidental JITing by JIT compiler
11814                          * that doesn't support bpf_tail_call yet
11815                          */
11816                         insn->imm = 0;
11817                         insn->code = BPF_JMP | BPF_TAIL_CALL;
11818
11819                         aux = &env->insn_aux_data[i + delta];
11820                         if (env->bpf_capable && !expect_blinding &&
11821                             prog->jit_requested &&
11822                             !bpf_map_key_poisoned(aux) &&
11823                             !bpf_map_ptr_poisoned(aux) &&
11824                             !bpf_map_ptr_unpriv(aux)) {
11825                                 struct bpf_jit_poke_descriptor desc = {
11826                                         .reason = BPF_POKE_REASON_TAIL_CALL,
11827                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11828                                         .tail_call.key = bpf_map_key_immediate(aux),
11829                                         .insn_idx = i + delta,
11830                                 };
11831
11832                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11833                                 if (ret < 0) {
11834                                         verbose(env, "adding tail call poke descriptor failed\n");
11835                                         return ret;
11836                                 }
11837
11838                                 insn->imm = ret + 1;
11839                                 continue;
11840                         }
11841
11842                         if (!bpf_map_ptr_unpriv(aux))
11843                                 continue;
11844
11845                         /* instead of changing every JIT dealing with tail_call
11846                          * emit two extra insns:
11847                          * if (index >= max_entries) goto out;
11848                          * index &= array->index_mask;
11849                          * to avoid out-of-bounds cpu speculation
11850                          */
11851                         if (bpf_map_ptr_poisoned(aux)) {
11852                                 verbose(env, "tail_call abusing map_ptr\n");
11853                                 return -EINVAL;
11854                         }
11855
11856                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11857                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11858                                                   map_ptr->max_entries, 2);
11859                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11860                                                     container_of(map_ptr,
11861                                                                  struct bpf_array,
11862                                                                  map)->index_mask);
11863                         insn_buf[2] = *insn;
11864                         cnt = 3;
11865                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11866                         if (!new_prog)
11867                                 return -ENOMEM;
11868
11869                         delta    += cnt - 1;
11870                         env->prog = prog = new_prog;
11871                         insn      = new_prog->insnsi + i + delta;
11872                         continue;
11873                 }
11874
11875                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11876                  * and other inlining handlers are currently limited to 64 bit
11877                  * only.
11878                  */
11879                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11880                     (insn->imm == BPF_FUNC_map_lookup_elem ||
11881                      insn->imm == BPF_FUNC_map_update_elem ||
11882                      insn->imm == BPF_FUNC_map_delete_elem ||
11883                      insn->imm == BPF_FUNC_map_push_elem   ||
11884                      insn->imm == BPF_FUNC_map_pop_elem    ||
11885                      insn->imm == BPF_FUNC_map_peek_elem)) {
11886                         aux = &env->insn_aux_data[i + delta];
11887                         if (bpf_map_ptr_poisoned(aux))
11888                                 goto patch_call_imm;
11889
11890                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11891                         ops = map_ptr->ops;
11892                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
11893                             ops->map_gen_lookup) {
11894                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11895                                 if (cnt == -EOPNOTSUPP)
11896                                         goto patch_map_ops_generic;
11897                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11898                                         verbose(env, "bpf verifier is misconfigured\n");
11899                                         return -EINVAL;
11900                                 }
11901
11902                                 new_prog = bpf_patch_insn_data(env, i + delta,
11903                                                                insn_buf, cnt);
11904                                 if (!new_prog)
11905                                         return -ENOMEM;
11906
11907                                 delta    += cnt - 1;
11908                                 env->prog = prog = new_prog;
11909                                 insn      = new_prog->insnsi + i + delta;
11910                                 continue;
11911                         }
11912
11913                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11914                                      (void *(*)(struct bpf_map *map, void *key))NULL));
11915                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11916                                      (int (*)(struct bpf_map *map, void *key))NULL));
11917                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11918                                      (int (*)(struct bpf_map *map, void *key, void *value,
11919                                               u64 flags))NULL));
11920                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11921                                      (int (*)(struct bpf_map *map, void *value,
11922                                               u64 flags))NULL));
11923                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11924                                      (int (*)(struct bpf_map *map, void *value))NULL));
11925                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11926                                      (int (*)(struct bpf_map *map, void *value))NULL));
11927 patch_map_ops_generic:
11928                         switch (insn->imm) {
11929                         case BPF_FUNC_map_lookup_elem:
11930                                 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11931                                             __bpf_call_base;
11932                                 continue;
11933                         case BPF_FUNC_map_update_elem:
11934                                 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11935                                             __bpf_call_base;
11936                                 continue;
11937                         case BPF_FUNC_map_delete_elem:
11938                                 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11939                                             __bpf_call_base;
11940                                 continue;
11941                         case BPF_FUNC_map_push_elem:
11942                                 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11943                                             __bpf_call_base;
11944                                 continue;
11945                         case BPF_FUNC_map_pop_elem:
11946                                 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11947                                             __bpf_call_base;
11948                                 continue;
11949                         case BPF_FUNC_map_peek_elem:
11950                                 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11951                                             __bpf_call_base;
11952                                 continue;
11953                         }
11954
11955                         goto patch_call_imm;
11956                 }
11957
11958                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11959                     insn->imm == BPF_FUNC_jiffies64) {
11960                         struct bpf_insn ld_jiffies_addr[2] = {
11961                                 BPF_LD_IMM64(BPF_REG_0,
11962                                              (unsigned long)&jiffies),
11963                         };
11964
11965                         insn_buf[0] = ld_jiffies_addr[0];
11966                         insn_buf[1] = ld_jiffies_addr[1];
11967                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11968                                                   BPF_REG_0, 0);
11969                         cnt = 3;
11970
11971                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11972                                                        cnt);
11973                         if (!new_prog)
11974                                 return -ENOMEM;
11975
11976                         delta    += cnt - 1;
11977                         env->prog = prog = new_prog;
11978                         insn      = new_prog->insnsi + i + delta;
11979                         continue;
11980                 }
11981
11982 patch_call_imm:
11983                 fn = env->ops->get_func_proto(insn->imm, env->prog);
11984                 /* all functions that have prototype and verifier allowed
11985                  * programs to call them, must be real in-kernel functions
11986                  */
11987                 if (!fn->func) {
11988                         verbose(env,
11989                                 "kernel subsystem misconfigured func %s#%d\n",
11990                                 func_id_name(insn->imm), insn->imm);
11991                         return -EFAULT;
11992                 }
11993                 insn->imm = fn->func - __bpf_call_base;
11994         }
11995
11996         /* Since poke tab is now finalized, publish aux to tracker. */
11997         for (i = 0; i < prog->aux->size_poke_tab; i++) {
11998                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11999                 if (!map_ptr->ops->map_poke_track ||
12000                     !map_ptr->ops->map_poke_untrack ||
12001                     !map_ptr->ops->map_poke_run) {
12002                         verbose(env, "bpf verifier is misconfigured\n");
12003                         return -EINVAL;
12004                 }
12005
12006                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12007                 if (ret < 0) {
12008                         verbose(env, "tracking tail call prog failed\n");
12009                         return ret;
12010                 }
12011         }
12012
12013         return 0;
12014 }
12015
12016 static void free_states(struct bpf_verifier_env *env)
12017 {
12018         struct bpf_verifier_state_list *sl, *sln;
12019         int i;
12020
12021         sl = env->free_list;
12022         while (sl) {
12023                 sln = sl->next;
12024                 free_verifier_state(&sl->state, false);
12025                 kfree(sl);
12026                 sl = sln;
12027         }
12028         env->free_list = NULL;
12029
12030         if (!env->explored_states)
12031                 return;
12032
12033         for (i = 0; i < state_htab_size(env); i++) {
12034                 sl = env->explored_states[i];
12035
12036                 while (sl) {
12037                         sln = sl->next;
12038                         free_verifier_state(&sl->state, false);
12039                         kfree(sl);
12040                         sl = sln;
12041                 }
12042                 env->explored_states[i] = NULL;
12043         }
12044 }
12045
12046 /* The verifier is using insn_aux_data[] to store temporary data during
12047  * verification and to store information for passes that run after the
12048  * verification like dead code sanitization. do_check_common() for subprogram N
12049  * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12050  * temporary data after do_check_common() finds that subprogram N cannot be
12051  * verified independently. pass_cnt counts the number of times
12052  * do_check_common() was run and insn->aux->seen tells the pass number
12053  * insn_aux_data was touched. These variables are compared to clear temporary
12054  * data from failed pass. For testing and experiments do_check_common() can be
12055  * run multiple times even when prior attempt to verify is unsuccessful.
12056  */
12057 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12058 {
12059         struct bpf_insn *insn = env->prog->insnsi;
12060         struct bpf_insn_aux_data *aux;
12061         int i, class;
12062
12063         for (i = 0; i < env->prog->len; i++) {
12064                 class = BPF_CLASS(insn[i].code);
12065                 if (class != BPF_LDX && class != BPF_STX)
12066                         continue;
12067                 aux = &env->insn_aux_data[i];
12068                 if (aux->seen != env->pass_cnt)
12069                         continue;
12070                 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12071         }
12072 }
12073
12074 static int do_check_common(struct bpf_verifier_env *env, int subprog)
12075 {
12076         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12077         struct bpf_verifier_state *state;
12078         struct bpf_reg_state *regs;
12079         int ret, i;
12080
12081         env->prev_linfo = NULL;
12082         env->pass_cnt++;
12083
12084         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12085         if (!state)
12086                 return -ENOMEM;
12087         state->curframe = 0;
12088         state->speculative = false;
12089         state->branches = 1;
12090         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12091         if (!state->frame[0]) {
12092                 kfree(state);
12093                 return -ENOMEM;
12094         }
12095         env->cur_state = state;
12096         init_func_state(env, state->frame[0],
12097                         BPF_MAIN_FUNC /* callsite */,
12098                         0 /* frameno */,
12099                         subprog);
12100
12101         regs = state->frame[state->curframe]->regs;
12102         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12103                 ret = btf_prepare_func_args(env, subprog, regs);
12104                 if (ret)
12105                         goto out;
12106                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12107                         if (regs[i].type == PTR_TO_CTX)
12108                                 mark_reg_known_zero(env, regs, i);
12109                         else if (regs[i].type == SCALAR_VALUE)
12110                                 mark_reg_unknown(env, regs, i);
12111                         else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12112                                 const u32 mem_size = regs[i].mem_size;
12113
12114                                 mark_reg_known_zero(env, regs, i);
12115                                 regs[i].mem_size = mem_size;
12116                                 regs[i].id = ++env->id_gen;
12117                         }
12118                 }
12119         } else {
12120                 /* 1st arg to a function */
12121                 regs[BPF_REG_1].type = PTR_TO_CTX;
12122                 mark_reg_known_zero(env, regs, BPF_REG_1);
12123                 ret = btf_check_func_arg_match(env, subprog, regs);
12124                 if (ret == -EFAULT)
12125                         /* unlikely verifier bug. abort.
12126                          * ret == 0 and ret < 0 are sadly acceptable for
12127                          * main() function due to backward compatibility.
12128                          * Like socket filter program may be written as:
12129                          * int bpf_prog(struct pt_regs *ctx)
12130                          * and never dereference that ctx in the program.
12131                          * 'struct pt_regs' is a type mismatch for socket
12132                          * filter that should be using 'struct __sk_buff'.
12133                          */
12134                         goto out;
12135         }
12136
12137         ret = do_check(env);
12138 out:
12139         /* check for NULL is necessary, since cur_state can be freed inside
12140          * do_check() under memory pressure.
12141          */
12142         if (env->cur_state) {
12143                 free_verifier_state(env->cur_state, true);
12144                 env->cur_state = NULL;
12145         }
12146         while (!pop_stack(env, NULL, NULL, false));
12147         if (!ret && pop_log)
12148                 bpf_vlog_reset(&env->log, 0);
12149         free_states(env);
12150         if (ret)
12151                 /* clean aux data in case subprog was rejected */
12152                 sanitize_insn_aux_data(env);
12153         return ret;
12154 }
12155
12156 /* Verify all global functions in a BPF program one by one based on their BTF.
12157  * All global functions must pass verification. Otherwise the whole program is rejected.
12158  * Consider:
12159  * int bar(int);
12160  * int foo(int f)
12161  * {
12162  *    return bar(f);
12163  * }
12164  * int bar(int b)
12165  * {
12166  *    ...
12167  * }
12168  * foo() will be verified first for R1=any_scalar_value. During verification it
12169  * will be assumed that bar() already verified successfully and call to bar()
12170  * from foo() will be checked for type match only. Later bar() will be verified
12171  * independently to check that it's safe for R1=any_scalar_value.
12172  */
12173 static int do_check_subprogs(struct bpf_verifier_env *env)
12174 {
12175         struct bpf_prog_aux *aux = env->prog->aux;
12176         int i, ret;
12177
12178         if (!aux->func_info)
12179                 return 0;
12180
12181         for (i = 1; i < env->subprog_cnt; i++) {
12182                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12183                         continue;
12184                 env->insn_idx = env->subprog_info[i].start;
12185                 WARN_ON_ONCE(env->insn_idx == 0);
12186                 ret = do_check_common(env, i);
12187                 if (ret) {
12188                         return ret;
12189                 } else if (env->log.level & BPF_LOG_LEVEL) {
12190                         verbose(env,
12191                                 "Func#%d is safe for any args that match its prototype\n",
12192                                 i);
12193                 }
12194         }
12195         return 0;
12196 }
12197
12198 static int do_check_main(struct bpf_verifier_env *env)
12199 {
12200         int ret;
12201
12202         env->insn_idx = 0;
12203         ret = do_check_common(env, 0);
12204         if (!ret)
12205                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12206         return ret;
12207 }
12208
12209
12210 static void print_verification_stats(struct bpf_verifier_env *env)
12211 {
12212         int i;
12213
12214         if (env->log.level & BPF_LOG_STATS) {
12215                 verbose(env, "verification time %lld usec\n",
12216                         div_u64(env->verification_time, 1000));
12217                 verbose(env, "stack depth ");
12218                 for (i = 0; i < env->subprog_cnt; i++) {
12219                         u32 depth = env->subprog_info[i].stack_depth;
12220
12221                         verbose(env, "%d", depth);
12222                         if (i + 1 < env->subprog_cnt)
12223                                 verbose(env, "+");
12224                 }
12225                 verbose(env, "\n");
12226         }
12227         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12228                 "total_states %d peak_states %d mark_read %d\n",
12229                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12230                 env->max_states_per_insn, env->total_states,
12231                 env->peak_states, env->longest_mark_read_walk);
12232 }
12233
12234 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12235 {
12236         const struct btf_type *t, *func_proto;
12237         const struct bpf_struct_ops *st_ops;
12238         const struct btf_member *member;
12239         struct bpf_prog *prog = env->prog;
12240         u32 btf_id, member_idx;
12241         const char *mname;
12242
12243         if (!prog->gpl_compatible) {
12244                 verbose(env, "struct ops programs must have a GPL compatible license\n");
12245                 return -EINVAL;
12246         }
12247
12248         btf_id = prog->aux->attach_btf_id;
12249         st_ops = bpf_struct_ops_find(btf_id);
12250         if (!st_ops) {
12251                 verbose(env, "attach_btf_id %u is not a supported struct\n",
12252                         btf_id);
12253                 return -ENOTSUPP;
12254         }
12255
12256         t = st_ops->type;
12257         member_idx = prog->expected_attach_type;
12258         if (member_idx >= btf_type_vlen(t)) {
12259                 verbose(env, "attach to invalid member idx %u of struct %s\n",
12260                         member_idx, st_ops->name);
12261                 return -EINVAL;
12262         }
12263
12264         member = &btf_type_member(t)[member_idx];
12265         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12266         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12267                                                NULL);
12268         if (!func_proto) {
12269                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12270                         mname, member_idx, st_ops->name);
12271                 return -EINVAL;
12272         }
12273
12274         if (st_ops->check_member) {
12275                 int err = st_ops->check_member(t, member);
12276
12277                 if (err) {
12278                         verbose(env, "attach to unsupported member %s of struct %s\n",
12279                                 mname, st_ops->name);
12280                         return err;
12281                 }
12282         }
12283
12284         prog->aux->attach_func_proto = func_proto;
12285         prog->aux->attach_func_name = mname;
12286         env->ops = st_ops->verifier_ops;
12287
12288         return 0;
12289 }
12290 #define SECURITY_PREFIX "security_"
12291
12292 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12293 {
12294         if (within_error_injection_list(addr) ||
12295             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12296                 return 0;
12297
12298         return -EINVAL;
12299 }
12300
12301 /* list of non-sleepable functions that are otherwise on
12302  * ALLOW_ERROR_INJECTION list
12303  */
12304 BTF_SET_START(btf_non_sleepable_error_inject)
12305 /* Three functions below can be called from sleepable and non-sleepable context.
12306  * Assume non-sleepable from bpf safety point of view.
12307  */
12308 BTF_ID(func, __add_to_page_cache_locked)
12309 BTF_ID(func, should_fail_alloc_page)
12310 BTF_ID(func, should_failslab)
12311 BTF_SET_END(btf_non_sleepable_error_inject)
12312
12313 static int check_non_sleepable_error_inject(u32 btf_id)
12314 {
12315         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12316 }
12317
12318 int bpf_check_attach_target(struct bpf_verifier_log *log,
12319                             const struct bpf_prog *prog,
12320                             const struct bpf_prog *tgt_prog,
12321                             u32 btf_id,
12322                             struct bpf_attach_target_info *tgt_info)
12323 {
12324         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12325         const char prefix[] = "btf_trace_";
12326         int ret = 0, subprog = -1, i;
12327         const struct btf_type *t;
12328         bool conservative = true;
12329         const char *tname;
12330         struct btf *btf;
12331         long addr = 0;
12332
12333         if (!btf_id) {
12334                 bpf_log(log, "Tracing programs must provide btf_id\n");
12335                 return -EINVAL;
12336         }
12337         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
12338         if (!btf) {
12339                 bpf_log(log,
12340                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12341                 return -EINVAL;
12342         }
12343         t = btf_type_by_id(btf, btf_id);
12344         if (!t) {
12345                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12346                 return -EINVAL;
12347         }
12348         tname = btf_name_by_offset(btf, t->name_off);
12349         if (!tname) {
12350                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12351                 return -EINVAL;
12352         }
12353         if (tgt_prog) {
12354                 struct bpf_prog_aux *aux = tgt_prog->aux;
12355
12356                 for (i = 0; i < aux->func_info_cnt; i++)
12357                         if (aux->func_info[i].type_id == btf_id) {
12358                                 subprog = i;
12359                                 break;
12360                         }
12361                 if (subprog == -1) {
12362                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
12363                         return -EINVAL;
12364                 }
12365                 conservative = aux->func_info_aux[subprog].unreliable;
12366                 if (prog_extension) {
12367                         if (conservative) {
12368                                 bpf_log(log,
12369                                         "Cannot replace static functions\n");
12370                                 return -EINVAL;
12371                         }
12372                         if (!prog->jit_requested) {
12373                                 bpf_log(log,
12374                                         "Extension programs should be JITed\n");
12375                                 return -EINVAL;
12376                         }
12377                 }
12378                 if (!tgt_prog->jited) {
12379                         bpf_log(log, "Can attach to only JITed progs\n");
12380                         return -EINVAL;
12381                 }
12382                 if (tgt_prog->type == prog->type) {
12383                         /* Cannot fentry/fexit another fentry/fexit program.
12384                          * Cannot attach program extension to another extension.
12385                          * It's ok to attach fentry/fexit to extension program.
12386                          */
12387                         bpf_log(log, "Cannot recursively attach\n");
12388                         return -EINVAL;
12389                 }
12390                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12391                     prog_extension &&
12392                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12393                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12394                         /* Program extensions can extend all program types
12395                          * except fentry/fexit. The reason is the following.
12396                          * The fentry/fexit programs are used for performance
12397                          * analysis, stats and can be attached to any program
12398                          * type except themselves. When extension program is
12399                          * replacing XDP function it is necessary to allow
12400                          * performance analysis of all functions. Both original
12401                          * XDP program and its program extension. Hence
12402                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12403                          * allowed. If extending of fentry/fexit was allowed it
12404                          * would be possible to create long call chain
12405                          * fentry->extension->fentry->extension beyond
12406                          * reasonable stack size. Hence extending fentry is not
12407                          * allowed.
12408                          */
12409                         bpf_log(log, "Cannot extend fentry/fexit\n");
12410                         return -EINVAL;
12411                 }
12412         } else {
12413                 if (prog_extension) {
12414                         bpf_log(log, "Cannot replace kernel functions\n");
12415                         return -EINVAL;
12416                 }
12417         }
12418
12419         switch (prog->expected_attach_type) {
12420         case BPF_TRACE_RAW_TP:
12421                 if (tgt_prog) {
12422                         bpf_log(log,
12423                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12424                         return -EINVAL;
12425                 }
12426                 if (!btf_type_is_typedef(t)) {
12427                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
12428                                 btf_id);
12429                         return -EINVAL;
12430                 }
12431                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12432                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12433                                 btf_id, tname);
12434                         return -EINVAL;
12435                 }
12436                 tname += sizeof(prefix) - 1;
12437                 t = btf_type_by_id(btf, t->type);
12438                 if (!btf_type_is_ptr(t))
12439                         /* should never happen in valid vmlinux build */
12440                         return -EINVAL;
12441                 t = btf_type_by_id(btf, t->type);
12442                 if (!btf_type_is_func_proto(t))
12443                         /* should never happen in valid vmlinux build */
12444                         return -EINVAL;
12445
12446                 break;
12447         case BPF_TRACE_ITER:
12448                 if (!btf_type_is_func(t)) {
12449                         bpf_log(log, "attach_btf_id %u is not a function\n",
12450                                 btf_id);
12451                         return -EINVAL;
12452                 }
12453                 t = btf_type_by_id(btf, t->type);
12454                 if (!btf_type_is_func_proto(t))
12455                         return -EINVAL;
12456                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12457                 if (ret)
12458                         return ret;
12459                 break;
12460         default:
12461                 if (!prog_extension)
12462                         return -EINVAL;
12463                 fallthrough;
12464         case BPF_MODIFY_RETURN:
12465         case BPF_LSM_MAC:
12466         case BPF_TRACE_FENTRY:
12467         case BPF_TRACE_FEXIT:
12468                 if (!btf_type_is_func(t)) {
12469                         bpf_log(log, "attach_btf_id %u is not a function\n",
12470                                 btf_id);
12471                         return -EINVAL;
12472                 }
12473                 if (prog_extension &&
12474                     btf_check_type_match(log, prog, btf, t))
12475                         return -EINVAL;
12476                 t = btf_type_by_id(btf, t->type);
12477                 if (!btf_type_is_func_proto(t))
12478                         return -EINVAL;
12479
12480                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12481                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12482                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12483                         return -EINVAL;
12484
12485                 if (tgt_prog && conservative)
12486                         t = NULL;
12487
12488                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12489                 if (ret < 0)
12490                         return ret;
12491
12492                 if (tgt_prog) {
12493                         if (subprog == 0)
12494                                 addr = (long) tgt_prog->bpf_func;
12495                         else
12496                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12497                 } else {
12498                         addr = kallsyms_lookup_name(tname);
12499                         if (!addr) {
12500                                 bpf_log(log,
12501                                         "The address of function %s cannot be found\n",
12502                                         tname);
12503                                 return -ENOENT;
12504                         }
12505                 }
12506
12507                 if (prog->aux->sleepable) {
12508                         ret = -EINVAL;
12509                         switch (prog->type) {
12510                         case BPF_PROG_TYPE_TRACING:
12511                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12512                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12513                                  */
12514                                 if (!check_non_sleepable_error_inject(btf_id) &&
12515                                     within_error_injection_list(addr))
12516                                         ret = 0;
12517                                 break;
12518                         case BPF_PROG_TYPE_LSM:
12519                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12520                                  * Only some of them are sleepable.
12521                                  */
12522                                 if (bpf_lsm_is_sleepable_hook(btf_id))
12523                                         ret = 0;
12524                                 break;
12525                         default:
12526                                 break;
12527                         }
12528                         if (ret) {
12529                                 bpf_log(log, "%s is not sleepable\n", tname);
12530                                 return ret;
12531                         }
12532                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12533                         if (tgt_prog) {
12534                                 bpf_log(log, "can't modify return codes of BPF programs\n");
12535                                 return -EINVAL;
12536                         }
12537                         ret = check_attach_modify_return(addr, tname);
12538                         if (ret) {
12539                                 bpf_log(log, "%s() is not modifiable\n", tname);
12540                                 return ret;
12541                         }
12542                 }
12543
12544                 break;
12545         }
12546         tgt_info->tgt_addr = addr;
12547         tgt_info->tgt_name = tname;
12548         tgt_info->tgt_type = t;
12549         return 0;
12550 }
12551
12552 static int check_attach_btf_id(struct bpf_verifier_env *env)
12553 {
12554         struct bpf_prog *prog = env->prog;
12555         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12556         struct bpf_attach_target_info tgt_info = {};
12557         u32 btf_id = prog->aux->attach_btf_id;
12558         struct bpf_trampoline *tr;
12559         int ret;
12560         u64 key;
12561
12562         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12563             prog->type != BPF_PROG_TYPE_LSM) {
12564                 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12565                 return -EINVAL;
12566         }
12567
12568         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12569                 return check_struct_ops_btf_id(env);
12570
12571         if (prog->type != BPF_PROG_TYPE_TRACING &&
12572             prog->type != BPF_PROG_TYPE_LSM &&
12573             prog->type != BPF_PROG_TYPE_EXT)
12574                 return 0;
12575
12576         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12577         if (ret)
12578                 return ret;
12579
12580         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12581                 /* to make freplace equivalent to their targets, they need to
12582                  * inherit env->ops and expected_attach_type for the rest of the
12583                  * verification
12584                  */
12585                 env->ops = bpf_verifier_ops[tgt_prog->type];
12586                 prog->expected_attach_type = tgt_prog->expected_attach_type;
12587         }
12588
12589         /* store info about the attachment target that will be used later */
12590         prog->aux->attach_func_proto = tgt_info.tgt_type;
12591         prog->aux->attach_func_name = tgt_info.tgt_name;
12592
12593         if (tgt_prog) {
12594                 prog->aux->saved_dst_prog_type = tgt_prog->type;
12595                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12596         }
12597
12598         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12599                 prog->aux->attach_btf_trace = true;
12600                 return 0;
12601         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12602                 if (!bpf_iter_prog_supported(prog))
12603                         return -EINVAL;
12604                 return 0;
12605         }
12606
12607         if (prog->type == BPF_PROG_TYPE_LSM) {
12608                 ret = bpf_lsm_verify_prog(&env->log, prog);
12609                 if (ret < 0)
12610                         return ret;
12611         }
12612
12613         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
12614         tr = bpf_trampoline_get(key, &tgt_info);
12615         if (!tr)
12616                 return -ENOMEM;
12617
12618         prog->aux->dst_trampoline = tr;
12619         return 0;
12620 }
12621
12622 struct btf *bpf_get_btf_vmlinux(void)
12623 {
12624         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12625                 mutex_lock(&bpf_verifier_lock);
12626                 if (!btf_vmlinux)
12627                         btf_vmlinux = btf_parse_vmlinux();
12628                 mutex_unlock(&bpf_verifier_lock);
12629         }
12630         return btf_vmlinux;
12631 }
12632
12633 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12634               union bpf_attr __user *uattr)
12635 {
12636         u64 start_time = ktime_get_ns();
12637         struct bpf_verifier_env *env;
12638         struct bpf_verifier_log *log;
12639         int i, len, ret = -EINVAL;
12640         bool is_priv;
12641
12642         /* no program is valid */
12643         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12644                 return -EINVAL;
12645
12646         /* 'struct bpf_verifier_env' can be global, but since it's not small,
12647          * allocate/free it every time bpf_check() is called
12648          */
12649         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12650         if (!env)
12651                 return -ENOMEM;
12652         log = &env->log;
12653
12654         len = (*prog)->len;
12655         env->insn_aux_data =
12656                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12657         ret = -ENOMEM;
12658         if (!env->insn_aux_data)
12659                 goto err_free_env;
12660         for (i = 0; i < len; i++)
12661                 env->insn_aux_data[i].orig_idx = i;
12662         env->prog = *prog;
12663         env->ops = bpf_verifier_ops[env->prog->type];
12664         is_priv = bpf_capable();
12665
12666         bpf_get_btf_vmlinux();
12667
12668         /* grab the mutex to protect few globals used by verifier */
12669         if (!is_priv)
12670                 mutex_lock(&bpf_verifier_lock);
12671
12672         if (attr->log_level || attr->log_buf || attr->log_size) {
12673                 /* user requested verbose verifier output
12674                  * and supplied buffer to store the verification trace
12675                  */
12676                 log->level = attr->log_level;
12677                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12678                 log->len_total = attr->log_size;
12679
12680                 ret = -EINVAL;
12681                 /* log attributes have to be sane */
12682                 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
12683                     !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
12684                         goto err_unlock;
12685         }
12686
12687         if (IS_ERR(btf_vmlinux)) {
12688                 /* Either gcc or pahole or kernel are broken. */
12689                 verbose(env, "in-kernel BTF is malformed\n");
12690                 ret = PTR_ERR(btf_vmlinux);
12691                 goto skip_full_check;
12692         }
12693
12694         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12695         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12696                 env->strict_alignment = true;
12697         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12698                 env->strict_alignment = false;
12699
12700         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12701         env->allow_uninit_stack = bpf_allow_uninit_stack();
12702         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12703         env->bypass_spec_v1 = bpf_bypass_spec_v1();
12704         env->bypass_spec_v4 = bpf_bypass_spec_v4();
12705         env->bpf_capable = bpf_capable();
12706
12707         if (is_priv)
12708                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12709
12710         if (bpf_prog_is_dev_bound(env->prog->aux)) {
12711                 ret = bpf_prog_offload_verifier_prep(env->prog);
12712                 if (ret)
12713                         goto skip_full_check;
12714         }
12715
12716         env->explored_states = kvcalloc(state_htab_size(env),
12717                                        sizeof(struct bpf_verifier_state_list *),
12718                                        GFP_USER);
12719         ret = -ENOMEM;
12720         if (!env->explored_states)
12721                 goto skip_full_check;
12722
12723         ret = check_subprogs(env);
12724         if (ret < 0)
12725                 goto skip_full_check;
12726
12727         ret = check_btf_info(env, attr, uattr);
12728         if (ret < 0)
12729                 goto skip_full_check;
12730
12731         ret = check_attach_btf_id(env);
12732         if (ret)
12733                 goto skip_full_check;
12734
12735         ret = resolve_pseudo_ldimm64(env);
12736         if (ret < 0)
12737                 goto skip_full_check;
12738
12739         ret = check_cfg(env);
12740         if (ret < 0)
12741                 goto skip_full_check;
12742
12743         ret = do_check_subprogs(env);
12744         ret = ret ?: do_check_main(env);
12745
12746         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12747                 ret = bpf_prog_offload_finalize(env);
12748
12749 skip_full_check:
12750         kvfree(env->explored_states);
12751
12752         if (ret == 0)
12753                 ret = check_max_stack_depth(env);
12754
12755         /* instruction rewrites happen after this point */
12756         if (is_priv) {
12757                 if (ret == 0)
12758                         opt_hard_wire_dead_code_branches(env);
12759                 if (ret == 0)
12760                         ret = opt_remove_dead_code(env);
12761                 if (ret == 0)
12762                         ret = opt_remove_nops(env);
12763         } else {
12764                 if (ret == 0)
12765                         sanitize_dead_code(env);
12766         }
12767
12768         if (ret == 0)
12769                 /* program is valid, convert *(u32*)(ctx + off) accesses */
12770                 ret = convert_ctx_accesses(env);
12771
12772         if (ret == 0)
12773                 ret = fixup_bpf_calls(env);
12774
12775         /* do 32-bit optimization after insn patching has done so those patched
12776          * insns could be handled correctly.
12777          */
12778         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12779                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12780                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12781                                                                      : false;
12782         }
12783
12784         if (ret == 0)
12785                 ret = fixup_call_args(env);
12786
12787         env->verification_time = ktime_get_ns() - start_time;
12788         print_verification_stats(env);
12789
12790         if (log->level && bpf_verifier_log_full(log))
12791                 ret = -ENOSPC;
12792         if (log->level && !log->ubuf) {
12793                 ret = -EFAULT;
12794                 goto err_release_maps;
12795         }
12796
12797         if (ret)
12798                 goto err_release_maps;
12799
12800         if (env->used_map_cnt) {
12801                 /* if program passed verifier, update used_maps in bpf_prog_info */
12802                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12803                                                           sizeof(env->used_maps[0]),
12804                                                           GFP_KERNEL);
12805
12806                 if (!env->prog->aux->used_maps) {
12807                         ret = -ENOMEM;
12808                         goto err_release_maps;
12809                 }
12810
12811                 memcpy(env->prog->aux->used_maps, env->used_maps,
12812                        sizeof(env->used_maps[0]) * env->used_map_cnt);
12813                 env->prog->aux->used_map_cnt = env->used_map_cnt;
12814         }
12815         if (env->used_btf_cnt) {
12816                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
12817                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
12818                                                           sizeof(env->used_btfs[0]),
12819                                                           GFP_KERNEL);
12820                 if (!env->prog->aux->used_btfs) {
12821                         ret = -ENOMEM;
12822                         goto err_release_maps;
12823                 }
12824
12825                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
12826                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
12827                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
12828         }
12829         if (env->used_map_cnt || env->used_btf_cnt) {
12830                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12831                  * bpf_ld_imm64 instructions
12832                  */
12833                 convert_pseudo_ld_imm64(env);
12834         }
12835
12836         adjust_btf_func(env);
12837
12838 err_release_maps:
12839         if (!env->prog->aux->used_maps)
12840                 /* if we didn't copy map pointers into bpf_prog_info, release
12841                  * them now. Otherwise free_used_maps() will release them.
12842                  */
12843                 release_maps(env);
12844         if (!env->prog->aux->used_btfs)
12845                 release_btfs(env);
12846
12847         /* extension progs temporarily inherit the attach_type of their targets
12848            for verification purposes, so set it back to zero before returning
12849          */
12850         if (env->prog->type == BPF_PROG_TYPE_EXT)
12851                 env->prog->expected_attach_type = 0;
12852
12853         *prog = env->prog;
12854 err_unlock:
12855         if (!is_priv)
12856                 mutex_unlock(&bpf_verifier_lock);
12857         vfree(env->insn_aux_data);
12858 err_free_env:
12859         kfree(env);
12860         return ret;
12861 }