GNU Linux-libre 5.10.215-gnu1
[releases.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 struct bpf_call_arg_meta {
232         struct bpf_map *map_ptr;
233         bool raw_mode;
234         bool pkt_access;
235         int regno;
236         int access_size;
237         int mem_size;
238         u64 msize_max_value;
239         int ref_obj_id;
240         int func_id;
241         u32 btf_id;
242         u32 ret_btf_id;
243 };
244
245 struct btf *btf_vmlinux;
246
247 static DEFINE_MUTEX(bpf_verifier_lock);
248
249 static const struct bpf_line_info *
250 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
251 {
252         const struct bpf_line_info *linfo;
253         const struct bpf_prog *prog;
254         u32 i, nr_linfo;
255
256         prog = env->prog;
257         nr_linfo = prog->aux->nr_linfo;
258
259         if (!nr_linfo || insn_off >= prog->len)
260                 return NULL;
261
262         linfo = prog->aux->linfo;
263         for (i = 1; i < nr_linfo; i++)
264                 if (insn_off < linfo[i].insn_off)
265                         break;
266
267         return &linfo[i - 1];
268 }
269
270 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
271                        va_list args)
272 {
273         unsigned int n;
274
275         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
276
277         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
278                   "verifier log line truncated - local buffer too short\n");
279
280         n = min(log->len_total - log->len_used - 1, n);
281         log->kbuf[n] = '\0';
282
283         if (log->level == BPF_LOG_KERNEL) {
284                 pr_err("BPF:%s\n", log->kbuf);
285                 return;
286         }
287         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
288                 log->len_used += n;
289         else
290                 log->ubuf = NULL;
291 }
292
293 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
294 {
295         char zero = 0;
296
297         if (!bpf_verifier_log_needed(log))
298                 return;
299
300         log->len_used = new_pos;
301         if (put_user(zero, log->ubuf + new_pos))
302                 log->ubuf = NULL;
303 }
304
305 /* log_level controls verbosity level of eBPF verifier.
306  * bpf_verifier_log_write() is used to dump the verification trace to the log,
307  * so the user can figure out what's wrong with the program
308  */
309 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
310                                            const char *fmt, ...)
311 {
312         va_list args;
313
314         if (!bpf_verifier_log_needed(&env->log))
315                 return;
316
317         va_start(args, fmt);
318         bpf_verifier_vlog(&env->log, fmt, args);
319         va_end(args);
320 }
321 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
322
323 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
324 {
325         struct bpf_verifier_env *env = private_data;
326         va_list args;
327
328         if (!bpf_verifier_log_needed(&env->log))
329                 return;
330
331         va_start(args, fmt);
332         bpf_verifier_vlog(&env->log, fmt, args);
333         va_end(args);
334 }
335
336 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
337                             const char *fmt, ...)
338 {
339         va_list args;
340
341         if (!bpf_verifier_log_needed(log))
342                 return;
343
344         va_start(args, fmt);
345         bpf_verifier_vlog(log, fmt, args);
346         va_end(args);
347 }
348
349 static const char *ltrim(const char *s)
350 {
351         while (isspace(*s))
352                 s++;
353
354         return s;
355 }
356
357 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
358                                          u32 insn_off,
359                                          const char *prefix_fmt, ...)
360 {
361         const struct bpf_line_info *linfo;
362
363         if (!bpf_verifier_log_needed(&env->log))
364                 return;
365
366         linfo = find_linfo(env, insn_off);
367         if (!linfo || linfo == env->prev_linfo)
368                 return;
369
370         if (prefix_fmt) {
371                 va_list args;
372
373                 va_start(args, prefix_fmt);
374                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
375                 va_end(args);
376         }
377
378         verbose(env, "%s\n",
379                 ltrim(btf_name_by_offset(env->prog->aux->btf,
380                                          linfo->line_off)));
381
382         env->prev_linfo = linfo;
383 }
384
385 static bool type_is_pkt_pointer(enum bpf_reg_type type)
386 {
387         return type == PTR_TO_PACKET ||
388                type == PTR_TO_PACKET_META;
389 }
390
391 static bool type_is_sk_pointer(enum bpf_reg_type type)
392 {
393         return type == PTR_TO_SOCKET ||
394                 type == PTR_TO_SOCK_COMMON ||
395                 type == PTR_TO_TCP_SOCK ||
396                 type == PTR_TO_XDP_SOCK;
397 }
398
399 static bool reg_type_not_null(enum bpf_reg_type type)
400 {
401         return type == PTR_TO_SOCKET ||
402                 type == PTR_TO_TCP_SOCK ||
403                 type == PTR_TO_MAP_VALUE ||
404                 type == PTR_TO_SOCK_COMMON;
405 }
406
407 static bool reg_type_may_be_null(enum bpf_reg_type type)
408 {
409         return type == PTR_TO_MAP_VALUE_OR_NULL ||
410                type == PTR_TO_SOCKET_OR_NULL ||
411                type == PTR_TO_SOCK_COMMON_OR_NULL ||
412                type == PTR_TO_TCP_SOCK_OR_NULL ||
413                type == PTR_TO_BTF_ID_OR_NULL ||
414                type == PTR_TO_MEM_OR_NULL ||
415                type == PTR_TO_RDONLY_BUF_OR_NULL ||
416                type == PTR_TO_RDWR_BUF_OR_NULL;
417 }
418
419 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
420 {
421         return reg->type == PTR_TO_MAP_VALUE &&
422                 map_value_has_spin_lock(reg->map_ptr);
423 }
424
425 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
426 {
427         return type == PTR_TO_SOCKET ||
428                 type == PTR_TO_SOCKET_OR_NULL ||
429                 type == PTR_TO_TCP_SOCK ||
430                 type == PTR_TO_TCP_SOCK_OR_NULL ||
431                 type == PTR_TO_MEM ||
432                 type == PTR_TO_MEM_OR_NULL;
433 }
434
435 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
436 {
437         return type == ARG_PTR_TO_SOCK_COMMON;
438 }
439
440 static bool arg_type_may_be_null(enum bpf_arg_type type)
441 {
442         return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
443                type == ARG_PTR_TO_MEM_OR_NULL ||
444                type == ARG_PTR_TO_CTX_OR_NULL ||
445                type == ARG_PTR_TO_SOCKET_OR_NULL ||
446                type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
447 }
448
449 /* Determine whether the function releases some resources allocated by another
450  * function call. The first reference type argument will be assumed to be
451  * released by release_reference().
452  */
453 static bool is_release_function(enum bpf_func_id func_id)
454 {
455         return func_id == BPF_FUNC_sk_release ||
456                func_id == BPF_FUNC_ringbuf_submit ||
457                func_id == BPF_FUNC_ringbuf_discard;
458 }
459
460 static bool may_be_acquire_function(enum bpf_func_id func_id)
461 {
462         return func_id == BPF_FUNC_sk_lookup_tcp ||
463                 func_id == BPF_FUNC_sk_lookup_udp ||
464                 func_id == BPF_FUNC_skc_lookup_tcp ||
465                 func_id == BPF_FUNC_map_lookup_elem ||
466                 func_id == BPF_FUNC_ringbuf_reserve;
467 }
468
469 static bool is_acquire_function(enum bpf_func_id func_id,
470                                 const struct bpf_map *map)
471 {
472         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
473
474         if (func_id == BPF_FUNC_sk_lookup_tcp ||
475             func_id == BPF_FUNC_sk_lookup_udp ||
476             func_id == BPF_FUNC_skc_lookup_tcp ||
477             func_id == BPF_FUNC_ringbuf_reserve)
478                 return true;
479
480         if (func_id == BPF_FUNC_map_lookup_elem &&
481             (map_type == BPF_MAP_TYPE_SOCKMAP ||
482              map_type == BPF_MAP_TYPE_SOCKHASH))
483                 return true;
484
485         return false;
486 }
487
488 static bool is_ptr_cast_function(enum bpf_func_id func_id)
489 {
490         return func_id == BPF_FUNC_tcp_sock ||
491                 func_id == BPF_FUNC_sk_fullsock ||
492                 func_id == BPF_FUNC_skc_to_tcp_sock ||
493                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
494                 func_id == BPF_FUNC_skc_to_udp6_sock ||
495                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
496                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
497 }
498
499 /* string representation of 'enum bpf_reg_type' */
500 static const char * const reg_type_str[] = {
501         [NOT_INIT]              = "?",
502         [SCALAR_VALUE]          = "inv",
503         [PTR_TO_CTX]            = "ctx",
504         [CONST_PTR_TO_MAP]      = "map_ptr",
505         [PTR_TO_MAP_VALUE]      = "map_value",
506         [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
507         [PTR_TO_STACK]          = "fp",
508         [PTR_TO_PACKET]         = "pkt",
509         [PTR_TO_PACKET_META]    = "pkt_meta",
510         [PTR_TO_PACKET_END]     = "pkt_end",
511         [PTR_TO_FLOW_KEYS]      = "flow_keys",
512         [PTR_TO_SOCKET]         = "sock",
513         [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
514         [PTR_TO_SOCK_COMMON]    = "sock_common",
515         [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
516         [PTR_TO_TCP_SOCK]       = "tcp_sock",
517         [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
518         [PTR_TO_TP_BUFFER]      = "tp_buffer",
519         [PTR_TO_XDP_SOCK]       = "xdp_sock",
520         [PTR_TO_BTF_ID]         = "ptr_",
521         [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
522         [PTR_TO_PERCPU_BTF_ID]  = "percpu_ptr_",
523         [PTR_TO_MEM]            = "mem",
524         [PTR_TO_MEM_OR_NULL]    = "mem_or_null",
525         [PTR_TO_RDONLY_BUF]     = "rdonly_buf",
526         [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
527         [PTR_TO_RDWR_BUF]       = "rdwr_buf",
528         [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
529 };
530
531 static char slot_type_char[] = {
532         [STACK_INVALID] = '?',
533         [STACK_SPILL]   = 'r',
534         [STACK_MISC]    = 'm',
535         [STACK_ZERO]    = '0',
536 };
537
538 static void print_liveness(struct bpf_verifier_env *env,
539                            enum bpf_reg_liveness live)
540 {
541         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
542             verbose(env, "_");
543         if (live & REG_LIVE_READ)
544                 verbose(env, "r");
545         if (live & REG_LIVE_WRITTEN)
546                 verbose(env, "w");
547         if (live & REG_LIVE_DONE)
548                 verbose(env, "D");
549 }
550
551 static struct bpf_func_state *func(struct bpf_verifier_env *env,
552                                    const struct bpf_reg_state *reg)
553 {
554         struct bpf_verifier_state *cur = env->cur_state;
555
556         return cur->frame[reg->frameno];
557 }
558
559 const char *kernel_type_name(u32 id)
560 {
561         return btf_name_by_offset(btf_vmlinux,
562                                   btf_type_by_id(btf_vmlinux, id)->name_off);
563 }
564
565 /* The reg state of a pointer or a bounded scalar was saved when
566  * it was spilled to the stack.
567  */
568 static bool is_spilled_reg(const struct bpf_stack_state *stack)
569 {
570         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
571 }
572
573 static void scrub_spilled_slot(u8 *stype)
574 {
575         if (*stype != STACK_INVALID)
576                 *stype = STACK_MISC;
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_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 (is_spilled_reg(&state->stack[i])) {
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 bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1090 {
1091         return type_is_pkt_pointer(reg->type);
1092 }
1093
1094 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1095 {
1096         return reg_is_pkt_pointer(reg) ||
1097                reg->type == PTR_TO_PACKET_END;
1098 }
1099
1100 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1101 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1102                                     enum bpf_reg_type which)
1103 {
1104         /* The register can already have a range from prior markings.
1105          * This is fine as long as it hasn't been advanced from its
1106          * origin.
1107          */
1108         return reg->type == which &&
1109                reg->id == 0 &&
1110                reg->off == 0 &&
1111                tnum_equals_const(reg->var_off, 0);
1112 }
1113
1114 /* Reset the min/max bounds of a register */
1115 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1116 {
1117         reg->smin_value = S64_MIN;
1118         reg->smax_value = S64_MAX;
1119         reg->umin_value = 0;
1120         reg->umax_value = U64_MAX;
1121
1122         reg->s32_min_value = S32_MIN;
1123         reg->s32_max_value = S32_MAX;
1124         reg->u32_min_value = 0;
1125         reg->u32_max_value = U32_MAX;
1126 }
1127
1128 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1129 {
1130         reg->smin_value = S64_MIN;
1131         reg->smax_value = S64_MAX;
1132         reg->umin_value = 0;
1133         reg->umax_value = U64_MAX;
1134 }
1135
1136 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1137 {
1138         reg->s32_min_value = S32_MIN;
1139         reg->s32_max_value = S32_MAX;
1140         reg->u32_min_value = 0;
1141         reg->u32_max_value = U32_MAX;
1142 }
1143
1144 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1145 {
1146         struct tnum var32_off = tnum_subreg(reg->var_off);
1147
1148         /* min signed is max(sign bit) | min(other bits) */
1149         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1150                         var32_off.value | (var32_off.mask & S32_MIN));
1151         /* max signed is min(sign bit) | max(other bits) */
1152         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1153                         var32_off.value | (var32_off.mask & S32_MAX));
1154         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1155         reg->u32_max_value = min(reg->u32_max_value,
1156                                  (u32)(var32_off.value | var32_off.mask));
1157 }
1158
1159 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1160 {
1161         /* min signed is max(sign bit) | min(other bits) */
1162         reg->smin_value = max_t(s64, reg->smin_value,
1163                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1164         /* max signed is min(sign bit) | max(other bits) */
1165         reg->smax_value = min_t(s64, reg->smax_value,
1166                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1167         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1168         reg->umax_value = min(reg->umax_value,
1169                               reg->var_off.value | reg->var_off.mask);
1170 }
1171
1172 static void __update_reg_bounds(struct bpf_reg_state *reg)
1173 {
1174         __update_reg32_bounds(reg);
1175         __update_reg64_bounds(reg);
1176 }
1177
1178 /* Uses signed min/max values to inform unsigned, and vice-versa */
1179 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1180 {
1181         /* Learn sign from signed bounds.
1182          * If we cannot cross the sign boundary, then signed and unsigned bounds
1183          * are the same, so combine.  This works even in the negative case, e.g.
1184          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1185          */
1186         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1187                 reg->s32_min_value = reg->u32_min_value =
1188                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1189                 reg->s32_max_value = reg->u32_max_value =
1190                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1191                 return;
1192         }
1193         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1194          * boundary, so we must be careful.
1195          */
1196         if ((s32)reg->u32_max_value >= 0) {
1197                 /* Positive.  We can't learn anything from the smin, but smax
1198                  * is positive, hence safe.
1199                  */
1200                 reg->s32_min_value = reg->u32_min_value;
1201                 reg->s32_max_value = reg->u32_max_value =
1202                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1203         } else if ((s32)reg->u32_min_value < 0) {
1204                 /* Negative.  We can't learn anything from the smax, but smin
1205                  * is negative, hence safe.
1206                  */
1207                 reg->s32_min_value = reg->u32_min_value =
1208                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1209                 reg->s32_max_value = reg->u32_max_value;
1210         }
1211 }
1212
1213 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1214 {
1215         /* Learn sign from signed bounds.
1216          * If we cannot cross the sign boundary, then signed and unsigned bounds
1217          * are the same, so combine.  This works even in the negative case, e.g.
1218          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1219          */
1220         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1221                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1222                                                           reg->umin_value);
1223                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1224                                                           reg->umax_value);
1225                 return;
1226         }
1227         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1228          * boundary, so we must be careful.
1229          */
1230         if ((s64)reg->umax_value >= 0) {
1231                 /* Positive.  We can't learn anything from the smin, but smax
1232                  * is positive, hence safe.
1233                  */
1234                 reg->smin_value = reg->umin_value;
1235                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1236                                                           reg->umax_value);
1237         } else if ((s64)reg->umin_value < 0) {
1238                 /* Negative.  We can't learn anything from the smax, but smin
1239                  * is negative, hence safe.
1240                  */
1241                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1242                                                           reg->umin_value);
1243                 reg->smax_value = reg->umax_value;
1244         }
1245 }
1246
1247 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1248 {
1249         __reg32_deduce_bounds(reg);
1250         __reg64_deduce_bounds(reg);
1251 }
1252
1253 /* Attempts to improve var_off based on unsigned min/max information */
1254 static void __reg_bound_offset(struct bpf_reg_state *reg)
1255 {
1256         struct tnum var64_off = tnum_intersect(reg->var_off,
1257                                                tnum_range(reg->umin_value,
1258                                                           reg->umax_value));
1259         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1260                                                 tnum_range(reg->u32_min_value,
1261                                                            reg->u32_max_value));
1262
1263         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1264 }
1265
1266 static void reg_bounds_sync(struct bpf_reg_state *reg)
1267 {
1268         /* We might have learned new bounds from the var_off. */
1269         __update_reg_bounds(reg);
1270         /* We might have learned something about the sign bit. */
1271         __reg_deduce_bounds(reg);
1272         /* We might have learned some bits from the bounds. */
1273         __reg_bound_offset(reg);
1274         /* Intersecting with the old var_off might have improved our bounds
1275          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1276          * then new var_off is (0; 0x7f...fc) which improves our umax.
1277          */
1278         __update_reg_bounds(reg);
1279 }
1280
1281 static bool __reg32_bound_s64(s32 a)
1282 {
1283         return a >= 0 && a <= S32_MAX;
1284 }
1285
1286 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1287 {
1288         reg->umin_value = reg->u32_min_value;
1289         reg->umax_value = reg->u32_max_value;
1290
1291         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1292          * be positive otherwise set to worse case bounds and refine later
1293          * from tnum.
1294          */
1295         if (__reg32_bound_s64(reg->s32_min_value) &&
1296             __reg32_bound_s64(reg->s32_max_value)) {
1297                 reg->smin_value = reg->s32_min_value;
1298                 reg->smax_value = reg->s32_max_value;
1299         } else {
1300                 reg->smin_value = 0;
1301                 reg->smax_value = U32_MAX;
1302         }
1303 }
1304
1305 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1306 {
1307         /* special case when 64-bit register has upper 32-bit register
1308          * zeroed. Typically happens after zext or <<32, >>32 sequence
1309          * allowing us to use 32-bit bounds directly,
1310          */
1311         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1312                 __reg_assign_32_into_64(reg);
1313         } else {
1314                 /* Otherwise the best we can do is push lower 32bit known and
1315                  * unknown bits into register (var_off set from jmp logic)
1316                  * then learn as much as possible from the 64-bit tnum
1317                  * known and unknown bits. The previous smin/smax bounds are
1318                  * invalid here because of jmp32 compare so mark them unknown
1319                  * so they do not impact tnum bounds calculation.
1320                  */
1321                 __mark_reg64_unbounded(reg);
1322         }
1323         reg_bounds_sync(reg);
1324 }
1325
1326 static bool __reg64_bound_s32(s64 a)
1327 {
1328         return a >= S32_MIN && a <= S32_MAX;
1329 }
1330
1331 static bool __reg64_bound_u32(u64 a)
1332 {
1333         return a >= U32_MIN && a <= U32_MAX;
1334 }
1335
1336 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1337 {
1338         __mark_reg32_unbounded(reg);
1339         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1340                 reg->s32_min_value = (s32)reg->smin_value;
1341                 reg->s32_max_value = (s32)reg->smax_value;
1342         }
1343         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1344                 reg->u32_min_value = (u32)reg->umin_value;
1345                 reg->u32_max_value = (u32)reg->umax_value;
1346         }
1347         reg_bounds_sync(reg);
1348 }
1349
1350 /* Mark a register as having a completely unknown (scalar) value. */
1351 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1352                                struct bpf_reg_state *reg)
1353 {
1354         /*
1355          * Clear type, id, off, and union(map_ptr, range) and
1356          * padding between 'type' and union
1357          */
1358         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1359         reg->type = SCALAR_VALUE;
1360         reg->var_off = tnum_unknown;
1361         reg->frameno = 0;
1362         reg->precise = !env->bpf_capable;
1363         __mark_reg_unbounded(reg);
1364 }
1365
1366 static void mark_reg_unknown(struct bpf_verifier_env *env,
1367                              struct bpf_reg_state *regs, u32 regno)
1368 {
1369         if (WARN_ON(regno >= MAX_BPF_REG)) {
1370                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1371                 /* Something bad happened, let's kill all regs except FP */
1372                 for (regno = 0; regno < BPF_REG_FP; regno++)
1373                         __mark_reg_not_init(env, regs + regno);
1374                 return;
1375         }
1376         __mark_reg_unknown(env, regs + regno);
1377 }
1378
1379 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1380                                 struct bpf_reg_state *reg)
1381 {
1382         __mark_reg_unknown(env, reg);
1383         reg->type = NOT_INIT;
1384 }
1385
1386 static void mark_reg_not_init(struct bpf_verifier_env *env,
1387                               struct bpf_reg_state *regs, u32 regno)
1388 {
1389         if (WARN_ON(regno >= MAX_BPF_REG)) {
1390                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1391                 /* Something bad happened, let's kill all regs except FP */
1392                 for (regno = 0; regno < BPF_REG_FP; regno++)
1393                         __mark_reg_not_init(env, regs + regno);
1394                 return;
1395         }
1396         __mark_reg_not_init(env, regs + regno);
1397 }
1398
1399 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1400                             struct bpf_reg_state *regs, u32 regno,
1401                             enum bpf_reg_type reg_type, u32 btf_id)
1402 {
1403         if (reg_type == SCALAR_VALUE) {
1404                 mark_reg_unknown(env, regs, regno);
1405                 return;
1406         }
1407         mark_reg_known_zero(env, regs, regno);
1408         regs[regno].type = PTR_TO_BTF_ID;
1409         regs[regno].btf_id = btf_id;
1410 }
1411
1412 #define DEF_NOT_SUBREG  (0)
1413 static void init_reg_state(struct bpf_verifier_env *env,
1414                            struct bpf_func_state *state)
1415 {
1416         struct bpf_reg_state *regs = state->regs;
1417         int i;
1418
1419         for (i = 0; i < MAX_BPF_REG; i++) {
1420                 mark_reg_not_init(env, regs, i);
1421                 regs[i].live = REG_LIVE_NONE;
1422                 regs[i].parent = NULL;
1423                 regs[i].subreg_def = DEF_NOT_SUBREG;
1424         }
1425
1426         /* frame pointer */
1427         regs[BPF_REG_FP].type = PTR_TO_STACK;
1428         mark_reg_known_zero(env, regs, BPF_REG_FP);
1429         regs[BPF_REG_FP].frameno = state->frameno;
1430 }
1431
1432 #define BPF_MAIN_FUNC (-1)
1433 static void init_func_state(struct bpf_verifier_env *env,
1434                             struct bpf_func_state *state,
1435                             int callsite, int frameno, int subprogno)
1436 {
1437         state->callsite = callsite;
1438         state->frameno = frameno;
1439         state->subprogno = subprogno;
1440         init_reg_state(env, state);
1441 }
1442
1443 enum reg_arg_type {
1444         SRC_OP,         /* register is used as source operand */
1445         DST_OP,         /* register is used as destination operand */
1446         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1447 };
1448
1449 static int cmp_subprogs(const void *a, const void *b)
1450 {
1451         return ((struct bpf_subprog_info *)a)->start -
1452                ((struct bpf_subprog_info *)b)->start;
1453 }
1454
1455 static int find_subprog(struct bpf_verifier_env *env, int off)
1456 {
1457         struct bpf_subprog_info *p;
1458
1459         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1460                     sizeof(env->subprog_info[0]), cmp_subprogs);
1461         if (!p)
1462                 return -ENOENT;
1463         return p - env->subprog_info;
1464
1465 }
1466
1467 static int add_subprog(struct bpf_verifier_env *env, int off)
1468 {
1469         int insn_cnt = env->prog->len;
1470         int ret;
1471
1472         if (off >= insn_cnt || off < 0) {
1473                 verbose(env, "call to invalid destination\n");
1474                 return -EINVAL;
1475         }
1476         ret = find_subprog(env, off);
1477         if (ret >= 0)
1478                 return 0;
1479         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1480                 verbose(env, "too many subprograms\n");
1481                 return -E2BIG;
1482         }
1483         env->subprog_info[env->subprog_cnt++].start = off;
1484         sort(env->subprog_info, env->subprog_cnt,
1485              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1486         return 0;
1487 }
1488
1489 static int check_subprogs(struct bpf_verifier_env *env)
1490 {
1491         int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1492         struct bpf_subprog_info *subprog = env->subprog_info;
1493         struct bpf_insn *insn = env->prog->insnsi;
1494         int insn_cnt = env->prog->len;
1495
1496         /* Add entry function. */
1497         ret = add_subprog(env, 0);
1498         if (ret < 0)
1499                 return ret;
1500
1501         /* determine subprog starts. The end is one before the next starts */
1502         for (i = 0; i < insn_cnt; i++) {
1503                 if (insn[i].code != (BPF_JMP | BPF_CALL))
1504                         continue;
1505                 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1506                         continue;
1507                 if (!env->bpf_capable) {
1508                         verbose(env,
1509                                 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1510                         return -EPERM;
1511                 }
1512                 ret = add_subprog(env, i + insn[i].imm + 1);
1513                 if (ret < 0)
1514                         return ret;
1515         }
1516
1517         /* Add a fake 'exit' subprog which could simplify subprog iteration
1518          * logic. 'subprog_cnt' should not be increased.
1519          */
1520         subprog[env->subprog_cnt].start = insn_cnt;
1521
1522         if (env->log.level & BPF_LOG_LEVEL2)
1523                 for (i = 0; i < env->subprog_cnt; i++)
1524                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
1525
1526         /* now check that all jumps are within the same subprog */
1527         subprog_start = subprog[cur_subprog].start;
1528         subprog_end = subprog[cur_subprog + 1].start;
1529         for (i = 0; i < insn_cnt; i++) {
1530                 u8 code = insn[i].code;
1531
1532                 if (code == (BPF_JMP | BPF_CALL) &&
1533                     insn[i].imm == BPF_FUNC_tail_call &&
1534                     insn[i].src_reg != BPF_PSEUDO_CALL)
1535                         subprog[cur_subprog].has_tail_call = true;
1536                 if (BPF_CLASS(code) == BPF_LD &&
1537                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1538                         subprog[cur_subprog].has_ld_abs = true;
1539                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1540                         goto next;
1541                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1542                         goto next;
1543                 off = i + insn[i].off + 1;
1544                 if (off < subprog_start || off >= subprog_end) {
1545                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
1546                         return -EINVAL;
1547                 }
1548 next:
1549                 if (i == subprog_end - 1) {
1550                         /* to avoid fall-through from one subprog into another
1551                          * the last insn of the subprog should be either exit
1552                          * or unconditional jump back
1553                          */
1554                         if (code != (BPF_JMP | BPF_EXIT) &&
1555                             code != (BPF_JMP | BPF_JA)) {
1556                                 verbose(env, "last insn is not an exit or jmp\n");
1557                                 return -EINVAL;
1558                         }
1559                         subprog_start = subprog_end;
1560                         cur_subprog++;
1561                         if (cur_subprog < env->subprog_cnt)
1562                                 subprog_end = subprog[cur_subprog + 1].start;
1563                 }
1564         }
1565         return 0;
1566 }
1567
1568 /* Parentage chain of this register (or stack slot) should take care of all
1569  * issues like callee-saved registers, stack slot allocation time, etc.
1570  */
1571 static int mark_reg_read(struct bpf_verifier_env *env,
1572                          const struct bpf_reg_state *state,
1573                          struct bpf_reg_state *parent, u8 flag)
1574 {
1575         bool writes = parent == state->parent; /* Observe write marks */
1576         int cnt = 0;
1577
1578         while (parent) {
1579                 /* if read wasn't screened by an earlier write ... */
1580                 if (writes && state->live & REG_LIVE_WRITTEN)
1581                         break;
1582                 if (parent->live & REG_LIVE_DONE) {
1583                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1584                                 reg_type_str[parent->type],
1585                                 parent->var_off.value, parent->off);
1586                         return -EFAULT;
1587                 }
1588                 /* The first condition is more likely to be true than the
1589                  * second, checked it first.
1590                  */
1591                 if ((parent->live & REG_LIVE_READ) == flag ||
1592                     parent->live & REG_LIVE_READ64)
1593                         /* The parentage chain never changes and
1594                          * this parent was already marked as LIVE_READ.
1595                          * There is no need to keep walking the chain again and
1596                          * keep re-marking all parents as LIVE_READ.
1597                          * This case happens when the same register is read
1598                          * multiple times without writes into it in-between.
1599                          * Also, if parent has the stronger REG_LIVE_READ64 set,
1600                          * then no need to set the weak REG_LIVE_READ32.
1601                          */
1602                         break;
1603                 /* ... then we depend on parent's value */
1604                 parent->live |= flag;
1605                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1606                 if (flag == REG_LIVE_READ64)
1607                         parent->live &= ~REG_LIVE_READ32;
1608                 state = parent;
1609                 parent = state->parent;
1610                 writes = true;
1611                 cnt++;
1612         }
1613
1614         if (env->longest_mark_read_walk < cnt)
1615                 env->longest_mark_read_walk = cnt;
1616         return 0;
1617 }
1618
1619 /* This function is supposed to be used by the following 32-bit optimization
1620  * code only. It returns TRUE if the source or destination register operates
1621  * on 64-bit, otherwise return FALSE.
1622  */
1623 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1624                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1625 {
1626         u8 code, class, op;
1627
1628         code = insn->code;
1629         class = BPF_CLASS(code);
1630         op = BPF_OP(code);
1631         if (class == BPF_JMP) {
1632                 /* BPF_EXIT for "main" will reach here. Return TRUE
1633                  * conservatively.
1634                  */
1635                 if (op == BPF_EXIT)
1636                         return true;
1637                 if (op == BPF_CALL) {
1638                         /* BPF to BPF call will reach here because of marking
1639                          * caller saved clobber with DST_OP_NO_MARK for which we
1640                          * don't care the register def because they are anyway
1641                          * marked as NOT_INIT already.
1642                          */
1643                         if (insn->src_reg == BPF_PSEUDO_CALL)
1644                                 return false;
1645                         /* Helper call will reach here because of arg type
1646                          * check, conservatively return TRUE.
1647                          */
1648                         if (t == SRC_OP)
1649                                 return true;
1650
1651                         return false;
1652                 }
1653         }
1654
1655         if (class == BPF_ALU64 || class == BPF_JMP ||
1656             /* BPF_END always use BPF_ALU class. */
1657             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1658                 return true;
1659
1660         if (class == BPF_ALU || class == BPF_JMP32)
1661                 return false;
1662
1663         if (class == BPF_LDX) {
1664                 if (t != SRC_OP)
1665                         return BPF_SIZE(code) == BPF_DW;
1666                 /* LDX source must be ptr. */
1667                 return true;
1668         }
1669
1670         if (class == BPF_STX) {
1671                 if (reg->type != SCALAR_VALUE)
1672                         return true;
1673                 return BPF_SIZE(code) == BPF_DW;
1674         }
1675
1676         if (class == BPF_LD) {
1677                 u8 mode = BPF_MODE(code);
1678
1679                 /* LD_IMM64 */
1680                 if (mode == BPF_IMM)
1681                         return true;
1682
1683                 /* Both LD_IND and LD_ABS return 32-bit data. */
1684                 if (t != SRC_OP)
1685                         return  false;
1686
1687                 /* Implicit ctx ptr. */
1688                 if (regno == BPF_REG_6)
1689                         return true;
1690
1691                 /* Explicit source could be any width. */
1692                 return true;
1693         }
1694
1695         if (class == BPF_ST)
1696                 /* The only source register for BPF_ST is a ptr. */
1697                 return true;
1698
1699         /* Conservatively return true at default. */
1700         return true;
1701 }
1702
1703 /* Return TRUE if INSN doesn't have explicit value define. */
1704 static bool insn_no_def(struct bpf_insn *insn)
1705 {
1706         u8 class = BPF_CLASS(insn->code);
1707
1708         return (class == BPF_JMP || class == BPF_JMP32 ||
1709                 class == BPF_STX || class == BPF_ST);
1710 }
1711
1712 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1713 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1714 {
1715         if (insn_no_def(insn))
1716                 return false;
1717
1718         return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1719 }
1720
1721 static void mark_insn_zext(struct bpf_verifier_env *env,
1722                            struct bpf_reg_state *reg)
1723 {
1724         s32 def_idx = reg->subreg_def;
1725
1726         if (def_idx == DEF_NOT_SUBREG)
1727                 return;
1728
1729         env->insn_aux_data[def_idx - 1].zext_dst = true;
1730         /* The dst will be zero extended, so won't be sub-register anymore. */
1731         reg->subreg_def = DEF_NOT_SUBREG;
1732 }
1733
1734 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1735                          enum reg_arg_type t)
1736 {
1737         struct bpf_verifier_state *vstate = env->cur_state;
1738         struct bpf_func_state *state = vstate->frame[vstate->curframe];
1739         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1740         struct bpf_reg_state *reg, *regs = state->regs;
1741         bool rw64;
1742
1743         if (regno >= MAX_BPF_REG) {
1744                 verbose(env, "R%d is invalid\n", regno);
1745                 return -EINVAL;
1746         }
1747
1748         reg = &regs[regno];
1749         rw64 = is_reg64(env, insn, regno, reg, t);
1750         if (t == SRC_OP) {
1751                 /* check whether register used as source operand can be read */
1752                 if (reg->type == NOT_INIT) {
1753                         verbose(env, "R%d !read_ok\n", regno);
1754                         return -EACCES;
1755                 }
1756                 /* We don't need to worry about FP liveness because it's read-only */
1757                 if (regno == BPF_REG_FP)
1758                         return 0;
1759
1760                 if (rw64)
1761                         mark_insn_zext(env, reg);
1762
1763                 return mark_reg_read(env, reg, reg->parent,
1764                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1765         } else {
1766                 /* check whether register used as dest operand can be written to */
1767                 if (regno == BPF_REG_FP) {
1768                         verbose(env, "frame pointer is read only\n");
1769                         return -EACCES;
1770                 }
1771                 reg->live |= REG_LIVE_WRITTEN;
1772                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1773                 if (t == DST_OP)
1774                         mark_reg_unknown(env, regs, regno);
1775         }
1776         return 0;
1777 }
1778
1779 /* for any branch, call, exit record the history of jmps in the given state */
1780 static int push_jmp_history(struct bpf_verifier_env *env,
1781                             struct bpf_verifier_state *cur)
1782 {
1783         u32 cnt = cur->jmp_history_cnt;
1784         struct bpf_idx_pair *p;
1785
1786         cnt++;
1787         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1788         if (!p)
1789                 return -ENOMEM;
1790         p[cnt - 1].idx = env->insn_idx;
1791         p[cnt - 1].prev_idx = env->prev_insn_idx;
1792         cur->jmp_history = p;
1793         cur->jmp_history_cnt = cnt;
1794         return 0;
1795 }
1796
1797 /* Backtrack one insn at a time. If idx is not at the top of recorded
1798  * history then previous instruction came from straight line execution.
1799  */
1800 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1801                              u32 *history)
1802 {
1803         u32 cnt = *history;
1804
1805         if (cnt && st->jmp_history[cnt - 1].idx == i) {
1806                 i = st->jmp_history[cnt - 1].prev_idx;
1807                 (*history)--;
1808         } else {
1809                 i--;
1810         }
1811         return i;
1812 }
1813
1814 /* For given verifier state backtrack_insn() is called from the last insn to
1815  * the first insn. Its purpose is to compute a bitmask of registers and
1816  * stack slots that needs precision in the parent verifier state.
1817  */
1818 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1819                           u32 *reg_mask, u64 *stack_mask)
1820 {
1821         const struct bpf_insn_cbs cbs = {
1822                 .cb_print       = verbose,
1823                 .private_data   = env,
1824         };
1825         struct bpf_insn *insn = env->prog->insnsi + idx;
1826         u8 class = BPF_CLASS(insn->code);
1827         u8 opcode = BPF_OP(insn->code);
1828         u8 mode = BPF_MODE(insn->code);
1829         u32 dreg = 1u << insn->dst_reg;
1830         u32 sreg = 1u << insn->src_reg;
1831         u32 spi;
1832
1833         if (insn->code == 0)
1834                 return 0;
1835         if (env->log.level & BPF_LOG_LEVEL) {
1836                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1837                 verbose(env, "%d: ", idx);
1838                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1839         }
1840
1841         if (class == BPF_ALU || class == BPF_ALU64) {
1842                 if (!(*reg_mask & dreg))
1843                         return 0;
1844                 if (opcode == BPF_END || opcode == BPF_NEG) {
1845                         /* sreg is reserved and unused
1846                          * dreg still need precision before this insn
1847                          */
1848                         return 0;
1849                 } else if (opcode == BPF_MOV) {
1850                         if (BPF_SRC(insn->code) == BPF_X) {
1851                                 /* dreg = sreg
1852                                  * dreg needs precision after this insn
1853                                  * sreg needs precision before this insn
1854                                  */
1855                                 *reg_mask &= ~dreg;
1856                                 *reg_mask |= sreg;
1857                         } else {
1858                                 /* dreg = K
1859                                  * dreg needs precision after this insn.
1860                                  * Corresponding register is already marked
1861                                  * as precise=true in this verifier state.
1862                                  * No further markings in parent are necessary
1863                                  */
1864                                 *reg_mask &= ~dreg;
1865                         }
1866                 } else {
1867                         if (BPF_SRC(insn->code) == BPF_X) {
1868                                 /* dreg += sreg
1869                                  * both dreg and sreg need precision
1870                                  * before this insn
1871                                  */
1872                                 *reg_mask |= sreg;
1873                         } /* else dreg += K
1874                            * dreg still needs precision before this insn
1875                            */
1876                 }
1877         } else if (class == BPF_LDX) {
1878                 if (!(*reg_mask & dreg))
1879                         return 0;
1880                 *reg_mask &= ~dreg;
1881
1882                 /* scalars can only be spilled into stack w/o losing precision.
1883                  * Load from any other memory can be zero extended.
1884                  * The desire to keep that precision is already indicated
1885                  * by 'precise' mark in corresponding register of this state.
1886                  * No further tracking necessary.
1887                  */
1888                 if (insn->src_reg != BPF_REG_FP)
1889                         return 0;
1890
1891                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1892                  * that [fp - off] slot contains scalar that needs to be
1893                  * tracked with precision
1894                  */
1895                 spi = (-insn->off - 1) / BPF_REG_SIZE;
1896                 if (spi >= 64) {
1897                         verbose(env, "BUG spi %d\n", spi);
1898                         WARN_ONCE(1, "verifier backtracking bug");
1899                         return -EFAULT;
1900                 }
1901                 *stack_mask |= 1ull << spi;
1902         } else if (class == BPF_STX || class == BPF_ST) {
1903                 if (*reg_mask & dreg)
1904                         /* stx & st shouldn't be using _scalar_ dst_reg
1905                          * to access memory. It means backtracking
1906                          * encountered a case of pointer subtraction.
1907                          */
1908                         return -ENOTSUPP;
1909                 /* scalars can only be spilled into stack */
1910                 if (insn->dst_reg != BPF_REG_FP)
1911                         return 0;
1912                 spi = (-insn->off - 1) / BPF_REG_SIZE;
1913                 if (spi >= 64) {
1914                         verbose(env, "BUG spi %d\n", spi);
1915                         WARN_ONCE(1, "verifier backtracking bug");
1916                         return -EFAULT;
1917                 }
1918                 if (!(*stack_mask & (1ull << spi)))
1919                         return 0;
1920                 *stack_mask &= ~(1ull << spi);
1921                 if (class == BPF_STX)
1922                         *reg_mask |= sreg;
1923         } else if (class == BPF_JMP || class == BPF_JMP32) {
1924                 if (opcode == BPF_CALL) {
1925                         if (insn->src_reg == BPF_PSEUDO_CALL)
1926                                 return -ENOTSUPP;
1927                         /* regular helper call sets R0 */
1928                         *reg_mask &= ~1;
1929                         if (*reg_mask & 0x3f) {
1930                                 /* if backtracing was looking for registers R1-R5
1931                                  * they should have been found already.
1932                                  */
1933                                 verbose(env, "BUG regs %x\n", *reg_mask);
1934                                 WARN_ONCE(1, "verifier backtracking bug");
1935                                 return -EFAULT;
1936                         }
1937                 } else if (opcode == BPF_EXIT) {
1938                         return -ENOTSUPP;
1939                 } else if (BPF_SRC(insn->code) == BPF_X) {
1940                         if (!(*reg_mask & (dreg | sreg)))
1941                                 return 0;
1942                         /* dreg <cond> sreg
1943                          * Both dreg and sreg need precision before
1944                          * this insn. If only sreg was marked precise
1945                          * before it would be equally necessary to
1946                          * propagate it to dreg.
1947                          */
1948                         *reg_mask |= (sreg | dreg);
1949                          /* else dreg <cond> K
1950                           * Only dreg still needs precision before
1951                           * this insn, so for the K-based conditional
1952                           * there is nothing new to be marked.
1953                           */
1954                 }
1955         } else if (class == BPF_LD) {
1956                 if (!(*reg_mask & dreg))
1957                         return 0;
1958                 *reg_mask &= ~dreg;
1959                 /* It's ld_imm64 or ld_abs or ld_ind.
1960                  * For ld_imm64 no further tracking of precision
1961                  * into parent is necessary
1962                  */
1963                 if (mode == BPF_IND || mode == BPF_ABS)
1964                         /* to be analyzed */
1965                         return -ENOTSUPP;
1966         }
1967         return 0;
1968 }
1969
1970 /* the scalar precision tracking algorithm:
1971  * . at the start all registers have precise=false.
1972  * . scalar ranges are tracked as normal through alu and jmp insns.
1973  * . once precise value of the scalar register is used in:
1974  *   .  ptr + scalar alu
1975  *   . if (scalar cond K|scalar)
1976  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
1977  *   backtrack through the verifier states and mark all registers and
1978  *   stack slots with spilled constants that these scalar regisers
1979  *   should be precise.
1980  * . during state pruning two registers (or spilled stack slots)
1981  *   are equivalent if both are not precise.
1982  *
1983  * Note the verifier cannot simply walk register parentage chain,
1984  * since many different registers and stack slots could have been
1985  * used to compute single precise scalar.
1986  *
1987  * The approach of starting with precise=true for all registers and then
1988  * backtrack to mark a register as not precise when the verifier detects
1989  * that program doesn't care about specific value (e.g., when helper
1990  * takes register as ARG_ANYTHING parameter) is not safe.
1991  *
1992  * It's ok to walk single parentage chain of the verifier states.
1993  * It's possible that this backtracking will go all the way till 1st insn.
1994  * All other branches will be explored for needing precision later.
1995  *
1996  * The backtracking needs to deal with cases like:
1997  *   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)
1998  * r9 -= r8
1999  * r5 = r9
2000  * if r5 > 0x79f goto pc+7
2001  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2002  * r5 += 1
2003  * ...
2004  * call bpf_perf_event_output#25
2005  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2006  *
2007  * and this case:
2008  * r6 = 1
2009  * call foo // uses callee's r6 inside to compute r0
2010  * r0 += r6
2011  * if r0 == 0 goto
2012  *
2013  * to track above reg_mask/stack_mask needs to be independent for each frame.
2014  *
2015  * Also if parent's curframe > frame where backtracking started,
2016  * the verifier need to mark registers in both frames, otherwise callees
2017  * may incorrectly prune callers. This is similar to
2018  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2019  *
2020  * For now backtracking falls back into conservative marking.
2021  */
2022 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2023                                      struct bpf_verifier_state *st)
2024 {
2025         struct bpf_func_state *func;
2026         struct bpf_reg_state *reg;
2027         int i, j;
2028
2029         /* big hammer: mark all scalars precise in this path.
2030          * pop_stack may still get !precise scalars.
2031          * We also skip current state and go straight to first parent state,
2032          * because precision markings in current non-checkpointed state are
2033          * not needed. See why in the comment in __mark_chain_precision below.
2034          */
2035         for (st = st->parent; st; st = st->parent) {
2036                 for (i = 0; i <= st->curframe; i++) {
2037                         func = st->frame[i];
2038                         for (j = 0; j < BPF_REG_FP; j++) {
2039                                 reg = &func->regs[j];
2040                                 if (reg->type != SCALAR_VALUE)
2041                                         continue;
2042                                 reg->precise = true;
2043                         }
2044                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2045                                 if (!is_spilled_reg(&func->stack[j]))
2046                                         continue;
2047                                 reg = &func->stack[j].spilled_ptr;
2048                                 if (reg->type != SCALAR_VALUE)
2049                                         continue;
2050                                 reg->precise = true;
2051                         }
2052                 }
2053         }
2054 }
2055
2056 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2057 {
2058         struct bpf_func_state *func;
2059         struct bpf_reg_state *reg;
2060         int i, j;
2061
2062         for (i = 0; i <= st->curframe; i++) {
2063                 func = st->frame[i];
2064                 for (j = 0; j < BPF_REG_FP; j++) {
2065                         reg = &func->regs[j];
2066                         if (reg->type != SCALAR_VALUE)
2067                                 continue;
2068                         reg->precise = false;
2069                 }
2070                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2071                         if (!is_spilled_reg(&func->stack[j]))
2072                                 continue;
2073                         reg = &func->stack[j].spilled_ptr;
2074                         if (reg->type != SCALAR_VALUE)
2075                                 continue;
2076                         reg->precise = false;
2077                 }
2078         }
2079 }
2080
2081 /*
2082  * __mark_chain_precision() backtracks BPF program instruction sequence and
2083  * chain of verifier states making sure that register *regno* (if regno >= 0)
2084  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2085  * SCALARS, as well as any other registers and slots that contribute to
2086  * a tracked state of given registers/stack slots, depending on specific BPF
2087  * assembly instructions (see backtrack_insns() for exact instruction handling
2088  * logic). This backtracking relies on recorded jmp_history and is able to
2089  * traverse entire chain of parent states. This process ends only when all the
2090  * necessary registers/slots and their transitive dependencies are marked as
2091  * precise.
2092  *
2093  * One important and subtle aspect is that precise marks *do not matter* in
2094  * the currently verified state (current state). It is important to understand
2095  * why this is the case.
2096  *
2097  * First, note that current state is the state that is not yet "checkpointed",
2098  * i.e., it is not yet put into env->explored_states, and it has no children
2099  * states as well. It's ephemeral, and can end up either a) being discarded if
2100  * compatible explored state is found at some point or BPF_EXIT instruction is
2101  * reached or b) checkpointed and put into env->explored_states, branching out
2102  * into one or more children states.
2103  *
2104  * In the former case, precise markings in current state are completely
2105  * ignored by state comparison code (see regsafe() for details). Only
2106  * checkpointed ("old") state precise markings are important, and if old
2107  * state's register/slot is precise, regsafe() assumes current state's
2108  * register/slot as precise and checks value ranges exactly and precisely. If
2109  * states turn out to be compatible, current state's necessary precise
2110  * markings and any required parent states' precise markings are enforced
2111  * after the fact with propagate_precision() logic, after the fact. But it's
2112  * important to realize that in this case, even after marking current state
2113  * registers/slots as precise, we immediately discard current state. So what
2114  * actually matters is any of the precise markings propagated into current
2115  * state's parent states, which are always checkpointed (due to b) case above).
2116  * As such, for scenario a) it doesn't matter if current state has precise
2117  * markings set or not.
2118  *
2119  * Now, for the scenario b), checkpointing and forking into child(ren)
2120  * state(s). Note that before current state gets to checkpointing step, any
2121  * processed instruction always assumes precise SCALAR register/slot
2122  * knowledge: if precise value or range is useful to prune jump branch, BPF
2123  * verifier takes this opportunity enthusiastically. Similarly, when
2124  * register's value is used to calculate offset or memory address, exact
2125  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2126  * what we mentioned above about state comparison ignoring precise markings
2127  * during state comparison, BPF verifier ignores and also assumes precise
2128  * markings *at will* during instruction verification process. But as verifier
2129  * assumes precision, it also propagates any precision dependencies across
2130  * parent states, which are not yet finalized, so can be further restricted
2131  * based on new knowledge gained from restrictions enforced by their children
2132  * states. This is so that once those parent states are finalized, i.e., when
2133  * they have no more active children state, state comparison logic in
2134  * is_state_visited() would enforce strict and precise SCALAR ranges, if
2135  * required for correctness.
2136  *
2137  * To build a bit more intuition, note also that once a state is checkpointed,
2138  * the path we took to get to that state is not important. This is crucial
2139  * property for state pruning. When state is checkpointed and finalized at
2140  * some instruction index, it can be correctly and safely used to "short
2141  * circuit" any *compatible* state that reaches exactly the same instruction
2142  * index. I.e., if we jumped to that instruction from a completely different
2143  * code path than original finalized state was derived from, it doesn't
2144  * matter, current state can be discarded because from that instruction
2145  * forward having a compatible state will ensure we will safely reach the
2146  * exit. States describe preconditions for further exploration, but completely
2147  * forget the history of how we got here.
2148  *
2149  * This also means that even if we needed precise SCALAR range to get to
2150  * finalized state, but from that point forward *that same* SCALAR register is
2151  * never used in a precise context (i.e., it's precise value is not needed for
2152  * correctness), it's correct and safe to mark such register as "imprecise"
2153  * (i.e., precise marking set to false). This is what we rely on when we do
2154  * not set precise marking in current state. If no child state requires
2155  * precision for any given SCALAR register, it's safe to dictate that it can
2156  * be imprecise. If any child state does require this register to be precise,
2157  * we'll mark it precise later retroactively during precise markings
2158  * propagation from child state to parent states.
2159  *
2160  * Skipping precise marking setting in current state is a mild version of
2161  * relying on the above observation. But we can utilize this property even
2162  * more aggressively by proactively forgetting any precise marking in the
2163  * current state (which we inherited from the parent state), right before we
2164  * checkpoint it and branch off into new child state. This is done by
2165  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2166  * finalized states which help in short circuiting more future states.
2167  */
2168 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2169                                   int spi)
2170 {
2171         struct bpf_verifier_state *st = env->cur_state;
2172         int first_idx = st->first_insn_idx;
2173         int last_idx = env->insn_idx;
2174         struct bpf_func_state *func;
2175         struct bpf_reg_state *reg;
2176         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2177         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2178         bool skip_first = true;
2179         bool new_marks = false;
2180         int i, err;
2181
2182         if (!env->bpf_capable)
2183                 return 0;
2184
2185         /* Do sanity checks against current state of register and/or stack
2186          * slot, but don't set precise flag in current state, as precision
2187          * tracking in the current state is unnecessary.
2188          */
2189         func = st->frame[frame];
2190         if (regno >= 0) {
2191                 reg = &func->regs[regno];
2192                 if (reg->type != SCALAR_VALUE) {
2193                         WARN_ONCE(1, "backtracing misuse");
2194                         return -EFAULT;
2195                 }
2196                 new_marks = true;
2197         }
2198
2199         while (spi >= 0) {
2200                 if (!is_spilled_reg(&func->stack[spi])) {
2201                         stack_mask = 0;
2202                         break;
2203                 }
2204                 reg = &func->stack[spi].spilled_ptr;
2205                 if (reg->type != SCALAR_VALUE) {
2206                         stack_mask = 0;
2207                         break;
2208                 }
2209                 new_marks = true;
2210                 break;
2211         }
2212
2213         if (!new_marks)
2214                 return 0;
2215         if (!reg_mask && !stack_mask)
2216                 return 0;
2217
2218         for (;;) {
2219                 DECLARE_BITMAP(mask, 64);
2220                 u32 history = st->jmp_history_cnt;
2221
2222                 if (env->log.level & BPF_LOG_LEVEL)
2223                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2224
2225                 if (last_idx < 0) {
2226                         /* we are at the entry into subprog, which
2227                          * is expected for global funcs, but only if
2228                          * requested precise registers are R1-R5
2229                          * (which are global func's input arguments)
2230                          */
2231                         if (st->curframe == 0 &&
2232                             st->frame[0]->subprogno > 0 &&
2233                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
2234                             stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2235                                 bitmap_from_u64(mask, reg_mask);
2236                                 for_each_set_bit(i, mask, 32) {
2237                                         reg = &st->frame[0]->regs[i];
2238                                         if (reg->type != SCALAR_VALUE) {
2239                                                 reg_mask &= ~(1u << i);
2240                                                 continue;
2241                                         }
2242                                         reg->precise = true;
2243                                 }
2244                                 return 0;
2245                         }
2246
2247                         verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
2248                                 st->frame[0]->subprogno, reg_mask, stack_mask);
2249                         WARN_ONCE(1, "verifier backtracking bug");
2250                         return -EFAULT;
2251                 }
2252
2253                 for (i = last_idx;;) {
2254                         if (skip_first) {
2255                                 err = 0;
2256                                 skip_first = false;
2257                         } else {
2258                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2259                         }
2260                         if (err == -ENOTSUPP) {
2261                                 mark_all_scalars_precise(env, st);
2262                                 return 0;
2263                         } else if (err) {
2264                                 return err;
2265                         }
2266                         if (!reg_mask && !stack_mask)
2267                                 /* Found assignment(s) into tracked register in this state.
2268                                  * Since this state is already marked, just return.
2269                                  * Nothing to be tracked further in the parent state.
2270                                  */
2271                                 return 0;
2272                         if (i == first_idx)
2273                                 break;
2274                         i = get_prev_insn_idx(st, i, &history);
2275                         if (i >= env->prog->len) {
2276                                 /* This can happen if backtracking reached insn 0
2277                                  * and there are still reg_mask or stack_mask
2278                                  * to backtrack.
2279                                  * It means the backtracking missed the spot where
2280                                  * particular register was initialized with a constant.
2281                                  */
2282                                 verbose(env, "BUG backtracking idx %d\n", i);
2283                                 WARN_ONCE(1, "verifier backtracking bug");
2284                                 return -EFAULT;
2285                         }
2286                 }
2287                 st = st->parent;
2288                 if (!st)
2289                         break;
2290
2291                 new_marks = false;
2292                 func = st->frame[frame];
2293                 bitmap_from_u64(mask, reg_mask);
2294                 for_each_set_bit(i, mask, 32) {
2295                         reg = &func->regs[i];
2296                         if (reg->type != SCALAR_VALUE) {
2297                                 reg_mask &= ~(1u << i);
2298                                 continue;
2299                         }
2300                         if (!reg->precise)
2301                                 new_marks = true;
2302                         reg->precise = true;
2303                 }
2304
2305                 bitmap_from_u64(mask, stack_mask);
2306                 for_each_set_bit(i, mask, 64) {
2307                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2308                                 /* the sequence of instructions:
2309                                  * 2: (bf) r3 = r10
2310                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2311                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2312                                  * doesn't contain jmps. It's backtracked
2313                                  * as a single block.
2314                                  * During backtracking insn 3 is not recognized as
2315                                  * stack access, so at the end of backtracking
2316                                  * stack slot fp-8 is still marked in stack_mask.
2317                                  * However the parent state may not have accessed
2318                                  * fp-8 and it's "unallocated" stack space.
2319                                  * In such case fallback to conservative.
2320                                  */
2321                                 mark_all_scalars_precise(env, st);
2322                                 return 0;
2323                         }
2324
2325                         if (!is_spilled_reg(&func->stack[i])) {
2326                                 stack_mask &= ~(1ull << i);
2327                                 continue;
2328                         }
2329                         reg = &func->stack[i].spilled_ptr;
2330                         if (reg->type != SCALAR_VALUE) {
2331                                 stack_mask &= ~(1ull << i);
2332                                 continue;
2333                         }
2334                         if (!reg->precise)
2335                                 new_marks = true;
2336                         reg->precise = true;
2337                 }
2338                 if (env->log.level & BPF_LOG_LEVEL) {
2339                         print_verifier_state(env, func);
2340                         verbose(env, "parent %s regs=%x stack=%llx marks\n",
2341                                 new_marks ? "didn't have" : "already had",
2342                                 reg_mask, stack_mask);
2343                 }
2344
2345                 if (!reg_mask && !stack_mask)
2346                         break;
2347                 if (!new_marks)
2348                         break;
2349
2350                 last_idx = st->last_insn_idx;
2351                 first_idx = st->first_insn_idx;
2352         }
2353         return 0;
2354 }
2355
2356 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2357 {
2358         return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2359 }
2360
2361 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2362 {
2363         return __mark_chain_precision(env, frame, regno, -1);
2364 }
2365
2366 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2367 {
2368         return __mark_chain_precision(env, frame, -1, spi);
2369 }
2370
2371 static bool is_spillable_regtype(enum bpf_reg_type type)
2372 {
2373         switch (type) {
2374         case PTR_TO_MAP_VALUE:
2375         case PTR_TO_MAP_VALUE_OR_NULL:
2376         case PTR_TO_STACK:
2377         case PTR_TO_CTX:
2378         case PTR_TO_PACKET:
2379         case PTR_TO_PACKET_META:
2380         case PTR_TO_PACKET_END:
2381         case PTR_TO_FLOW_KEYS:
2382         case CONST_PTR_TO_MAP:
2383         case PTR_TO_SOCKET:
2384         case PTR_TO_SOCKET_OR_NULL:
2385         case PTR_TO_SOCK_COMMON:
2386         case PTR_TO_SOCK_COMMON_OR_NULL:
2387         case PTR_TO_TCP_SOCK:
2388         case PTR_TO_TCP_SOCK_OR_NULL:
2389         case PTR_TO_XDP_SOCK:
2390         case PTR_TO_BTF_ID:
2391         case PTR_TO_BTF_ID_OR_NULL:
2392         case PTR_TO_RDONLY_BUF:
2393         case PTR_TO_RDONLY_BUF_OR_NULL:
2394         case PTR_TO_RDWR_BUF:
2395         case PTR_TO_RDWR_BUF_OR_NULL:
2396         case PTR_TO_PERCPU_BTF_ID:
2397         case PTR_TO_MEM:
2398         case PTR_TO_MEM_OR_NULL:
2399                 return true;
2400         default:
2401                 return false;
2402         }
2403 }
2404
2405 /* Does this register contain a constant zero? */
2406 static bool register_is_null(struct bpf_reg_state *reg)
2407 {
2408         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2409 }
2410
2411 static bool register_is_const(struct bpf_reg_state *reg)
2412 {
2413         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2414 }
2415
2416 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2417 {
2418         return tnum_is_unknown(reg->var_off) &&
2419                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2420                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2421                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2422                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2423 }
2424
2425 static bool register_is_bounded(struct bpf_reg_state *reg)
2426 {
2427         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2428 }
2429
2430 static bool __is_pointer_value(bool allow_ptr_leaks,
2431                                const struct bpf_reg_state *reg)
2432 {
2433         if (allow_ptr_leaks)
2434                 return false;
2435
2436         return reg->type != SCALAR_VALUE;
2437 }
2438
2439 /* Copy src state preserving dst->parent and dst->live fields */
2440 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
2441 {
2442         struct bpf_reg_state *parent = dst->parent;
2443         enum bpf_reg_liveness live = dst->live;
2444
2445         *dst = *src;
2446         dst->parent = parent;
2447         dst->live = live;
2448 }
2449
2450 static void save_register_state(struct bpf_func_state *state,
2451                                 int spi, struct bpf_reg_state *reg,
2452                                 int size)
2453 {
2454         int i;
2455
2456         copy_register_state(&state->stack[spi].spilled_ptr, reg);
2457         if (size == BPF_REG_SIZE)
2458                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2459
2460         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2461                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2462
2463         /* size < 8 bytes spill */
2464         for (; i; i--)
2465                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2466 }
2467
2468 static bool is_bpf_st_mem(struct bpf_insn *insn)
2469 {
2470         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
2471 }
2472
2473 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2474  * stack boundary and alignment are checked in check_mem_access()
2475  */
2476 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2477                                        /* stack frame we're writing to */
2478                                        struct bpf_func_state *state,
2479                                        int off, int size, int value_regno,
2480                                        int insn_idx)
2481 {
2482         struct bpf_func_state *cur; /* state of the current function */
2483         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2484         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
2485         struct bpf_reg_state *reg = NULL;
2486         u32 dst_reg = insn->dst_reg;
2487
2488         err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2489                                  state->acquired_refs, true);
2490         if (err)
2491                 return err;
2492         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2493          * so it's aligned access and [off, off + size) are within stack limits
2494          */
2495         if (!env->allow_ptr_leaks &&
2496             is_spilled_reg(&state->stack[spi]) &&
2497             size != BPF_REG_SIZE) {
2498                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2499                 return -EACCES;
2500         }
2501
2502         cur = env->cur_state->frame[env->cur_state->curframe];
2503         if (value_regno >= 0)
2504                 reg = &cur->regs[value_regno];
2505         if (!env->bypass_spec_v4) {
2506                 bool sanitize = reg && is_spillable_regtype(reg->type);
2507
2508                 for (i = 0; i < size; i++) {
2509                         u8 type = state->stack[spi].slot_type[i];
2510
2511                         if (type != STACK_MISC && type != STACK_ZERO) {
2512                                 sanitize = true;
2513                                 break;
2514                         }
2515                 }
2516
2517                 if (sanitize)
2518                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2519         }
2520
2521         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2522             !register_is_null(reg) && env->bpf_capable) {
2523                 if (dst_reg != BPF_REG_FP) {
2524                         /* The backtracking logic can only recognize explicit
2525                          * stack slot address like [fp - 8]. Other spill of
2526                          * scalar via different register has to be conervative.
2527                          * Backtrack from here and mark all registers as precise
2528                          * that contributed into 'reg' being a constant.
2529                          */
2530                         err = mark_chain_precision(env, value_regno);
2531                         if (err)
2532                                 return err;
2533                 }
2534                 save_register_state(state, spi, reg, size);
2535                 /* Break the relation on a narrowing spill. */
2536                 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
2537                         state->stack[spi].spilled_ptr.id = 0;
2538         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
2539                    insn->imm != 0 && env->bpf_capable) {
2540                 struct bpf_reg_state fake_reg = {};
2541
2542                 __mark_reg_known(&fake_reg, insn->imm);
2543                 fake_reg.type = SCALAR_VALUE;
2544                 save_register_state(state, spi, &fake_reg, size);
2545         } else if (reg && is_spillable_regtype(reg->type)) {
2546                 /* register containing pointer is being spilled into stack */
2547                 if (size != BPF_REG_SIZE) {
2548                         verbose_linfo(env, insn_idx, "; ");
2549                         verbose(env, "invalid size of register spill\n");
2550                         return -EACCES;
2551                 }
2552                 if (state != cur && reg->type == PTR_TO_STACK) {
2553                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2554                         return -EINVAL;
2555                 }
2556                 save_register_state(state, spi, reg, size);
2557         } else {
2558                 u8 type = STACK_MISC;
2559
2560                 /* regular write of data into stack destroys any spilled ptr */
2561                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2562                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2563                 if (is_spilled_reg(&state->stack[spi]))
2564                         for (i = 0; i < BPF_REG_SIZE; i++)
2565                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2566
2567                 /* only mark the slot as written if all 8 bytes were written
2568                  * otherwise read propagation may incorrectly stop too soon
2569                  * when stack slots are partially written.
2570                  * This heuristic means that read propagation will be
2571                  * conservative, since it will add reg_live_read marks
2572                  * to stack slots all the way to first state when programs
2573                  * writes+reads less than 8 bytes
2574                  */
2575                 if (size == BPF_REG_SIZE)
2576                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2577
2578                 /* when we zero initialize stack slots mark them as such */
2579                 if ((reg && register_is_null(reg)) ||
2580                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
2581                         /* backtracking doesn't work for STACK_ZERO yet. */
2582                         err = mark_chain_precision(env, value_regno);
2583                         if (err)
2584                                 return err;
2585                         type = STACK_ZERO;
2586                 }
2587
2588                 /* Mark slots affected by this stack write. */
2589                 for (i = 0; i < size; i++)
2590                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2591                                 type;
2592         }
2593         return 0;
2594 }
2595
2596 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2597  * known to contain a variable offset.
2598  * This function checks whether the write is permitted and conservatively
2599  * tracks the effects of the write, considering that each stack slot in the
2600  * dynamic range is potentially written to.
2601  *
2602  * 'off' includes 'regno->off'.
2603  * 'value_regno' can be -1, meaning that an unknown value is being written to
2604  * the stack.
2605  *
2606  * Spilled pointers in range are not marked as written because we don't know
2607  * what's going to be actually written. This means that read propagation for
2608  * future reads cannot be terminated by this write.
2609  *
2610  * For privileged programs, uninitialized stack slots are considered
2611  * initialized by this write (even though we don't know exactly what offsets
2612  * are going to be written to). The idea is that we don't want the verifier to
2613  * reject future reads that access slots written to through variable offsets.
2614  */
2615 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2616                                      /* func where register points to */
2617                                      struct bpf_func_state *state,
2618                                      int ptr_regno, int off, int size,
2619                                      int value_regno, int insn_idx)
2620 {
2621         struct bpf_func_state *cur; /* state of the current function */
2622         int min_off, max_off;
2623         int i, err;
2624         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2625         bool writing_zero = false;
2626         /* set if the fact that we're writing a zero is used to let any
2627          * stack slots remain STACK_ZERO
2628          */
2629         bool zero_used = false;
2630
2631         cur = env->cur_state->frame[env->cur_state->curframe];
2632         ptr_reg = &cur->regs[ptr_regno];
2633         min_off = ptr_reg->smin_value + off;
2634         max_off = ptr_reg->smax_value + off + size;
2635         if (value_regno >= 0)
2636                 value_reg = &cur->regs[value_regno];
2637         if (value_reg && register_is_null(value_reg))
2638                 writing_zero = true;
2639
2640         err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2641                                  state->acquired_refs, true);
2642         if (err)
2643                 return err;
2644
2645
2646         /* Variable offset writes destroy any spilled pointers in range. */
2647         for (i = min_off; i < max_off; i++) {
2648                 u8 new_type, *stype;
2649                 int slot, spi;
2650
2651                 slot = -i - 1;
2652                 spi = slot / BPF_REG_SIZE;
2653                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2654
2655                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
2656                         /* Reject the write if range we may write to has not
2657                          * been initialized beforehand. If we didn't reject
2658                          * here, the ptr status would be erased below (even
2659                          * though not all slots are actually overwritten),
2660                          * possibly opening the door to leaks.
2661                          *
2662                          * We do however catch STACK_INVALID case below, and
2663                          * only allow reading possibly uninitialized memory
2664                          * later for CAP_PERFMON, as the write may not happen to
2665                          * that slot.
2666                          */
2667                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2668                                 insn_idx, i);
2669                         return -EINVAL;
2670                 }
2671
2672                 /* Erase all spilled pointers. */
2673                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2674
2675                 /* Update the slot type. */
2676                 new_type = STACK_MISC;
2677                 if (writing_zero && *stype == STACK_ZERO) {
2678                         new_type = STACK_ZERO;
2679                         zero_used = true;
2680                 }
2681                 /* If the slot is STACK_INVALID, we check whether it's OK to
2682                  * pretend that it will be initialized by this write. The slot
2683                  * might not actually be written to, and so if we mark it as
2684                  * initialized future reads might leak uninitialized memory.
2685                  * For privileged programs, we will accept such reads to slots
2686                  * that may or may not be written because, if we're reject
2687                  * them, the error would be too confusing.
2688                  */
2689                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2690                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2691                                         insn_idx, i);
2692                         return -EINVAL;
2693                 }
2694                 *stype = new_type;
2695         }
2696         if (zero_used) {
2697                 /* backtracking doesn't work for STACK_ZERO yet. */
2698                 err = mark_chain_precision(env, value_regno);
2699                 if (err)
2700                         return err;
2701         }
2702         return 0;
2703 }
2704
2705 /* When register 'dst_regno' is assigned some values from stack[min_off,
2706  * max_off), we set the register's type according to the types of the
2707  * respective stack slots. If all the stack values are known to be zeros, then
2708  * so is the destination reg. Otherwise, the register is considered to be
2709  * SCALAR. This function does not deal with register filling; the caller must
2710  * ensure that all spilled registers in the stack range have been marked as
2711  * read.
2712  */
2713 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2714                                 /* func where src register points to */
2715                                 struct bpf_func_state *ptr_state,
2716                                 int min_off, int max_off, int dst_regno)
2717 {
2718         struct bpf_verifier_state *vstate = env->cur_state;
2719         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2720         int i, slot, spi;
2721         u8 *stype;
2722         int zeros = 0;
2723
2724         for (i = min_off; i < max_off; i++) {
2725                 slot = -i - 1;
2726                 spi = slot / BPF_REG_SIZE;
2727                 stype = ptr_state->stack[spi].slot_type;
2728                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2729                         break;
2730                 zeros++;
2731         }
2732         if (zeros == max_off - min_off) {
2733                 /* any access_size read into register is zero extended,
2734                  * so the whole register == const_zero
2735                  */
2736                 __mark_reg_const_zero(&state->regs[dst_regno]);
2737                 /* backtracking doesn't support STACK_ZERO yet,
2738                  * so mark it precise here, so that later
2739                  * backtracking can stop here.
2740                  * Backtracking may not need this if this register
2741                  * doesn't participate in pointer adjustment.
2742                  * Forward propagation of precise flag is not
2743                  * necessary either. This mark is only to stop
2744                  * backtracking. Any register that contributed
2745                  * to const 0 was marked precise before spill.
2746                  */
2747                 state->regs[dst_regno].precise = true;
2748         } else {
2749                 /* have read misc data from the stack */
2750                 mark_reg_unknown(env, state->regs, dst_regno);
2751         }
2752         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2753 }
2754
2755 /* Read the stack at 'off' and put the results into the register indicated by
2756  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2757  * spilled reg.
2758  *
2759  * 'dst_regno' can be -1, meaning that the read value is not going to a
2760  * register.
2761  *
2762  * The access is assumed to be within the current stack bounds.
2763  */
2764 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2765                                       /* func where src register points to */
2766                                       struct bpf_func_state *reg_state,
2767                                       int off, int size, int dst_regno)
2768 {
2769         struct bpf_verifier_state *vstate = env->cur_state;
2770         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2771         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2772         struct bpf_reg_state *reg;
2773         u8 *stype, type;
2774
2775         stype = reg_state->stack[spi].slot_type;
2776         reg = &reg_state->stack[spi].spilled_ptr;
2777
2778         if (is_spilled_reg(&reg_state->stack[spi])) {
2779                 u8 spill_size = 1;
2780
2781                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
2782                         spill_size++;
2783
2784                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
2785                         if (reg->type != SCALAR_VALUE) {
2786                                 verbose_linfo(env, env->insn_idx, "; ");
2787                                 verbose(env, "invalid size of register fill\n");
2788                                 return -EACCES;
2789                         }
2790
2791                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2792                         if (dst_regno < 0)
2793                                 return 0;
2794
2795                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
2796                                 /* The earlier check_reg_arg() has decided the
2797                                  * subreg_def for this insn.  Save it first.
2798                                  */
2799                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
2800
2801                                 copy_register_state(&state->regs[dst_regno], reg);
2802                                 state->regs[dst_regno].subreg_def = subreg_def;
2803                         } else {
2804                                 for (i = 0; i < size; i++) {
2805                                         type = stype[(slot - i) % BPF_REG_SIZE];
2806                                         if (type == STACK_SPILL)
2807                                                 continue;
2808                                         if (type == STACK_MISC)
2809                                                 continue;
2810                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
2811                                                 off, i, size);
2812                                         return -EACCES;
2813                                 }
2814                                 mark_reg_unknown(env, state->regs, dst_regno);
2815                         }
2816                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2817                         return 0;
2818                 }
2819
2820                 if (dst_regno >= 0) {
2821                         /* restore register state from stack */
2822                         copy_register_state(&state->regs[dst_regno], reg);
2823                         /* mark reg as written since spilled pointer state likely
2824                          * has its liveness marks cleared by is_state_visited()
2825                          * which resets stack/reg liveness for state transitions
2826                          */
2827                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2828                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2829                         /* If dst_regno==-1, the caller is asking us whether
2830                          * it is acceptable to use this value as a SCALAR_VALUE
2831                          * (e.g. for XADD).
2832                          * We must not allow unprivileged callers to do that
2833                          * with spilled pointers.
2834                          */
2835                         verbose(env, "leaking pointer from stack off %d\n",
2836                                 off);
2837                         return -EACCES;
2838                 }
2839                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2840         } else {
2841                 for (i = 0; i < size; i++) {
2842                         type = stype[(slot - i) % BPF_REG_SIZE];
2843                         if (type == STACK_MISC)
2844                                 continue;
2845                         if (type == STACK_ZERO)
2846                                 continue;
2847                         verbose(env, "invalid read from stack off %d+%d size %d\n",
2848                                 off, i, size);
2849                         return -EACCES;
2850                 }
2851                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2852                 if (dst_regno >= 0)
2853                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2854         }
2855         return 0;
2856 }
2857
2858 enum stack_access_src {
2859         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2860         ACCESS_HELPER = 2,  /* the access is performed by a helper */
2861 };
2862
2863 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2864                                          int regno, int off, int access_size,
2865                                          bool zero_size_allowed,
2866                                          enum stack_access_src type,
2867                                          struct bpf_call_arg_meta *meta);
2868
2869 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2870 {
2871         return cur_regs(env) + regno;
2872 }
2873
2874 /* Read the stack at 'ptr_regno + off' and put the result into the register
2875  * 'dst_regno'.
2876  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2877  * but not its variable offset.
2878  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2879  *
2880  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2881  * filling registers (i.e. reads of spilled register cannot be detected when
2882  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2883  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2884  * offset; for a fixed offset check_stack_read_fixed_off should be used
2885  * instead.
2886  */
2887 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2888                                     int ptr_regno, int off, int size, int dst_regno)
2889 {
2890         /* The state of the source register. */
2891         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2892         struct bpf_func_state *ptr_state = func(env, reg);
2893         int err;
2894         int min_off, max_off;
2895
2896         /* Note that we pass a NULL meta, so raw access will not be permitted.
2897          */
2898         err = check_stack_range_initialized(env, ptr_regno, off, size,
2899                                             false, ACCESS_DIRECT, NULL);
2900         if (err)
2901                 return err;
2902
2903         min_off = reg->smin_value + off;
2904         max_off = reg->smax_value + off;
2905         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2906         return 0;
2907 }
2908
2909 /* check_stack_read dispatches to check_stack_read_fixed_off or
2910  * check_stack_read_var_off.
2911  *
2912  * The caller must ensure that the offset falls within the allocated stack
2913  * bounds.
2914  *
2915  * 'dst_regno' is a register which will receive the value from the stack. It
2916  * can be -1, meaning that the read value is not going to a register.
2917  */
2918 static int check_stack_read(struct bpf_verifier_env *env,
2919                             int ptr_regno, int off, int size,
2920                             int dst_regno)
2921 {
2922         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2923         struct bpf_func_state *state = func(env, reg);
2924         int err;
2925         /* Some accesses are only permitted with a static offset. */
2926         bool var_off = !tnum_is_const(reg->var_off);
2927
2928         /* The offset is required to be static when reads don't go to a
2929          * register, in order to not leak pointers (see
2930          * check_stack_read_fixed_off).
2931          */
2932         if (dst_regno < 0 && var_off) {
2933                 char tn_buf[48];
2934
2935                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2936                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2937                         tn_buf, off, size);
2938                 return -EACCES;
2939         }
2940         /* Variable offset is prohibited for unprivileged mode for simplicity
2941          * since it requires corresponding support in Spectre masking for stack
2942          * ALU. See also retrieve_ptr_limit(). The check in
2943          * check_stack_access_for_ptr_arithmetic() called by
2944          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
2945          * with variable offsets, therefore no check is required here. Further,
2946          * just checking it here would be insufficient as speculative stack
2947          * writes could still lead to unsafe speculative behaviour.
2948          */
2949         if (!var_off) {
2950                 off += reg->var_off.value;
2951                 err = check_stack_read_fixed_off(env, state, off, size,
2952                                                  dst_regno);
2953         } else {
2954                 /* Variable offset stack reads need more conservative handling
2955                  * than fixed offset ones. Note that dst_regno >= 0 on this
2956                  * branch.
2957                  */
2958                 err = check_stack_read_var_off(env, ptr_regno, off, size,
2959                                                dst_regno);
2960         }
2961         return err;
2962 }
2963
2964
2965 /* check_stack_write dispatches to check_stack_write_fixed_off or
2966  * check_stack_write_var_off.
2967  *
2968  * 'ptr_regno' is the register used as a pointer into the stack.
2969  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2970  * 'value_regno' is the register whose value we're writing to the stack. It can
2971  * be -1, meaning that we're not writing from a register.
2972  *
2973  * The caller must ensure that the offset falls within the maximum stack size.
2974  */
2975 static int check_stack_write(struct bpf_verifier_env *env,
2976                              int ptr_regno, int off, int size,
2977                              int value_regno, int insn_idx)
2978 {
2979         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2980         struct bpf_func_state *state = func(env, reg);
2981         int err;
2982
2983         if (tnum_is_const(reg->var_off)) {
2984                 off += reg->var_off.value;
2985                 err = check_stack_write_fixed_off(env, state, off, size,
2986                                                   value_regno, insn_idx);
2987         } else {
2988                 /* Variable offset stack reads need more conservative handling
2989                  * than fixed offset ones.
2990                  */
2991                 err = check_stack_write_var_off(env, state,
2992                                                 ptr_regno, off, size,
2993                                                 value_regno, insn_idx);
2994         }
2995         return err;
2996 }
2997
2998 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2999                                  int off, int size, enum bpf_access_type type)
3000 {
3001         struct bpf_reg_state *regs = cur_regs(env);
3002         struct bpf_map *map = regs[regno].map_ptr;
3003         u32 cap = bpf_map_flags_to_cap(map);
3004
3005         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3006                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3007                         map->value_size, off, size);
3008                 return -EACCES;
3009         }
3010
3011         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3012                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3013                         map->value_size, off, size);
3014                 return -EACCES;
3015         }
3016
3017         return 0;
3018 }
3019
3020 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3021 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3022                               int off, int size, u32 mem_size,
3023                               bool zero_size_allowed)
3024 {
3025         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3026         struct bpf_reg_state *reg;
3027
3028         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3029                 return 0;
3030
3031         reg = &cur_regs(env)[regno];
3032         switch (reg->type) {
3033         case PTR_TO_MAP_VALUE:
3034                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3035                         mem_size, off, size);
3036                 break;
3037         case PTR_TO_PACKET:
3038         case PTR_TO_PACKET_META:
3039         case PTR_TO_PACKET_END:
3040                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3041                         off, size, regno, reg->id, off, mem_size);
3042                 break;
3043         case PTR_TO_MEM:
3044         default:
3045                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3046                         mem_size, off, size);
3047         }
3048
3049         return -EACCES;
3050 }
3051
3052 /* check read/write into a memory region with possible variable offset */
3053 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3054                                    int off, int size, u32 mem_size,
3055                                    bool zero_size_allowed)
3056 {
3057         struct bpf_verifier_state *vstate = env->cur_state;
3058         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3059         struct bpf_reg_state *reg = &state->regs[regno];
3060         int err;
3061
3062         /* We may have adjusted the register pointing to memory region, so we
3063          * need to try adding each of min_value and max_value to off
3064          * to make sure our theoretical access will be safe.
3065          */
3066         if (env->log.level & BPF_LOG_LEVEL)
3067                 print_verifier_state(env, state);
3068
3069         /* The minimum value is only important with signed
3070          * comparisons where we can't assume the floor of a
3071          * value is 0.  If we are using signed variables for our
3072          * index'es we need to make sure that whatever we use
3073          * will have a set floor within our range.
3074          */
3075         if (reg->smin_value < 0 &&
3076             (reg->smin_value == S64_MIN ||
3077              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3078               reg->smin_value + off < 0)) {
3079                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3080                         regno);
3081                 return -EACCES;
3082         }
3083         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3084                                  mem_size, zero_size_allowed);
3085         if (err) {
3086                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3087                         regno);
3088                 return err;
3089         }
3090
3091         /* If we haven't set a max value then we need to bail since we can't be
3092          * sure we won't do bad things.
3093          * If reg->umax_value + off could overflow, treat that as unbounded too.
3094          */
3095         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3096                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3097                         regno);
3098                 return -EACCES;
3099         }
3100         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3101                                  mem_size, zero_size_allowed);
3102         if (err) {
3103                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3104                         regno);
3105                 return err;
3106         }
3107
3108         return 0;
3109 }
3110
3111 /* check read/write into a map element with possible variable offset */
3112 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3113                             int off, int size, bool zero_size_allowed)
3114 {
3115         struct bpf_verifier_state *vstate = env->cur_state;
3116         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3117         struct bpf_reg_state *reg = &state->regs[regno];
3118         struct bpf_map *map = reg->map_ptr;
3119         int err;
3120
3121         err = check_mem_region_access(env, regno, off, size, map->value_size,
3122                                       zero_size_allowed);
3123         if (err)
3124                 return err;
3125
3126         if (map_value_has_spin_lock(map)) {
3127                 u32 lock = map->spin_lock_off;
3128
3129                 /* if any part of struct bpf_spin_lock can be touched by
3130                  * load/store reject this program.
3131                  * To check that [x1, x2) overlaps with [y1, y2)
3132                  * it is sufficient to check x1 < y2 && y1 < x2.
3133                  */
3134                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3135                      lock < reg->umax_value + off + size) {
3136                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3137                         return -EACCES;
3138                 }
3139         }
3140         return err;
3141 }
3142
3143 #define MAX_PACKET_OFF 0xffff
3144
3145 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3146 {
3147         return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3148 }
3149
3150 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3151                                        const struct bpf_call_arg_meta *meta,
3152                                        enum bpf_access_type t)
3153 {
3154         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3155
3156         switch (prog_type) {
3157         /* Program types only with direct read access go here! */
3158         case BPF_PROG_TYPE_LWT_IN:
3159         case BPF_PROG_TYPE_LWT_OUT:
3160         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3161         case BPF_PROG_TYPE_SK_REUSEPORT:
3162         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3163         case BPF_PROG_TYPE_CGROUP_SKB:
3164                 if (t == BPF_WRITE)
3165                         return false;
3166                 fallthrough;
3167
3168         /* Program types with direct read + write access go here! */
3169         case BPF_PROG_TYPE_SCHED_CLS:
3170         case BPF_PROG_TYPE_SCHED_ACT:
3171         case BPF_PROG_TYPE_XDP:
3172         case BPF_PROG_TYPE_LWT_XMIT:
3173         case BPF_PROG_TYPE_SK_SKB:
3174         case BPF_PROG_TYPE_SK_MSG:
3175                 if (meta)
3176                         return meta->pkt_access;
3177
3178                 env->seen_direct_write = true;
3179                 return true;
3180
3181         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3182                 if (t == BPF_WRITE)
3183                         env->seen_direct_write = true;
3184
3185                 return true;
3186
3187         default:
3188                 return false;
3189         }
3190 }
3191
3192 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3193                                int size, bool zero_size_allowed)
3194 {
3195         struct bpf_reg_state *regs = cur_regs(env);
3196         struct bpf_reg_state *reg = &regs[regno];
3197         int err;
3198
3199         /* We may have added a variable offset to the packet pointer; but any
3200          * reg->range we have comes after that.  We are only checking the fixed
3201          * offset.
3202          */
3203
3204         /* We don't allow negative numbers, because we aren't tracking enough
3205          * detail to prove they're safe.
3206          */
3207         if (reg->smin_value < 0) {
3208                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3209                         regno);
3210                 return -EACCES;
3211         }
3212
3213         err = reg->range < 0 ? -EINVAL :
3214               __check_mem_access(env, regno, off, size, reg->range,
3215                                  zero_size_allowed);
3216         if (err) {
3217                 verbose(env, "R%d offset is outside of the packet\n", regno);
3218                 return err;
3219         }
3220
3221         /* __check_mem_access has made sure "off + size - 1" is within u16.
3222          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3223          * otherwise find_good_pkt_pointers would have refused to set range info
3224          * that __check_mem_access would have rejected this pkt access.
3225          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3226          */
3227         env->prog->aux->max_pkt_offset =
3228                 max_t(u32, env->prog->aux->max_pkt_offset,
3229                       off + reg->umax_value + size - 1);
3230
3231         return err;
3232 }
3233
3234 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3235 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3236                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
3237                             u32 *btf_id)
3238 {
3239         struct bpf_insn_access_aux info = {
3240                 .reg_type = *reg_type,
3241                 .log = &env->log,
3242         };
3243
3244         if (env->ops->is_valid_access &&
3245             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3246                 /* A non zero info.ctx_field_size indicates that this field is a
3247                  * candidate for later verifier transformation to load the whole
3248                  * field and then apply a mask when accessed with a narrower
3249                  * access than actual ctx access size. A zero info.ctx_field_size
3250                  * will only allow for whole field access and rejects any other
3251                  * type of narrower access.
3252                  */
3253                 *reg_type = info.reg_type;
3254
3255                 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
3256                         *btf_id = info.btf_id;
3257                 else
3258                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3259                 /* remember the offset of last byte accessed in ctx */
3260                 if (env->prog->aux->max_ctx_offset < off + size)
3261                         env->prog->aux->max_ctx_offset = off + size;
3262                 return 0;
3263         }
3264
3265         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3266         return -EACCES;
3267 }
3268
3269 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3270                                   int size)
3271 {
3272         if (size < 0 || off < 0 ||
3273             (u64)off + size > sizeof(struct bpf_flow_keys)) {
3274                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3275                         off, size);
3276                 return -EACCES;
3277         }
3278         return 0;
3279 }
3280
3281 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3282                              u32 regno, int off, int size,
3283                              enum bpf_access_type t)
3284 {
3285         struct bpf_reg_state *regs = cur_regs(env);
3286         struct bpf_reg_state *reg = &regs[regno];
3287         struct bpf_insn_access_aux info = {};
3288         bool valid;
3289
3290         if (reg->smin_value < 0) {
3291                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3292                         regno);
3293                 return -EACCES;
3294         }
3295
3296         switch (reg->type) {
3297         case PTR_TO_SOCK_COMMON:
3298                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3299                 break;
3300         case PTR_TO_SOCKET:
3301                 valid = bpf_sock_is_valid_access(off, size, t, &info);
3302                 break;
3303         case PTR_TO_TCP_SOCK:
3304                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3305                 break;
3306         case PTR_TO_XDP_SOCK:
3307                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3308                 break;
3309         default:
3310                 valid = false;
3311         }
3312
3313
3314         if (valid) {
3315                 env->insn_aux_data[insn_idx].ctx_field_size =
3316                         info.ctx_field_size;
3317                 return 0;
3318         }
3319
3320         verbose(env, "R%d invalid %s access off=%d size=%d\n",
3321                 regno, reg_type_str[reg->type], off, size);
3322
3323         return -EACCES;
3324 }
3325
3326 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3327 {
3328         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3329 }
3330
3331 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3332 {
3333         const struct bpf_reg_state *reg = reg_state(env, regno);
3334
3335         return reg->type == PTR_TO_CTX;
3336 }
3337
3338 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3339 {
3340         const struct bpf_reg_state *reg = reg_state(env, regno);
3341
3342         return type_is_sk_pointer(reg->type);
3343 }
3344
3345 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3346 {
3347         const struct bpf_reg_state *reg = reg_state(env, regno);
3348
3349         return type_is_pkt_pointer(reg->type);
3350 }
3351
3352 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3353 {
3354         const struct bpf_reg_state *reg = reg_state(env, regno);
3355
3356         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3357         return reg->type == PTR_TO_FLOW_KEYS;
3358 }
3359
3360 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3361                                    const struct bpf_reg_state *reg,
3362                                    int off, int size, bool strict)
3363 {
3364         struct tnum reg_off;
3365         int ip_align;
3366
3367         /* Byte size accesses are always allowed. */
3368         if (!strict || size == 1)
3369                 return 0;
3370
3371         /* For platforms that do not have a Kconfig enabling
3372          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3373          * NET_IP_ALIGN is universally set to '2'.  And on platforms
3374          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3375          * to this code only in strict mode where we want to emulate
3376          * the NET_IP_ALIGN==2 checking.  Therefore use an
3377          * unconditional IP align value of '2'.
3378          */
3379         ip_align = 2;
3380
3381         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3382         if (!tnum_is_aligned(reg_off, size)) {
3383                 char tn_buf[48];
3384
3385                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3386                 verbose(env,
3387                         "misaligned packet access off %d+%s+%d+%d size %d\n",
3388                         ip_align, tn_buf, reg->off, off, size);
3389                 return -EACCES;
3390         }
3391
3392         return 0;
3393 }
3394
3395 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3396                                        const struct bpf_reg_state *reg,
3397                                        const char *pointer_desc,
3398                                        int off, int size, bool strict)
3399 {
3400         struct tnum reg_off;
3401
3402         /* Byte size accesses are always allowed. */
3403         if (!strict || size == 1)
3404                 return 0;
3405
3406         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3407         if (!tnum_is_aligned(reg_off, size)) {
3408                 char tn_buf[48];
3409
3410                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3411                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3412                         pointer_desc, tn_buf, reg->off, off, size);
3413                 return -EACCES;
3414         }
3415
3416         return 0;
3417 }
3418
3419 static int check_ptr_alignment(struct bpf_verifier_env *env,
3420                                const struct bpf_reg_state *reg, int off,
3421                                int size, bool strict_alignment_once)
3422 {
3423         bool strict = env->strict_alignment || strict_alignment_once;
3424         const char *pointer_desc = "";
3425
3426         switch (reg->type) {
3427         case PTR_TO_PACKET:
3428         case PTR_TO_PACKET_META:
3429                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3430                  * right in front, treat it the very same way.
3431                  */
3432                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3433         case PTR_TO_FLOW_KEYS:
3434                 pointer_desc = "flow keys ";
3435                 break;
3436         case PTR_TO_MAP_VALUE:
3437                 pointer_desc = "value ";
3438                 break;
3439         case PTR_TO_CTX:
3440                 pointer_desc = "context ";
3441                 break;
3442         case PTR_TO_STACK:
3443                 pointer_desc = "stack ";
3444                 /* The stack spill tracking logic in check_stack_write_fixed_off()
3445                  * and check_stack_read_fixed_off() relies on stack accesses being
3446                  * aligned.
3447                  */
3448                 strict = true;
3449                 break;
3450         case PTR_TO_SOCKET:
3451                 pointer_desc = "sock ";
3452                 break;
3453         case PTR_TO_SOCK_COMMON:
3454                 pointer_desc = "sock_common ";
3455                 break;
3456         case PTR_TO_TCP_SOCK:
3457                 pointer_desc = "tcp_sock ";
3458                 break;
3459         case PTR_TO_XDP_SOCK:
3460                 pointer_desc = "xdp_sock ";
3461                 break;
3462         default:
3463                 break;
3464         }
3465         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3466                                            strict);
3467 }
3468
3469 static int update_stack_depth(struct bpf_verifier_env *env,
3470                               const struct bpf_func_state *func,
3471                               int off)
3472 {
3473         u16 stack = env->subprog_info[func->subprogno].stack_depth;
3474
3475         if (stack >= -off)
3476                 return 0;
3477
3478         /* update known max for given subprogram */
3479         env->subprog_info[func->subprogno].stack_depth = -off;
3480         return 0;
3481 }
3482
3483 /* starting from main bpf function walk all instructions of the function
3484  * and recursively walk all callees that given function can call.
3485  * Ignore jump and exit insns.
3486  * Since recursion is prevented by check_cfg() this algorithm
3487  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3488  */
3489 static int check_max_stack_depth(struct bpf_verifier_env *env)
3490 {
3491         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3492         struct bpf_subprog_info *subprog = env->subprog_info;
3493         struct bpf_insn *insn = env->prog->insnsi;
3494         bool tail_call_reachable = false;
3495         int ret_insn[MAX_CALL_FRAMES];
3496         int ret_prog[MAX_CALL_FRAMES];
3497         int j;
3498
3499 process_func:
3500         /* protect against potential stack overflow that might happen when
3501          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3502          * depth for such case down to 256 so that the worst case scenario
3503          * would result in 8k stack size (32 which is tailcall limit * 256 =
3504          * 8k).
3505          *
3506          * To get the idea what might happen, see an example:
3507          * func1 -> sub rsp, 128
3508          *  subfunc1 -> sub rsp, 256
3509          *  tailcall1 -> add rsp, 256
3510          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3511          *   subfunc2 -> sub rsp, 64
3512          *   subfunc22 -> sub rsp, 128
3513          *   tailcall2 -> add rsp, 128
3514          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3515          *
3516          * tailcall will unwind the current stack frame but it will not get rid
3517          * of caller's stack as shown on the example above.
3518          */
3519         if (idx && subprog[idx].has_tail_call && depth >= 256) {
3520                 verbose(env,
3521                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3522                         depth);
3523                 return -EACCES;
3524         }
3525         /* round up to 32-bytes, since this is granularity
3526          * of interpreter stack size
3527          */
3528         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3529         if (depth > MAX_BPF_STACK) {
3530                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3531                         frame + 1, depth);
3532                 return -EACCES;
3533         }
3534 continue_func:
3535         subprog_end = subprog[idx + 1].start;
3536         for (; i < subprog_end; i++) {
3537                 if (insn[i].code != (BPF_JMP | BPF_CALL))
3538                         continue;
3539                 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3540                         continue;
3541                 /* remember insn and function to return to */
3542                 ret_insn[frame] = i + 1;
3543                 ret_prog[frame] = idx;
3544
3545                 /* find the callee */
3546                 i = i + insn[i].imm + 1;
3547                 idx = find_subprog(env, i);
3548                 if (idx < 0) {
3549                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3550                                   i);
3551                         return -EFAULT;
3552                 }
3553
3554                 if (subprog[idx].has_tail_call)
3555                         tail_call_reachable = true;
3556
3557                 frame++;
3558                 if (frame >= MAX_CALL_FRAMES) {
3559                         verbose(env, "the call stack of %d frames is too deep !\n",
3560                                 frame);
3561                         return -E2BIG;
3562                 }
3563                 goto process_func;
3564         }
3565         /* if tail call got detected across bpf2bpf calls then mark each of the
3566          * currently present subprog frames as tail call reachable subprogs;
3567          * this info will be utilized by JIT so that we will be preserving the
3568          * tail call counter throughout bpf2bpf calls combined with tailcalls
3569          */
3570         if (tail_call_reachable)
3571                 for (j = 0; j < frame; j++)
3572                         subprog[ret_prog[j]].tail_call_reachable = true;
3573         if (subprog[0].tail_call_reachable)
3574                 env->prog->aux->tail_call_reachable = true;
3575
3576         /* end of for() loop means the last insn of the 'subprog'
3577          * was reached. Doesn't matter whether it was JA or EXIT
3578          */
3579         if (frame == 0)
3580                 return 0;
3581         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3582         frame--;
3583         i = ret_insn[frame];
3584         idx = ret_prog[frame];
3585         goto continue_func;
3586 }
3587
3588 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3589 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3590                                   const struct bpf_insn *insn, int idx)
3591 {
3592         int start = idx + insn->imm + 1, subprog;
3593
3594         subprog = find_subprog(env, start);
3595         if (subprog < 0) {
3596                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3597                           start);
3598                 return -EFAULT;
3599         }
3600         return env->subprog_info[subprog].stack_depth;
3601 }
3602 #endif
3603
3604 int check_ctx_reg(struct bpf_verifier_env *env,
3605                   const struct bpf_reg_state *reg, int regno)
3606 {
3607         /* Access to ctx or passing it to a helper is only allowed in
3608          * its original, unmodified form.
3609          */
3610
3611         if (reg->off) {
3612                 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3613                         regno, reg->off);
3614                 return -EACCES;
3615         }
3616
3617         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3618                 char tn_buf[48];
3619
3620                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3621                 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3622                 return -EACCES;
3623         }
3624
3625         return 0;
3626 }
3627
3628 static int __check_buffer_access(struct bpf_verifier_env *env,
3629                                  const char *buf_info,
3630                                  const struct bpf_reg_state *reg,
3631                                  int regno, int off, int size)
3632 {
3633         if (off < 0) {
3634                 verbose(env,
3635                         "R%d invalid %s buffer access: off=%d, size=%d\n",
3636                         regno, buf_info, off, size);
3637                 return -EACCES;
3638         }
3639         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3640                 char tn_buf[48];
3641
3642                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3643                 verbose(env,
3644                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3645                         regno, off, tn_buf);
3646                 return -EACCES;
3647         }
3648
3649         return 0;
3650 }
3651
3652 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3653                                   const struct bpf_reg_state *reg,
3654                                   int regno, int off, int size)
3655 {
3656         int err;
3657
3658         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3659         if (err)
3660                 return err;
3661
3662         if (off + size > env->prog->aux->max_tp_access)
3663                 env->prog->aux->max_tp_access = off + size;
3664
3665         return 0;
3666 }
3667
3668 static int check_buffer_access(struct bpf_verifier_env *env,
3669                                const struct bpf_reg_state *reg,
3670                                int regno, int off, int size,
3671                                bool zero_size_allowed,
3672                                const char *buf_info,
3673                                u32 *max_access)
3674 {
3675         int err;
3676
3677         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3678         if (err)
3679                 return err;
3680
3681         if (off + size > *max_access)
3682                 *max_access = off + size;
3683
3684         return 0;
3685 }
3686
3687 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3688 static void zext_32_to_64(struct bpf_reg_state *reg)
3689 {
3690         reg->var_off = tnum_subreg(reg->var_off);
3691         __reg_assign_32_into_64(reg);
3692 }
3693
3694 /* truncate register to smaller size (in bytes)
3695  * must be called with size < BPF_REG_SIZE
3696  */
3697 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3698 {
3699         u64 mask;
3700
3701         /* clear high bits in bit representation */
3702         reg->var_off = tnum_cast(reg->var_off, size);
3703
3704         /* fix arithmetic bounds */
3705         mask = ((u64)1 << (size * 8)) - 1;
3706         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3707                 reg->umin_value &= mask;
3708                 reg->umax_value &= mask;
3709         } else {
3710                 reg->umin_value = 0;
3711                 reg->umax_value = mask;
3712         }
3713         reg->smin_value = reg->umin_value;
3714         reg->smax_value = reg->umax_value;
3715
3716         /* If size is smaller than 32bit register the 32bit register
3717          * values are also truncated so we push 64-bit bounds into
3718          * 32-bit bounds. Above were truncated < 32-bits already.
3719          */
3720         if (size >= 4)
3721                 return;
3722         __reg_combine_64_into_32(reg);
3723 }
3724
3725 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3726 {
3727         /* A map is considered read-only if the following condition are true:
3728          *
3729          * 1) BPF program side cannot change any of the map content. The
3730          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
3731          *    and was set at map creation time.
3732          * 2) The map value(s) have been initialized from user space by a
3733          *    loader and then "frozen", such that no new map update/delete
3734          *    operations from syscall side are possible for the rest of
3735          *    the map's lifetime from that point onwards.
3736          * 3) Any parallel/pending map update/delete operations from syscall
3737          *    side have been completed. Only after that point, it's safe to
3738          *    assume that map value(s) are immutable.
3739          */
3740         return (map->map_flags & BPF_F_RDONLY_PROG) &&
3741                READ_ONCE(map->frozen) &&
3742                !bpf_map_write_active(map);
3743 }
3744
3745 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3746 {
3747         void *ptr;
3748         u64 addr;
3749         int err;
3750
3751         err = map->ops->map_direct_value_addr(map, &addr, off);
3752         if (err)
3753                 return err;
3754         ptr = (void *)(long)addr + off;
3755
3756         switch (size) {
3757         case sizeof(u8):
3758                 *val = (u64)*(u8 *)ptr;
3759                 break;
3760         case sizeof(u16):
3761                 *val = (u64)*(u16 *)ptr;
3762                 break;
3763         case sizeof(u32):
3764                 *val = (u64)*(u32 *)ptr;
3765                 break;
3766         case sizeof(u64):
3767                 *val = *(u64 *)ptr;
3768                 break;
3769         default:
3770                 return -EINVAL;
3771         }
3772         return 0;
3773 }
3774
3775 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3776                                    struct bpf_reg_state *regs,
3777                                    int regno, int off, int size,
3778                                    enum bpf_access_type atype,
3779                                    int value_regno)
3780 {
3781         struct bpf_reg_state *reg = regs + regno;
3782         const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3783         const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3784         u32 btf_id;
3785         int ret;
3786
3787         if (off < 0) {
3788                 verbose(env,
3789                         "R%d is ptr_%s invalid negative access: off=%d\n",
3790                         regno, tname, off);
3791                 return -EACCES;
3792         }
3793         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3794                 char tn_buf[48];
3795
3796                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3797                 verbose(env,
3798                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3799                         regno, tname, off, tn_buf);
3800                 return -EACCES;
3801         }
3802
3803         if (env->ops->btf_struct_access) {
3804                 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3805                                                   atype, &btf_id);
3806         } else {
3807                 if (atype != BPF_READ) {
3808                         verbose(env, "only read is supported\n");
3809                         return -EACCES;
3810                 }
3811
3812                 ret = btf_struct_access(&env->log, t, off, size, atype,
3813                                         &btf_id);
3814         }
3815
3816         if (ret < 0)
3817                 return ret;
3818
3819         if (atype == BPF_READ && value_regno >= 0)
3820                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3821
3822         return 0;
3823 }
3824
3825 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3826                                    struct bpf_reg_state *regs,
3827                                    int regno, int off, int size,
3828                                    enum bpf_access_type atype,
3829                                    int value_regno)
3830 {
3831         struct bpf_reg_state *reg = regs + regno;
3832         struct bpf_map *map = reg->map_ptr;
3833         const struct btf_type *t;
3834         const char *tname;
3835         u32 btf_id;
3836         int ret;
3837
3838         if (!btf_vmlinux) {
3839                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3840                 return -ENOTSUPP;
3841         }
3842
3843         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3844                 verbose(env, "map_ptr access not supported for map type %d\n",
3845                         map->map_type);
3846                 return -ENOTSUPP;
3847         }
3848
3849         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3850         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3851
3852         if (!env->allow_ptr_to_map_access) {
3853                 verbose(env,
3854                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3855                         tname);
3856                 return -EPERM;
3857         }
3858
3859         if (off < 0) {
3860                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3861                         regno, tname, off);
3862                 return -EACCES;
3863         }
3864
3865         if (atype != BPF_READ) {
3866                 verbose(env, "only read from %s is supported\n", tname);
3867                 return -EACCES;
3868         }
3869
3870         ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3871         if (ret < 0)
3872                 return ret;
3873
3874         if (value_regno >= 0)
3875                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3876
3877         return 0;
3878 }
3879
3880 /* Check that the stack access at the given offset is within bounds. The
3881  * maximum valid offset is -1.
3882  *
3883  * The minimum valid offset is -MAX_BPF_STACK for writes, and
3884  * -state->allocated_stack for reads.
3885  */
3886 static int check_stack_slot_within_bounds(int off,
3887                                           struct bpf_func_state *state,
3888                                           enum bpf_access_type t)
3889 {
3890         int min_valid_off;
3891
3892         if (t == BPF_WRITE)
3893                 min_valid_off = -MAX_BPF_STACK;
3894         else
3895                 min_valid_off = -state->allocated_stack;
3896
3897         if (off < min_valid_off || off > -1)
3898                 return -EACCES;
3899         return 0;
3900 }
3901
3902 /* Check that the stack access at 'regno + off' falls within the maximum stack
3903  * bounds.
3904  *
3905  * 'off' includes `regno->offset`, but not its dynamic part (if any).
3906  */
3907 static int check_stack_access_within_bounds(
3908                 struct bpf_verifier_env *env,
3909                 int regno, int off, int access_size,
3910                 enum stack_access_src src, enum bpf_access_type type)
3911 {
3912         struct bpf_reg_state *regs = cur_regs(env);
3913         struct bpf_reg_state *reg = regs + regno;
3914         struct bpf_func_state *state = func(env, reg);
3915         int min_off, max_off;
3916         int err;
3917         char *err_extra;
3918
3919         if (src == ACCESS_HELPER)
3920                 /* We don't know if helpers are reading or writing (or both). */
3921                 err_extra = " indirect access to";
3922         else if (type == BPF_READ)
3923                 err_extra = " read from";
3924         else
3925                 err_extra = " write to";
3926
3927         if (tnum_is_const(reg->var_off)) {
3928                 min_off = reg->var_off.value + off;
3929                 max_off = min_off + access_size;
3930         } else {
3931                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3932                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
3933                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3934                                 err_extra, regno);
3935                         return -EACCES;
3936                 }
3937                 min_off = reg->smin_value + off;
3938                 max_off = reg->smax_value + off + access_size;
3939         }
3940
3941         err = check_stack_slot_within_bounds(min_off, state, type);
3942         if (!err && max_off > 0)
3943                 err = -EINVAL; /* out of stack access into non-negative offsets */
3944         if (!err && access_size < 0)
3945                 /* access_size should not be negative (or overflow an int); others checks
3946                  * along the way should have prevented such an access.
3947                  */
3948                 err = -EFAULT; /* invalid negative access size; integer overflow? */
3949
3950         if (err) {
3951                 if (tnum_is_const(reg->var_off)) {
3952                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3953                                 err_extra, regno, off, access_size);
3954                 } else {
3955                         char tn_buf[48];
3956
3957                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3958                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3959                                 err_extra, regno, tn_buf, access_size);
3960                 }
3961         }
3962         return err;
3963 }
3964
3965 /* check whether memory at (regno + off) is accessible for t = (read | write)
3966  * if t==write, value_regno is a register which value is stored into memory
3967  * if t==read, value_regno is a register which will receive the value from memory
3968  * if t==write && value_regno==-1, some unknown value is stored into memory
3969  * if t==read && value_regno==-1, don't care what we read from memory
3970  */
3971 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3972                             int off, int bpf_size, enum bpf_access_type t,
3973                             int value_regno, bool strict_alignment_once)
3974 {
3975         struct bpf_reg_state *regs = cur_regs(env);
3976         struct bpf_reg_state *reg = regs + regno;
3977         struct bpf_func_state *state;
3978         int size, err = 0;
3979
3980         size = bpf_size_to_bytes(bpf_size);
3981         if (size < 0)
3982                 return size;
3983
3984         /* alignment checks will add in reg->off themselves */
3985         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3986         if (err)
3987                 return err;
3988
3989         /* for access checks, reg->off is just part of off */
3990         off += reg->off;
3991
3992         if (reg->type == PTR_TO_MAP_VALUE) {
3993                 if (t == BPF_WRITE && value_regno >= 0 &&
3994                     is_pointer_value(env, value_regno)) {
3995                         verbose(env, "R%d leaks addr into map\n", value_regno);
3996                         return -EACCES;
3997                 }
3998                 err = check_map_access_type(env, regno, off, size, t);
3999                 if (err)
4000                         return err;
4001                 err = check_map_access(env, regno, off, size, false);
4002                 if (!err && t == BPF_READ && value_regno >= 0) {
4003                         struct bpf_map *map = reg->map_ptr;
4004
4005                         /* if map is read-only, track its contents as scalars */
4006                         if (tnum_is_const(reg->var_off) &&
4007                             bpf_map_is_rdonly(map) &&
4008                             map->ops->map_direct_value_addr) {
4009                                 int map_off = off + reg->var_off.value;
4010                                 u64 val = 0;
4011
4012                                 err = bpf_map_direct_read(map, map_off, size,
4013                                                           &val);
4014                                 if (err)
4015                                         return err;
4016
4017                                 regs[value_regno].type = SCALAR_VALUE;
4018                                 __mark_reg_known(&regs[value_regno], val);
4019                         } else {
4020                                 mark_reg_unknown(env, regs, value_regno);
4021                         }
4022                 }
4023         } else if (reg->type == PTR_TO_MEM) {
4024                 if (t == BPF_WRITE && value_regno >= 0 &&
4025                     is_pointer_value(env, value_regno)) {
4026                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4027                         return -EACCES;
4028                 }
4029                 err = check_mem_region_access(env, regno, off, size,
4030                                               reg->mem_size, false);
4031                 if (!err && t == BPF_READ && value_regno >= 0)
4032                         mark_reg_unknown(env, regs, value_regno);
4033         } else if (reg->type == PTR_TO_CTX) {
4034                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4035                 u32 btf_id = 0;
4036
4037                 if (t == BPF_WRITE && value_regno >= 0 &&
4038                     is_pointer_value(env, value_regno)) {
4039                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4040                         return -EACCES;
4041                 }
4042
4043                 err = check_ctx_reg(env, reg, regno);
4044                 if (err < 0)
4045                         return err;
4046
4047                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
4048                 if (err)
4049                         verbose_linfo(env, insn_idx, "; ");
4050                 if (!err && t == BPF_READ && value_regno >= 0) {
4051                         /* ctx access returns either a scalar, or a
4052                          * PTR_TO_PACKET[_META,_END]. In the latter
4053                          * case, we know the offset is zero.
4054                          */
4055                         if (reg_type == SCALAR_VALUE) {
4056                                 mark_reg_unknown(env, regs, value_regno);
4057                         } else {
4058                                 mark_reg_known_zero(env, regs,
4059                                                     value_regno);
4060                                 if (reg_type_may_be_null(reg_type))
4061                                         regs[value_regno].id = ++env->id_gen;
4062                                 /* A load of ctx field could have different
4063                                  * actual load size with the one encoded in the
4064                                  * insn. When the dst is PTR, it is for sure not
4065                                  * a sub-register.
4066                                  */
4067                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4068                                 if (reg_type == PTR_TO_BTF_ID ||
4069                                     reg_type == PTR_TO_BTF_ID_OR_NULL)
4070                                         regs[value_regno].btf_id = btf_id;
4071                         }
4072                         regs[value_regno].type = reg_type;
4073                 }
4074
4075         } else if (reg->type == PTR_TO_STACK) {
4076                 /* Basic bounds checks. */
4077                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4078                 if (err)
4079                         return err;
4080
4081                 state = func(env, reg);
4082                 err = update_stack_depth(env, state, off);
4083                 if (err)
4084                         return err;
4085
4086                 if (t == BPF_READ)
4087                         err = check_stack_read(env, regno, off, size,
4088                                                value_regno);
4089                 else
4090                         err = check_stack_write(env, regno, off, size,
4091                                                 value_regno, insn_idx);
4092         } else if (reg_is_pkt_pointer(reg)) {
4093                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4094                         verbose(env, "cannot write into packet\n");
4095                         return -EACCES;
4096                 }
4097                 if (t == BPF_WRITE && value_regno >= 0 &&
4098                     is_pointer_value(env, value_regno)) {
4099                         verbose(env, "R%d leaks addr into packet\n",
4100                                 value_regno);
4101                         return -EACCES;
4102                 }
4103                 err = check_packet_access(env, regno, off, size, false);
4104                 if (!err && t == BPF_READ && value_regno >= 0)
4105                         mark_reg_unknown(env, regs, value_regno);
4106         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4107                 if (t == BPF_WRITE && value_regno >= 0 &&
4108                     is_pointer_value(env, value_regno)) {
4109                         verbose(env, "R%d leaks addr into flow keys\n",
4110                                 value_regno);
4111                         return -EACCES;
4112                 }
4113
4114                 err = check_flow_keys_access(env, off, size);
4115                 if (!err && t == BPF_READ && value_regno >= 0)
4116                         mark_reg_unknown(env, regs, value_regno);
4117         } else if (type_is_sk_pointer(reg->type)) {
4118                 if (t == BPF_WRITE) {
4119                         verbose(env, "R%d cannot write into %s\n",
4120                                 regno, reg_type_str[reg->type]);
4121                         return -EACCES;
4122                 }
4123                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4124                 if (!err && value_regno >= 0)
4125                         mark_reg_unknown(env, regs, value_regno);
4126         } else if (reg->type == PTR_TO_TP_BUFFER) {
4127                 err = check_tp_buffer_access(env, reg, regno, off, size);
4128                 if (!err && t == BPF_READ && value_regno >= 0)
4129                         mark_reg_unknown(env, regs, value_regno);
4130         } else if (reg->type == PTR_TO_BTF_ID) {
4131                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4132                                               value_regno);
4133         } else if (reg->type == CONST_PTR_TO_MAP) {
4134                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4135                                               value_regno);
4136         } else if (reg->type == PTR_TO_RDONLY_BUF) {
4137                 if (t == BPF_WRITE) {
4138                         verbose(env, "R%d cannot write into %s\n",
4139                                 regno, reg_type_str[reg->type]);
4140                         return -EACCES;
4141                 }
4142                 err = check_buffer_access(env, reg, regno, off, size, false,
4143                                           "rdonly",
4144                                           &env->prog->aux->max_rdonly_access);
4145                 if (!err && value_regno >= 0)
4146                         mark_reg_unknown(env, regs, value_regno);
4147         } else if (reg->type == PTR_TO_RDWR_BUF) {
4148                 err = check_buffer_access(env, reg, regno, off, size, false,
4149                                           "rdwr",
4150                                           &env->prog->aux->max_rdwr_access);
4151                 if (!err && t == BPF_READ && value_regno >= 0)
4152                         mark_reg_unknown(env, regs, value_regno);
4153         } else {
4154                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4155                         reg_type_str[reg->type]);
4156                 return -EACCES;
4157         }
4158
4159         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4160             regs[value_regno].type == SCALAR_VALUE) {
4161                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4162                 coerce_reg_to_size(&regs[value_regno], size);
4163         }
4164         return err;
4165 }
4166
4167 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4168 {
4169         int err;
4170
4171         if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
4172             insn->imm != 0) {
4173                 verbose(env, "BPF_XADD uses reserved fields\n");
4174                 return -EINVAL;
4175         }
4176
4177         /* check src1 operand */
4178         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4179         if (err)
4180                 return err;
4181
4182         /* check src2 operand */
4183         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4184         if (err)
4185                 return err;
4186
4187         if (is_pointer_value(env, insn->src_reg)) {
4188                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4189                 return -EACCES;
4190         }
4191
4192         if (is_ctx_reg(env, insn->dst_reg) ||
4193             is_pkt_reg(env, insn->dst_reg) ||
4194             is_flow_key_reg(env, insn->dst_reg) ||
4195             is_sk_reg(env, insn->dst_reg)) {
4196                 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
4197                         insn->dst_reg,
4198                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
4199                 return -EACCES;
4200         }
4201
4202         /* check whether atomic_add can read the memory */
4203         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4204                                BPF_SIZE(insn->code), BPF_READ, -1, true);
4205         if (err)
4206                 return err;
4207
4208         /* check whether atomic_add can write into the same memory */
4209         return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4210                                 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4211 }
4212
4213 /* When register 'regno' is used to read the stack (either directly or through
4214  * a helper function) make sure that it's within stack boundary and, depending
4215  * on the access type, that all elements of the stack are initialized.
4216  *
4217  * 'off' includes 'regno->off', but not its dynamic part (if any).
4218  *
4219  * All registers that have been spilled on the stack in the slots within the
4220  * read offsets are marked as read.
4221  */
4222 static int check_stack_range_initialized(
4223                 struct bpf_verifier_env *env, int regno, int off,
4224                 int access_size, bool zero_size_allowed,
4225                 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4226 {
4227         struct bpf_reg_state *reg = reg_state(env, regno);
4228         struct bpf_func_state *state = func(env, reg);
4229         int err, min_off, max_off, i, j, slot, spi;
4230         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4231         enum bpf_access_type bounds_check_type;
4232         /* Some accesses can write anything into the stack, others are
4233          * read-only.
4234          */
4235         bool clobber = false;
4236
4237         if (access_size == 0 && !zero_size_allowed) {
4238                 verbose(env, "invalid zero-sized read\n");
4239                 return -EACCES;
4240         }
4241
4242         if (type == ACCESS_HELPER) {
4243                 /* The bounds checks for writes are more permissive than for
4244                  * reads. However, if raw_mode is not set, we'll do extra
4245                  * checks below.
4246                  */
4247                 bounds_check_type = BPF_WRITE;
4248                 clobber = true;
4249         } else {
4250                 bounds_check_type = BPF_READ;
4251         }
4252         err = check_stack_access_within_bounds(env, regno, off, access_size,
4253                                                type, bounds_check_type);
4254         if (err)
4255                 return err;
4256
4257
4258         if (tnum_is_const(reg->var_off)) {
4259                 min_off = max_off = reg->var_off.value + off;
4260         } else {
4261                 /* Variable offset is prohibited for unprivileged mode for
4262                  * simplicity since it requires corresponding support in
4263                  * Spectre masking for stack ALU.
4264                  * See also retrieve_ptr_limit().
4265                  */
4266                 if (!env->bypass_spec_v1) {
4267                         char tn_buf[48];
4268
4269                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4270                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4271                                 regno, err_extra, tn_buf);
4272                         return -EACCES;
4273                 }
4274                 /* Only initialized buffer on stack is allowed to be accessed
4275                  * with variable offset. With uninitialized buffer it's hard to
4276                  * guarantee that whole memory is marked as initialized on
4277                  * helper return since specific bounds are unknown what may
4278                  * cause uninitialized stack leaking.
4279                  */
4280                 if (meta && meta->raw_mode)
4281                         meta = NULL;
4282
4283                 min_off = reg->smin_value + off;
4284                 max_off = reg->smax_value + off;
4285         }
4286
4287         if (meta && meta->raw_mode) {
4288                 meta->access_size = access_size;
4289                 meta->regno = regno;
4290                 return 0;
4291         }
4292
4293         for (i = min_off; i < max_off + access_size; i++) {
4294                 u8 *stype;
4295
4296                 slot = -i - 1;
4297                 spi = slot / BPF_REG_SIZE;
4298                 if (state->allocated_stack <= slot)
4299                         goto err;
4300                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4301                 if (*stype == STACK_MISC)
4302                         goto mark;
4303                 if (*stype == STACK_ZERO) {
4304                         if (clobber) {
4305                                 /* helper can write anything into the stack */
4306                                 *stype = STACK_MISC;
4307                         }
4308                         goto mark;
4309                 }
4310
4311                 if (is_spilled_reg(&state->stack[spi]) &&
4312                     state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4313                         goto mark;
4314
4315                 if (is_spilled_reg(&state->stack[spi]) &&
4316                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4317                      env->allow_ptr_leaks)) {
4318                         if (clobber) {
4319                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4320                                 for (j = 0; j < BPF_REG_SIZE; j++)
4321                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4322                         }
4323                         goto mark;
4324                 }
4325
4326 err:
4327                 if (tnum_is_const(reg->var_off)) {
4328                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4329                                 err_extra, regno, min_off, i - min_off, access_size);
4330                 } else {
4331                         char tn_buf[48];
4332
4333                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4334                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4335                                 err_extra, regno, tn_buf, i - min_off, access_size);
4336                 }
4337                 return -EACCES;
4338 mark:
4339                 /* reading any byte out of 8-byte 'spill_slot' will cause
4340                  * the whole slot to be marked as 'read'
4341                  */
4342                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4343                               state->stack[spi].spilled_ptr.parent,
4344                               REG_LIVE_READ64);
4345         }
4346         return update_stack_depth(env, state, min_off);
4347 }
4348
4349 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4350                                    int access_size, bool zero_size_allowed,
4351                                    struct bpf_call_arg_meta *meta)
4352 {
4353         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4354
4355         switch (reg->type) {
4356         case PTR_TO_PACKET:
4357         case PTR_TO_PACKET_META:
4358                 return check_packet_access(env, regno, reg->off, access_size,
4359                                            zero_size_allowed);
4360         case PTR_TO_MAP_VALUE:
4361                 if (check_map_access_type(env, regno, reg->off, access_size,
4362                                           meta && meta->raw_mode ? BPF_WRITE :
4363                                           BPF_READ))
4364                         return -EACCES;
4365                 return check_map_access(env, regno, reg->off, access_size,
4366                                         zero_size_allowed);
4367         case PTR_TO_MEM:
4368                 return check_mem_region_access(env, regno, reg->off,
4369                                                access_size, reg->mem_size,
4370                                                zero_size_allowed);
4371         case PTR_TO_RDONLY_BUF:
4372                 if (meta && meta->raw_mode)
4373                         return -EACCES;
4374                 return check_buffer_access(env, reg, regno, reg->off,
4375                                            access_size, zero_size_allowed,
4376                                            "rdonly",
4377                                            &env->prog->aux->max_rdonly_access);
4378         case PTR_TO_RDWR_BUF:
4379                 return check_buffer_access(env, reg, regno, reg->off,
4380                                            access_size, zero_size_allowed,
4381                                            "rdwr",
4382                                            &env->prog->aux->max_rdwr_access);
4383         case PTR_TO_STACK:
4384                 return check_stack_range_initialized(
4385                                 env,
4386                                 regno, reg->off, access_size,
4387                                 zero_size_allowed, ACCESS_HELPER, meta);
4388         default: /* scalar_value or invalid ptr */
4389                 /* Allow zero-byte read from NULL, regardless of pointer type */
4390                 if (zero_size_allowed && access_size == 0 &&
4391                     register_is_null(reg))
4392                         return 0;
4393
4394                 verbose(env, "R%d type=%s expected=%s\n", regno,
4395                         reg_type_str[reg->type],
4396                         reg_type_str[PTR_TO_STACK]);
4397                 return -EACCES;
4398         }
4399 }
4400
4401 /* Implementation details:
4402  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4403  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4404  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4405  * value_or_null->value transition, since the verifier only cares about
4406  * the range of access to valid map value pointer and doesn't care about actual
4407  * address of the map element.
4408  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4409  * reg->id > 0 after value_or_null->value transition. By doing so
4410  * two bpf_map_lookups will be considered two different pointers that
4411  * point to different bpf_spin_locks.
4412  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4413  * dead-locks.
4414  * Since only one bpf_spin_lock is allowed the checks are simpler than
4415  * reg_is_refcounted() logic. The verifier needs to remember only
4416  * one spin_lock instead of array of acquired_refs.
4417  * cur_state->active_spin_lock remembers which map value element got locked
4418  * and clears it after bpf_spin_unlock.
4419  */
4420 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4421                              bool is_lock)
4422 {
4423         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4424         struct bpf_verifier_state *cur = env->cur_state;
4425         bool is_const = tnum_is_const(reg->var_off);
4426         struct bpf_map *map = reg->map_ptr;
4427         u64 val = reg->var_off.value;
4428
4429         if (!is_const) {
4430                 verbose(env,
4431                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4432                         regno);
4433                 return -EINVAL;
4434         }
4435         if (!map->btf) {
4436                 verbose(env,
4437                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4438                         map->name);
4439                 return -EINVAL;
4440         }
4441         if (!map_value_has_spin_lock(map)) {
4442                 if (map->spin_lock_off == -E2BIG)
4443                         verbose(env,
4444                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4445                                 map->name);
4446                 else if (map->spin_lock_off == -ENOENT)
4447                         verbose(env,
4448                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4449                                 map->name);
4450                 else
4451                         verbose(env,
4452                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4453                                 map->name);
4454                 return -EINVAL;
4455         }
4456         if (map->spin_lock_off != val + reg->off) {
4457                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4458                         val + reg->off);
4459                 return -EINVAL;
4460         }
4461         if (is_lock) {
4462                 if (cur->active_spin_lock) {
4463                         verbose(env,
4464                                 "Locking two bpf_spin_locks are not allowed\n");
4465                         return -EINVAL;
4466                 }
4467                 cur->active_spin_lock = reg->id;
4468         } else {
4469                 if (!cur->active_spin_lock) {
4470                         verbose(env, "bpf_spin_unlock without taking a lock\n");
4471                         return -EINVAL;
4472                 }
4473                 if (cur->active_spin_lock != reg->id) {
4474                         verbose(env, "bpf_spin_unlock of different lock\n");
4475                         return -EINVAL;
4476                 }
4477                 cur->active_spin_lock = 0;
4478         }
4479         return 0;
4480 }
4481
4482 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4483 {
4484         return type == ARG_PTR_TO_MEM ||
4485                type == ARG_PTR_TO_MEM_OR_NULL ||
4486                type == ARG_PTR_TO_UNINIT_MEM;
4487 }
4488
4489 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4490 {
4491         return type == ARG_CONST_SIZE ||
4492                type == ARG_CONST_SIZE_OR_ZERO;
4493 }
4494
4495 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4496 {
4497         return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4498 }
4499
4500 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4501 {
4502         return type == ARG_PTR_TO_INT ||
4503                type == ARG_PTR_TO_LONG;
4504 }
4505
4506 static int int_ptr_type_to_size(enum bpf_arg_type type)
4507 {
4508         if (type == ARG_PTR_TO_INT)
4509                 return sizeof(u32);
4510         else if (type == ARG_PTR_TO_LONG)
4511                 return sizeof(u64);
4512
4513         return -EINVAL;
4514 }
4515
4516 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4517                                  const struct bpf_call_arg_meta *meta,
4518                                  enum bpf_arg_type *arg_type)
4519 {
4520         if (!meta->map_ptr) {
4521                 /* kernel subsystem misconfigured verifier */
4522                 verbose(env, "invalid map_ptr to access map->type\n");
4523                 return -EACCES;
4524         }
4525
4526         switch (meta->map_ptr->map_type) {
4527         case BPF_MAP_TYPE_SOCKMAP:
4528         case BPF_MAP_TYPE_SOCKHASH:
4529                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4530                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4531                 } else {
4532                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
4533                         return -EINVAL;
4534                 }
4535                 break;
4536
4537         default:
4538                 break;
4539         }
4540         return 0;
4541 }
4542
4543 struct bpf_reg_types {
4544         const enum bpf_reg_type types[10];
4545         u32 *btf_id;
4546 };
4547
4548 static const struct bpf_reg_types map_key_value_types = {
4549         .types = {
4550                 PTR_TO_STACK,
4551                 PTR_TO_PACKET,
4552                 PTR_TO_PACKET_META,
4553                 PTR_TO_MAP_VALUE,
4554         },
4555 };
4556
4557 static const struct bpf_reg_types sock_types = {
4558         .types = {
4559                 PTR_TO_SOCK_COMMON,
4560                 PTR_TO_SOCKET,
4561                 PTR_TO_TCP_SOCK,
4562                 PTR_TO_XDP_SOCK,
4563         },
4564 };
4565
4566 #ifdef CONFIG_NET
4567 static const struct bpf_reg_types btf_id_sock_common_types = {
4568         .types = {
4569                 PTR_TO_SOCK_COMMON,
4570                 PTR_TO_SOCKET,
4571                 PTR_TO_TCP_SOCK,
4572                 PTR_TO_XDP_SOCK,
4573                 PTR_TO_BTF_ID,
4574         },
4575         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4576 };
4577 #endif
4578
4579 static const struct bpf_reg_types mem_types = {
4580         .types = {
4581                 PTR_TO_STACK,
4582                 PTR_TO_PACKET,
4583                 PTR_TO_PACKET_META,
4584                 PTR_TO_MAP_VALUE,
4585                 PTR_TO_MEM,
4586                 PTR_TO_RDONLY_BUF,
4587                 PTR_TO_RDWR_BUF,
4588         },
4589 };
4590
4591 static const struct bpf_reg_types int_ptr_types = {
4592         .types = {
4593                 PTR_TO_STACK,
4594                 PTR_TO_PACKET,
4595                 PTR_TO_PACKET_META,
4596                 PTR_TO_MAP_VALUE,
4597         },
4598 };
4599
4600 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4601 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4602 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4603 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4604 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4605 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4606 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4607 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4608
4609 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4610         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
4611         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
4612         [ARG_PTR_TO_UNINIT_MAP_VALUE]   = &map_key_value_types,
4613         [ARG_PTR_TO_MAP_VALUE_OR_NULL]  = &map_key_value_types,
4614         [ARG_CONST_SIZE]                = &scalar_types,
4615         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
4616         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
4617         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
4618         [ARG_PTR_TO_CTX]                = &context_types,
4619         [ARG_PTR_TO_CTX_OR_NULL]        = &context_types,
4620         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
4621 #ifdef CONFIG_NET
4622         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4623 #endif
4624         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
4625         [ARG_PTR_TO_SOCKET_OR_NULL]     = &fullsock_types,
4626         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
4627         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
4628         [ARG_PTR_TO_MEM]                = &mem_types,
4629         [ARG_PTR_TO_MEM_OR_NULL]        = &mem_types,
4630         [ARG_PTR_TO_UNINIT_MEM]         = &mem_types,
4631         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
4632         [ARG_PTR_TO_ALLOC_MEM_OR_NULL]  = &alloc_mem_types,
4633         [ARG_PTR_TO_INT]                = &int_ptr_types,
4634         [ARG_PTR_TO_LONG]               = &int_ptr_types,
4635         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
4636 };
4637
4638 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4639                           enum bpf_arg_type arg_type,
4640                           const u32 *arg_btf_id)
4641 {
4642         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4643         enum bpf_reg_type expected, type = reg->type;
4644         const struct bpf_reg_types *compatible;
4645         int i, j;
4646
4647         compatible = compatible_reg_types[arg_type];
4648         if (!compatible) {
4649                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4650                 return -EFAULT;
4651         }
4652
4653         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4654                 expected = compatible->types[i];
4655                 if (expected == NOT_INIT)
4656                         break;
4657
4658                 if (type == expected)
4659                         goto found;
4660         }
4661
4662         verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4663         for (j = 0; j + 1 < i; j++)
4664                 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4665         verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4666         return -EACCES;
4667
4668 found:
4669         if (type == PTR_TO_BTF_ID) {
4670                 if (!arg_btf_id) {
4671                         if (!compatible->btf_id) {
4672                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4673                                 return -EFAULT;
4674                         }
4675                         arg_btf_id = compatible->btf_id;
4676                 }
4677
4678                 if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4679                                           *arg_btf_id)) {
4680                         verbose(env, "R%d is of type %s but %s is expected\n",
4681                                 regno, kernel_type_name(reg->btf_id),
4682                                 kernel_type_name(*arg_btf_id));
4683                         return -EACCES;
4684                 }
4685
4686                 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4687                         verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4688                                 regno);
4689                         return -EACCES;
4690                 }
4691         }
4692
4693         return 0;
4694 }
4695
4696 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4697                           struct bpf_call_arg_meta *meta,
4698                           const struct bpf_func_proto *fn)
4699 {
4700         u32 regno = BPF_REG_1 + arg;
4701         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4702         enum bpf_arg_type arg_type = fn->arg_type[arg];
4703         enum bpf_reg_type type = reg->type;
4704         int err = 0;
4705
4706         if (arg_type == ARG_DONTCARE)
4707                 return 0;
4708
4709         err = check_reg_arg(env, regno, SRC_OP);
4710         if (err)
4711                 return err;
4712
4713         if (arg_type == ARG_ANYTHING) {
4714                 if (is_pointer_value(env, regno)) {
4715                         verbose(env, "R%d leaks addr into helper function\n",
4716                                 regno);
4717                         return -EACCES;
4718                 }
4719                 return 0;
4720         }
4721
4722         if (type_is_pkt_pointer(type) &&
4723             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4724                 verbose(env, "helper access to the packet is not allowed\n");
4725                 return -EACCES;
4726         }
4727
4728         if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4729             arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4730             arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4731                 err = resolve_map_arg_type(env, meta, &arg_type);
4732                 if (err)
4733                         return err;
4734         }
4735
4736         if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4737                 /* A NULL register has a SCALAR_VALUE type, so skip
4738                  * type checking.
4739                  */
4740                 goto skip_type_check;
4741
4742         err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4743         if (err)
4744                 return err;
4745
4746         if (type == PTR_TO_CTX) {
4747                 err = check_ctx_reg(env, reg, regno);
4748                 if (err < 0)
4749                         return err;
4750         }
4751
4752 skip_type_check:
4753         if (reg->ref_obj_id) {
4754                 if (meta->ref_obj_id) {
4755                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4756                                 regno, reg->ref_obj_id,
4757                                 meta->ref_obj_id);
4758                         return -EFAULT;
4759                 }
4760                 meta->ref_obj_id = reg->ref_obj_id;
4761         }
4762
4763         if (arg_type == ARG_CONST_MAP_PTR) {
4764                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4765                 meta->map_ptr = reg->map_ptr;
4766         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4767                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4768                  * check that [key, key + map->key_size) are within
4769                  * stack limits and initialized
4770                  */
4771                 if (!meta->map_ptr) {
4772                         /* in function declaration map_ptr must come before
4773                          * map_key, so that it's verified and known before
4774                          * we have to check map_key here. Otherwise it means
4775                          * that kernel subsystem misconfigured verifier
4776                          */
4777                         verbose(env, "invalid map_ptr to access map->key\n");
4778                         return -EACCES;
4779                 }
4780                 err = check_helper_mem_access(env, regno,
4781                                               meta->map_ptr->key_size, false,
4782                                               NULL);
4783         } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4784                    (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4785                     !register_is_null(reg)) ||
4786                    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4787                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4788                  * check [value, value + map->value_size) validity
4789                  */
4790                 if (!meta->map_ptr) {
4791                         /* kernel subsystem misconfigured verifier */
4792                         verbose(env, "invalid map_ptr to access map->value\n");
4793                         return -EACCES;
4794                 }
4795                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4796                 err = check_helper_mem_access(env, regno,
4797                                               meta->map_ptr->value_size, false,
4798                                               meta);
4799         } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4800                 if (!reg->btf_id) {
4801                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4802                         return -EACCES;
4803                 }
4804                 meta->ret_btf_id = reg->btf_id;
4805         } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4806                 if (meta->func_id == BPF_FUNC_spin_lock) {
4807                         if (process_spin_lock(env, regno, true))
4808                                 return -EACCES;
4809                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4810                         if (process_spin_lock(env, regno, false))
4811                                 return -EACCES;
4812                 } else {
4813                         verbose(env, "verifier internal error\n");
4814                         return -EFAULT;
4815                 }
4816         } else if (arg_type_is_mem_ptr(arg_type)) {
4817                 /* The access to this pointer is only checked when we hit the
4818                  * next is_mem_size argument below.
4819                  */
4820                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4821         } else if (arg_type_is_mem_size(arg_type)) {
4822                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4823
4824                 /* This is used to refine r0 return value bounds for helpers
4825                  * that enforce this value as an upper bound on return values.
4826                  * See do_refine_retval_range() for helpers that can refine
4827                  * the return value. C type of helper is u32 so we pull register
4828                  * bound from umax_value however, if negative verifier errors
4829                  * out. Only upper bounds can be learned because retval is an
4830                  * int type and negative retvals are allowed.
4831                  */
4832                 meta->msize_max_value = reg->umax_value;
4833
4834                 /* The register is SCALAR_VALUE; the access check
4835                  * happens using its boundaries.
4836                  */
4837                 if (!tnum_is_const(reg->var_off))
4838                         /* For unprivileged variable accesses, disable raw
4839                          * mode so that the program is required to
4840                          * initialize all the memory that the helper could
4841                          * just partially fill up.
4842                          */
4843                         meta = NULL;
4844
4845                 if (reg->smin_value < 0) {
4846                         verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4847                                 regno);
4848                         return -EACCES;
4849                 }
4850
4851                 if (reg->umin_value == 0) {
4852                         err = check_helper_mem_access(env, regno - 1, 0,
4853                                                       zero_size_allowed,
4854                                                       meta);
4855                         if (err)
4856                                 return err;
4857                 }
4858
4859                 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4860                         verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4861                                 regno);
4862                         return -EACCES;
4863                 }
4864                 err = check_helper_mem_access(env, regno - 1,
4865                                               reg->umax_value,
4866                                               zero_size_allowed, meta);
4867                 if (!err)
4868                         err = mark_chain_precision(env, regno);
4869         } else if (arg_type_is_alloc_size(arg_type)) {
4870                 if (!tnum_is_const(reg->var_off)) {
4871                         verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4872                                 regno);
4873                         return -EACCES;
4874                 }
4875                 meta->mem_size = reg->var_off.value;
4876         } else if (arg_type_is_int_ptr(arg_type)) {
4877                 int size = int_ptr_type_to_size(arg_type);
4878
4879                 err = check_helper_mem_access(env, regno, size, false, meta);
4880                 if (err)
4881                         return err;
4882                 err = check_ptr_alignment(env, reg, 0, size, true);
4883         }
4884
4885         return err;
4886 }
4887
4888 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4889 {
4890         enum bpf_attach_type eatype = env->prog->expected_attach_type;
4891         enum bpf_prog_type type = resolve_prog_type(env->prog);
4892
4893         if (func_id != BPF_FUNC_map_update_elem)
4894                 return false;
4895
4896         /* It's not possible to get access to a locked struct sock in these
4897          * contexts, so updating is safe.
4898          */
4899         switch (type) {
4900         case BPF_PROG_TYPE_TRACING:
4901                 if (eatype == BPF_TRACE_ITER)
4902                         return true;
4903                 break;
4904         case BPF_PROG_TYPE_SOCKET_FILTER:
4905         case BPF_PROG_TYPE_SCHED_CLS:
4906         case BPF_PROG_TYPE_SCHED_ACT:
4907         case BPF_PROG_TYPE_XDP:
4908         case BPF_PROG_TYPE_SK_REUSEPORT:
4909         case BPF_PROG_TYPE_FLOW_DISSECTOR:
4910         case BPF_PROG_TYPE_SK_LOOKUP:
4911                 return true;
4912         default:
4913                 break;
4914         }
4915
4916         verbose(env, "cannot update sockmap in this context\n");
4917         return false;
4918 }
4919
4920 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4921 {
4922         return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4923 }
4924
4925 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4926                                         struct bpf_map *map, int func_id)
4927 {
4928         if (!map)
4929                 return 0;
4930
4931         /* We need a two way check, first is from map perspective ... */
4932         switch (map->map_type) {
4933         case BPF_MAP_TYPE_PROG_ARRAY:
4934                 if (func_id != BPF_FUNC_tail_call)
4935                         goto error;
4936                 break;
4937         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4938                 if (func_id != BPF_FUNC_perf_event_read &&
4939                     func_id != BPF_FUNC_perf_event_output &&
4940                     func_id != BPF_FUNC_skb_output &&
4941                     func_id != BPF_FUNC_perf_event_read_value &&
4942                     func_id != BPF_FUNC_xdp_output)
4943                         goto error;
4944                 break;
4945         case BPF_MAP_TYPE_RINGBUF:
4946                 if (func_id != BPF_FUNC_ringbuf_output &&
4947                     func_id != BPF_FUNC_ringbuf_reserve &&
4948                     func_id != BPF_FUNC_ringbuf_query)
4949                         goto error;
4950                 break;
4951         case BPF_MAP_TYPE_STACK_TRACE:
4952                 if (func_id != BPF_FUNC_get_stackid)
4953                         goto error;
4954                 break;
4955         case BPF_MAP_TYPE_CGROUP_ARRAY:
4956                 if (func_id != BPF_FUNC_skb_under_cgroup &&
4957                     func_id != BPF_FUNC_current_task_under_cgroup)
4958                         goto error;
4959                 break;
4960         case BPF_MAP_TYPE_CGROUP_STORAGE:
4961         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4962                 if (func_id != BPF_FUNC_get_local_storage)
4963                         goto error;
4964                 break;
4965         case BPF_MAP_TYPE_DEVMAP:
4966         case BPF_MAP_TYPE_DEVMAP_HASH:
4967                 if (func_id != BPF_FUNC_redirect_map &&
4968                     func_id != BPF_FUNC_map_lookup_elem)
4969                         goto error;
4970                 break;
4971         /* Restrict bpf side of cpumap and xskmap, open when use-cases
4972          * appear.
4973          */
4974         case BPF_MAP_TYPE_CPUMAP:
4975                 if (func_id != BPF_FUNC_redirect_map)
4976                         goto error;
4977                 break;
4978         case BPF_MAP_TYPE_XSKMAP:
4979                 if (func_id != BPF_FUNC_redirect_map &&
4980                     func_id != BPF_FUNC_map_lookup_elem)
4981                         goto error;
4982                 break;
4983         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4984         case BPF_MAP_TYPE_HASH_OF_MAPS:
4985                 if (func_id != BPF_FUNC_map_lookup_elem)
4986                         goto error;
4987                 break;
4988         case BPF_MAP_TYPE_SOCKMAP:
4989                 if (func_id != BPF_FUNC_sk_redirect_map &&
4990                     func_id != BPF_FUNC_sock_map_update &&
4991                     func_id != BPF_FUNC_map_delete_elem &&
4992                     func_id != BPF_FUNC_msg_redirect_map &&
4993                     func_id != BPF_FUNC_sk_select_reuseport &&
4994                     func_id != BPF_FUNC_map_lookup_elem &&
4995                     !may_update_sockmap(env, func_id))
4996                         goto error;
4997                 break;
4998         case BPF_MAP_TYPE_SOCKHASH:
4999                 if (func_id != BPF_FUNC_sk_redirect_hash &&
5000                     func_id != BPF_FUNC_sock_hash_update &&
5001                     func_id != BPF_FUNC_map_delete_elem &&
5002                     func_id != BPF_FUNC_msg_redirect_hash &&
5003                     func_id != BPF_FUNC_sk_select_reuseport &&
5004                     func_id != BPF_FUNC_map_lookup_elem &&
5005                     !may_update_sockmap(env, func_id))
5006                         goto error;
5007                 break;
5008         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5009                 if (func_id != BPF_FUNC_sk_select_reuseport)
5010                         goto error;
5011                 break;
5012         case BPF_MAP_TYPE_QUEUE:
5013         case BPF_MAP_TYPE_STACK:
5014                 if (func_id != BPF_FUNC_map_peek_elem &&
5015                     func_id != BPF_FUNC_map_pop_elem &&
5016                     func_id != BPF_FUNC_map_push_elem)
5017                         goto error;
5018                 break;
5019         case BPF_MAP_TYPE_SK_STORAGE:
5020                 if (func_id != BPF_FUNC_sk_storage_get &&
5021                     func_id != BPF_FUNC_sk_storage_delete)
5022                         goto error;
5023                 break;
5024         case BPF_MAP_TYPE_INODE_STORAGE:
5025                 if (func_id != BPF_FUNC_inode_storage_get &&
5026                     func_id != BPF_FUNC_inode_storage_delete)
5027                         goto error;
5028                 break;
5029         default:
5030                 break;
5031         }
5032
5033         /* ... and second from the function itself. */
5034         switch (func_id) {
5035         case BPF_FUNC_tail_call:
5036                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5037                         goto error;
5038                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5039                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5040                         return -EINVAL;
5041                 }
5042                 break;
5043         case BPF_FUNC_perf_event_read:
5044         case BPF_FUNC_perf_event_output:
5045         case BPF_FUNC_perf_event_read_value:
5046         case BPF_FUNC_skb_output:
5047         case BPF_FUNC_xdp_output:
5048                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5049                         goto error;
5050                 break;
5051         case BPF_FUNC_ringbuf_output:
5052         case BPF_FUNC_ringbuf_reserve:
5053         case BPF_FUNC_ringbuf_query:
5054                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5055                         goto error;
5056                 break;
5057         case BPF_FUNC_get_stackid:
5058                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5059                         goto error;
5060                 break;
5061         case BPF_FUNC_current_task_under_cgroup:
5062         case BPF_FUNC_skb_under_cgroup:
5063                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5064                         goto error;
5065                 break;
5066         case BPF_FUNC_redirect_map:
5067                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5068                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5069                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
5070                     map->map_type != BPF_MAP_TYPE_XSKMAP)
5071                         goto error;
5072                 break;
5073         case BPF_FUNC_sk_redirect_map:
5074         case BPF_FUNC_msg_redirect_map:
5075         case BPF_FUNC_sock_map_update:
5076                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5077                         goto error;
5078                 break;
5079         case BPF_FUNC_sk_redirect_hash:
5080         case BPF_FUNC_msg_redirect_hash:
5081         case BPF_FUNC_sock_hash_update:
5082                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5083                         goto error;
5084                 break;
5085         case BPF_FUNC_get_local_storage:
5086                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5087                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5088                         goto error;
5089                 break;
5090         case BPF_FUNC_sk_select_reuseport:
5091                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5092                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5093                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
5094                         goto error;
5095                 break;
5096         case BPF_FUNC_map_peek_elem:
5097         case BPF_FUNC_map_pop_elem:
5098         case BPF_FUNC_map_push_elem:
5099                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5100                     map->map_type != BPF_MAP_TYPE_STACK)
5101                         goto error;
5102                 break;
5103         case BPF_FUNC_sk_storage_get:
5104         case BPF_FUNC_sk_storage_delete:
5105                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5106                         goto error;
5107                 break;
5108         case BPF_FUNC_inode_storage_get:
5109         case BPF_FUNC_inode_storage_delete:
5110                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5111                         goto error;
5112                 break;
5113         default:
5114                 break;
5115         }
5116
5117         return 0;
5118 error:
5119         verbose(env, "cannot pass map_type %d into func %s#%d\n",
5120                 map->map_type, func_id_name(func_id), func_id);
5121         return -EINVAL;
5122 }
5123
5124 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5125 {
5126         int count = 0;
5127
5128         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5129                 count++;
5130         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5131                 count++;
5132         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5133                 count++;
5134         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5135                 count++;
5136         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5137                 count++;
5138
5139         /* We only support one arg being in raw mode at the moment,
5140          * which is sufficient for the helper functions we have
5141          * right now.
5142          */
5143         return count <= 1;
5144 }
5145
5146 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5147                                     enum bpf_arg_type arg_next)
5148 {
5149         return (arg_type_is_mem_ptr(arg_curr) &&
5150                 !arg_type_is_mem_size(arg_next)) ||
5151                (!arg_type_is_mem_ptr(arg_curr) &&
5152                 arg_type_is_mem_size(arg_next));
5153 }
5154
5155 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5156 {
5157         /* bpf_xxx(..., buf, len) call will access 'len'
5158          * bytes from memory 'buf'. Both arg types need
5159          * to be paired, so make sure there's no buggy
5160          * helper function specification.
5161          */
5162         if (arg_type_is_mem_size(fn->arg1_type) ||
5163             arg_type_is_mem_ptr(fn->arg5_type)  ||
5164             check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5165             check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5166             check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5167             check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5168                 return false;
5169
5170         return true;
5171 }
5172
5173 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5174 {
5175         int count = 0;
5176
5177         if (arg_type_may_be_refcounted(fn->arg1_type))
5178                 count++;
5179         if (arg_type_may_be_refcounted(fn->arg2_type))
5180                 count++;
5181         if (arg_type_may_be_refcounted(fn->arg3_type))
5182                 count++;
5183         if (arg_type_may_be_refcounted(fn->arg4_type))
5184                 count++;
5185         if (arg_type_may_be_refcounted(fn->arg5_type))
5186                 count++;
5187
5188         /* A reference acquiring function cannot acquire
5189          * another refcounted ptr.
5190          */
5191         if (may_be_acquire_function(func_id) && count)
5192                 return false;
5193
5194         /* We only support one arg being unreferenced at the moment,
5195          * which is sufficient for the helper functions we have right now.
5196          */
5197         return count <= 1;
5198 }
5199
5200 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5201 {
5202         int i;
5203
5204         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5205                 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5206                         return false;
5207
5208                 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5209                         return false;
5210         }
5211
5212         return true;
5213 }
5214
5215 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5216 {
5217         return check_raw_mode_ok(fn) &&
5218                check_arg_pair_ok(fn) &&
5219                check_btf_id_ok(fn) &&
5220                check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5221 }
5222
5223 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5224  * are now invalid, so turn them into unknown SCALAR_VALUE.
5225  */
5226 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5227 {
5228         struct bpf_func_state *state;
5229         struct bpf_reg_state *reg;
5230
5231         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5232                 if (reg_is_pkt_pointer_any(reg))
5233                         __mark_reg_unknown(env, reg);
5234         }));
5235 }
5236
5237 enum {
5238         AT_PKT_END = -1,
5239         BEYOND_PKT_END = -2,
5240 };
5241
5242 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5243 {
5244         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5245         struct bpf_reg_state *reg = &state->regs[regn];
5246
5247         if (reg->type != PTR_TO_PACKET)
5248                 /* PTR_TO_PACKET_META is not supported yet */
5249                 return;
5250
5251         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5252          * How far beyond pkt_end it goes is unknown.
5253          * if (!range_open) it's the case of pkt >= pkt_end
5254          * if (range_open) it's the case of pkt > pkt_end
5255          * hence this pointer is at least 1 byte bigger than pkt_end
5256          */
5257         if (range_open)
5258                 reg->range = BEYOND_PKT_END;
5259         else
5260                 reg->range = AT_PKT_END;
5261 }
5262
5263 /* The pointer with the specified id has released its reference to kernel
5264  * resources. Identify all copies of the same pointer and clear the reference.
5265  */
5266 static int release_reference(struct bpf_verifier_env *env,
5267                              int ref_obj_id)
5268 {
5269         struct bpf_func_state *state;
5270         struct bpf_reg_state *reg;
5271         int err;
5272
5273         err = release_reference_state(cur_func(env), ref_obj_id);
5274         if (err)
5275                 return err;
5276
5277         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5278                 if (reg->ref_obj_id == ref_obj_id) {
5279                         if (!env->allow_ptr_leaks)
5280                                 __mark_reg_not_init(env, reg);
5281                         else
5282                                 __mark_reg_unknown(env, reg);
5283                 }
5284         }));
5285
5286         return 0;
5287 }
5288
5289 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5290                                     struct bpf_reg_state *regs)
5291 {
5292         int i;
5293
5294         /* after the call registers r0 - r5 were scratched */
5295         for (i = 0; i < CALLER_SAVED_REGS; i++) {
5296                 mark_reg_not_init(env, regs, caller_saved[i]);
5297                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5298         }
5299 }
5300
5301 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5302                            int *insn_idx)
5303 {
5304         struct bpf_verifier_state *state = env->cur_state;
5305         struct bpf_func_info_aux *func_info_aux;
5306         struct bpf_func_state *caller, *callee;
5307         int i, err, subprog, target_insn;
5308         bool is_global = false;
5309
5310         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5311                 verbose(env, "the call stack of %d frames is too deep\n",
5312                         state->curframe + 2);
5313                 return -E2BIG;
5314         }
5315
5316         target_insn = *insn_idx + insn->imm;
5317         subprog = find_subprog(env, target_insn + 1);
5318         if (subprog < 0) {
5319                 verbose(env, "verifier bug. No program starts at insn %d\n",
5320                         target_insn + 1);
5321                 return -EFAULT;
5322         }
5323
5324         caller = state->frame[state->curframe];
5325         if (state->frame[state->curframe + 1]) {
5326                 verbose(env, "verifier bug. Frame %d already allocated\n",
5327                         state->curframe + 1);
5328                 return -EFAULT;
5329         }
5330
5331         func_info_aux = env->prog->aux->func_info_aux;
5332         if (func_info_aux)
5333                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5334         err = btf_check_func_arg_match(env, subprog, caller->regs);
5335         if (err == -EFAULT)
5336                 return err;
5337         if (is_global) {
5338                 if (err) {
5339                         verbose(env, "Caller passes invalid args into func#%d\n",
5340                                 subprog);
5341                         return err;
5342                 } else {
5343                         if (env->log.level & BPF_LOG_LEVEL)
5344                                 verbose(env,
5345                                         "Func#%d is global and valid. Skipping.\n",
5346                                         subprog);
5347                         clear_caller_saved_regs(env, caller->regs);
5348
5349                         /* All global functions return a 64-bit SCALAR_VALUE */
5350                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
5351                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5352
5353                         /* continue with next insn after call */
5354                         return 0;
5355                 }
5356         }
5357
5358         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5359         if (!callee)
5360                 return -ENOMEM;
5361         state->frame[state->curframe + 1] = callee;
5362
5363         /* callee cannot access r0, r6 - r9 for reading and has to write
5364          * into its own stack before reading from it.
5365          * callee can read/write into caller's stack
5366          */
5367         init_func_state(env, callee,
5368                         /* remember the callsite, it will be used by bpf_exit */
5369                         *insn_idx /* callsite */,
5370                         state->curframe + 1 /* frameno within this callchain */,
5371                         subprog /* subprog number within this prog */);
5372
5373         /* Transfer references to the callee */
5374         err = transfer_reference_state(callee, caller);
5375         if (err)
5376                 return err;
5377
5378         /* copy r1 - r5 args that callee can access.  The copy includes parent
5379          * pointers, which connects us up to the liveness chain
5380          */
5381         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5382                 callee->regs[i] = caller->regs[i];
5383
5384         clear_caller_saved_regs(env, caller->regs);
5385
5386         /* only increment it after check_reg_arg() finished */
5387         state->curframe++;
5388
5389         /* and go analyze first insn of the callee */
5390         *insn_idx = target_insn;
5391
5392         if (env->log.level & BPF_LOG_LEVEL) {
5393                 verbose(env, "caller:\n");
5394                 print_verifier_state(env, caller);
5395                 verbose(env, "callee:\n");
5396                 print_verifier_state(env, callee);
5397         }
5398         return 0;
5399 }
5400
5401 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5402 {
5403         struct bpf_verifier_state *state = env->cur_state;
5404         struct bpf_func_state *caller, *callee;
5405         struct bpf_reg_state *r0;
5406         int err;
5407
5408         callee = state->frame[state->curframe];
5409         r0 = &callee->regs[BPF_REG_0];
5410         if (r0->type == PTR_TO_STACK) {
5411                 /* technically it's ok to return caller's stack pointer
5412                  * (or caller's caller's pointer) back to the caller,
5413                  * since these pointers are valid. Only current stack
5414                  * pointer will be invalid as soon as function exits,
5415                  * but let's be conservative
5416                  */
5417                 verbose(env, "cannot return stack pointer to the caller\n");
5418                 return -EINVAL;
5419         }
5420
5421         state->curframe--;
5422         caller = state->frame[state->curframe];
5423         /* return to the caller whatever r0 had in the callee */
5424         caller->regs[BPF_REG_0] = *r0;
5425
5426         /* Transfer references to the caller */
5427         err = transfer_reference_state(caller, callee);
5428         if (err)
5429                 return err;
5430
5431         *insn_idx = callee->callsite + 1;
5432         if (env->log.level & BPF_LOG_LEVEL) {
5433                 verbose(env, "returning from callee:\n");
5434                 print_verifier_state(env, callee);
5435                 verbose(env, "to caller at %d:\n", *insn_idx);
5436                 print_verifier_state(env, caller);
5437         }
5438         /* clear everything in the callee */
5439         free_func_state(callee);
5440         state->frame[state->curframe + 1] = NULL;
5441         return 0;
5442 }
5443
5444 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5445                                    int func_id,
5446                                    struct bpf_call_arg_meta *meta)
5447 {
5448         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5449
5450         if (ret_type != RET_INTEGER ||
5451             (func_id != BPF_FUNC_get_stack &&
5452              func_id != BPF_FUNC_probe_read_str &&
5453              func_id != BPF_FUNC_probe_read_kernel_str &&
5454              func_id != BPF_FUNC_probe_read_user_str))
5455                 return;
5456
5457         ret_reg->smax_value = meta->msize_max_value;
5458         ret_reg->s32_max_value = meta->msize_max_value;
5459         ret_reg->smin_value = -MAX_ERRNO;
5460         ret_reg->s32_min_value = -MAX_ERRNO;
5461         reg_bounds_sync(ret_reg);
5462 }
5463
5464 static int
5465 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5466                 int func_id, int insn_idx)
5467 {
5468         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5469         struct bpf_map *map = meta->map_ptr;
5470
5471         if (func_id != BPF_FUNC_tail_call &&
5472             func_id != BPF_FUNC_map_lookup_elem &&
5473             func_id != BPF_FUNC_map_update_elem &&
5474             func_id != BPF_FUNC_map_delete_elem &&
5475             func_id != BPF_FUNC_map_push_elem &&
5476             func_id != BPF_FUNC_map_pop_elem &&
5477             func_id != BPF_FUNC_map_peek_elem)
5478                 return 0;
5479
5480         if (map == NULL) {
5481                 verbose(env, "kernel subsystem misconfigured verifier\n");
5482                 return -EINVAL;
5483         }
5484
5485         /* In case of read-only, some additional restrictions
5486          * need to be applied in order to prevent altering the
5487          * state of the map from program side.
5488          */
5489         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5490             (func_id == BPF_FUNC_map_delete_elem ||
5491              func_id == BPF_FUNC_map_update_elem ||
5492              func_id == BPF_FUNC_map_push_elem ||
5493              func_id == BPF_FUNC_map_pop_elem)) {
5494                 verbose(env, "write into map forbidden\n");
5495                 return -EACCES;
5496         }
5497
5498         if (!BPF_MAP_PTR(aux->map_ptr_state))
5499                 bpf_map_ptr_store(aux, meta->map_ptr,
5500                                   !meta->map_ptr->bypass_spec_v1);
5501         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5502                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5503                                   !meta->map_ptr->bypass_spec_v1);
5504         return 0;
5505 }
5506
5507 static int
5508 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5509                 int func_id, int insn_idx)
5510 {
5511         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5512         struct bpf_reg_state *regs = cur_regs(env), *reg;
5513         struct bpf_map *map = meta->map_ptr;
5514         u64 val, max;
5515         int err;
5516
5517         if (func_id != BPF_FUNC_tail_call)
5518                 return 0;
5519         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5520                 verbose(env, "kernel subsystem misconfigured verifier\n");
5521                 return -EINVAL;
5522         }
5523
5524         reg = &regs[BPF_REG_3];
5525         val = reg->var_off.value;
5526         max = map->max_entries;
5527
5528         if (!(register_is_const(reg) && val < max)) {
5529                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5530                 return 0;
5531         }
5532
5533         err = mark_chain_precision(env, BPF_REG_3);
5534         if (err)
5535                 return err;
5536         if (bpf_map_key_unseen(aux))
5537                 bpf_map_key_store(aux, val);
5538         else if (!bpf_map_key_poisoned(aux) &&
5539                   bpf_map_key_immediate(aux) != val)
5540                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5541         return 0;
5542 }
5543
5544 static int check_reference_leak(struct bpf_verifier_env *env)
5545 {
5546         struct bpf_func_state *state = cur_func(env);
5547         int i;
5548
5549         for (i = 0; i < state->acquired_refs; i++) {
5550                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5551                         state->refs[i].id, state->refs[i].insn_idx);
5552         }
5553         return state->acquired_refs ? -EINVAL : 0;
5554 }
5555
5556 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5557 {
5558         const struct bpf_func_proto *fn = NULL;
5559         struct bpf_reg_state *regs;
5560         struct bpf_call_arg_meta meta;
5561         bool changes_data;
5562         int i, err;
5563
5564         /* find function prototype */
5565         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5566                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5567                         func_id);
5568                 return -EINVAL;
5569         }
5570
5571         if (env->ops->get_func_proto)
5572                 fn = env->ops->get_func_proto(func_id, env->prog);
5573         if (!fn) {
5574                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5575                         func_id);
5576                 return -EINVAL;
5577         }
5578
5579         /* eBPF programs must be GPL compatible to use GPL-ed functions */
5580         if (!env->prog->gpl_compatible && fn->gpl_only) {
5581                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5582                 return -EINVAL;
5583         }
5584
5585         if (fn->allowed && !fn->allowed(env->prog)) {
5586                 verbose(env, "helper call is not allowed in probe\n");
5587                 return -EINVAL;
5588         }
5589
5590         /* With LD_ABS/IND some JITs save/restore skb from r1. */
5591         changes_data = bpf_helper_changes_pkt_data(fn->func);
5592         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5593                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5594                         func_id_name(func_id), func_id);
5595                 return -EINVAL;
5596         }
5597
5598         memset(&meta, 0, sizeof(meta));
5599         meta.pkt_access = fn->pkt_access;
5600
5601         err = check_func_proto(fn, func_id);
5602         if (err) {
5603                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5604                         func_id_name(func_id), func_id);
5605                 return err;
5606         }
5607
5608         meta.func_id = func_id;
5609         /* check args */
5610         for (i = 0; i < 5; i++) {
5611                 err = check_func_arg(env, i, &meta, fn);
5612                 if (err)
5613                         return err;
5614         }
5615
5616         err = record_func_map(env, &meta, func_id, insn_idx);
5617         if (err)
5618                 return err;
5619
5620         err = record_func_key(env, &meta, func_id, insn_idx);
5621         if (err)
5622                 return err;
5623
5624         /* Mark slots with STACK_MISC in case of raw mode, stack offset
5625          * is inferred from register state.
5626          */
5627         for (i = 0; i < meta.access_size; i++) {
5628                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5629                                        BPF_WRITE, -1, false);
5630                 if (err)
5631                         return err;
5632         }
5633
5634         if (func_id == BPF_FUNC_tail_call) {
5635                 err = check_reference_leak(env);
5636                 if (err) {
5637                         verbose(env, "tail_call would lead to reference leak\n");
5638                         return err;
5639                 }
5640         } else if (is_release_function(func_id)) {
5641                 err = release_reference(env, meta.ref_obj_id);
5642                 if (err) {
5643                         verbose(env, "func %s#%d reference has not been acquired before\n",
5644                                 func_id_name(func_id), func_id);
5645                         return err;
5646                 }
5647         }
5648
5649         regs = cur_regs(env);
5650
5651         /* check that flags argument in get_local_storage(map, flags) is 0,
5652          * this is required because get_local_storage() can't return an error.
5653          */
5654         if (func_id == BPF_FUNC_get_local_storage &&
5655             !register_is_null(&regs[BPF_REG_2])) {
5656                 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5657                 return -EINVAL;
5658         }
5659
5660         /* reset caller saved regs */
5661         for (i = 0; i < CALLER_SAVED_REGS; i++) {
5662                 mark_reg_not_init(env, regs, caller_saved[i]);
5663                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5664         }
5665
5666         /* helper call returns 64-bit value. */
5667         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5668
5669         /* update return register (already marked as written above) */
5670         if (fn->ret_type == RET_INTEGER) {
5671                 /* sets type to SCALAR_VALUE */
5672                 mark_reg_unknown(env, regs, BPF_REG_0);
5673         } else if (fn->ret_type == RET_VOID) {
5674                 regs[BPF_REG_0].type = NOT_INIT;
5675         } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5676                    fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5677                 /* There is no offset yet applied, variable or fixed */
5678                 mark_reg_known_zero(env, regs, BPF_REG_0);
5679                 /* remember map_ptr, so that check_map_access()
5680                  * can check 'value_size' boundary of memory access
5681                  * to map element returned from bpf_map_lookup_elem()
5682                  */
5683                 if (meta.map_ptr == NULL) {
5684                         verbose(env,
5685                                 "kernel subsystem misconfigured verifier\n");
5686                         return -EINVAL;
5687                 }
5688                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
5689                 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5690                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
5691                         if (map_value_has_spin_lock(meta.map_ptr))
5692                                 regs[BPF_REG_0].id = ++env->id_gen;
5693                 } else {
5694                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5695                 }
5696         } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5697                 mark_reg_known_zero(env, regs, BPF_REG_0);
5698                 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
5699         } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5700                 mark_reg_known_zero(env, regs, BPF_REG_0);
5701                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5702         } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5703                 mark_reg_known_zero(env, regs, BPF_REG_0);
5704                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5705         } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5706                 mark_reg_known_zero(env, regs, BPF_REG_0);
5707                 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5708                 regs[BPF_REG_0].mem_size = meta.mem_size;
5709         } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5710                    fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
5711                 const struct btf_type *t;
5712
5713                 mark_reg_known_zero(env, regs, BPF_REG_0);
5714                 t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
5715                 if (!btf_type_is_struct(t)) {
5716                         u32 tsize;
5717                         const struct btf_type *ret;
5718                         const char *tname;
5719
5720                         /* resolve the type size of ksym. */
5721                         ret = btf_resolve_size(btf_vmlinux, t, &tsize);
5722                         if (IS_ERR(ret)) {
5723                                 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5724                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5725                                         tname, PTR_ERR(ret));
5726                                 return -EINVAL;
5727                         }
5728                         regs[BPF_REG_0].type =
5729                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5730                                 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
5731                         regs[BPF_REG_0].mem_size = tsize;
5732                 } else {
5733                         regs[BPF_REG_0].type =
5734                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5735                                 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
5736                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5737                 }
5738         } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
5739                 int ret_btf_id;
5740
5741                 mark_reg_known_zero(env, regs, BPF_REG_0);
5742                 regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
5743                 ret_btf_id = *fn->ret_btf_id;
5744                 if (ret_btf_id == 0) {
5745                         verbose(env, "invalid return type %d of func %s#%d\n",
5746                                 fn->ret_type, func_id_name(func_id), func_id);
5747                         return -EINVAL;
5748                 }
5749                 regs[BPF_REG_0].btf_id = ret_btf_id;
5750         } else {
5751                 verbose(env, "unknown return type %d of func %s#%d\n",
5752                         fn->ret_type, func_id_name(func_id), func_id);
5753                 return -EINVAL;
5754         }
5755
5756         if (reg_type_may_be_null(regs[BPF_REG_0].type))
5757                 regs[BPF_REG_0].id = ++env->id_gen;
5758
5759         if (is_ptr_cast_function(func_id)) {
5760                 /* For release_reference() */
5761                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5762         } else if (is_acquire_function(func_id, meta.map_ptr)) {
5763                 int id = acquire_reference_state(env, insn_idx);
5764
5765                 if (id < 0)
5766                         return id;
5767                 /* For mark_ptr_or_null_reg() */
5768                 regs[BPF_REG_0].id = id;
5769                 /* For release_reference() */
5770                 regs[BPF_REG_0].ref_obj_id = id;
5771         }
5772
5773         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5774
5775         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5776         if (err)
5777                 return err;
5778
5779         if ((func_id == BPF_FUNC_get_stack ||
5780              func_id == BPF_FUNC_get_task_stack) &&
5781             !env->prog->has_callchain_buf) {
5782                 const char *err_str;
5783
5784 #ifdef CONFIG_PERF_EVENTS
5785                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5786                 err_str = "cannot get callchain buffer for func %s#%d\n";
5787 #else
5788                 err = -ENOTSUPP;
5789                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5790 #endif
5791                 if (err) {
5792                         verbose(env, err_str, func_id_name(func_id), func_id);
5793                         return err;
5794                 }
5795
5796                 env->prog->has_callchain_buf = true;
5797         }
5798
5799         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5800                 env->prog->call_get_stack = true;
5801
5802         if (changes_data)
5803                 clear_all_pkt_pointers(env);
5804         return 0;
5805 }
5806
5807 static bool signed_add_overflows(s64 a, s64 b)
5808 {
5809         /* Do the add in u64, where overflow is well-defined */
5810         s64 res = (s64)((u64)a + (u64)b);
5811
5812         if (b < 0)
5813                 return res > a;
5814         return res < a;
5815 }
5816
5817 static bool signed_add32_overflows(s32 a, s32 b)
5818 {
5819         /* Do the add in u32, where overflow is well-defined */
5820         s32 res = (s32)((u32)a + (u32)b);
5821
5822         if (b < 0)
5823                 return res > a;
5824         return res < a;
5825 }
5826
5827 static bool signed_sub_overflows(s64 a, s64 b)
5828 {
5829         /* Do the sub in u64, where overflow is well-defined */
5830         s64 res = (s64)((u64)a - (u64)b);
5831
5832         if (b < 0)
5833                 return res < a;
5834         return res > a;
5835 }
5836
5837 static bool signed_sub32_overflows(s32 a, s32 b)
5838 {
5839         /* Do the sub in u32, where overflow is well-defined */
5840         s32 res = (s32)((u32)a - (u32)b);
5841
5842         if (b < 0)
5843                 return res < a;
5844         return res > a;
5845 }
5846
5847 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5848                                   const struct bpf_reg_state *reg,
5849                                   enum bpf_reg_type type)
5850 {
5851         bool known = tnum_is_const(reg->var_off);
5852         s64 val = reg->var_off.value;
5853         s64 smin = reg->smin_value;
5854
5855         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5856                 verbose(env, "math between %s pointer and %lld is not allowed\n",
5857                         reg_type_str[type], val);
5858                 return false;
5859         }
5860
5861         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5862                 verbose(env, "%s pointer offset %d is not allowed\n",
5863                         reg_type_str[type], reg->off);
5864                 return false;
5865         }
5866
5867         if (smin == S64_MIN) {
5868                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5869                         reg_type_str[type]);
5870                 return false;
5871         }
5872
5873         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5874                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5875                         smin, reg_type_str[type]);
5876                 return false;
5877         }
5878
5879         return true;
5880 }
5881
5882 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5883 {
5884         return &env->insn_aux_data[env->insn_idx];
5885 }
5886
5887 enum {
5888         REASON_BOUNDS   = -1,
5889         REASON_TYPE     = -2,
5890         REASON_PATHS    = -3,
5891         REASON_LIMIT    = -4,
5892         REASON_STACK    = -5,
5893 };
5894
5895 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5896                               u32 *alu_limit, bool mask_to_left)
5897 {
5898         u32 max = 0, ptr_limit = 0;
5899
5900         switch (ptr_reg->type) {
5901         case PTR_TO_STACK:
5902                 /* Offset 0 is out-of-bounds, but acceptable start for the
5903                  * left direction, see BPF_REG_FP. Also, unknown scalar
5904                  * offset where we would need to deal with min/max bounds is
5905                  * currently prohibited for unprivileged.
5906                  */
5907                 max = MAX_BPF_STACK + mask_to_left;
5908                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
5909                 break;
5910         case PTR_TO_MAP_VALUE:
5911                 max = ptr_reg->map_ptr->value_size;
5912                 ptr_limit = (mask_to_left ?
5913                              ptr_reg->smin_value :
5914                              ptr_reg->umax_value) + ptr_reg->off;
5915                 break;
5916         default:
5917                 return REASON_TYPE;
5918         }
5919
5920         if (ptr_limit >= max)
5921                 return REASON_LIMIT;
5922         *alu_limit = ptr_limit;
5923         return 0;
5924 }
5925
5926 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5927                                     const struct bpf_insn *insn)
5928 {
5929         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5930 }
5931
5932 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5933                                        u32 alu_state, u32 alu_limit)
5934 {
5935         /* If we arrived here from different branches with different
5936          * state or limits to sanitize, then this won't work.
5937          */
5938         if (aux->alu_state &&
5939             (aux->alu_state != alu_state ||
5940              aux->alu_limit != alu_limit))
5941                 return REASON_PATHS;
5942
5943         /* Corresponding fixup done in fixup_bpf_calls(). */
5944         aux->alu_state = alu_state;
5945         aux->alu_limit = alu_limit;
5946         return 0;
5947 }
5948
5949 static int sanitize_val_alu(struct bpf_verifier_env *env,
5950                             struct bpf_insn *insn)
5951 {
5952         struct bpf_insn_aux_data *aux = cur_aux(env);
5953
5954         if (can_skip_alu_sanitation(env, insn))
5955                 return 0;
5956
5957         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5958 }
5959
5960 static bool sanitize_needed(u8 opcode)
5961 {
5962         return opcode == BPF_ADD || opcode == BPF_SUB;
5963 }
5964
5965 struct bpf_sanitize_info {
5966         struct bpf_insn_aux_data aux;
5967         bool mask_to_left;
5968 };
5969
5970 static struct bpf_verifier_state *
5971 sanitize_speculative_path(struct bpf_verifier_env *env,
5972                           const struct bpf_insn *insn,
5973                           u32 next_idx, u32 curr_idx)
5974 {
5975         struct bpf_verifier_state *branch;
5976         struct bpf_reg_state *regs;
5977
5978         branch = push_stack(env, next_idx, curr_idx, true);
5979         if (branch && insn) {
5980                 regs = branch->frame[branch->curframe]->regs;
5981                 if (BPF_SRC(insn->code) == BPF_K) {
5982                         mark_reg_unknown(env, regs, insn->dst_reg);
5983                 } else if (BPF_SRC(insn->code) == BPF_X) {
5984                         mark_reg_unknown(env, regs, insn->dst_reg);
5985                         mark_reg_unknown(env, regs, insn->src_reg);
5986                 }
5987         }
5988         return branch;
5989 }
5990
5991 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5992                             struct bpf_insn *insn,
5993                             const struct bpf_reg_state *ptr_reg,
5994                             const struct bpf_reg_state *off_reg,
5995                             struct bpf_reg_state *dst_reg,
5996                             struct bpf_sanitize_info *info,
5997                             const bool commit_window)
5998 {
5999         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6000         struct bpf_verifier_state *vstate = env->cur_state;
6001         bool off_is_imm = tnum_is_const(off_reg->var_off);
6002         bool off_is_neg = off_reg->smin_value < 0;
6003         bool ptr_is_dst_reg = ptr_reg == dst_reg;
6004         u8 opcode = BPF_OP(insn->code);
6005         u32 alu_state, alu_limit;
6006         struct bpf_reg_state tmp;
6007         bool ret;
6008         int err;
6009
6010         if (can_skip_alu_sanitation(env, insn))
6011                 return 0;
6012
6013         /* We already marked aux for masking from non-speculative
6014          * paths, thus we got here in the first place. We only care
6015          * to explore bad access from here.
6016          */
6017         if (vstate->speculative)
6018                 goto do_sim;
6019
6020         if (!commit_window) {
6021                 if (!tnum_is_const(off_reg->var_off) &&
6022                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6023                         return REASON_BOUNDS;
6024
6025                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6026                                      (opcode == BPF_SUB && !off_is_neg);
6027         }
6028
6029         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6030         if (err < 0)
6031                 return err;
6032
6033         if (commit_window) {
6034                 /* In commit phase we narrow the masking window based on
6035                  * the observed pointer move after the simulated operation.
6036                  */
6037                 alu_state = info->aux.alu_state;
6038                 alu_limit = abs(info->aux.alu_limit - alu_limit);
6039         } else {
6040                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6041                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6042                 alu_state |= ptr_is_dst_reg ?
6043                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6044
6045                 /* Limit pruning on unknown scalars to enable deep search for
6046                  * potential masking differences from other program paths.
6047                  */
6048                 if (!off_is_imm)
6049                         env->explore_alu_limits = true;
6050         }
6051
6052         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6053         if (err < 0)
6054                 return err;
6055 do_sim:
6056         /* If we're in commit phase, we're done here given we already
6057          * pushed the truncated dst_reg into the speculative verification
6058          * stack.
6059          *
6060          * Also, when register is a known constant, we rewrite register-based
6061          * operation to immediate-based, and thus do not need masking (and as
6062          * a consequence, do not need to simulate the zero-truncation either).
6063          */
6064         if (commit_window || off_is_imm)
6065                 return 0;
6066
6067         /* Simulate and find potential out-of-bounds access under
6068          * speculative execution from truncation as a result of
6069          * masking when off was not within expected range. If off
6070          * sits in dst, then we temporarily need to move ptr there
6071          * to simulate dst (== 0) +/-= ptr. Needed, for example,
6072          * for cases where we use K-based arithmetic in one direction
6073          * and truncated reg-based in the other in order to explore
6074          * bad access.
6075          */
6076         if (!ptr_is_dst_reg) {
6077                 tmp = *dst_reg;
6078                 copy_register_state(dst_reg, ptr_reg);
6079         }
6080         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6081                                         env->insn_idx);
6082         if (!ptr_is_dst_reg && ret)
6083                 *dst_reg = tmp;
6084         return !ret ? REASON_STACK : 0;
6085 }
6086
6087 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6088 {
6089         struct bpf_verifier_state *vstate = env->cur_state;
6090
6091         /* If we simulate paths under speculation, we don't update the
6092          * insn as 'seen' such that when we verify unreachable paths in
6093          * the non-speculative domain, sanitize_dead_code() can still
6094          * rewrite/sanitize them.
6095          */
6096         if (!vstate->speculative)
6097                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6098 }
6099
6100 static int sanitize_err(struct bpf_verifier_env *env,
6101                         const struct bpf_insn *insn, int reason,
6102                         const struct bpf_reg_state *off_reg,
6103                         const struct bpf_reg_state *dst_reg)
6104 {
6105         static const char *err = "pointer arithmetic with it prohibited for !root";
6106         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6107         u32 dst = insn->dst_reg, src = insn->src_reg;
6108
6109         switch (reason) {
6110         case REASON_BOUNDS:
6111                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6112                         off_reg == dst_reg ? dst : src, err);
6113                 break;
6114         case REASON_TYPE:
6115                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6116                         off_reg == dst_reg ? src : dst, err);
6117                 break;
6118         case REASON_PATHS:
6119                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6120                         dst, op, err);
6121                 break;
6122         case REASON_LIMIT:
6123                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6124                         dst, op, err);
6125                 break;
6126         case REASON_STACK:
6127                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6128                         dst, err);
6129                 break;
6130         default:
6131                 verbose(env, "verifier internal error: unknown reason (%d)\n",
6132                         reason);
6133                 break;
6134         }
6135
6136         return -EACCES;
6137 }
6138
6139 /* check that stack access falls within stack limits and that 'reg' doesn't
6140  * have a variable offset.
6141  *
6142  * Variable offset is prohibited for unprivileged mode for simplicity since it
6143  * requires corresponding support in Spectre masking for stack ALU.  See also
6144  * retrieve_ptr_limit().
6145  *
6146  *
6147  * 'off' includes 'reg->off'.
6148  */
6149 static int check_stack_access_for_ptr_arithmetic(
6150                                 struct bpf_verifier_env *env,
6151                                 int regno,
6152                                 const struct bpf_reg_state *reg,
6153                                 int off)
6154 {
6155         if (!tnum_is_const(reg->var_off)) {
6156                 char tn_buf[48];
6157
6158                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6159                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6160                         regno, tn_buf, off);
6161                 return -EACCES;
6162         }
6163
6164         if (off >= 0 || off < -MAX_BPF_STACK) {
6165                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6166                         "prohibited for !root; off=%d\n", regno, off);
6167                 return -EACCES;
6168         }
6169
6170         return 0;
6171 }
6172
6173 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6174                                  const struct bpf_insn *insn,
6175                                  const struct bpf_reg_state *dst_reg)
6176 {
6177         u32 dst = insn->dst_reg;
6178
6179         /* For unprivileged we require that resulting offset must be in bounds
6180          * in order to be able to sanitize access later on.
6181          */
6182         if (env->bypass_spec_v1)
6183                 return 0;
6184
6185         switch (dst_reg->type) {
6186         case PTR_TO_STACK:
6187                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6188                                         dst_reg->off + dst_reg->var_off.value))
6189                         return -EACCES;
6190                 break;
6191         case PTR_TO_MAP_VALUE:
6192                 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6193                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6194                                 "prohibited for !root\n", dst);
6195                         return -EACCES;
6196                 }
6197                 break;
6198         default:
6199                 break;
6200         }
6201
6202         return 0;
6203 }
6204
6205 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6206  * Caller should also handle BPF_MOV case separately.
6207  * If we return -EACCES, caller may want to try again treating pointer as a
6208  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6209  */
6210 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6211                                    struct bpf_insn *insn,
6212                                    const struct bpf_reg_state *ptr_reg,
6213                                    const struct bpf_reg_state *off_reg)
6214 {
6215         struct bpf_verifier_state *vstate = env->cur_state;
6216         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6217         struct bpf_reg_state *regs = state->regs, *dst_reg;
6218         bool known = tnum_is_const(off_reg->var_off);
6219         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6220             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6221         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6222             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6223         struct bpf_sanitize_info info = {};
6224         u8 opcode = BPF_OP(insn->code);
6225         u32 dst = insn->dst_reg;
6226         int ret;
6227
6228         dst_reg = &regs[dst];
6229
6230         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6231             smin_val > smax_val || umin_val > umax_val) {
6232                 /* Taint dst register if offset had invalid bounds derived from
6233                  * e.g. dead branches.
6234                  */
6235                 __mark_reg_unknown(env, dst_reg);
6236                 return 0;
6237         }
6238
6239         if (BPF_CLASS(insn->code) != BPF_ALU64) {
6240                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6241                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6242                         __mark_reg_unknown(env, dst_reg);
6243                         return 0;
6244                 }
6245
6246                 verbose(env,
6247                         "R%d 32-bit pointer arithmetic prohibited\n",
6248                         dst);
6249                 return -EACCES;
6250         }
6251
6252         switch (ptr_reg->type) {
6253         case PTR_TO_MAP_VALUE_OR_NULL:
6254                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6255                         dst, reg_type_str[ptr_reg->type]);
6256                 return -EACCES;
6257         case CONST_PTR_TO_MAP:
6258                 /* smin_val represents the known value */
6259                 if (known && smin_val == 0 && opcode == BPF_ADD)
6260                         break;
6261                 fallthrough;
6262         case PTR_TO_PACKET_END:
6263         case PTR_TO_SOCKET:
6264         case PTR_TO_SOCK_COMMON:
6265         case PTR_TO_TCP_SOCK:
6266         case PTR_TO_XDP_SOCK:
6267 reject:
6268                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6269                         dst, reg_type_str[ptr_reg->type]);
6270                 return -EACCES;
6271         default:
6272                 if (reg_type_may_be_null(ptr_reg->type))
6273                         goto reject;
6274                 break;
6275         }
6276
6277         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6278          * The id may be overwritten later if we create a new variable offset.
6279          */
6280         dst_reg->type = ptr_reg->type;
6281         dst_reg->id = ptr_reg->id;
6282
6283         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6284             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6285                 return -EINVAL;
6286
6287         /* pointer types do not carry 32-bit bounds at the moment. */
6288         __mark_reg32_unbounded(dst_reg);
6289
6290         if (sanitize_needed(opcode)) {
6291                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6292                                        &info, false);
6293                 if (ret < 0)
6294                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
6295         }
6296
6297         switch (opcode) {
6298         case BPF_ADD:
6299                 /* We can take a fixed offset as long as it doesn't overflow
6300                  * the s32 'off' field
6301                  */
6302                 if (known && (ptr_reg->off + smin_val ==
6303                               (s64)(s32)(ptr_reg->off + smin_val))) {
6304                         /* pointer += K.  Accumulate it into fixed offset */
6305                         dst_reg->smin_value = smin_ptr;
6306                         dst_reg->smax_value = smax_ptr;
6307                         dst_reg->umin_value = umin_ptr;
6308                         dst_reg->umax_value = umax_ptr;
6309                         dst_reg->var_off = ptr_reg->var_off;
6310                         dst_reg->off = ptr_reg->off + smin_val;
6311                         dst_reg->raw = ptr_reg->raw;
6312                         break;
6313                 }
6314                 /* A new variable offset is created.  Note that off_reg->off
6315                  * == 0, since it's a scalar.
6316                  * dst_reg gets the pointer type and since some positive
6317                  * integer value was added to the pointer, give it a new 'id'
6318                  * if it's a PTR_TO_PACKET.
6319                  * this creates a new 'base' pointer, off_reg (variable) gets
6320                  * added into the variable offset, and we copy the fixed offset
6321                  * from ptr_reg.
6322                  */
6323                 if (signed_add_overflows(smin_ptr, smin_val) ||
6324                     signed_add_overflows(smax_ptr, smax_val)) {
6325                         dst_reg->smin_value = S64_MIN;
6326                         dst_reg->smax_value = S64_MAX;
6327                 } else {
6328                         dst_reg->smin_value = smin_ptr + smin_val;
6329                         dst_reg->smax_value = smax_ptr + smax_val;
6330                 }
6331                 if (umin_ptr + umin_val < umin_ptr ||
6332                     umax_ptr + umax_val < umax_ptr) {
6333                         dst_reg->umin_value = 0;
6334                         dst_reg->umax_value = U64_MAX;
6335                 } else {
6336                         dst_reg->umin_value = umin_ptr + umin_val;
6337                         dst_reg->umax_value = umax_ptr + umax_val;
6338                 }
6339                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6340                 dst_reg->off = ptr_reg->off;
6341                 dst_reg->raw = ptr_reg->raw;
6342                 if (reg_is_pkt_pointer(ptr_reg)) {
6343                         dst_reg->id = ++env->id_gen;
6344                         /* something was added to pkt_ptr, set range to zero */
6345                         dst_reg->raw = 0;
6346                 }
6347                 break;
6348         case BPF_SUB:
6349                 if (dst_reg == off_reg) {
6350                         /* scalar -= pointer.  Creates an unknown scalar */
6351                         verbose(env, "R%d tried to subtract pointer from scalar\n",
6352                                 dst);
6353                         return -EACCES;
6354                 }
6355                 /* We don't allow subtraction from FP, because (according to
6356                  * test_verifier.c test "invalid fp arithmetic", JITs might not
6357                  * be able to deal with it.
6358                  */
6359                 if (ptr_reg->type == PTR_TO_STACK) {
6360                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
6361                                 dst);
6362                         return -EACCES;
6363                 }
6364                 if (known && (ptr_reg->off - smin_val ==
6365                               (s64)(s32)(ptr_reg->off - smin_val))) {
6366                         /* pointer -= K.  Subtract it from fixed offset */
6367                         dst_reg->smin_value = smin_ptr;
6368                         dst_reg->smax_value = smax_ptr;
6369                         dst_reg->umin_value = umin_ptr;
6370                         dst_reg->umax_value = umax_ptr;
6371                         dst_reg->var_off = ptr_reg->var_off;
6372                         dst_reg->id = ptr_reg->id;
6373                         dst_reg->off = ptr_reg->off - smin_val;
6374                         dst_reg->raw = ptr_reg->raw;
6375                         break;
6376                 }
6377                 /* A new variable offset is created.  If the subtrahend is known
6378                  * nonnegative, then any reg->range we had before is still good.
6379                  */
6380                 if (signed_sub_overflows(smin_ptr, smax_val) ||
6381                     signed_sub_overflows(smax_ptr, smin_val)) {
6382                         /* Overflow possible, we know nothing */
6383                         dst_reg->smin_value = S64_MIN;
6384                         dst_reg->smax_value = S64_MAX;
6385                 } else {
6386                         dst_reg->smin_value = smin_ptr - smax_val;
6387                         dst_reg->smax_value = smax_ptr - smin_val;
6388                 }
6389                 if (umin_ptr < umax_val) {
6390                         /* Overflow possible, we know nothing */
6391                         dst_reg->umin_value = 0;
6392                         dst_reg->umax_value = U64_MAX;
6393                 } else {
6394                         /* Cannot overflow (as long as bounds are consistent) */
6395                         dst_reg->umin_value = umin_ptr - umax_val;
6396                         dst_reg->umax_value = umax_ptr - umin_val;
6397                 }
6398                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6399                 dst_reg->off = ptr_reg->off;
6400                 dst_reg->raw = ptr_reg->raw;
6401                 if (reg_is_pkt_pointer(ptr_reg)) {
6402                         dst_reg->id = ++env->id_gen;
6403                         /* something was added to pkt_ptr, set range to zero */
6404                         if (smin_val < 0)
6405                                 dst_reg->raw = 0;
6406                 }
6407                 break;
6408         case BPF_AND:
6409         case BPF_OR:
6410         case BPF_XOR:
6411                 /* bitwise ops on pointers are troublesome, prohibit. */
6412                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6413                         dst, bpf_alu_string[opcode >> 4]);
6414                 return -EACCES;
6415         default:
6416                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6417                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6418                         dst, bpf_alu_string[opcode >> 4]);
6419                 return -EACCES;
6420         }
6421
6422         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6423                 return -EINVAL;
6424         reg_bounds_sync(dst_reg);
6425         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6426                 return -EACCES;
6427         if (sanitize_needed(opcode)) {
6428                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6429                                        &info, true);
6430                 if (ret < 0)
6431                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
6432         }
6433
6434         return 0;
6435 }
6436
6437 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6438                                  struct bpf_reg_state *src_reg)
6439 {
6440         s32 smin_val = src_reg->s32_min_value;
6441         s32 smax_val = src_reg->s32_max_value;
6442         u32 umin_val = src_reg->u32_min_value;
6443         u32 umax_val = src_reg->u32_max_value;
6444
6445         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6446             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6447                 dst_reg->s32_min_value = S32_MIN;
6448                 dst_reg->s32_max_value = S32_MAX;
6449         } else {
6450                 dst_reg->s32_min_value += smin_val;
6451                 dst_reg->s32_max_value += smax_val;
6452         }
6453         if (dst_reg->u32_min_value + umin_val < umin_val ||
6454             dst_reg->u32_max_value + umax_val < umax_val) {
6455                 dst_reg->u32_min_value = 0;
6456                 dst_reg->u32_max_value = U32_MAX;
6457         } else {
6458                 dst_reg->u32_min_value += umin_val;
6459                 dst_reg->u32_max_value += umax_val;
6460         }
6461 }
6462
6463 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6464                                struct bpf_reg_state *src_reg)
6465 {
6466         s64 smin_val = src_reg->smin_value;
6467         s64 smax_val = src_reg->smax_value;
6468         u64 umin_val = src_reg->umin_value;
6469         u64 umax_val = src_reg->umax_value;
6470
6471         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6472             signed_add_overflows(dst_reg->smax_value, smax_val)) {
6473                 dst_reg->smin_value = S64_MIN;
6474                 dst_reg->smax_value = S64_MAX;
6475         } else {
6476                 dst_reg->smin_value += smin_val;
6477                 dst_reg->smax_value += smax_val;
6478         }
6479         if (dst_reg->umin_value + umin_val < umin_val ||
6480             dst_reg->umax_value + umax_val < umax_val) {
6481                 dst_reg->umin_value = 0;
6482                 dst_reg->umax_value = U64_MAX;
6483         } else {
6484                 dst_reg->umin_value += umin_val;
6485                 dst_reg->umax_value += umax_val;
6486         }
6487 }
6488
6489 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6490                                  struct bpf_reg_state *src_reg)
6491 {
6492         s32 smin_val = src_reg->s32_min_value;
6493         s32 smax_val = src_reg->s32_max_value;
6494         u32 umin_val = src_reg->u32_min_value;
6495         u32 umax_val = src_reg->u32_max_value;
6496
6497         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6498             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6499                 /* Overflow possible, we know nothing */
6500                 dst_reg->s32_min_value = S32_MIN;
6501                 dst_reg->s32_max_value = S32_MAX;
6502         } else {
6503                 dst_reg->s32_min_value -= smax_val;
6504                 dst_reg->s32_max_value -= smin_val;
6505         }
6506         if (dst_reg->u32_min_value < umax_val) {
6507                 /* Overflow possible, we know nothing */
6508                 dst_reg->u32_min_value = 0;
6509                 dst_reg->u32_max_value = U32_MAX;
6510         } else {
6511                 /* Cannot overflow (as long as bounds are consistent) */
6512                 dst_reg->u32_min_value -= umax_val;
6513                 dst_reg->u32_max_value -= umin_val;
6514         }
6515 }
6516
6517 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6518                                struct bpf_reg_state *src_reg)
6519 {
6520         s64 smin_val = src_reg->smin_value;
6521         s64 smax_val = src_reg->smax_value;
6522         u64 umin_val = src_reg->umin_value;
6523         u64 umax_val = src_reg->umax_value;
6524
6525         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6526             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6527                 /* Overflow possible, we know nothing */
6528                 dst_reg->smin_value = S64_MIN;
6529                 dst_reg->smax_value = S64_MAX;
6530         } else {
6531                 dst_reg->smin_value -= smax_val;
6532                 dst_reg->smax_value -= smin_val;
6533         }
6534         if (dst_reg->umin_value < umax_val) {
6535                 /* Overflow possible, we know nothing */
6536                 dst_reg->umin_value = 0;
6537                 dst_reg->umax_value = U64_MAX;
6538         } else {
6539                 /* Cannot overflow (as long as bounds are consistent) */
6540                 dst_reg->umin_value -= umax_val;
6541                 dst_reg->umax_value -= umin_val;
6542         }
6543 }
6544
6545 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6546                                  struct bpf_reg_state *src_reg)
6547 {
6548         s32 smin_val = src_reg->s32_min_value;
6549         u32 umin_val = src_reg->u32_min_value;
6550         u32 umax_val = src_reg->u32_max_value;
6551
6552         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6553                 /* Ain't nobody got time to multiply that sign */
6554                 __mark_reg32_unbounded(dst_reg);
6555                 return;
6556         }
6557         /* Both values are positive, so we can work with unsigned and
6558          * copy the result to signed (unless it exceeds S32_MAX).
6559          */
6560         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6561                 /* Potential overflow, we know nothing */
6562                 __mark_reg32_unbounded(dst_reg);
6563                 return;
6564         }
6565         dst_reg->u32_min_value *= umin_val;
6566         dst_reg->u32_max_value *= umax_val;
6567         if (dst_reg->u32_max_value > S32_MAX) {
6568                 /* Overflow possible, we know nothing */
6569                 dst_reg->s32_min_value = S32_MIN;
6570                 dst_reg->s32_max_value = S32_MAX;
6571         } else {
6572                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6573                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6574         }
6575 }
6576
6577 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6578                                struct bpf_reg_state *src_reg)
6579 {
6580         s64 smin_val = src_reg->smin_value;
6581         u64 umin_val = src_reg->umin_value;
6582         u64 umax_val = src_reg->umax_value;
6583
6584         if (smin_val < 0 || dst_reg->smin_value < 0) {
6585                 /* Ain't nobody got time to multiply that sign */
6586                 __mark_reg64_unbounded(dst_reg);
6587                 return;
6588         }
6589         /* Both values are positive, so we can work with unsigned and
6590          * copy the result to signed (unless it exceeds S64_MAX).
6591          */
6592         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6593                 /* Potential overflow, we know nothing */
6594                 __mark_reg64_unbounded(dst_reg);
6595                 return;
6596         }
6597         dst_reg->umin_value *= umin_val;
6598         dst_reg->umax_value *= umax_val;
6599         if (dst_reg->umax_value > S64_MAX) {
6600                 /* Overflow possible, we know nothing */
6601                 dst_reg->smin_value = S64_MIN;
6602                 dst_reg->smax_value = S64_MAX;
6603         } else {
6604                 dst_reg->smin_value = dst_reg->umin_value;
6605                 dst_reg->smax_value = dst_reg->umax_value;
6606         }
6607 }
6608
6609 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6610                                  struct bpf_reg_state *src_reg)
6611 {
6612         bool src_known = tnum_subreg_is_const(src_reg->var_off);
6613         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6614         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6615         s32 smin_val = src_reg->s32_min_value;
6616         u32 umax_val = src_reg->u32_max_value;
6617
6618         if (src_known && dst_known) {
6619                 __mark_reg32_known(dst_reg, var32_off.value);
6620                 return;
6621         }
6622
6623         /* We get our minimum from the var_off, since that's inherently
6624          * bitwise.  Our maximum is the minimum of the operands' maxima.
6625          */
6626         dst_reg->u32_min_value = var32_off.value;
6627         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6628         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6629                 /* Lose signed bounds when ANDing negative numbers,
6630                  * ain't nobody got time for that.
6631                  */
6632                 dst_reg->s32_min_value = S32_MIN;
6633                 dst_reg->s32_max_value = S32_MAX;
6634         } else {
6635                 /* ANDing two positives gives a positive, so safe to
6636                  * cast result into s64.
6637                  */
6638                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6639                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6640         }
6641 }
6642
6643 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6644                                struct bpf_reg_state *src_reg)
6645 {
6646         bool src_known = tnum_is_const(src_reg->var_off);
6647         bool dst_known = tnum_is_const(dst_reg->var_off);
6648         s64 smin_val = src_reg->smin_value;
6649         u64 umax_val = src_reg->umax_value;
6650
6651         if (src_known && dst_known) {
6652                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6653                 return;
6654         }
6655
6656         /* We get our minimum from the var_off, since that's inherently
6657          * bitwise.  Our maximum is the minimum of the operands' maxima.
6658          */
6659         dst_reg->umin_value = dst_reg->var_off.value;
6660         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6661         if (dst_reg->smin_value < 0 || smin_val < 0) {
6662                 /* Lose signed bounds when ANDing negative numbers,
6663                  * ain't nobody got time for that.
6664                  */
6665                 dst_reg->smin_value = S64_MIN;
6666                 dst_reg->smax_value = S64_MAX;
6667         } else {
6668                 /* ANDing two positives gives a positive, so safe to
6669                  * cast result into s64.
6670                  */
6671                 dst_reg->smin_value = dst_reg->umin_value;
6672                 dst_reg->smax_value = dst_reg->umax_value;
6673         }
6674         /* We may learn something more from the var_off */
6675         __update_reg_bounds(dst_reg);
6676 }
6677
6678 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6679                                 struct bpf_reg_state *src_reg)
6680 {
6681         bool src_known = tnum_subreg_is_const(src_reg->var_off);
6682         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6683         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6684         s32 smin_val = src_reg->s32_min_value;
6685         u32 umin_val = src_reg->u32_min_value;
6686
6687         if (src_known && dst_known) {
6688                 __mark_reg32_known(dst_reg, var32_off.value);
6689                 return;
6690         }
6691
6692         /* We get our maximum from the var_off, and our minimum is the
6693          * maximum of the operands' minima
6694          */
6695         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6696         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6697         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6698                 /* Lose signed bounds when ORing negative numbers,
6699                  * ain't nobody got time for that.
6700                  */
6701                 dst_reg->s32_min_value = S32_MIN;
6702                 dst_reg->s32_max_value = S32_MAX;
6703         } else {
6704                 /* ORing two positives gives a positive, so safe to
6705                  * cast result into s64.
6706                  */
6707                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6708                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6709         }
6710 }
6711
6712 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6713                               struct bpf_reg_state *src_reg)
6714 {
6715         bool src_known = tnum_is_const(src_reg->var_off);
6716         bool dst_known = tnum_is_const(dst_reg->var_off);
6717         s64 smin_val = src_reg->smin_value;
6718         u64 umin_val = src_reg->umin_value;
6719
6720         if (src_known && dst_known) {
6721                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6722                 return;
6723         }
6724
6725         /* We get our maximum from the var_off, and our minimum is the
6726          * maximum of the operands' minima
6727          */
6728         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6729         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6730         if (dst_reg->smin_value < 0 || smin_val < 0) {
6731                 /* Lose signed bounds when ORing negative numbers,
6732                  * ain't nobody got time for that.
6733                  */
6734                 dst_reg->smin_value = S64_MIN;
6735                 dst_reg->smax_value = S64_MAX;
6736         } else {
6737                 /* ORing two positives gives a positive, so safe to
6738                  * cast result into s64.
6739                  */
6740                 dst_reg->smin_value = dst_reg->umin_value;
6741                 dst_reg->smax_value = dst_reg->umax_value;
6742         }
6743         /* We may learn something more from the var_off */
6744         __update_reg_bounds(dst_reg);
6745 }
6746
6747 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6748                                  struct bpf_reg_state *src_reg)
6749 {
6750         bool src_known = tnum_subreg_is_const(src_reg->var_off);
6751         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6752         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6753         s32 smin_val = src_reg->s32_min_value;
6754
6755         if (src_known && dst_known) {
6756                 __mark_reg32_known(dst_reg, var32_off.value);
6757                 return;
6758         }
6759
6760         /* We get both minimum and maximum from the var32_off. */
6761         dst_reg->u32_min_value = var32_off.value;
6762         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6763
6764         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6765                 /* XORing two positive sign numbers gives a positive,
6766                  * so safe to cast u32 result into s32.
6767                  */
6768                 dst_reg->s32_min_value = dst_reg->u32_min_value;
6769                 dst_reg->s32_max_value = dst_reg->u32_max_value;
6770         } else {
6771                 dst_reg->s32_min_value = S32_MIN;
6772                 dst_reg->s32_max_value = S32_MAX;
6773         }
6774 }
6775
6776 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6777                                struct bpf_reg_state *src_reg)
6778 {
6779         bool src_known = tnum_is_const(src_reg->var_off);
6780         bool dst_known = tnum_is_const(dst_reg->var_off);
6781         s64 smin_val = src_reg->smin_value;
6782
6783         if (src_known && dst_known) {
6784                 /* dst_reg->var_off.value has been updated earlier */
6785                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6786                 return;
6787         }
6788
6789         /* We get both minimum and maximum from the var_off. */
6790         dst_reg->umin_value = dst_reg->var_off.value;
6791         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6792
6793         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6794                 /* XORing two positive sign numbers gives a positive,
6795                  * so safe to cast u64 result into s64.
6796                  */
6797                 dst_reg->smin_value = dst_reg->umin_value;
6798                 dst_reg->smax_value = dst_reg->umax_value;
6799         } else {
6800                 dst_reg->smin_value = S64_MIN;
6801                 dst_reg->smax_value = S64_MAX;
6802         }
6803
6804         __update_reg_bounds(dst_reg);
6805 }
6806
6807 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6808                                    u64 umin_val, u64 umax_val)
6809 {
6810         /* We lose all sign bit information (except what we can pick
6811          * up from var_off)
6812          */
6813         dst_reg->s32_min_value = S32_MIN;
6814         dst_reg->s32_max_value = S32_MAX;
6815         /* If we might shift our top bit out, then we know nothing */
6816         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6817                 dst_reg->u32_min_value = 0;
6818                 dst_reg->u32_max_value = U32_MAX;
6819         } else {
6820                 dst_reg->u32_min_value <<= umin_val;
6821                 dst_reg->u32_max_value <<= umax_val;
6822         }
6823 }
6824
6825 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6826                                  struct bpf_reg_state *src_reg)
6827 {
6828         u32 umax_val = src_reg->u32_max_value;
6829         u32 umin_val = src_reg->u32_min_value;
6830         /* u32 alu operation will zext upper bits */
6831         struct tnum subreg = tnum_subreg(dst_reg->var_off);
6832
6833         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6834         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6835         /* Not required but being careful mark reg64 bounds as unknown so
6836          * that we are forced to pick them up from tnum and zext later and
6837          * if some path skips this step we are still safe.
6838          */
6839         __mark_reg64_unbounded(dst_reg);
6840         __update_reg32_bounds(dst_reg);
6841 }
6842
6843 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6844                                    u64 umin_val, u64 umax_val)
6845 {
6846         /* Special case <<32 because it is a common compiler pattern to sign
6847          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6848          * positive we know this shift will also be positive so we can track
6849          * bounds correctly. Otherwise we lose all sign bit information except
6850          * what we can pick up from var_off. Perhaps we can generalize this
6851          * later to shifts of any length.
6852          */
6853         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6854                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6855         else
6856                 dst_reg->smax_value = S64_MAX;
6857
6858         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6859                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6860         else
6861                 dst_reg->smin_value = S64_MIN;
6862
6863         /* If we might shift our top bit out, then we know nothing */
6864         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6865                 dst_reg->umin_value = 0;
6866                 dst_reg->umax_value = U64_MAX;
6867         } else {
6868                 dst_reg->umin_value <<= umin_val;
6869                 dst_reg->umax_value <<= umax_val;
6870         }
6871 }
6872
6873 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6874                                struct bpf_reg_state *src_reg)
6875 {
6876         u64 umax_val = src_reg->umax_value;
6877         u64 umin_val = src_reg->umin_value;
6878
6879         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6880         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6881         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6882
6883         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6884         /* We may learn something more from the var_off */
6885         __update_reg_bounds(dst_reg);
6886 }
6887
6888 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6889                                  struct bpf_reg_state *src_reg)
6890 {
6891         struct tnum subreg = tnum_subreg(dst_reg->var_off);
6892         u32 umax_val = src_reg->u32_max_value;
6893         u32 umin_val = src_reg->u32_min_value;
6894
6895         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6896          * be negative, then either:
6897          * 1) src_reg might be zero, so the sign bit of the result is
6898          *    unknown, so we lose our signed bounds
6899          * 2) it's known negative, thus the unsigned bounds capture the
6900          *    signed bounds
6901          * 3) the signed bounds cross zero, so they tell us nothing
6902          *    about the result
6903          * If the value in dst_reg is known nonnegative, then again the
6904          * unsigned bounts capture the signed bounds.
6905          * Thus, in all cases it suffices to blow away our signed bounds
6906          * and rely on inferring new ones from the unsigned bounds and
6907          * var_off of the result.
6908          */
6909         dst_reg->s32_min_value = S32_MIN;
6910         dst_reg->s32_max_value = S32_MAX;
6911
6912         dst_reg->var_off = tnum_rshift(subreg, umin_val);
6913         dst_reg->u32_min_value >>= umax_val;
6914         dst_reg->u32_max_value >>= umin_val;
6915
6916         __mark_reg64_unbounded(dst_reg);
6917         __update_reg32_bounds(dst_reg);
6918 }
6919
6920 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6921                                struct bpf_reg_state *src_reg)
6922 {
6923         u64 umax_val = src_reg->umax_value;
6924         u64 umin_val = src_reg->umin_value;
6925
6926         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6927          * be negative, then either:
6928          * 1) src_reg might be zero, so the sign bit of the result is
6929          *    unknown, so we lose our signed bounds
6930          * 2) it's known negative, thus the unsigned bounds capture the
6931          *    signed bounds
6932          * 3) the signed bounds cross zero, so they tell us nothing
6933          *    about the result
6934          * If the value in dst_reg is known nonnegative, then again the
6935          * unsigned bounts capture the signed bounds.
6936          * Thus, in all cases it suffices to blow away our signed bounds
6937          * and rely on inferring new ones from the unsigned bounds and
6938          * var_off of the result.
6939          */
6940         dst_reg->smin_value = S64_MIN;
6941         dst_reg->smax_value = S64_MAX;
6942         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6943         dst_reg->umin_value >>= umax_val;
6944         dst_reg->umax_value >>= umin_val;
6945
6946         /* Its not easy to operate on alu32 bounds here because it depends
6947          * on bits being shifted in. Take easy way out and mark unbounded
6948          * so we can recalculate later from tnum.
6949          */
6950         __mark_reg32_unbounded(dst_reg);
6951         __update_reg_bounds(dst_reg);
6952 }
6953
6954 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6955                                   struct bpf_reg_state *src_reg)
6956 {
6957         u64 umin_val = src_reg->u32_min_value;
6958
6959         /* Upon reaching here, src_known is true and
6960          * umax_val is equal to umin_val.
6961          */
6962         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6963         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6964
6965         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6966
6967         /* blow away the dst_reg umin_value/umax_value and rely on
6968          * dst_reg var_off to refine the result.
6969          */
6970         dst_reg->u32_min_value = 0;
6971         dst_reg->u32_max_value = U32_MAX;
6972
6973         __mark_reg64_unbounded(dst_reg);
6974         __update_reg32_bounds(dst_reg);
6975 }
6976
6977 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6978                                 struct bpf_reg_state *src_reg)
6979 {
6980         u64 umin_val = src_reg->umin_value;
6981
6982         /* Upon reaching here, src_known is true and umax_val is equal
6983          * to umin_val.
6984          */
6985         dst_reg->smin_value >>= umin_val;
6986         dst_reg->smax_value >>= umin_val;
6987
6988         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
6989
6990         /* blow away the dst_reg umin_value/umax_value and rely on
6991          * dst_reg var_off to refine the result.
6992          */
6993         dst_reg->umin_value = 0;
6994         dst_reg->umax_value = U64_MAX;
6995
6996         /* Its not easy to operate on alu32 bounds here because it depends
6997          * on bits being shifted in from upper 32-bits. Take easy way out
6998          * and mark unbounded so we can recalculate later from tnum.
6999          */
7000         __mark_reg32_unbounded(dst_reg);
7001         __update_reg_bounds(dst_reg);
7002 }
7003
7004 /* WARNING: This function does calculations on 64-bit values, but the actual
7005  * execution may occur on 32-bit values. Therefore, things like bitshifts
7006  * need extra checks in the 32-bit case.
7007  */
7008 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7009                                       struct bpf_insn *insn,
7010                                       struct bpf_reg_state *dst_reg,
7011                                       struct bpf_reg_state src_reg)
7012 {
7013         struct bpf_reg_state *regs = cur_regs(env);
7014         u8 opcode = BPF_OP(insn->code);
7015         bool src_known;
7016         s64 smin_val, smax_val;
7017         u64 umin_val, umax_val;
7018         s32 s32_min_val, s32_max_val;
7019         u32 u32_min_val, u32_max_val;
7020         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7021         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7022         int ret;
7023
7024         smin_val = src_reg.smin_value;
7025         smax_val = src_reg.smax_value;
7026         umin_val = src_reg.umin_value;
7027         umax_val = src_reg.umax_value;
7028
7029         s32_min_val = src_reg.s32_min_value;
7030         s32_max_val = src_reg.s32_max_value;
7031         u32_min_val = src_reg.u32_min_value;
7032         u32_max_val = src_reg.u32_max_value;
7033
7034         if (alu32) {
7035                 src_known = tnum_subreg_is_const(src_reg.var_off);
7036                 if ((src_known &&
7037                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7038                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7039                         /* Taint dst register if offset had invalid bounds
7040                          * derived from e.g. dead branches.
7041                          */
7042                         __mark_reg_unknown(env, dst_reg);
7043                         return 0;
7044                 }
7045         } else {
7046                 src_known = tnum_is_const(src_reg.var_off);
7047                 if ((src_known &&
7048                      (smin_val != smax_val || umin_val != umax_val)) ||
7049                     smin_val > smax_val || umin_val > umax_val) {
7050                         /* Taint dst register if offset had invalid bounds
7051                          * derived from e.g. dead branches.
7052                          */
7053                         __mark_reg_unknown(env, dst_reg);
7054                         return 0;
7055                 }
7056         }
7057
7058         if (!src_known &&
7059             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7060                 __mark_reg_unknown(env, dst_reg);
7061                 return 0;
7062         }
7063
7064         if (sanitize_needed(opcode)) {
7065                 ret = sanitize_val_alu(env, insn);
7066                 if (ret < 0)
7067                         return sanitize_err(env, insn, ret, NULL, NULL);
7068         }
7069
7070         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7071          * There are two classes of instructions: The first class we track both
7072          * alu32 and alu64 sign/unsigned bounds independently this provides the
7073          * greatest amount of precision when alu operations are mixed with jmp32
7074          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7075          * and BPF_OR. This is possible because these ops have fairly easy to
7076          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7077          * See alu32 verifier tests for examples. The second class of
7078          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7079          * with regards to tracking sign/unsigned bounds because the bits may
7080          * cross subreg boundaries in the alu64 case. When this happens we mark
7081          * the reg unbounded in the subreg bound space and use the resulting
7082          * tnum to calculate an approximation of the sign/unsigned bounds.
7083          */
7084         switch (opcode) {
7085         case BPF_ADD:
7086                 scalar32_min_max_add(dst_reg, &src_reg);
7087                 scalar_min_max_add(dst_reg, &src_reg);
7088                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7089                 break;
7090         case BPF_SUB:
7091                 scalar32_min_max_sub(dst_reg, &src_reg);
7092                 scalar_min_max_sub(dst_reg, &src_reg);
7093                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7094                 break;
7095         case BPF_MUL:
7096                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7097                 scalar32_min_max_mul(dst_reg, &src_reg);
7098                 scalar_min_max_mul(dst_reg, &src_reg);
7099                 break;
7100         case BPF_AND:
7101                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7102                 scalar32_min_max_and(dst_reg, &src_reg);
7103                 scalar_min_max_and(dst_reg, &src_reg);
7104                 break;
7105         case BPF_OR:
7106                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7107                 scalar32_min_max_or(dst_reg, &src_reg);
7108                 scalar_min_max_or(dst_reg, &src_reg);
7109                 break;
7110         case BPF_XOR:
7111                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7112                 scalar32_min_max_xor(dst_reg, &src_reg);
7113                 scalar_min_max_xor(dst_reg, &src_reg);
7114                 break;
7115         case BPF_LSH:
7116                 if (umax_val >= insn_bitness) {
7117                         /* Shifts greater than 31 or 63 are undefined.
7118                          * This includes shifts by a negative number.
7119                          */
7120                         mark_reg_unknown(env, regs, insn->dst_reg);
7121                         break;
7122                 }
7123                 if (alu32)
7124                         scalar32_min_max_lsh(dst_reg, &src_reg);
7125                 else
7126                         scalar_min_max_lsh(dst_reg, &src_reg);
7127                 break;
7128         case BPF_RSH:
7129                 if (umax_val >= insn_bitness) {
7130                         /* Shifts greater than 31 or 63 are undefined.
7131                          * This includes shifts by a negative number.
7132                          */
7133                         mark_reg_unknown(env, regs, insn->dst_reg);
7134                         break;
7135                 }
7136                 if (alu32)
7137                         scalar32_min_max_rsh(dst_reg, &src_reg);
7138                 else
7139                         scalar_min_max_rsh(dst_reg, &src_reg);
7140                 break;
7141         case BPF_ARSH:
7142                 if (umax_val >= insn_bitness) {
7143                         /* Shifts greater than 31 or 63 are undefined.
7144                          * This includes shifts by a negative number.
7145                          */
7146                         mark_reg_unknown(env, regs, insn->dst_reg);
7147                         break;
7148                 }
7149                 if (alu32)
7150                         scalar32_min_max_arsh(dst_reg, &src_reg);
7151                 else
7152                         scalar_min_max_arsh(dst_reg, &src_reg);
7153                 break;
7154         default:
7155                 mark_reg_unknown(env, regs, insn->dst_reg);
7156                 break;
7157         }
7158
7159         /* ALU32 ops are zero extended into 64bit register */
7160         if (alu32)
7161                 zext_32_to_64(dst_reg);
7162         reg_bounds_sync(dst_reg);
7163         return 0;
7164 }
7165
7166 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7167  * and var_off.
7168  */
7169 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7170                                    struct bpf_insn *insn)
7171 {
7172         struct bpf_verifier_state *vstate = env->cur_state;
7173         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7174         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7175         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7176         u8 opcode = BPF_OP(insn->code);
7177         int err;
7178
7179         dst_reg = &regs[insn->dst_reg];
7180         src_reg = NULL;
7181         if (dst_reg->type != SCALAR_VALUE)
7182                 ptr_reg = dst_reg;
7183         else
7184                 /* Make sure ID is cleared otherwise dst_reg min/max could be
7185                  * incorrectly propagated into other registers by find_equal_scalars()
7186                  */
7187                 dst_reg->id = 0;
7188         if (BPF_SRC(insn->code) == BPF_X) {
7189                 src_reg = &regs[insn->src_reg];
7190                 if (src_reg->type != SCALAR_VALUE) {
7191                         if (dst_reg->type != SCALAR_VALUE) {
7192                                 /* Combining two pointers by any ALU op yields
7193                                  * an arbitrary scalar. Disallow all math except
7194                                  * pointer subtraction
7195                                  */
7196                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7197                                         mark_reg_unknown(env, regs, insn->dst_reg);
7198                                         return 0;
7199                                 }
7200                                 verbose(env, "R%d pointer %s pointer prohibited\n",
7201                                         insn->dst_reg,
7202                                         bpf_alu_string[opcode >> 4]);
7203                                 return -EACCES;
7204                         } else {
7205                                 /* scalar += pointer
7206                                  * This is legal, but we have to reverse our
7207                                  * src/dest handling in computing the range
7208                                  */
7209                                 err = mark_chain_precision(env, insn->dst_reg);
7210                                 if (err)
7211                                         return err;
7212                                 return adjust_ptr_min_max_vals(env, insn,
7213                                                                src_reg, dst_reg);
7214                         }
7215                 } else if (ptr_reg) {
7216                         /* pointer += scalar */
7217                         err = mark_chain_precision(env, insn->src_reg);
7218                         if (err)
7219                                 return err;
7220                         return adjust_ptr_min_max_vals(env, insn,
7221                                                        dst_reg, src_reg);
7222                 } else if (dst_reg->precise) {
7223                         /* if dst_reg is precise, src_reg should be precise as well */
7224                         err = mark_chain_precision(env, insn->src_reg);
7225                         if (err)
7226                                 return err;
7227                 }
7228         } else {
7229                 /* Pretend the src is a reg with a known value, since we only
7230                  * need to be able to read from this state.
7231                  */
7232                 off_reg.type = SCALAR_VALUE;
7233                 __mark_reg_known(&off_reg, insn->imm);
7234                 src_reg = &off_reg;
7235                 if (ptr_reg) /* pointer += K */
7236                         return adjust_ptr_min_max_vals(env, insn,
7237                                                        ptr_reg, src_reg);
7238         }
7239
7240         /* Got here implies adding two SCALAR_VALUEs */
7241         if (WARN_ON_ONCE(ptr_reg)) {
7242                 print_verifier_state(env, state);
7243                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7244                 return -EINVAL;
7245         }
7246         if (WARN_ON(!src_reg)) {
7247                 print_verifier_state(env, state);
7248                 verbose(env, "verifier internal error: no src_reg\n");
7249                 return -EINVAL;
7250         }
7251         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7252 }
7253
7254 /* check validity of 32-bit and 64-bit arithmetic operations */
7255 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7256 {
7257         struct bpf_reg_state *regs = cur_regs(env);
7258         u8 opcode = BPF_OP(insn->code);
7259         int err;
7260
7261         if (opcode == BPF_END || opcode == BPF_NEG) {
7262                 if (opcode == BPF_NEG) {
7263                         if (BPF_SRC(insn->code) != 0 ||
7264                             insn->src_reg != BPF_REG_0 ||
7265                             insn->off != 0 || insn->imm != 0) {
7266                                 verbose(env, "BPF_NEG uses reserved fields\n");
7267                                 return -EINVAL;
7268                         }
7269                 } else {
7270                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7271                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7272                             BPF_CLASS(insn->code) == BPF_ALU64) {
7273                                 verbose(env, "BPF_END uses reserved fields\n");
7274                                 return -EINVAL;
7275                         }
7276                 }
7277
7278                 /* check src operand */
7279                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7280                 if (err)
7281                         return err;
7282
7283                 if (is_pointer_value(env, insn->dst_reg)) {
7284                         verbose(env, "R%d pointer arithmetic prohibited\n",
7285                                 insn->dst_reg);
7286                         return -EACCES;
7287                 }
7288
7289                 /* check dest operand */
7290                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7291                 if (err)
7292                         return err;
7293
7294         } else if (opcode == BPF_MOV) {
7295
7296                 if (BPF_SRC(insn->code) == BPF_X) {
7297                         if (insn->imm != 0 || insn->off != 0) {
7298                                 verbose(env, "BPF_MOV uses reserved fields\n");
7299                                 return -EINVAL;
7300                         }
7301
7302                         /* check src operand */
7303                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
7304                         if (err)
7305                                 return err;
7306                 } else {
7307                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7308                                 verbose(env, "BPF_MOV uses reserved fields\n");
7309                                 return -EINVAL;
7310                         }
7311                 }
7312
7313                 /* check dest operand, mark as required later */
7314                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7315                 if (err)
7316                         return err;
7317
7318                 if (BPF_SRC(insn->code) == BPF_X) {
7319                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
7320                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7321
7322                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
7323                                 /* case: R1 = R2
7324                                  * copy register state to dest reg
7325                                  */
7326                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7327                                         /* Assign src and dst registers the same ID
7328                                          * that will be used by find_equal_scalars()
7329                                          * to propagate min/max range.
7330                                          */
7331                                         src_reg->id = ++env->id_gen;
7332                                 copy_register_state(dst_reg, src_reg);
7333                                 dst_reg->live |= REG_LIVE_WRITTEN;
7334                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
7335                         } else {
7336                                 /* R1 = (u32) R2 */
7337                                 if (is_pointer_value(env, insn->src_reg)) {
7338                                         verbose(env,
7339                                                 "R%d partial copy of pointer\n",
7340                                                 insn->src_reg);
7341                                         return -EACCES;
7342                                 } else if (src_reg->type == SCALAR_VALUE) {
7343                                         copy_register_state(dst_reg, src_reg);
7344                                         /* Make sure ID is cleared otherwise
7345                                          * dst_reg min/max could be incorrectly
7346                                          * propagated into src_reg by find_equal_scalars()
7347                                          */
7348                                         dst_reg->id = 0;
7349                                         dst_reg->live |= REG_LIVE_WRITTEN;
7350                                         dst_reg->subreg_def = env->insn_idx + 1;
7351                                 } else {
7352                                         mark_reg_unknown(env, regs,
7353                                                          insn->dst_reg);
7354                                 }
7355                                 zext_32_to_64(dst_reg);
7356                                 reg_bounds_sync(dst_reg);
7357                         }
7358                 } else {
7359                         /* case: R = imm
7360                          * remember the value we stored into this reg
7361                          */
7362                         /* clear any state __mark_reg_known doesn't set */
7363                         mark_reg_unknown(env, regs, insn->dst_reg);
7364                         regs[insn->dst_reg].type = SCALAR_VALUE;
7365                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
7366                                 __mark_reg_known(regs + insn->dst_reg,
7367                                                  insn->imm);
7368                         } else {
7369                                 __mark_reg_known(regs + insn->dst_reg,
7370                                                  (u32)insn->imm);
7371                         }
7372                 }
7373
7374         } else if (opcode > BPF_END) {
7375                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7376                 return -EINVAL;
7377
7378         } else {        /* all other ALU ops: and, sub, xor, add, ... */
7379
7380                 if (BPF_SRC(insn->code) == BPF_X) {
7381                         if (insn->imm != 0 || insn->off != 0) {
7382                                 verbose(env, "BPF_ALU uses reserved fields\n");
7383                                 return -EINVAL;
7384                         }
7385                         /* check src1 operand */
7386                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
7387                         if (err)
7388                                 return err;
7389                 } else {
7390                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7391                                 verbose(env, "BPF_ALU uses reserved fields\n");
7392                                 return -EINVAL;
7393                         }
7394                 }
7395
7396                 /* check src2 operand */
7397                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7398                 if (err)
7399                         return err;
7400
7401                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7402                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7403                         verbose(env, "div by zero\n");
7404                         return -EINVAL;
7405                 }
7406
7407                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7408                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7409                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7410
7411                         if (insn->imm < 0 || insn->imm >= size) {
7412                                 verbose(env, "invalid shift %d\n", insn->imm);
7413                                 return -EINVAL;
7414                         }
7415                 }
7416
7417                 /* check dest operand */
7418                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7419                 if (err)
7420                         return err;
7421
7422                 return adjust_reg_min_max_vals(env, insn);
7423         }
7424
7425         return 0;
7426 }
7427
7428 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7429                                    struct bpf_reg_state *dst_reg,
7430                                    enum bpf_reg_type type,
7431                                    bool range_right_open)
7432 {
7433         struct bpf_func_state *state;
7434         struct bpf_reg_state *reg;
7435         int new_range;
7436
7437         if (dst_reg->off < 0 ||
7438             (dst_reg->off == 0 && range_right_open))
7439                 /* This doesn't give us any range */
7440                 return;
7441
7442         if (dst_reg->umax_value > MAX_PACKET_OFF ||
7443             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7444                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
7445                  * than pkt_end, but that's because it's also less than pkt.
7446                  */
7447                 return;
7448
7449         new_range = dst_reg->off;
7450         if (range_right_open)
7451                 new_range++;
7452
7453         /* Examples for register markings:
7454          *
7455          * pkt_data in dst register:
7456          *
7457          *   r2 = r3;
7458          *   r2 += 8;
7459          *   if (r2 > pkt_end) goto <handle exception>
7460          *   <access okay>
7461          *
7462          *   r2 = r3;
7463          *   r2 += 8;
7464          *   if (r2 < pkt_end) goto <access okay>
7465          *   <handle exception>
7466          *
7467          *   Where:
7468          *     r2 == dst_reg, pkt_end == src_reg
7469          *     r2=pkt(id=n,off=8,r=0)
7470          *     r3=pkt(id=n,off=0,r=0)
7471          *
7472          * pkt_data in src register:
7473          *
7474          *   r2 = r3;
7475          *   r2 += 8;
7476          *   if (pkt_end >= r2) goto <access okay>
7477          *   <handle exception>
7478          *
7479          *   r2 = r3;
7480          *   r2 += 8;
7481          *   if (pkt_end <= r2) goto <handle exception>
7482          *   <access okay>
7483          *
7484          *   Where:
7485          *     pkt_end == dst_reg, r2 == src_reg
7486          *     r2=pkt(id=n,off=8,r=0)
7487          *     r3=pkt(id=n,off=0,r=0)
7488          *
7489          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7490          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7491          * and [r3, r3 + 8-1) respectively is safe to access depending on
7492          * the check.
7493          */
7494
7495         /* If our ids match, then we must have the same max_value.  And we
7496          * don't care about the other reg's fixed offset, since if it's too big
7497          * the range won't allow anything.
7498          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7499          */
7500         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
7501                 if (reg->type == type && reg->id == dst_reg->id)
7502                         /* keep the maximum range already checked */
7503                         reg->range = max(reg->range, new_range);
7504         }));
7505 }
7506
7507 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7508 {
7509         struct tnum subreg = tnum_subreg(reg->var_off);
7510         s32 sval = (s32)val;
7511
7512         switch (opcode) {
7513         case BPF_JEQ:
7514                 if (tnum_is_const(subreg))
7515                         return !!tnum_equals_const(subreg, val);
7516                 break;
7517         case BPF_JNE:
7518                 if (tnum_is_const(subreg))
7519                         return !tnum_equals_const(subreg, val);
7520                 break;
7521         case BPF_JSET:
7522                 if ((~subreg.mask & subreg.value) & val)
7523                         return 1;
7524                 if (!((subreg.mask | subreg.value) & val))
7525                         return 0;
7526                 break;
7527         case BPF_JGT:
7528                 if (reg->u32_min_value > val)
7529                         return 1;
7530                 else if (reg->u32_max_value <= val)
7531                         return 0;
7532                 break;
7533         case BPF_JSGT:
7534                 if (reg->s32_min_value > sval)
7535                         return 1;
7536                 else if (reg->s32_max_value <= sval)
7537                         return 0;
7538                 break;
7539         case BPF_JLT:
7540                 if (reg->u32_max_value < val)
7541                         return 1;
7542                 else if (reg->u32_min_value >= val)
7543                         return 0;
7544                 break;
7545         case BPF_JSLT:
7546                 if (reg->s32_max_value < sval)
7547                         return 1;
7548                 else if (reg->s32_min_value >= sval)
7549                         return 0;
7550                 break;
7551         case BPF_JGE:
7552                 if (reg->u32_min_value >= val)
7553                         return 1;
7554                 else if (reg->u32_max_value < val)
7555                         return 0;
7556                 break;
7557         case BPF_JSGE:
7558                 if (reg->s32_min_value >= sval)
7559                         return 1;
7560                 else if (reg->s32_max_value < sval)
7561                         return 0;
7562                 break;
7563         case BPF_JLE:
7564                 if (reg->u32_max_value <= val)
7565                         return 1;
7566                 else if (reg->u32_min_value > val)
7567                         return 0;
7568                 break;
7569         case BPF_JSLE:
7570                 if (reg->s32_max_value <= sval)
7571                         return 1;
7572                 else if (reg->s32_min_value > sval)
7573                         return 0;
7574                 break;
7575         }
7576
7577         return -1;
7578 }
7579
7580
7581 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7582 {
7583         s64 sval = (s64)val;
7584
7585         switch (opcode) {
7586         case BPF_JEQ:
7587                 if (tnum_is_const(reg->var_off))
7588                         return !!tnum_equals_const(reg->var_off, val);
7589                 break;
7590         case BPF_JNE:
7591                 if (tnum_is_const(reg->var_off))
7592                         return !tnum_equals_const(reg->var_off, val);
7593                 break;
7594         case BPF_JSET:
7595                 if ((~reg->var_off.mask & reg->var_off.value) & val)
7596                         return 1;
7597                 if (!((reg->var_off.mask | reg->var_off.value) & val))
7598                         return 0;
7599                 break;
7600         case BPF_JGT:
7601                 if (reg->umin_value > val)
7602                         return 1;
7603                 else if (reg->umax_value <= val)
7604                         return 0;
7605                 break;
7606         case BPF_JSGT:
7607                 if (reg->smin_value > sval)
7608                         return 1;
7609                 else if (reg->smax_value <= sval)
7610                         return 0;
7611                 break;
7612         case BPF_JLT:
7613                 if (reg->umax_value < val)
7614                         return 1;
7615                 else if (reg->umin_value >= val)
7616                         return 0;
7617                 break;
7618         case BPF_JSLT:
7619                 if (reg->smax_value < sval)
7620                         return 1;
7621                 else if (reg->smin_value >= sval)
7622                         return 0;
7623                 break;
7624         case BPF_JGE:
7625                 if (reg->umin_value >= val)
7626                         return 1;
7627                 else if (reg->umax_value < val)
7628                         return 0;
7629                 break;
7630         case BPF_JSGE:
7631                 if (reg->smin_value >= sval)
7632                         return 1;
7633                 else if (reg->smax_value < sval)
7634                         return 0;
7635                 break;
7636         case BPF_JLE:
7637                 if (reg->umax_value <= val)
7638                         return 1;
7639                 else if (reg->umin_value > val)
7640                         return 0;
7641                 break;
7642         case BPF_JSLE:
7643                 if (reg->smax_value <= sval)
7644                         return 1;
7645                 else if (reg->smin_value > sval)
7646                         return 0;
7647                 break;
7648         }
7649
7650         return -1;
7651 }
7652
7653 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7654  * and return:
7655  *  1 - branch will be taken and "goto target" will be executed
7656  *  0 - branch will not be taken and fall-through to next insn
7657  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7658  *      range [0,10]
7659  */
7660 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7661                            bool is_jmp32)
7662 {
7663         if (__is_pointer_value(false, reg)) {
7664                 if (!reg_type_not_null(reg->type))
7665                         return -1;
7666
7667                 /* If pointer is valid tests against zero will fail so we can
7668                  * use this to direct branch taken.
7669                  */
7670                 if (val != 0)
7671                         return -1;
7672
7673                 switch (opcode) {
7674                 case BPF_JEQ:
7675                         return 0;
7676                 case BPF_JNE:
7677                         return 1;
7678                 default:
7679                         return -1;
7680                 }
7681         }
7682
7683         if (is_jmp32)
7684                 return is_branch32_taken(reg, val, opcode);
7685         return is_branch64_taken(reg, val, opcode);
7686 }
7687
7688 static int flip_opcode(u32 opcode)
7689 {
7690         /* How can we transform "a <op> b" into "b <op> a"? */
7691         static const u8 opcode_flip[16] = {
7692                 /* these stay the same */
7693                 [BPF_JEQ  >> 4] = BPF_JEQ,
7694                 [BPF_JNE  >> 4] = BPF_JNE,
7695                 [BPF_JSET >> 4] = BPF_JSET,
7696                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7697                 [BPF_JGE  >> 4] = BPF_JLE,
7698                 [BPF_JGT  >> 4] = BPF_JLT,
7699                 [BPF_JLE  >> 4] = BPF_JGE,
7700                 [BPF_JLT  >> 4] = BPF_JGT,
7701                 [BPF_JSGE >> 4] = BPF_JSLE,
7702                 [BPF_JSGT >> 4] = BPF_JSLT,
7703                 [BPF_JSLE >> 4] = BPF_JSGE,
7704                 [BPF_JSLT >> 4] = BPF_JSGT
7705         };
7706         return opcode_flip[opcode >> 4];
7707 }
7708
7709 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7710                                    struct bpf_reg_state *src_reg,
7711                                    u8 opcode)
7712 {
7713         struct bpf_reg_state *pkt;
7714
7715         if (src_reg->type == PTR_TO_PACKET_END) {
7716                 pkt = dst_reg;
7717         } else if (dst_reg->type == PTR_TO_PACKET_END) {
7718                 pkt = src_reg;
7719                 opcode = flip_opcode(opcode);
7720         } else {
7721                 return -1;
7722         }
7723
7724         if (pkt->range >= 0)
7725                 return -1;
7726
7727         switch (opcode) {
7728         case BPF_JLE:
7729                 /* pkt <= pkt_end */
7730                 fallthrough;
7731         case BPF_JGT:
7732                 /* pkt > pkt_end */
7733                 if (pkt->range == BEYOND_PKT_END)
7734                         /* pkt has at last one extra byte beyond pkt_end */
7735                         return opcode == BPF_JGT;
7736                 break;
7737         case BPF_JLT:
7738                 /* pkt < pkt_end */
7739                 fallthrough;
7740         case BPF_JGE:
7741                 /* pkt >= pkt_end */
7742                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7743                         return opcode == BPF_JGE;
7744                 break;
7745         }
7746         return -1;
7747 }
7748
7749 /* Adjusts the register min/max values in the case that the dst_reg is the
7750  * variable register that we are working on, and src_reg is a constant or we're
7751  * simply doing a BPF_K check.
7752  * In JEQ/JNE cases we also adjust the var_off values.
7753  */
7754 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7755                             struct bpf_reg_state *false_reg,
7756                             u64 val, u32 val32,
7757                             u8 opcode, bool is_jmp32)
7758 {
7759         struct tnum false_32off = tnum_subreg(false_reg->var_off);
7760         struct tnum false_64off = false_reg->var_off;
7761         struct tnum true_32off = tnum_subreg(true_reg->var_off);
7762         struct tnum true_64off = true_reg->var_off;
7763         s64 sval = (s64)val;
7764         s32 sval32 = (s32)val32;
7765
7766         /* If the dst_reg is a pointer, we can't learn anything about its
7767          * variable offset from the compare (unless src_reg were a pointer into
7768          * the same object, but we don't bother with that.
7769          * Since false_reg and true_reg have the same type by construction, we
7770          * only need to check one of them for pointerness.
7771          */
7772         if (__is_pointer_value(false, false_reg))
7773                 return;
7774
7775         switch (opcode) {
7776         /* JEQ/JNE comparison doesn't change the register equivalence.
7777          *
7778          * r1 = r2;
7779          * if (r1 == 42) goto label;
7780          * ...
7781          * label: // here both r1 and r2 are known to be 42.
7782          *
7783          * Hence when marking register as known preserve it's ID.
7784          */
7785         case BPF_JEQ:
7786                 if (is_jmp32) {
7787                         __mark_reg32_known(true_reg, val32);
7788                         true_32off = tnum_subreg(true_reg->var_off);
7789                 } else {
7790                         ___mark_reg_known(true_reg, val);
7791                         true_64off = true_reg->var_off;
7792                 }
7793                 break;
7794         case BPF_JNE:
7795                 if (is_jmp32) {
7796                         __mark_reg32_known(false_reg, val32);
7797                         false_32off = tnum_subreg(false_reg->var_off);
7798                 } else {
7799                         ___mark_reg_known(false_reg, val);
7800                         false_64off = false_reg->var_off;
7801                 }
7802                 break;
7803         case BPF_JSET:
7804                 if (is_jmp32) {
7805                         false_32off = tnum_and(false_32off, tnum_const(~val32));
7806                         if (is_power_of_2(val32))
7807                                 true_32off = tnum_or(true_32off,
7808                                                      tnum_const(val32));
7809                 } else {
7810                         false_64off = tnum_and(false_64off, tnum_const(~val));
7811                         if (is_power_of_2(val))
7812                                 true_64off = tnum_or(true_64off,
7813                                                      tnum_const(val));
7814                 }
7815                 break;
7816         case BPF_JGE:
7817         case BPF_JGT:
7818         {
7819                 if (is_jmp32) {
7820                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
7821                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7822
7823                         false_reg->u32_max_value = min(false_reg->u32_max_value,
7824                                                        false_umax);
7825                         true_reg->u32_min_value = max(true_reg->u32_min_value,
7826                                                       true_umin);
7827                 } else {
7828                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
7829                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7830
7831                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
7832                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
7833                 }
7834                 break;
7835         }
7836         case BPF_JSGE:
7837         case BPF_JSGT:
7838         {
7839                 if (is_jmp32) {
7840                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
7841                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7842
7843                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7844                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7845                 } else {
7846                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
7847                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7848
7849                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
7850                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
7851                 }
7852                 break;
7853         }
7854         case BPF_JLE:
7855         case BPF_JLT:
7856         {
7857                 if (is_jmp32) {
7858                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
7859                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7860
7861                         false_reg->u32_min_value = max(false_reg->u32_min_value,
7862                                                        false_umin);
7863                         true_reg->u32_max_value = min(true_reg->u32_max_value,
7864                                                       true_umax);
7865                 } else {
7866                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
7867                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7868
7869                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
7870                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
7871                 }
7872                 break;
7873         }
7874         case BPF_JSLE:
7875         case BPF_JSLT:
7876         {
7877                 if (is_jmp32) {
7878                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
7879                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7880
7881                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7882                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7883                 } else {
7884                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
7885                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7886
7887                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
7888                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
7889                 }
7890                 break;
7891         }
7892         default:
7893                 return;
7894         }
7895
7896         if (is_jmp32) {
7897                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7898                                              tnum_subreg(false_32off));
7899                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7900                                             tnum_subreg(true_32off));
7901                 __reg_combine_32_into_64(false_reg);
7902                 __reg_combine_32_into_64(true_reg);
7903         } else {
7904                 false_reg->var_off = false_64off;
7905                 true_reg->var_off = true_64off;
7906                 __reg_combine_64_into_32(false_reg);
7907                 __reg_combine_64_into_32(true_reg);
7908         }
7909 }
7910
7911 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7912  * the variable reg.
7913  */
7914 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7915                                 struct bpf_reg_state *false_reg,
7916                                 u64 val, u32 val32,
7917                                 u8 opcode, bool is_jmp32)
7918 {
7919         opcode = flip_opcode(opcode);
7920         /* This uses zero as "not present in table"; luckily the zero opcode,
7921          * BPF_JA, can't get here.
7922          */
7923         if (opcode)
7924                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7925 }
7926
7927 /* Regs are known to be equal, so intersect their min/max/var_off */
7928 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7929                                   struct bpf_reg_state *dst_reg)
7930 {
7931         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7932                                                         dst_reg->umin_value);
7933         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7934                                                         dst_reg->umax_value);
7935         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7936                                                         dst_reg->smin_value);
7937         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7938                                                         dst_reg->smax_value);
7939         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7940                                                              dst_reg->var_off);
7941         reg_bounds_sync(src_reg);
7942         reg_bounds_sync(dst_reg);
7943 }
7944
7945 static void reg_combine_min_max(struct bpf_reg_state *true_src,
7946                                 struct bpf_reg_state *true_dst,
7947                                 struct bpf_reg_state *false_src,
7948                                 struct bpf_reg_state *false_dst,
7949                                 u8 opcode)
7950 {
7951         switch (opcode) {
7952         case BPF_JEQ:
7953                 __reg_combine_min_max(true_src, true_dst);
7954                 break;
7955         case BPF_JNE:
7956                 __reg_combine_min_max(false_src, false_dst);
7957                 break;
7958         }
7959 }
7960
7961 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7962                                  struct bpf_reg_state *reg, u32 id,
7963                                  bool is_null)
7964 {
7965         if (reg_type_may_be_null(reg->type) && reg->id == id &&
7966             !WARN_ON_ONCE(!reg->id)) {
7967                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7968                                  !tnum_equals_const(reg->var_off, 0) ||
7969                                  reg->off)) {
7970                         /* Old offset (both fixed and variable parts) should
7971                          * have been known-zero, because we don't allow pointer
7972                          * arithmetic on pointers that might be NULL. If we
7973                          * see this happening, don't convert the register.
7974                          */
7975                         return;
7976                 }
7977                 if (is_null) {
7978                         reg->type = SCALAR_VALUE;
7979                 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
7980                         const struct bpf_map *map = reg->map_ptr;
7981
7982                         if (map->inner_map_meta) {
7983                                 reg->type = CONST_PTR_TO_MAP;
7984                                 reg->map_ptr = map->inner_map_meta;
7985                         } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
7986                                 reg->type = PTR_TO_XDP_SOCK;
7987                         } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7988                                    map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7989                                 reg->type = PTR_TO_SOCKET;
7990                         } else {
7991                                 reg->type = PTR_TO_MAP_VALUE;
7992                         }
7993                 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7994                         reg->type = PTR_TO_SOCKET;
7995                 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7996                         reg->type = PTR_TO_SOCK_COMMON;
7997                 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7998                         reg->type = PTR_TO_TCP_SOCK;
7999                 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
8000                         reg->type = PTR_TO_BTF_ID;
8001                 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
8002                         reg->type = PTR_TO_MEM;
8003                 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
8004                         reg->type = PTR_TO_RDONLY_BUF;
8005                 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
8006                         reg->type = PTR_TO_RDWR_BUF;
8007                 }
8008                 if (is_null) {
8009                         /* We don't need id and ref_obj_id from this point
8010                          * onwards anymore, thus we should better reset it,
8011                          * so that state pruning has chances to take effect.
8012                          */
8013                         reg->id = 0;
8014                         reg->ref_obj_id = 0;
8015                 } else if (!reg_may_point_to_spin_lock(reg)) {
8016                         /* For not-NULL ptr, reg->ref_obj_id will be reset
8017                          * in release_reference().
8018                          *
8019                          * reg->id is still used by spin_lock ptr. Other
8020                          * than spin_lock ptr type, reg->id can be reset.
8021                          */
8022                         reg->id = 0;
8023                 }
8024         }
8025 }
8026
8027 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8028  * be folded together at some point.
8029  */
8030 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8031                                   bool is_null)
8032 {
8033         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8034         struct bpf_reg_state *regs = state->regs, *reg;
8035         u32 ref_obj_id = regs[regno].ref_obj_id;
8036         u32 id = regs[regno].id;
8037
8038         if (ref_obj_id && ref_obj_id == id && is_null)
8039                 /* regs[regno] is in the " == NULL" branch.
8040                  * No one could have freed the reference state before
8041                  * doing the NULL check.
8042                  */
8043                 WARN_ON_ONCE(release_reference_state(state, id));
8044
8045         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8046                 mark_ptr_or_null_reg(state, reg, id, is_null);
8047         }));
8048 }
8049
8050 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8051                                    struct bpf_reg_state *dst_reg,
8052                                    struct bpf_reg_state *src_reg,
8053                                    struct bpf_verifier_state *this_branch,
8054                                    struct bpf_verifier_state *other_branch)
8055 {
8056         if (BPF_SRC(insn->code) != BPF_X)
8057                 return false;
8058
8059         /* Pointers are always 64-bit. */
8060         if (BPF_CLASS(insn->code) == BPF_JMP32)
8061                 return false;
8062
8063         switch (BPF_OP(insn->code)) {
8064         case BPF_JGT:
8065                 if ((dst_reg->type == PTR_TO_PACKET &&
8066                      src_reg->type == PTR_TO_PACKET_END) ||
8067                     (dst_reg->type == PTR_TO_PACKET_META &&
8068                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8069                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8070                         find_good_pkt_pointers(this_branch, dst_reg,
8071                                                dst_reg->type, false);
8072                         mark_pkt_end(other_branch, insn->dst_reg, true);
8073                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8074                             src_reg->type == PTR_TO_PACKET) ||
8075                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8076                             src_reg->type == PTR_TO_PACKET_META)) {
8077                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8078                         find_good_pkt_pointers(other_branch, src_reg,
8079                                                src_reg->type, true);
8080                         mark_pkt_end(this_branch, insn->src_reg, false);
8081                 } else {
8082                         return false;
8083                 }
8084                 break;
8085         case BPF_JLT:
8086                 if ((dst_reg->type == PTR_TO_PACKET &&
8087                      src_reg->type == PTR_TO_PACKET_END) ||
8088                     (dst_reg->type == PTR_TO_PACKET_META &&
8089                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8090                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8091                         find_good_pkt_pointers(other_branch, dst_reg,
8092                                                dst_reg->type, true);
8093                         mark_pkt_end(this_branch, insn->dst_reg, false);
8094                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8095                             src_reg->type == PTR_TO_PACKET) ||
8096                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8097                             src_reg->type == PTR_TO_PACKET_META)) {
8098                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8099                         find_good_pkt_pointers(this_branch, src_reg,
8100                                                src_reg->type, false);
8101                         mark_pkt_end(other_branch, insn->src_reg, true);
8102                 } else {
8103                         return false;
8104                 }
8105                 break;
8106         case BPF_JGE:
8107                 if ((dst_reg->type == PTR_TO_PACKET &&
8108                      src_reg->type == PTR_TO_PACKET_END) ||
8109                     (dst_reg->type == PTR_TO_PACKET_META &&
8110                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8111                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8112                         find_good_pkt_pointers(this_branch, dst_reg,
8113                                                dst_reg->type, true);
8114                         mark_pkt_end(other_branch, insn->dst_reg, false);
8115                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8116                             src_reg->type == PTR_TO_PACKET) ||
8117                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8118                             src_reg->type == PTR_TO_PACKET_META)) {
8119                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8120                         find_good_pkt_pointers(other_branch, src_reg,
8121                                                src_reg->type, false);
8122                         mark_pkt_end(this_branch, insn->src_reg, true);
8123                 } else {
8124                         return false;
8125                 }
8126                 break;
8127         case BPF_JLE:
8128                 if ((dst_reg->type == PTR_TO_PACKET &&
8129                      src_reg->type == PTR_TO_PACKET_END) ||
8130                     (dst_reg->type == PTR_TO_PACKET_META &&
8131                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8132                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8133                         find_good_pkt_pointers(other_branch, dst_reg,
8134                                                dst_reg->type, false);
8135                         mark_pkt_end(this_branch, insn->dst_reg, true);
8136                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8137                             src_reg->type == PTR_TO_PACKET) ||
8138                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8139                             src_reg->type == PTR_TO_PACKET_META)) {
8140                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8141                         find_good_pkt_pointers(this_branch, src_reg,
8142                                                src_reg->type, true);
8143                         mark_pkt_end(other_branch, insn->src_reg, false);
8144                 } else {
8145                         return false;
8146                 }
8147                 break;
8148         default:
8149                 return false;
8150         }
8151
8152         return true;
8153 }
8154
8155 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8156                                struct bpf_reg_state *known_reg)
8157 {
8158         struct bpf_func_state *state;
8159         struct bpf_reg_state *reg;
8160
8161         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8162                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8163                         copy_register_state(reg, known_reg);
8164         }));
8165 }
8166
8167 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8168                              struct bpf_insn *insn, int *insn_idx)
8169 {
8170         struct bpf_verifier_state *this_branch = env->cur_state;
8171         struct bpf_verifier_state *other_branch;
8172         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8173         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8174         u8 opcode = BPF_OP(insn->code);
8175         bool is_jmp32;
8176         int pred = -1;
8177         int err;
8178
8179         /* Only conditional jumps are expected to reach here. */
8180         if (opcode == BPF_JA || opcode > BPF_JSLE) {
8181                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8182                 return -EINVAL;
8183         }
8184
8185         if (BPF_SRC(insn->code) == BPF_X) {
8186                 if (insn->imm != 0) {
8187                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8188                         return -EINVAL;
8189                 }
8190
8191                 /* check src1 operand */
8192                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8193                 if (err)
8194                         return err;
8195
8196                 if (is_pointer_value(env, insn->src_reg)) {
8197                         verbose(env, "R%d pointer comparison prohibited\n",
8198                                 insn->src_reg);
8199                         return -EACCES;
8200                 }
8201                 src_reg = &regs[insn->src_reg];
8202         } else {
8203                 if (insn->src_reg != BPF_REG_0) {
8204                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8205                         return -EINVAL;
8206                 }
8207         }
8208
8209         /* check src2 operand */
8210         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8211         if (err)
8212                 return err;
8213
8214         dst_reg = &regs[insn->dst_reg];
8215         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8216
8217         if (BPF_SRC(insn->code) == BPF_K) {
8218                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8219         } else if (src_reg->type == SCALAR_VALUE &&
8220                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8221                 pred = is_branch_taken(dst_reg,
8222                                        tnum_subreg(src_reg->var_off).value,
8223                                        opcode,
8224                                        is_jmp32);
8225         } else if (src_reg->type == SCALAR_VALUE &&
8226                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8227                 pred = is_branch_taken(dst_reg,
8228                                        src_reg->var_off.value,
8229                                        opcode,
8230                                        is_jmp32);
8231         } else if (reg_is_pkt_pointer_any(dst_reg) &&
8232                    reg_is_pkt_pointer_any(src_reg) &&
8233                    !is_jmp32) {
8234                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8235         }
8236
8237         if (pred >= 0) {
8238                 /* If we get here with a dst_reg pointer type it is because
8239                  * above is_branch_taken() special cased the 0 comparison.
8240                  */
8241                 if (!__is_pointer_value(false, dst_reg))
8242                         err = mark_chain_precision(env, insn->dst_reg);
8243                 if (BPF_SRC(insn->code) == BPF_X && !err &&
8244                     !__is_pointer_value(false, src_reg))
8245                         err = mark_chain_precision(env, insn->src_reg);
8246                 if (err)
8247                         return err;
8248         }
8249
8250         if (pred == 1) {
8251                 /* Only follow the goto, ignore fall-through. If needed, push
8252                  * the fall-through branch for simulation under speculative
8253                  * execution.
8254                  */
8255                 if (!env->bypass_spec_v1 &&
8256                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
8257                                                *insn_idx))
8258                         return -EFAULT;
8259                 *insn_idx += insn->off;
8260                 return 0;
8261         } else if (pred == 0) {
8262                 /* Only follow the fall-through branch, since that's where the
8263                  * program will go. If needed, push the goto branch for
8264                  * simulation under speculative execution.
8265                  */
8266                 if (!env->bypass_spec_v1 &&
8267                     !sanitize_speculative_path(env, insn,
8268                                                *insn_idx + insn->off + 1,
8269                                                *insn_idx))
8270                         return -EFAULT;
8271                 return 0;
8272         }
8273
8274         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8275                                   false);
8276         if (!other_branch)
8277                 return -EFAULT;
8278         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8279
8280         /* detect if we are comparing against a constant value so we can adjust
8281          * our min/max values for our dst register.
8282          * this is only legit if both are scalars (or pointers to the same
8283          * object, I suppose, but we don't support that right now), because
8284          * otherwise the different base pointers mean the offsets aren't
8285          * comparable.
8286          */
8287         if (BPF_SRC(insn->code) == BPF_X) {
8288                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8289
8290                 if (dst_reg->type == SCALAR_VALUE &&
8291                     src_reg->type == SCALAR_VALUE) {
8292                         if (tnum_is_const(src_reg->var_off) ||
8293                             (is_jmp32 &&
8294                              tnum_is_const(tnum_subreg(src_reg->var_off))))
8295                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8296                                                 dst_reg,
8297                                                 src_reg->var_off.value,
8298                                                 tnum_subreg(src_reg->var_off).value,
8299                                                 opcode, is_jmp32);
8300                         else if (tnum_is_const(dst_reg->var_off) ||
8301                                  (is_jmp32 &&
8302                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
8303                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8304                                                     src_reg,
8305                                                     dst_reg->var_off.value,
8306                                                     tnum_subreg(dst_reg->var_off).value,
8307                                                     opcode, is_jmp32);
8308                         else if (!is_jmp32 &&
8309                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
8310                                 /* Comparing for equality, we can combine knowledge */
8311                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8312                                                     &other_branch_regs[insn->dst_reg],
8313                                                     src_reg, dst_reg, opcode);
8314                         if (src_reg->id &&
8315                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8316                                 find_equal_scalars(this_branch, src_reg);
8317                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8318                         }
8319
8320                 }
8321         } else if (dst_reg->type == SCALAR_VALUE) {
8322                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8323                                         dst_reg, insn->imm, (u32)insn->imm,
8324                                         opcode, is_jmp32);
8325         }
8326
8327         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8328             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8329                 find_equal_scalars(this_branch, dst_reg);
8330                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8331         }
8332
8333         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8334          * NOTE: these optimizations below are related with pointer comparison
8335          *       which will never be JMP32.
8336          */
8337         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8338             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8339             reg_type_may_be_null(dst_reg->type)) {
8340                 /* Mark all identical registers in each branch as either
8341                  * safe or unknown depending R == 0 or R != 0 conditional.
8342                  */
8343                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8344                                       opcode == BPF_JNE);
8345                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8346                                       opcode == BPF_JEQ);
8347         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8348                                            this_branch, other_branch) &&
8349                    is_pointer_value(env, insn->dst_reg)) {
8350                 verbose(env, "R%d pointer comparison prohibited\n",
8351                         insn->dst_reg);
8352                 return -EACCES;
8353         }
8354         if (env->log.level & BPF_LOG_LEVEL)
8355                 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8356         return 0;
8357 }
8358
8359 /* verify BPF_LD_IMM64 instruction */
8360 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8361 {
8362         struct bpf_insn_aux_data *aux = cur_aux(env);
8363         struct bpf_reg_state *regs = cur_regs(env);
8364         struct bpf_reg_state *dst_reg;
8365         struct bpf_map *map;
8366         int err;
8367
8368         if (BPF_SIZE(insn->code) != BPF_DW) {
8369                 verbose(env, "invalid BPF_LD_IMM insn\n");
8370                 return -EINVAL;
8371         }
8372         if (insn->off != 0) {
8373                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8374                 return -EINVAL;
8375         }
8376
8377         err = check_reg_arg(env, insn->dst_reg, DST_OP);
8378         if (err)
8379                 return err;
8380
8381         dst_reg = &regs[insn->dst_reg];
8382         if (insn->src_reg == 0) {
8383                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8384
8385                 dst_reg->type = SCALAR_VALUE;
8386                 __mark_reg_known(&regs[insn->dst_reg], imm);
8387                 return 0;
8388         }
8389
8390         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8391                 mark_reg_known_zero(env, regs, insn->dst_reg);
8392
8393                 dst_reg->type = aux->btf_var.reg_type;
8394                 switch (dst_reg->type) {
8395                 case PTR_TO_MEM:
8396                         dst_reg->mem_size = aux->btf_var.mem_size;
8397                         break;
8398                 case PTR_TO_BTF_ID:
8399                 case PTR_TO_PERCPU_BTF_ID:
8400                         dst_reg->btf_id = aux->btf_var.btf_id;
8401                         break;
8402                 default:
8403                         verbose(env, "bpf verifier is misconfigured\n");
8404                         return -EFAULT;
8405                 }
8406                 return 0;
8407         }
8408
8409         map = env->used_maps[aux->map_index];
8410         mark_reg_known_zero(env, regs, insn->dst_reg);
8411         dst_reg->map_ptr = map;
8412
8413         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8414                 dst_reg->type = PTR_TO_MAP_VALUE;
8415                 dst_reg->off = aux->map_off;
8416                 if (map_value_has_spin_lock(map))
8417                         dst_reg->id = ++env->id_gen;
8418         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8419                 dst_reg->type = CONST_PTR_TO_MAP;
8420         } else {
8421                 verbose(env, "bpf verifier is misconfigured\n");
8422                 return -EINVAL;
8423         }
8424
8425         return 0;
8426 }
8427
8428 static bool may_access_skb(enum bpf_prog_type type)
8429 {
8430         switch (type) {
8431         case BPF_PROG_TYPE_SOCKET_FILTER:
8432         case BPF_PROG_TYPE_SCHED_CLS:
8433         case BPF_PROG_TYPE_SCHED_ACT:
8434                 return true;
8435         default:
8436                 return false;
8437         }
8438 }
8439
8440 /* verify safety of LD_ABS|LD_IND instructions:
8441  * - they can only appear in the programs where ctx == skb
8442  * - since they are wrappers of function calls, they scratch R1-R5 registers,
8443  *   preserve R6-R9, and store return value into R0
8444  *
8445  * Implicit input:
8446  *   ctx == skb == R6 == CTX
8447  *
8448  * Explicit input:
8449  *   SRC == any register
8450  *   IMM == 32-bit immediate
8451  *
8452  * Output:
8453  *   R0 - 8/16/32-bit skb data converted to cpu endianness
8454  */
8455 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8456 {
8457         struct bpf_reg_state *regs = cur_regs(env);
8458         static const int ctx_reg = BPF_REG_6;
8459         u8 mode = BPF_MODE(insn->code);
8460         int i, err;
8461
8462         if (!may_access_skb(resolve_prog_type(env->prog))) {
8463                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8464                 return -EINVAL;
8465         }
8466
8467         if (!env->ops->gen_ld_abs) {
8468                 verbose(env, "bpf verifier is misconfigured\n");
8469                 return -EINVAL;
8470         }
8471
8472         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8473             BPF_SIZE(insn->code) == BPF_DW ||
8474             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8475                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8476                 return -EINVAL;
8477         }
8478
8479         /* check whether implicit source operand (register R6) is readable */
8480         err = check_reg_arg(env, ctx_reg, SRC_OP);
8481         if (err)
8482                 return err;
8483
8484         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8485          * gen_ld_abs() may terminate the program at runtime, leading to
8486          * reference leak.
8487          */
8488         err = check_reference_leak(env);
8489         if (err) {
8490                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8491                 return err;
8492         }
8493
8494         if (env->cur_state->active_spin_lock) {
8495                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8496                 return -EINVAL;
8497         }
8498
8499         if (regs[ctx_reg].type != PTR_TO_CTX) {
8500                 verbose(env,
8501                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8502                 return -EINVAL;
8503         }
8504
8505         if (mode == BPF_IND) {
8506                 /* check explicit source operand */
8507                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8508                 if (err)
8509                         return err;
8510         }
8511
8512         err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8513         if (err < 0)
8514                 return err;
8515
8516         /* reset caller saved regs to unreadable */
8517         for (i = 0; i < CALLER_SAVED_REGS; i++) {
8518                 mark_reg_not_init(env, regs, caller_saved[i]);
8519                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8520         }
8521
8522         /* mark destination R0 register as readable, since it contains
8523          * the value fetched from the packet.
8524          * Already marked as written above.
8525          */
8526         mark_reg_unknown(env, regs, BPF_REG_0);
8527         /* ld_abs load up to 32-bit skb data. */
8528         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8529         return 0;
8530 }
8531
8532 static int check_return_code(struct bpf_verifier_env *env)
8533 {
8534         struct tnum enforce_attach_type_range = tnum_unknown;
8535         const struct bpf_prog *prog = env->prog;
8536         struct bpf_reg_state *reg;
8537         struct tnum range = tnum_range(0, 1);
8538         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8539         int err;
8540         const bool is_subprog = env->cur_state->frame[0]->subprogno;
8541
8542         /* LSM and struct_ops func-ptr's return type could be "void" */
8543         if (!is_subprog &&
8544             (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8545              prog_type == BPF_PROG_TYPE_LSM) &&
8546             !prog->aux->attach_func_proto->type)
8547                 return 0;
8548
8549         /* eBPF calling convetion is such that R0 is used
8550          * to return the value from eBPF program.
8551          * Make sure that it's readable at this time
8552          * of bpf_exit, which means that program wrote
8553          * something into it earlier
8554          */
8555         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8556         if (err)
8557                 return err;
8558
8559         if (is_pointer_value(env, BPF_REG_0)) {
8560                 verbose(env, "R0 leaks addr as return value\n");
8561                 return -EACCES;
8562         }
8563
8564         reg = cur_regs(env) + BPF_REG_0;
8565         if (is_subprog) {
8566                 if (reg->type != SCALAR_VALUE) {
8567                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8568                                 reg_type_str[reg->type]);
8569                         return -EINVAL;
8570                 }
8571                 return 0;
8572         }
8573
8574         switch (prog_type) {
8575         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8576                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8577                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8578                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8579                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8580                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8581                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8582                         range = tnum_range(1, 1);
8583                 break;
8584         case BPF_PROG_TYPE_CGROUP_SKB:
8585                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8586                         range = tnum_range(0, 3);
8587                         enforce_attach_type_range = tnum_range(2, 3);
8588                 }
8589                 break;
8590         case BPF_PROG_TYPE_CGROUP_SOCK:
8591         case BPF_PROG_TYPE_SOCK_OPS:
8592         case BPF_PROG_TYPE_CGROUP_DEVICE:
8593         case BPF_PROG_TYPE_CGROUP_SYSCTL:
8594         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8595                 break;
8596         case BPF_PROG_TYPE_RAW_TRACEPOINT:
8597                 if (!env->prog->aux->attach_btf_id)
8598                         return 0;
8599                 range = tnum_const(0);
8600                 break;
8601         case BPF_PROG_TYPE_TRACING:
8602                 switch (env->prog->expected_attach_type) {
8603                 case BPF_TRACE_FENTRY:
8604                 case BPF_TRACE_FEXIT:
8605                         range = tnum_const(0);
8606                         break;
8607                 case BPF_TRACE_RAW_TP:
8608                 case BPF_MODIFY_RETURN:
8609                         return 0;
8610                 case BPF_TRACE_ITER:
8611                         break;
8612                 default:
8613                         return -ENOTSUPP;
8614                 }
8615                 break;
8616         case BPF_PROG_TYPE_SK_LOOKUP:
8617                 range = tnum_range(SK_DROP, SK_PASS);
8618                 break;
8619         case BPF_PROG_TYPE_EXT:
8620                 /* freplace program can return anything as its return value
8621                  * depends on the to-be-replaced kernel func or bpf program.
8622                  */
8623         default:
8624                 return 0;
8625         }
8626
8627         if (reg->type != SCALAR_VALUE) {
8628                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8629                         reg_type_str[reg->type]);
8630                 return -EINVAL;
8631         }
8632
8633         if (!tnum_in(range, reg->var_off)) {
8634                 char tn_buf[48];
8635
8636                 verbose(env, "At program exit the register R0 ");
8637                 if (!tnum_is_unknown(reg->var_off)) {
8638                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8639                         verbose(env, "has value %s", tn_buf);
8640                 } else {
8641                         verbose(env, "has unknown scalar value");
8642                 }
8643                 tnum_strn(tn_buf, sizeof(tn_buf), range);
8644                 verbose(env, " should have been in %s\n", tn_buf);
8645                 return -EINVAL;
8646         }
8647
8648         if (!tnum_is_unknown(enforce_attach_type_range) &&
8649             tnum_in(enforce_attach_type_range, reg->var_off))
8650                 env->prog->enforce_expected_attach_type = 1;
8651         return 0;
8652 }
8653
8654 /* non-recursive DFS pseudo code
8655  * 1  procedure DFS-iterative(G,v):
8656  * 2      label v as discovered
8657  * 3      let S be a stack
8658  * 4      S.push(v)
8659  * 5      while S is not empty
8660  * 6            t <- S.pop()
8661  * 7            if t is what we're looking for:
8662  * 8                return t
8663  * 9            for all edges e in G.adjacentEdges(t) do
8664  * 10               if edge e is already labelled
8665  * 11                   continue with the next edge
8666  * 12               w <- G.adjacentVertex(t,e)
8667  * 13               if vertex w is not discovered and not explored
8668  * 14                   label e as tree-edge
8669  * 15                   label w as discovered
8670  * 16                   S.push(w)
8671  * 17                   continue at 5
8672  * 18               else if vertex w is discovered
8673  * 19                   label e as back-edge
8674  * 20               else
8675  * 21                   // vertex w is explored
8676  * 22                   label e as forward- or cross-edge
8677  * 23           label t as explored
8678  * 24           S.pop()
8679  *
8680  * convention:
8681  * 0x10 - discovered
8682  * 0x11 - discovered and fall-through edge labelled
8683  * 0x12 - discovered and fall-through and branch edges labelled
8684  * 0x20 - explored
8685  */
8686
8687 enum {
8688         DISCOVERED = 0x10,
8689         EXPLORED = 0x20,
8690         FALLTHROUGH = 1,
8691         BRANCH = 2,
8692 };
8693
8694 static u32 state_htab_size(struct bpf_verifier_env *env)
8695 {
8696         return env->prog->len;
8697 }
8698
8699 static struct bpf_verifier_state_list **explored_state(
8700                                         struct bpf_verifier_env *env,
8701                                         int idx)
8702 {
8703         struct bpf_verifier_state *cur = env->cur_state;
8704         struct bpf_func_state *state = cur->frame[cur->curframe];
8705
8706         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8707 }
8708
8709 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8710 {
8711         env->insn_aux_data[idx].prune_point = true;
8712 }
8713
8714 /* t, w, e - match pseudo-code above:
8715  * t - index of current instruction
8716  * w - next instruction
8717  * e - edge
8718  */
8719 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8720                      bool loop_ok)
8721 {
8722         int *insn_stack = env->cfg.insn_stack;
8723         int *insn_state = env->cfg.insn_state;
8724
8725         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8726                 return 0;
8727
8728         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8729                 return 0;
8730
8731         if (w < 0 || w >= env->prog->len) {
8732                 verbose_linfo(env, t, "%d: ", t);
8733                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
8734                 return -EINVAL;
8735         }
8736
8737         if (e == BRANCH)
8738                 /* mark branch target for state pruning */
8739                 init_explored_state(env, w);
8740
8741         if (insn_state[w] == 0) {
8742                 /* tree-edge */
8743                 insn_state[t] = DISCOVERED | e;
8744                 insn_state[w] = DISCOVERED;
8745                 if (env->cfg.cur_stack >= env->prog->len)
8746                         return -E2BIG;
8747                 insn_stack[env->cfg.cur_stack++] = w;
8748                 return 1;
8749         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8750                 if (loop_ok && env->bpf_capable)
8751                         return 0;
8752                 verbose_linfo(env, t, "%d: ", t);
8753                 verbose_linfo(env, w, "%d: ", w);
8754                 verbose(env, "back-edge from insn %d to %d\n", t, w);
8755                 return -EINVAL;
8756         } else if (insn_state[w] == EXPLORED) {
8757                 /* forward- or cross-edge */
8758                 insn_state[t] = DISCOVERED | e;
8759         } else {
8760                 verbose(env, "insn state internal bug\n");
8761                 return -EFAULT;
8762         }
8763         return 0;
8764 }
8765
8766 /* non-recursive depth-first-search to detect loops in BPF program
8767  * loop == back-edge in directed graph
8768  */
8769 static int check_cfg(struct bpf_verifier_env *env)
8770 {
8771         struct bpf_insn *insns = env->prog->insnsi;
8772         int insn_cnt = env->prog->len;
8773         int *insn_stack, *insn_state;
8774         int ret = 0;
8775         int i, t;
8776
8777         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8778         if (!insn_state)
8779                 return -ENOMEM;
8780
8781         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8782         if (!insn_stack) {
8783                 kvfree(insn_state);
8784                 return -ENOMEM;
8785         }
8786
8787         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8788         insn_stack[0] = 0; /* 0 is the first instruction */
8789         env->cfg.cur_stack = 1;
8790
8791 peek_stack:
8792         if (env->cfg.cur_stack == 0)
8793                 goto check_state;
8794         t = insn_stack[env->cfg.cur_stack - 1];
8795
8796         if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8797             BPF_CLASS(insns[t].code) == BPF_JMP32) {
8798                 u8 opcode = BPF_OP(insns[t].code);
8799
8800                 if (opcode == BPF_EXIT) {
8801                         goto mark_explored;
8802                 } else if (opcode == BPF_CALL) {
8803                         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8804                         if (ret == 1)
8805                                 goto peek_stack;
8806                         else if (ret < 0)
8807                                 goto err_free;
8808                         if (t + 1 < insn_cnt)
8809                                 init_explored_state(env, t + 1);
8810                         if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8811                                 init_explored_state(env, t);
8812                                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8813                                                 env, false);
8814                                 if (ret == 1)
8815                                         goto peek_stack;
8816                                 else if (ret < 0)
8817                                         goto err_free;
8818                         }
8819                 } else if (opcode == BPF_JA) {
8820                         if (BPF_SRC(insns[t].code) != BPF_K) {
8821                                 ret = -EINVAL;
8822                                 goto err_free;
8823                         }
8824                         /* unconditional jump with single edge */
8825                         ret = push_insn(t, t + insns[t].off + 1,
8826                                         FALLTHROUGH, env, true);
8827                         if (ret == 1)
8828                                 goto peek_stack;
8829                         else if (ret < 0)
8830                                 goto err_free;
8831                         /* unconditional jmp is not a good pruning point,
8832                          * but it's marked, since backtracking needs
8833                          * to record jmp history in is_state_visited().
8834                          */
8835                         init_explored_state(env, t + insns[t].off + 1);
8836                         /* tell verifier to check for equivalent states
8837                          * after every call and jump
8838                          */
8839                         if (t + 1 < insn_cnt)
8840                                 init_explored_state(env, t + 1);
8841                 } else {
8842                         /* conditional jump with two edges */
8843                         init_explored_state(env, t);
8844                         ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8845                         if (ret == 1)
8846                                 goto peek_stack;
8847                         else if (ret < 0)
8848                                 goto err_free;
8849
8850                         ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8851                         if (ret == 1)
8852                                 goto peek_stack;
8853                         else if (ret < 0)
8854                                 goto err_free;
8855                 }
8856         } else {
8857                 /* all other non-branch instructions with single
8858                  * fall-through edge
8859                  */
8860                 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8861                 if (ret == 1)
8862                         goto peek_stack;
8863                 else if (ret < 0)
8864                         goto err_free;
8865         }
8866
8867 mark_explored:
8868         insn_state[t] = EXPLORED;
8869         if (env->cfg.cur_stack-- <= 0) {
8870                 verbose(env, "pop stack internal bug\n");
8871                 ret = -EFAULT;
8872                 goto err_free;
8873         }
8874         goto peek_stack;
8875
8876 check_state:
8877         for (i = 0; i < insn_cnt; i++) {
8878                 if (insn_state[i] != EXPLORED) {
8879                         verbose(env, "unreachable insn %d\n", i);
8880                         ret = -EINVAL;
8881                         goto err_free;
8882                 }
8883         }
8884         ret = 0; /* cfg looks good */
8885
8886 err_free:
8887         kvfree(insn_state);
8888         kvfree(insn_stack);
8889         env->cfg.insn_state = env->cfg.insn_stack = NULL;
8890         return ret;
8891 }
8892
8893 static int check_abnormal_return(struct bpf_verifier_env *env)
8894 {
8895         int i;
8896
8897         for (i = 1; i < env->subprog_cnt; i++) {
8898                 if (env->subprog_info[i].has_ld_abs) {
8899                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8900                         return -EINVAL;
8901                 }
8902                 if (env->subprog_info[i].has_tail_call) {
8903                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8904                         return -EINVAL;
8905                 }
8906         }
8907         return 0;
8908 }
8909
8910 /* The minimum supported BTF func info size */
8911 #define MIN_BPF_FUNCINFO_SIZE   8
8912 #define MAX_FUNCINFO_REC_SIZE   252
8913
8914 static int check_btf_func(struct bpf_verifier_env *env,
8915                           const union bpf_attr *attr,
8916                           union bpf_attr __user *uattr)
8917 {
8918         const struct btf_type *type, *func_proto, *ret_type;
8919         u32 i, nfuncs, urec_size, min_size;
8920         u32 krec_size = sizeof(struct bpf_func_info);
8921         struct bpf_func_info *krecord;
8922         struct bpf_func_info_aux *info_aux = NULL;
8923         struct bpf_prog *prog;
8924         const struct btf *btf;
8925         void __user *urecord;
8926         u32 prev_offset = 0;
8927         bool scalar_return;
8928         int ret = -ENOMEM;
8929
8930         nfuncs = attr->func_info_cnt;
8931         if (!nfuncs) {
8932                 if (check_abnormal_return(env))
8933                         return -EINVAL;
8934                 return 0;
8935         }
8936
8937         if (nfuncs != env->subprog_cnt) {
8938                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8939                 return -EINVAL;
8940         }
8941
8942         urec_size = attr->func_info_rec_size;
8943         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8944             urec_size > MAX_FUNCINFO_REC_SIZE ||
8945             urec_size % sizeof(u32)) {
8946                 verbose(env, "invalid func info rec size %u\n", urec_size);
8947                 return -EINVAL;
8948         }
8949
8950         prog = env->prog;
8951         btf = prog->aux->btf;
8952
8953         urecord = u64_to_user_ptr(attr->func_info);
8954         min_size = min_t(u32, krec_size, urec_size);
8955
8956         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
8957         if (!krecord)
8958                 return -ENOMEM;
8959         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8960         if (!info_aux)
8961                 goto err_free;
8962
8963         for (i = 0; i < nfuncs; i++) {
8964                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8965                 if (ret) {
8966                         if (ret == -E2BIG) {
8967                                 verbose(env, "nonzero tailing record in func info");
8968                                 /* set the size kernel expects so loader can zero
8969                                  * out the rest of the record.
8970                                  */
8971                                 if (put_user(min_size, &uattr->func_info_rec_size))
8972                                         ret = -EFAULT;
8973                         }
8974                         goto err_free;
8975                 }
8976
8977                 if (copy_from_user(&krecord[i], urecord, min_size)) {
8978                         ret = -EFAULT;
8979                         goto err_free;
8980                 }
8981
8982                 /* check insn_off */
8983                 ret = -EINVAL;
8984                 if (i == 0) {
8985                         if (krecord[i].insn_off) {
8986                                 verbose(env,
8987                                         "nonzero insn_off %u for the first func info record",
8988                                         krecord[i].insn_off);
8989                                 goto err_free;
8990                         }
8991                 } else if (krecord[i].insn_off <= prev_offset) {
8992                         verbose(env,
8993                                 "same or smaller insn offset (%u) than previous func info record (%u)",
8994                                 krecord[i].insn_off, prev_offset);
8995                         goto err_free;
8996                 }
8997
8998                 if (env->subprog_info[i].start != krecord[i].insn_off) {
8999                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9000                         goto err_free;
9001                 }
9002
9003                 /* check type_id */
9004                 type = btf_type_by_id(btf, krecord[i].type_id);
9005                 if (!type || !btf_type_is_func(type)) {
9006                         verbose(env, "invalid type id %d in func info",
9007                                 krecord[i].type_id);
9008                         goto err_free;
9009                 }
9010                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9011
9012                 func_proto = btf_type_by_id(btf, type->type);
9013                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9014                         /* btf_func_check() already verified it during BTF load */
9015                         goto err_free;
9016                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9017                 scalar_return =
9018                         btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9019                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9020                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9021                         goto err_free;
9022                 }
9023                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9024                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9025                         goto err_free;
9026                 }
9027
9028                 prev_offset = krecord[i].insn_off;
9029                 urecord += urec_size;
9030         }
9031
9032         prog->aux->func_info = krecord;
9033         prog->aux->func_info_cnt = nfuncs;
9034         prog->aux->func_info_aux = info_aux;
9035         return 0;
9036
9037 err_free:
9038         kvfree(krecord);
9039         kfree(info_aux);
9040         return ret;
9041 }
9042
9043 static void adjust_btf_func(struct bpf_verifier_env *env)
9044 {
9045         struct bpf_prog_aux *aux = env->prog->aux;
9046         int i;
9047
9048         if (!aux->func_info)
9049                 return;
9050
9051         for (i = 0; i < env->subprog_cnt; i++)
9052                 aux->func_info[i].insn_off = env->subprog_info[i].start;
9053 }
9054
9055 #define MIN_BPF_LINEINFO_SIZE   (offsetof(struct bpf_line_info, line_col) + \
9056                 sizeof(((struct bpf_line_info *)(0))->line_col))
9057 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
9058
9059 static int check_btf_line(struct bpf_verifier_env *env,
9060                           const union bpf_attr *attr,
9061                           union bpf_attr __user *uattr)
9062 {
9063         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9064         struct bpf_subprog_info *sub;
9065         struct bpf_line_info *linfo;
9066         struct bpf_prog *prog;
9067         const struct btf *btf;
9068         void __user *ulinfo;
9069         int err;
9070
9071         nr_linfo = attr->line_info_cnt;
9072         if (!nr_linfo)
9073                 return 0;
9074         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
9075                 return -EINVAL;
9076
9077         rec_size = attr->line_info_rec_size;
9078         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9079             rec_size > MAX_LINEINFO_REC_SIZE ||
9080             rec_size & (sizeof(u32) - 1))
9081                 return -EINVAL;
9082
9083         /* Need to zero it in case the userspace may
9084          * pass in a smaller bpf_line_info object.
9085          */
9086         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9087                          GFP_KERNEL | __GFP_NOWARN);
9088         if (!linfo)
9089                 return -ENOMEM;
9090
9091         prog = env->prog;
9092         btf = prog->aux->btf;
9093
9094         s = 0;
9095         sub = env->subprog_info;
9096         ulinfo = u64_to_user_ptr(attr->line_info);
9097         expected_size = sizeof(struct bpf_line_info);
9098         ncopy = min_t(u32, expected_size, rec_size);
9099         for (i = 0; i < nr_linfo; i++) {
9100                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9101                 if (err) {
9102                         if (err == -E2BIG) {
9103                                 verbose(env, "nonzero tailing record in line_info");
9104                                 if (put_user(expected_size,
9105                                              &uattr->line_info_rec_size))
9106                                         err = -EFAULT;
9107                         }
9108                         goto err_free;
9109                 }
9110
9111                 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9112                         err = -EFAULT;
9113                         goto err_free;
9114                 }
9115
9116                 /*
9117                  * Check insn_off to ensure
9118                  * 1) strictly increasing AND
9119                  * 2) bounded by prog->len
9120                  *
9121                  * The linfo[0].insn_off == 0 check logically falls into
9122                  * the later "missing bpf_line_info for func..." case
9123                  * because the first linfo[0].insn_off must be the
9124                  * first sub also and the first sub must have
9125                  * subprog_info[0].start == 0.
9126                  */
9127                 if ((i && linfo[i].insn_off <= prev_offset) ||
9128                     linfo[i].insn_off >= prog->len) {
9129                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9130                                 i, linfo[i].insn_off, prev_offset,
9131                                 prog->len);
9132                         err = -EINVAL;
9133                         goto err_free;
9134                 }
9135
9136                 if (!prog->insnsi[linfo[i].insn_off].code) {
9137                         verbose(env,
9138                                 "Invalid insn code at line_info[%u].insn_off\n",
9139                                 i);
9140                         err = -EINVAL;
9141                         goto err_free;
9142                 }
9143
9144                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9145                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9146                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9147                         err = -EINVAL;
9148                         goto err_free;
9149                 }
9150
9151                 if (s != env->subprog_cnt) {
9152                         if (linfo[i].insn_off == sub[s].start) {
9153                                 sub[s].linfo_idx = i;
9154                                 s++;
9155                         } else if (sub[s].start < linfo[i].insn_off) {
9156                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
9157                                 err = -EINVAL;
9158                                 goto err_free;
9159                         }
9160                 }
9161
9162                 prev_offset = linfo[i].insn_off;
9163                 ulinfo += rec_size;
9164         }
9165
9166         if (s != env->subprog_cnt) {
9167                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9168                         env->subprog_cnt - s, s);
9169                 err = -EINVAL;
9170                 goto err_free;
9171         }
9172
9173         prog->aux->linfo = linfo;
9174         prog->aux->nr_linfo = nr_linfo;
9175
9176         return 0;
9177
9178 err_free:
9179         kvfree(linfo);
9180         return err;
9181 }
9182
9183 static int check_btf_info(struct bpf_verifier_env *env,
9184                           const union bpf_attr *attr,
9185                           union bpf_attr __user *uattr)
9186 {
9187         struct btf *btf;
9188         int err;
9189
9190         if (!attr->func_info_cnt && !attr->line_info_cnt) {
9191                 if (check_abnormal_return(env))
9192                         return -EINVAL;
9193                 return 0;
9194         }
9195
9196         btf = btf_get_by_fd(attr->prog_btf_fd);
9197         if (IS_ERR(btf))
9198                 return PTR_ERR(btf);
9199         env->prog->aux->btf = btf;
9200
9201         err = check_btf_func(env, attr, uattr);
9202         if (err)
9203                 return err;
9204
9205         err = check_btf_line(env, attr, uattr);
9206         if (err)
9207                 return err;
9208
9209         return 0;
9210 }
9211
9212 /* check %cur's range satisfies %old's */
9213 static bool range_within(struct bpf_reg_state *old,
9214                          struct bpf_reg_state *cur)
9215 {
9216         return old->umin_value <= cur->umin_value &&
9217                old->umax_value >= cur->umax_value &&
9218                old->smin_value <= cur->smin_value &&
9219                old->smax_value >= cur->smax_value &&
9220                old->u32_min_value <= cur->u32_min_value &&
9221                old->u32_max_value >= cur->u32_max_value &&
9222                old->s32_min_value <= cur->s32_min_value &&
9223                old->s32_max_value >= cur->s32_max_value;
9224 }
9225
9226 /* If in the old state two registers had the same id, then they need to have
9227  * the same id in the new state as well.  But that id could be different from
9228  * the old state, so we need to track the mapping from old to new ids.
9229  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9230  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9231  * regs with a different old id could still have new id 9, we don't care about
9232  * that.
9233  * So we look through our idmap to see if this old id has been seen before.  If
9234  * so, we require the new id to match; otherwise, we add the id pair to the map.
9235  */
9236 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
9237 {
9238         unsigned int i;
9239
9240         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
9241                 if (!idmap[i].old) {
9242                         /* Reached an empty slot; haven't seen this id before */
9243                         idmap[i].old = old_id;
9244                         idmap[i].cur = cur_id;
9245                         return true;
9246                 }
9247                 if (idmap[i].old == old_id)
9248                         return idmap[i].cur == cur_id;
9249         }
9250         /* We ran out of idmap slots, which should be impossible */
9251         WARN_ON_ONCE(1);
9252         return false;
9253 }
9254
9255 static void clean_func_state(struct bpf_verifier_env *env,
9256                              struct bpf_func_state *st)
9257 {
9258         enum bpf_reg_liveness live;
9259         int i, j;
9260
9261         for (i = 0; i < BPF_REG_FP; i++) {
9262                 live = st->regs[i].live;
9263                 /* liveness must not touch this register anymore */
9264                 st->regs[i].live |= REG_LIVE_DONE;
9265                 if (!(live & REG_LIVE_READ))
9266                         /* since the register is unused, clear its state
9267                          * to make further comparison simpler
9268                          */
9269                         __mark_reg_not_init(env, &st->regs[i]);
9270         }
9271
9272         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9273                 live = st->stack[i].spilled_ptr.live;
9274                 /* liveness must not touch this stack slot anymore */
9275                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9276                 if (!(live & REG_LIVE_READ)) {
9277                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9278                         for (j = 0; j < BPF_REG_SIZE; j++)
9279                                 st->stack[i].slot_type[j] = STACK_INVALID;
9280                 }
9281         }
9282 }
9283
9284 static void clean_verifier_state(struct bpf_verifier_env *env,
9285                                  struct bpf_verifier_state *st)
9286 {
9287         int i;
9288
9289         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9290                 /* all regs in this state in all frames were already marked */
9291                 return;
9292
9293         for (i = 0; i <= st->curframe; i++)
9294                 clean_func_state(env, st->frame[i]);
9295 }
9296
9297 /* the parentage chains form a tree.
9298  * the verifier states are added to state lists at given insn and
9299  * pushed into state stack for future exploration.
9300  * when the verifier reaches bpf_exit insn some of the verifer states
9301  * stored in the state lists have their final liveness state already,
9302  * but a lot of states will get revised from liveness point of view when
9303  * the verifier explores other branches.
9304  * Example:
9305  * 1: r0 = 1
9306  * 2: if r1 == 100 goto pc+1
9307  * 3: r0 = 2
9308  * 4: exit
9309  * when the verifier reaches exit insn the register r0 in the state list of
9310  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9311  * of insn 2 and goes exploring further. At the insn 4 it will walk the
9312  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9313  *
9314  * Since the verifier pushes the branch states as it sees them while exploring
9315  * the program the condition of walking the branch instruction for the second
9316  * time means that all states below this branch were already explored and
9317  * their final liveness markes are already propagated.
9318  * Hence when the verifier completes the search of state list in is_state_visited()
9319  * we can call this clean_live_states() function to mark all liveness states
9320  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9321  * will not be used.
9322  * This function also clears the registers and stack for states that !READ
9323  * to simplify state merging.
9324  *
9325  * Important note here that walking the same branch instruction in the callee
9326  * doesn't meant that the states are DONE. The verifier has to compare
9327  * the callsites
9328  */
9329 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9330                               struct bpf_verifier_state *cur)
9331 {
9332         struct bpf_verifier_state_list *sl;
9333         int i;
9334
9335         sl = *explored_state(env, insn);
9336         while (sl) {
9337                 if (sl->state.branches)
9338                         goto next;
9339                 if (sl->state.insn_idx != insn ||
9340                     sl->state.curframe != cur->curframe)
9341                         goto next;
9342                 for (i = 0; i <= cur->curframe; i++)
9343                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9344                                 goto next;
9345                 clean_verifier_state(env, &sl->state);
9346 next:
9347                 sl = sl->next;
9348         }
9349 }
9350
9351 /* Returns true if (rold safe implies rcur safe) */
9352 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9353                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
9354 {
9355         bool equal;
9356
9357         if (!(rold->live & REG_LIVE_READ))
9358                 /* explored state didn't use this */
9359                 return true;
9360
9361         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9362
9363         if (rold->type == PTR_TO_STACK)
9364                 /* two stack pointers are equal only if they're pointing to
9365                  * the same stack frame, since fp-8 in foo != fp-8 in bar
9366                  */
9367                 return equal && rold->frameno == rcur->frameno;
9368
9369         if (equal)
9370                 return true;
9371
9372         if (rold->type == NOT_INIT)
9373                 /* explored state can't have used this */
9374                 return true;
9375         if (rcur->type == NOT_INIT)
9376                 return false;
9377         switch (rold->type) {
9378         case SCALAR_VALUE:
9379                 if (env->explore_alu_limits)
9380                         return false;
9381                 if (rcur->type == SCALAR_VALUE) {
9382                         if (!rold->precise)
9383                                 return true;
9384                         /* new val must satisfy old val knowledge */
9385                         return range_within(rold, rcur) &&
9386                                tnum_in(rold->var_off, rcur->var_off);
9387                 } else {
9388                         /* We're trying to use a pointer in place of a scalar.
9389                          * Even if the scalar was unbounded, this could lead to
9390                          * pointer leaks because scalars are allowed to leak
9391                          * while pointers are not. We could make this safe in
9392                          * special cases if root is calling us, but it's
9393                          * probably not worth the hassle.
9394                          */
9395                         return false;
9396                 }
9397         case PTR_TO_MAP_VALUE:
9398                 /* If the new min/max/var_off satisfy the old ones and
9399                  * everything else matches, we are OK.
9400                  * 'id' is not compared, since it's only used for maps with
9401                  * bpf_spin_lock inside map element and in such cases if
9402                  * the rest of the prog is valid for one map element then
9403                  * it's valid for all map elements regardless of the key
9404                  * used in bpf_map_lookup()
9405                  */
9406                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9407                        range_within(rold, rcur) &&
9408                        tnum_in(rold->var_off, rcur->var_off);
9409         case PTR_TO_MAP_VALUE_OR_NULL:
9410                 /* a PTR_TO_MAP_VALUE could be safe to use as a
9411                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9412                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9413                  * checked, doing so could have affected others with the same
9414                  * id, and we can't check for that because we lost the id when
9415                  * we converted to a PTR_TO_MAP_VALUE.
9416                  */
9417                 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9418                         return false;
9419                 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9420                         return false;
9421                 /* Check our ids match any regs they're supposed to */
9422                 return check_ids(rold->id, rcur->id, idmap);
9423         case PTR_TO_PACKET_META:
9424         case PTR_TO_PACKET:
9425                 if (rcur->type != rold->type)
9426                         return false;
9427                 /* We must have at least as much range as the old ptr
9428                  * did, so that any accesses which were safe before are
9429                  * still safe.  This is true even if old range < old off,
9430                  * since someone could have accessed through (ptr - k), or
9431                  * even done ptr -= k in a register, to get a safe access.
9432                  */
9433                 if (rold->range > rcur->range)
9434                         return false;
9435                 /* If the offsets don't match, we can't trust our alignment;
9436                  * nor can we be sure that we won't fall out of range.
9437                  */
9438                 if (rold->off != rcur->off)
9439                         return false;
9440                 /* id relations must be preserved */
9441                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9442                         return false;
9443                 /* new val must satisfy old val knowledge */
9444                 return range_within(rold, rcur) &&
9445                        tnum_in(rold->var_off, rcur->var_off);
9446         case PTR_TO_CTX:
9447         case CONST_PTR_TO_MAP:
9448         case PTR_TO_PACKET_END:
9449         case PTR_TO_FLOW_KEYS:
9450         case PTR_TO_SOCKET:
9451         case PTR_TO_SOCKET_OR_NULL:
9452         case PTR_TO_SOCK_COMMON:
9453         case PTR_TO_SOCK_COMMON_OR_NULL:
9454         case PTR_TO_TCP_SOCK:
9455         case PTR_TO_TCP_SOCK_OR_NULL:
9456         case PTR_TO_XDP_SOCK:
9457                 /* Only valid matches are exact, which memcmp() above
9458                  * would have accepted
9459                  */
9460         default:
9461                 /* Don't know what's going on, just say it's not safe */
9462                 return false;
9463         }
9464
9465         /* Shouldn't get here; if we do, say it's not safe */
9466         WARN_ON_ONCE(1);
9467         return false;
9468 }
9469
9470 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
9471                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
9472 {
9473         int i, spi;
9474
9475         /* walk slots of the explored stack and ignore any additional
9476          * slots in the current stack, since explored(safe) state
9477          * didn't use them
9478          */
9479         for (i = 0; i < old->allocated_stack; i++) {
9480                 spi = i / BPF_REG_SIZE;
9481
9482                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9483                         i += BPF_REG_SIZE - 1;
9484                         /* explored state didn't use this */
9485                         continue;
9486                 }
9487
9488                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9489                         continue;
9490
9491                 /* explored stack has more populated slots than current stack
9492                  * and these slots were used
9493                  */
9494                 if (i >= cur->allocated_stack)
9495                         return false;
9496
9497                 /* if old state was safe with misc data in the stack
9498                  * it will be safe with zero-initialized stack.
9499                  * The opposite is not true
9500                  */
9501                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9502                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9503                         continue;
9504                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9505                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9506                         /* Ex: old explored (safe) state has STACK_SPILL in
9507                          * this stack slot, but current has STACK_MISC ->
9508                          * this verifier states are not equivalent,
9509                          * return false to continue verification of this path
9510                          */
9511                         return false;
9512                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
9513                         continue;
9514                 if (!is_spilled_reg(&old->stack[spi]))
9515                         continue;
9516                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
9517                              &cur->stack[spi].spilled_ptr, idmap))
9518                         /* when explored and current stack slot are both storing
9519                          * spilled registers, check that stored pointers types
9520                          * are the same as well.
9521                          * Ex: explored safe path could have stored
9522                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9523                          * but current path has stored:
9524                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9525                          * such verifier states are not equivalent.
9526                          * return false to continue verification of this path
9527                          */
9528                         return false;
9529         }
9530         return true;
9531 }
9532
9533 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9534 {
9535         if (old->acquired_refs != cur->acquired_refs)
9536                 return false;
9537         return !memcmp(old->refs, cur->refs,
9538                        sizeof(*old->refs) * old->acquired_refs);
9539 }
9540
9541 /* compare two verifier states
9542  *
9543  * all states stored in state_list are known to be valid, since
9544  * verifier reached 'bpf_exit' instruction through them
9545  *
9546  * this function is called when verifier exploring different branches of
9547  * execution popped from the state stack. If it sees an old state that has
9548  * more strict register state and more strict stack state then this execution
9549  * branch doesn't need to be explored further, since verifier already
9550  * concluded that more strict state leads to valid finish.
9551  *
9552  * Therefore two states are equivalent if register state is more conservative
9553  * and explored stack state is more conservative than the current one.
9554  * Example:
9555  *       explored                   current
9556  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9557  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9558  *
9559  * In other words if current stack state (one being explored) has more
9560  * valid slots than old one that already passed validation, it means
9561  * the verifier can stop exploring and conclude that current state is valid too
9562  *
9563  * Similarly with registers. If explored state has register type as invalid
9564  * whereas register type in current state is meaningful, it means that
9565  * the current state will reach 'bpf_exit' instruction safely
9566  */
9567 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
9568                               struct bpf_func_state *cur)
9569 {
9570         int i;
9571
9572         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
9573         for (i = 0; i < MAX_BPF_REG; i++)
9574                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
9575                              env->idmap_scratch))
9576                         return false;
9577
9578         if (!stacksafe(env, old, cur, env->idmap_scratch))
9579                 return false;
9580
9581         if (!refsafe(old, cur))
9582                 return false;
9583
9584         return true;
9585 }
9586
9587 static bool states_equal(struct bpf_verifier_env *env,
9588                          struct bpf_verifier_state *old,
9589                          struct bpf_verifier_state *cur)
9590 {
9591         int i;
9592
9593         if (old->curframe != cur->curframe)
9594                 return false;
9595
9596         /* Verification state from speculative execution simulation
9597          * must never prune a non-speculative execution one.
9598          */
9599         if (old->speculative && !cur->speculative)
9600                 return false;
9601
9602         if (old->active_spin_lock != cur->active_spin_lock)
9603                 return false;
9604
9605         /* for states to be equal callsites have to be the same
9606          * and all frame states need to be equivalent
9607          */
9608         for (i = 0; i <= old->curframe; i++) {
9609                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9610                         return false;
9611                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
9612                         return false;
9613         }
9614         return true;
9615 }
9616
9617 /* Return 0 if no propagation happened. Return negative error code if error
9618  * happened. Otherwise, return the propagated bit.
9619  */
9620 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9621                                   struct bpf_reg_state *reg,
9622                                   struct bpf_reg_state *parent_reg)
9623 {
9624         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9625         u8 flag = reg->live & REG_LIVE_READ;
9626         int err;
9627
9628         /* When comes here, read flags of PARENT_REG or REG could be any of
9629          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9630          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9631          */
9632         if (parent_flag == REG_LIVE_READ64 ||
9633             /* Or if there is no read flag from REG. */
9634             !flag ||
9635             /* Or if the read flag from REG is the same as PARENT_REG. */
9636             parent_flag == flag)
9637                 return 0;
9638
9639         err = mark_reg_read(env, reg, parent_reg, flag);
9640         if (err)
9641                 return err;
9642
9643         return flag;
9644 }
9645
9646 /* A write screens off any subsequent reads; but write marks come from the
9647  * straight-line code between a state and its parent.  When we arrive at an
9648  * equivalent state (jump target or such) we didn't arrive by the straight-line
9649  * code, so read marks in the state must propagate to the parent regardless
9650  * of the state's write marks. That's what 'parent == state->parent' comparison
9651  * in mark_reg_read() is for.
9652  */
9653 static int propagate_liveness(struct bpf_verifier_env *env,
9654                               const struct bpf_verifier_state *vstate,
9655                               struct bpf_verifier_state *vparent)
9656 {
9657         struct bpf_reg_state *state_reg, *parent_reg;
9658         struct bpf_func_state *state, *parent;
9659         int i, frame, err = 0;
9660
9661         if (vparent->curframe != vstate->curframe) {
9662                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9663                      vparent->curframe, vstate->curframe);
9664                 return -EFAULT;
9665         }
9666         /* Propagate read liveness of registers... */
9667         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9668         for (frame = 0; frame <= vstate->curframe; frame++) {
9669                 parent = vparent->frame[frame];
9670                 state = vstate->frame[frame];
9671                 parent_reg = parent->regs;
9672                 state_reg = state->regs;
9673                 /* We don't need to worry about FP liveness, it's read-only */
9674                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9675                         err = propagate_liveness_reg(env, &state_reg[i],
9676                                                      &parent_reg[i]);
9677                         if (err < 0)
9678                                 return err;
9679                         if (err == REG_LIVE_READ64)
9680                                 mark_insn_zext(env, &parent_reg[i]);
9681                 }
9682
9683                 /* Propagate stack slots. */
9684                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9685                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9686                         parent_reg = &parent->stack[i].spilled_ptr;
9687                         state_reg = &state->stack[i].spilled_ptr;
9688                         err = propagate_liveness_reg(env, state_reg,
9689                                                      parent_reg);
9690                         if (err < 0)
9691                                 return err;
9692                 }
9693         }
9694         return 0;
9695 }
9696
9697 /* find precise scalars in the previous equivalent state and
9698  * propagate them into the current state
9699  */
9700 static int propagate_precision(struct bpf_verifier_env *env,
9701                                const struct bpf_verifier_state *old)
9702 {
9703         struct bpf_reg_state *state_reg;
9704         struct bpf_func_state *state;
9705         int i, err = 0, fr;
9706
9707         for (fr = old->curframe; fr >= 0; fr--) {
9708                 state = old->frame[fr];
9709                 state_reg = state->regs;
9710                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9711                         if (state_reg->type != SCALAR_VALUE ||
9712                             !state_reg->precise ||
9713                             !(state_reg->live & REG_LIVE_READ))
9714                                 continue;
9715                         if (env->log.level & BPF_LOG_LEVEL2)
9716                                 verbose(env, "frame %d: propagating r%d\n", fr, i);
9717                         err = mark_chain_precision_frame(env, fr, i);
9718                         if (err < 0)
9719                                 return err;
9720                 }
9721
9722                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9723                         if (!is_spilled_reg(&state->stack[i]))
9724                                 continue;
9725                         state_reg = &state->stack[i].spilled_ptr;
9726                         if (state_reg->type != SCALAR_VALUE ||
9727                             !state_reg->precise ||
9728                             !(state_reg->live & REG_LIVE_READ))
9729                                 continue;
9730                         if (env->log.level & BPF_LOG_LEVEL2)
9731                                 verbose(env, "frame %d: propagating fp%d\n",
9732                                         fr, (-i - 1) * BPF_REG_SIZE);
9733                         err = mark_chain_precision_stack_frame(env, fr, i);
9734                         if (err < 0)
9735                                 return err;
9736                 }
9737         }
9738         return 0;
9739 }
9740
9741 static bool states_maybe_looping(struct bpf_verifier_state *old,
9742                                  struct bpf_verifier_state *cur)
9743 {
9744         struct bpf_func_state *fold, *fcur;
9745         int i, fr = cur->curframe;
9746
9747         if (old->curframe != fr)
9748                 return false;
9749
9750         fold = old->frame[fr];
9751         fcur = cur->frame[fr];
9752         for (i = 0; i < MAX_BPF_REG; i++)
9753                 if (memcmp(&fold->regs[i], &fcur->regs[i],
9754                            offsetof(struct bpf_reg_state, parent)))
9755                         return false;
9756         return true;
9757 }
9758
9759
9760 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9761 {
9762         struct bpf_verifier_state_list *new_sl;
9763         struct bpf_verifier_state_list *sl, **pprev;
9764         struct bpf_verifier_state *cur = env->cur_state, *new;
9765         int i, j, err, states_cnt = 0;
9766         bool add_new_state = env->test_state_freq ? true : false;
9767
9768         cur->last_insn_idx = env->prev_insn_idx;
9769         if (!env->insn_aux_data[insn_idx].prune_point)
9770                 /* this 'insn_idx' instruction wasn't marked, so we will not
9771                  * be doing state search here
9772                  */
9773                 return 0;
9774
9775         /* bpf progs typically have pruning point every 4 instructions
9776          * http://vger.kernel.org/bpfconf2019.html#session-1
9777          * Do not add new state for future pruning if the verifier hasn't seen
9778          * at least 2 jumps and at least 8 instructions.
9779          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9780          * In tests that amounts to up to 50% reduction into total verifier
9781          * memory consumption and 20% verifier time speedup.
9782          */
9783         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9784             env->insn_processed - env->prev_insn_processed >= 8)
9785                 add_new_state = true;
9786
9787         pprev = explored_state(env, insn_idx);
9788         sl = *pprev;
9789
9790         clean_live_states(env, insn_idx, cur);
9791
9792         while (sl) {
9793                 states_cnt++;
9794                 if (sl->state.insn_idx != insn_idx)
9795                         goto next;
9796                 if (sl->state.branches) {
9797                         if (states_maybe_looping(&sl->state, cur) &&
9798                             states_equal(env, &sl->state, cur)) {
9799                                 verbose_linfo(env, insn_idx, "; ");
9800                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9801                                 return -EINVAL;
9802                         }
9803                         /* if the verifier is processing a loop, avoid adding new state
9804                          * too often, since different loop iterations have distinct
9805                          * states and may not help future pruning.
9806                          * This threshold shouldn't be too low to make sure that
9807                          * a loop with large bound will be rejected quickly.
9808                          * The most abusive loop will be:
9809                          * r1 += 1
9810                          * if r1 < 1000000 goto pc-2
9811                          * 1M insn_procssed limit / 100 == 10k peak states.
9812                          * This threshold shouldn't be too high either, since states
9813                          * at the end of the loop are likely to be useful in pruning.
9814                          */
9815                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9816                             env->insn_processed - env->prev_insn_processed < 100)
9817                                 add_new_state = false;
9818                         goto miss;
9819                 }
9820                 if (states_equal(env, &sl->state, cur)) {
9821                         sl->hit_cnt++;
9822                         /* reached equivalent register/stack state,
9823                          * prune the search.
9824                          * Registers read by the continuation are read by us.
9825                          * If we have any write marks in env->cur_state, they
9826                          * will prevent corresponding reads in the continuation
9827                          * from reaching our parent (an explored_state).  Our
9828                          * own state will get the read marks recorded, but
9829                          * they'll be immediately forgotten as we're pruning
9830                          * this state and will pop a new one.
9831                          */
9832                         err = propagate_liveness(env, &sl->state, cur);
9833
9834                         /* if previous state reached the exit with precision and
9835                          * current state is equivalent to it (except precsion marks)
9836                          * the precision needs to be propagated back in
9837                          * the current state.
9838                          */
9839                         err = err ? : push_jmp_history(env, cur);
9840                         err = err ? : propagate_precision(env, &sl->state);
9841                         if (err)
9842                                 return err;
9843                         return 1;
9844                 }
9845 miss:
9846                 /* when new state is not going to be added do not increase miss count.
9847                  * Otherwise several loop iterations will remove the state
9848                  * recorded earlier. The goal of these heuristics is to have
9849                  * states from some iterations of the loop (some in the beginning
9850                  * and some at the end) to help pruning.
9851                  */
9852                 if (add_new_state)
9853                         sl->miss_cnt++;
9854                 /* heuristic to determine whether this state is beneficial
9855                  * to keep checking from state equivalence point of view.
9856                  * Higher numbers increase max_states_per_insn and verification time,
9857                  * but do not meaningfully decrease insn_processed.
9858                  */
9859                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9860                         /* the state is unlikely to be useful. Remove it to
9861                          * speed up verification
9862                          */
9863                         *pprev = sl->next;
9864                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9865                                 u32 br = sl->state.branches;
9866
9867                                 WARN_ONCE(br,
9868                                           "BUG live_done but branches_to_explore %d\n",
9869                                           br);
9870                                 free_verifier_state(&sl->state, false);
9871                                 kfree(sl);
9872                                 env->peak_states--;
9873                         } else {
9874                                 /* cannot free this state, since parentage chain may
9875                                  * walk it later. Add it for free_list instead to
9876                                  * be freed at the end of verification
9877                                  */
9878                                 sl->next = env->free_list;
9879                                 env->free_list = sl;
9880                         }
9881                         sl = *pprev;
9882                         continue;
9883                 }
9884 next:
9885                 pprev = &sl->next;
9886                 sl = *pprev;
9887         }
9888
9889         if (env->max_states_per_insn < states_cnt)
9890                 env->max_states_per_insn = states_cnt;
9891
9892         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9893                 return push_jmp_history(env, cur);
9894
9895         if (!add_new_state)
9896                 return push_jmp_history(env, cur);
9897
9898         /* There were no equivalent states, remember the current one.
9899          * Technically the current state is not proven to be safe yet,
9900          * but it will either reach outer most bpf_exit (which means it's safe)
9901          * or it will be rejected. When there are no loops the verifier won't be
9902          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9903          * again on the way to bpf_exit.
9904          * When looping the sl->state.branches will be > 0 and this state
9905          * will not be considered for equivalence until branches == 0.
9906          */
9907         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9908         if (!new_sl)
9909                 return -ENOMEM;
9910         env->total_states++;
9911         env->peak_states++;
9912         env->prev_jmps_processed = env->jmps_processed;
9913         env->prev_insn_processed = env->insn_processed;
9914
9915         /* forget precise markings we inherited, see __mark_chain_precision */
9916         if (env->bpf_capable)
9917                 mark_all_scalars_imprecise(env, cur);
9918
9919         /* add new state to the head of linked list */
9920         new = &new_sl->state;
9921         err = copy_verifier_state(new, cur);
9922         if (err) {
9923                 free_verifier_state(new, false);
9924                 kfree(new_sl);
9925                 return err;
9926         }
9927         new->insn_idx = insn_idx;
9928         WARN_ONCE(new->branches != 1,
9929                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9930
9931         cur->parent = new;
9932         cur->first_insn_idx = insn_idx;
9933         clear_jmp_history(cur);
9934         new_sl->next = *explored_state(env, insn_idx);
9935         *explored_state(env, insn_idx) = new_sl;
9936         /* connect new state to parentage chain. Current frame needs all
9937          * registers connected. Only r6 - r9 of the callers are alive (pushed
9938          * to the stack implicitly by JITs) so in callers' frames connect just
9939          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9940          * the state of the call instruction (with WRITTEN set), and r0 comes
9941          * from callee with its full parentage chain, anyway.
9942          */
9943         /* clear write marks in current state: the writes we did are not writes
9944          * our child did, so they don't screen off its reads from us.
9945          * (There are no read marks in current state, because reads always mark
9946          * their parent and current state never has children yet.  Only
9947          * explored_states can get read marks.)
9948          */
9949         for (j = 0; j <= cur->curframe; j++) {
9950                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9951                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9952                 for (i = 0; i < BPF_REG_FP; i++)
9953                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9954         }
9955
9956         /* all stack frames are accessible from callee, clear them all */
9957         for (j = 0; j <= cur->curframe; j++) {
9958                 struct bpf_func_state *frame = cur->frame[j];
9959                 struct bpf_func_state *newframe = new->frame[j];
9960
9961                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
9962                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
9963                         frame->stack[i].spilled_ptr.parent =
9964                                                 &newframe->stack[i].spilled_ptr;
9965                 }
9966         }
9967         return 0;
9968 }
9969
9970 /* Return true if it's OK to have the same insn return a different type. */
9971 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9972 {
9973         switch (type) {
9974         case PTR_TO_CTX:
9975         case PTR_TO_SOCKET:
9976         case PTR_TO_SOCKET_OR_NULL:
9977         case PTR_TO_SOCK_COMMON:
9978         case PTR_TO_SOCK_COMMON_OR_NULL:
9979         case PTR_TO_TCP_SOCK:
9980         case PTR_TO_TCP_SOCK_OR_NULL:
9981         case PTR_TO_XDP_SOCK:
9982         case PTR_TO_BTF_ID:
9983         case PTR_TO_BTF_ID_OR_NULL:
9984                 return false;
9985         default:
9986                 return true;
9987         }
9988 }
9989
9990 /* If an instruction was previously used with particular pointer types, then we
9991  * need to be careful to avoid cases such as the below, where it may be ok
9992  * for one branch accessing the pointer, but not ok for the other branch:
9993  *
9994  * R1 = sock_ptr
9995  * goto X;
9996  * ...
9997  * R1 = some_other_valid_ptr;
9998  * goto X;
9999  * ...
10000  * R2 = *(u32 *)(R1 + 0);
10001  */
10002 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10003 {
10004         return src != prev && (!reg_type_mismatch_ok(src) ||
10005                                !reg_type_mismatch_ok(prev));
10006 }
10007
10008 static int do_check(struct bpf_verifier_env *env)
10009 {
10010         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10011         struct bpf_verifier_state *state = env->cur_state;
10012         struct bpf_insn *insns = env->prog->insnsi;
10013         struct bpf_reg_state *regs;
10014         int insn_cnt = env->prog->len;
10015         bool do_print_state = false;
10016         int prev_insn_idx = -1;
10017
10018         for (;;) {
10019                 struct bpf_insn *insn;
10020                 u8 class;
10021                 int err;
10022
10023                 env->prev_insn_idx = prev_insn_idx;
10024                 if (env->insn_idx >= insn_cnt) {
10025                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
10026                                 env->insn_idx, insn_cnt);
10027                         return -EFAULT;
10028                 }
10029
10030                 insn = &insns[env->insn_idx];
10031                 class = BPF_CLASS(insn->code);
10032
10033                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10034                         verbose(env,
10035                                 "BPF program is too large. Processed %d insn\n",
10036                                 env->insn_processed);
10037                         return -E2BIG;
10038                 }
10039
10040                 err = is_state_visited(env, env->insn_idx);
10041                 if (err < 0)
10042                         return err;
10043                 if (err == 1) {
10044                         /* found equivalent state, can prune the search */
10045                         if (env->log.level & BPF_LOG_LEVEL) {
10046                                 if (do_print_state)
10047                                         verbose(env, "\nfrom %d to %d%s: safe\n",
10048                                                 env->prev_insn_idx, env->insn_idx,
10049                                                 env->cur_state->speculative ?
10050                                                 " (speculative execution)" : "");
10051                                 else
10052                                         verbose(env, "%d: safe\n", env->insn_idx);
10053                         }
10054                         goto process_bpf_exit;
10055                 }
10056
10057                 if (signal_pending(current))
10058                         return -EAGAIN;
10059
10060                 if (need_resched())
10061                         cond_resched();
10062
10063                 if (env->log.level & BPF_LOG_LEVEL2 ||
10064                     (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10065                         if (env->log.level & BPF_LOG_LEVEL2)
10066                                 verbose(env, "%d:", env->insn_idx);
10067                         else
10068                                 verbose(env, "\nfrom %d to %d%s:",
10069                                         env->prev_insn_idx, env->insn_idx,
10070                                         env->cur_state->speculative ?
10071                                         " (speculative execution)" : "");
10072                         print_verifier_state(env, state->frame[state->curframe]);
10073                         do_print_state = false;
10074                 }
10075
10076                 if (env->log.level & BPF_LOG_LEVEL) {
10077                         const struct bpf_insn_cbs cbs = {
10078                                 .cb_print       = verbose,
10079                                 .private_data   = env,
10080                         };
10081
10082                         verbose_linfo(env, env->insn_idx, "; ");
10083                         verbose(env, "%d: ", env->insn_idx);
10084                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10085                 }
10086
10087                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10088                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10089                                                            env->prev_insn_idx);
10090                         if (err)
10091                                 return err;
10092                 }
10093
10094                 regs = cur_regs(env);
10095                 sanitize_mark_insn_seen(env);
10096                 prev_insn_idx = env->insn_idx;
10097
10098                 if (class == BPF_ALU || class == BPF_ALU64) {
10099                         err = check_alu_op(env, insn);
10100                         if (err)
10101                                 return err;
10102
10103                 } else if (class == BPF_LDX) {
10104                         enum bpf_reg_type *prev_src_type, src_reg_type;
10105
10106                         /* check for reserved fields is already done */
10107
10108                         /* check src operand */
10109                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10110                         if (err)
10111                                 return err;
10112
10113                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10114                         if (err)
10115                                 return err;
10116
10117                         src_reg_type = regs[insn->src_reg].type;
10118
10119                         /* check that memory (src_reg + off) is readable,
10120                          * the state of dst_reg will be updated by this func
10121                          */
10122                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
10123                                                insn->off, BPF_SIZE(insn->code),
10124                                                BPF_READ, insn->dst_reg, false);
10125                         if (err)
10126                                 return err;
10127
10128                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10129
10130                         if (*prev_src_type == NOT_INIT) {
10131                                 /* saw a valid insn
10132                                  * dst_reg = *(u32 *)(src_reg + off)
10133                                  * save type to validate intersecting paths
10134                                  */
10135                                 *prev_src_type = src_reg_type;
10136
10137                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10138                                 /* ABuser program is trying to use the same insn
10139                                  * dst_reg = *(u32*) (src_reg + off)
10140                                  * with different pointer types:
10141                                  * src_reg == ctx in one branch and
10142                                  * src_reg == stack|map in some other branch.
10143                                  * Reject it.
10144                                  */
10145                                 verbose(env, "same insn cannot be used with different pointers\n");
10146                                 return -EINVAL;
10147                         }
10148
10149                 } else if (class == BPF_STX) {
10150                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
10151
10152                         if (BPF_MODE(insn->code) == BPF_XADD) {
10153                                 err = check_xadd(env, env->insn_idx, insn);
10154                                 if (err)
10155                                         return err;
10156                                 env->insn_idx++;
10157                                 continue;
10158                         }
10159
10160                         /* check src1 operand */
10161                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10162                         if (err)
10163                                 return err;
10164                         /* check src2 operand */
10165                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10166                         if (err)
10167                                 return err;
10168
10169                         dst_reg_type = regs[insn->dst_reg].type;
10170
10171                         /* check that memory (dst_reg + off) is writeable */
10172                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10173                                                insn->off, BPF_SIZE(insn->code),
10174                                                BPF_WRITE, insn->src_reg, false);
10175                         if (err)
10176                                 return err;
10177
10178                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10179
10180                         if (*prev_dst_type == NOT_INIT) {
10181                                 *prev_dst_type = dst_reg_type;
10182                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10183                                 verbose(env, "same insn cannot be used with different pointers\n");
10184                                 return -EINVAL;
10185                         }
10186
10187                 } else if (class == BPF_ST) {
10188                         if (BPF_MODE(insn->code) != BPF_MEM ||
10189                             insn->src_reg != BPF_REG_0) {
10190                                 verbose(env, "BPF_ST uses reserved fields\n");
10191                                 return -EINVAL;
10192                         }
10193                         /* check src operand */
10194                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10195                         if (err)
10196                                 return err;
10197
10198                         if (is_ctx_reg(env, insn->dst_reg)) {
10199                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10200                                         insn->dst_reg,
10201                                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
10202                                 return -EACCES;
10203                         }
10204
10205                         /* check that memory (dst_reg + off) is writeable */
10206                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10207                                                insn->off, BPF_SIZE(insn->code),
10208                                                BPF_WRITE, -1, false);
10209                         if (err)
10210                                 return err;
10211
10212                 } else if (class == BPF_JMP || class == BPF_JMP32) {
10213                         u8 opcode = BPF_OP(insn->code);
10214
10215                         env->jmps_processed++;
10216                         if (opcode == BPF_CALL) {
10217                                 if (BPF_SRC(insn->code) != BPF_K ||
10218                                     insn->off != 0 ||
10219                                     (insn->src_reg != BPF_REG_0 &&
10220                                      insn->src_reg != BPF_PSEUDO_CALL) ||
10221                                     insn->dst_reg != BPF_REG_0 ||
10222                                     class == BPF_JMP32) {
10223                                         verbose(env, "BPF_CALL uses reserved fields\n");
10224                                         return -EINVAL;
10225                                 }
10226
10227                                 if (env->cur_state->active_spin_lock &&
10228                                     (insn->src_reg == BPF_PSEUDO_CALL ||
10229                                      insn->imm != BPF_FUNC_spin_unlock)) {
10230                                         verbose(env, "function calls are not allowed while holding a lock\n");
10231                                         return -EINVAL;
10232                                 }
10233                                 if (insn->src_reg == BPF_PSEUDO_CALL)
10234                                         err = check_func_call(env, insn, &env->insn_idx);
10235                                 else
10236                                         err = check_helper_call(env, insn->imm, env->insn_idx);
10237                                 if (err)
10238                                         return err;
10239
10240                         } else if (opcode == BPF_JA) {
10241                                 if (BPF_SRC(insn->code) != BPF_K ||
10242                                     insn->imm != 0 ||
10243                                     insn->src_reg != BPF_REG_0 ||
10244                                     insn->dst_reg != BPF_REG_0 ||
10245                                     class == BPF_JMP32) {
10246                                         verbose(env, "BPF_JA uses reserved fields\n");
10247                                         return -EINVAL;
10248                                 }
10249
10250                                 env->insn_idx += insn->off + 1;
10251                                 continue;
10252
10253                         } else if (opcode == BPF_EXIT) {
10254                                 if (BPF_SRC(insn->code) != BPF_K ||
10255                                     insn->imm != 0 ||
10256                                     insn->src_reg != BPF_REG_0 ||
10257                                     insn->dst_reg != BPF_REG_0 ||
10258                                     class == BPF_JMP32) {
10259                                         verbose(env, "BPF_EXIT uses reserved fields\n");
10260                                         return -EINVAL;
10261                                 }
10262
10263                                 if (env->cur_state->active_spin_lock) {
10264                                         verbose(env, "bpf_spin_unlock is missing\n");
10265                                         return -EINVAL;
10266                                 }
10267
10268                                 if (state->curframe) {
10269                                         /* exit from nested function */
10270                                         err = prepare_func_exit(env, &env->insn_idx);
10271                                         if (err)
10272                                                 return err;
10273                                         do_print_state = true;
10274                                         continue;
10275                                 }
10276
10277                                 err = check_reference_leak(env);
10278                                 if (err)
10279                                         return err;
10280
10281                                 err = check_return_code(env);
10282                                 if (err)
10283                                         return err;
10284 process_bpf_exit:
10285                                 update_branch_counts(env, env->cur_state);
10286                                 err = pop_stack(env, &prev_insn_idx,
10287                                                 &env->insn_idx, pop_log);
10288                                 if (err < 0) {
10289                                         if (err != -ENOENT)
10290                                                 return err;
10291                                         break;
10292                                 } else {
10293                                         do_print_state = true;
10294                                         continue;
10295                                 }
10296                         } else {
10297                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
10298                                 if (err)
10299                                         return err;
10300                         }
10301                 } else if (class == BPF_LD) {
10302                         u8 mode = BPF_MODE(insn->code);
10303
10304                         if (mode == BPF_ABS || mode == BPF_IND) {
10305                                 err = check_ld_abs(env, insn);
10306                                 if (err)
10307                                         return err;
10308
10309                         } else if (mode == BPF_IMM) {
10310                                 err = check_ld_imm(env, insn);
10311                                 if (err)
10312                                         return err;
10313
10314                                 env->insn_idx++;
10315                                 sanitize_mark_insn_seen(env);
10316                         } else {
10317                                 verbose(env, "invalid BPF_LD mode\n");
10318                                 return -EINVAL;
10319                         }
10320                 } else {
10321                         verbose(env, "unknown insn class %d\n", class);
10322                         return -EINVAL;
10323                 }
10324
10325                 env->insn_idx++;
10326         }
10327
10328         return 0;
10329 }
10330
10331 /* replace pseudo btf_id with kernel symbol address */
10332 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10333                                struct bpf_insn *insn,
10334                                struct bpf_insn_aux_data *aux)
10335 {
10336         const struct btf_var_secinfo *vsi;
10337         const struct btf_type *datasec;
10338         const struct btf_type *t;
10339         const char *sym_name;
10340         bool percpu = false;
10341         u32 type, id = insn->imm;
10342         s32 datasec_id;
10343         u64 addr;
10344         int i;
10345
10346         if (!btf_vmlinux) {
10347                 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10348                 return -EINVAL;
10349         }
10350
10351         if (insn[1].imm != 0) {
10352                 verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10353                 return -EINVAL;
10354         }
10355
10356         t = btf_type_by_id(btf_vmlinux, id);
10357         if (!t) {
10358                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10359                 return -ENOENT;
10360         }
10361
10362         if (!btf_type_is_var(t)) {
10363                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10364                         id);
10365                 return -EINVAL;
10366         }
10367
10368         sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
10369         addr = kallsyms_lookup_name(sym_name);
10370         if (!addr) {
10371                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10372                         sym_name);
10373                 return -ENOENT;
10374         }
10375
10376         datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
10377                                            BTF_KIND_DATASEC);
10378         if (datasec_id > 0) {
10379                 datasec = btf_type_by_id(btf_vmlinux, datasec_id);
10380                 for_each_vsi(i, datasec, vsi) {
10381                         if (vsi->type == id) {
10382                                 percpu = true;
10383                                 break;
10384                         }
10385                 }
10386         }
10387
10388         insn[0].imm = (u32)addr;
10389         insn[1].imm = addr >> 32;
10390
10391         type = t->type;
10392         t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
10393         if (percpu) {
10394                 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10395                 aux->btf_var.btf_id = type;
10396         } else if (!btf_type_is_struct(t)) {
10397                 const struct btf_type *ret;
10398                 const char *tname;
10399                 u32 tsize;
10400
10401                 /* resolve the type size of ksym. */
10402                 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
10403                 if (IS_ERR(ret)) {
10404                         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
10405                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10406                                 tname, PTR_ERR(ret));
10407                         return -EINVAL;
10408                 }
10409                 aux->btf_var.reg_type = PTR_TO_MEM;
10410                 aux->btf_var.mem_size = tsize;
10411         } else {
10412                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
10413                 aux->btf_var.btf_id = type;
10414         }
10415         return 0;
10416 }
10417
10418 static int check_map_prealloc(struct bpf_map *map)
10419 {
10420         return (map->map_type != BPF_MAP_TYPE_HASH &&
10421                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10422                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10423                 !(map->map_flags & BPF_F_NO_PREALLOC);
10424 }
10425
10426 static bool is_tracing_prog_type(enum bpf_prog_type type)
10427 {
10428         switch (type) {
10429         case BPF_PROG_TYPE_KPROBE:
10430         case BPF_PROG_TYPE_TRACEPOINT:
10431         case BPF_PROG_TYPE_PERF_EVENT:
10432         case BPF_PROG_TYPE_RAW_TRACEPOINT:
10433                 return true;
10434         default:
10435                 return false;
10436         }
10437 }
10438
10439 static bool is_preallocated_map(struct bpf_map *map)
10440 {
10441         if (!check_map_prealloc(map))
10442                 return false;
10443         if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10444                 return false;
10445         return true;
10446 }
10447
10448 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10449                                         struct bpf_map *map,
10450                                         struct bpf_prog *prog)
10451
10452 {
10453         enum bpf_prog_type prog_type = resolve_prog_type(prog);
10454         /*
10455          * Validate that trace type programs use preallocated hash maps.
10456          *
10457          * For programs attached to PERF events this is mandatory as the
10458          * perf NMI can hit any arbitrary code sequence.
10459          *
10460          * All other trace types using preallocated hash maps are unsafe as
10461          * well because tracepoint or kprobes can be inside locked regions
10462          * of the memory allocator or at a place where a recursion into the
10463          * memory allocator would see inconsistent state.
10464          *
10465          * On RT enabled kernels run-time allocation of all trace type
10466          * programs is strictly prohibited due to lock type constraints. On
10467          * !RT kernels it is allowed for backwards compatibility reasons for
10468          * now, but warnings are emitted so developers are made aware of
10469          * the unsafety and can fix their programs before this is enforced.
10470          */
10471         if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10472                 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10473                         verbose(env, "perf_event programs can only use preallocated hash map\n");
10474                         return -EINVAL;
10475                 }
10476                 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10477                         verbose(env, "trace type programs can only use preallocated hash map\n");
10478                         return -EINVAL;
10479                 }
10480                 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10481                 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10482         }
10483
10484         if ((is_tracing_prog_type(prog_type) ||
10485              prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
10486             map_value_has_spin_lock(map)) {
10487                 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10488                 return -EINVAL;
10489         }
10490
10491         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10492             !bpf_offload_prog_map_match(prog, map)) {
10493                 verbose(env, "offload device mismatch between prog and map\n");
10494                 return -EINVAL;
10495         }
10496
10497         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10498                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10499                 return -EINVAL;
10500         }
10501
10502         if (prog->aux->sleepable)
10503                 switch (map->map_type) {
10504                 case BPF_MAP_TYPE_HASH:
10505                 case BPF_MAP_TYPE_LRU_HASH:
10506                 case BPF_MAP_TYPE_ARRAY:
10507                         if (!is_preallocated_map(map)) {
10508                                 verbose(env,
10509                                         "Sleepable programs can only use preallocated hash maps\n");
10510                                 return -EINVAL;
10511                         }
10512                         break;
10513                 default:
10514                         verbose(env,
10515                                 "Sleepable programs can only use array and hash maps\n");
10516                         return -EINVAL;
10517                 }
10518
10519         return 0;
10520 }
10521
10522 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10523 {
10524         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10525                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10526 }
10527
10528 /* find and rewrite pseudo imm in ld_imm64 instructions:
10529  *
10530  * 1. if it accesses map FD, replace it with actual map pointer.
10531  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10532  *
10533  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10534  */
10535 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10536 {
10537         struct bpf_insn *insn = env->prog->insnsi;
10538         int insn_cnt = env->prog->len;
10539         int i, j, err;
10540
10541         err = bpf_prog_calc_tag(env->prog);
10542         if (err)
10543                 return err;
10544
10545         for (i = 0; i < insn_cnt; i++, insn++) {
10546                 if (BPF_CLASS(insn->code) == BPF_LDX &&
10547                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10548                         verbose(env, "BPF_LDX uses reserved fields\n");
10549                         return -EINVAL;
10550                 }
10551
10552                 if (BPF_CLASS(insn->code) == BPF_STX &&
10553                     ((BPF_MODE(insn->code) != BPF_MEM &&
10554                       BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
10555                         verbose(env, "BPF_STX uses reserved fields\n");
10556                         return -EINVAL;
10557                 }
10558
10559                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10560                         struct bpf_insn_aux_data *aux;
10561                         struct bpf_map *map;
10562                         struct fd f;
10563                         u64 addr;
10564
10565                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
10566                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10567                             insn[1].off != 0) {
10568                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
10569                                 return -EINVAL;
10570                         }
10571
10572                         if (insn[0].src_reg == 0)
10573                                 /* valid generic load 64-bit imm */
10574                                 goto next_insn;
10575
10576                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10577                                 aux = &env->insn_aux_data[i];
10578                                 err = check_pseudo_btf_id(env, insn, aux);
10579                                 if (err)
10580                                         return err;
10581                                 goto next_insn;
10582                         }
10583
10584                         /* In final convert_pseudo_ld_imm64() step, this is
10585                          * converted into regular 64-bit imm load insn.
10586                          */
10587                         if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10588                              insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10589                             (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10590                              insn[1].imm != 0)) {
10591                                 verbose(env,
10592                                         "unrecognized bpf_ld_imm64 insn\n");
10593                                 return -EINVAL;
10594                         }
10595
10596                         f = fdget(insn[0].imm);
10597                         map = __bpf_map_get(f);
10598                         if (IS_ERR(map)) {
10599                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
10600                                         insn[0].imm);
10601                                 return PTR_ERR(map);
10602                         }
10603
10604                         err = check_map_prog_compatibility(env, map, env->prog);
10605                         if (err) {
10606                                 fdput(f);
10607                                 return err;
10608                         }
10609
10610                         aux = &env->insn_aux_data[i];
10611                         if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10612                                 addr = (unsigned long)map;
10613                         } else {
10614                                 u32 off = insn[1].imm;
10615
10616                                 if (off >= BPF_MAX_VAR_OFF) {
10617                                         verbose(env, "direct value offset of %u is not allowed\n", off);
10618                                         fdput(f);
10619                                         return -EINVAL;
10620                                 }
10621
10622                                 if (!map->ops->map_direct_value_addr) {
10623                                         verbose(env, "no direct value access support for this map type\n");
10624                                         fdput(f);
10625                                         return -EINVAL;
10626                                 }
10627
10628                                 err = map->ops->map_direct_value_addr(map, &addr, off);
10629                                 if (err) {
10630                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10631                                                 map->value_size, off);
10632                                         fdput(f);
10633                                         return err;
10634                                 }
10635
10636                                 aux->map_off = off;
10637                                 addr += off;
10638                         }
10639
10640                         insn[0].imm = (u32)addr;
10641                         insn[1].imm = addr >> 32;
10642
10643                         /* check whether we recorded this map already */
10644                         for (j = 0; j < env->used_map_cnt; j++) {
10645                                 if (env->used_maps[j] == map) {
10646                                         aux->map_index = j;
10647                                         fdput(f);
10648                                         goto next_insn;
10649                                 }
10650                         }
10651
10652                         if (env->used_map_cnt >= MAX_USED_MAPS) {
10653                                 fdput(f);
10654                                 return -E2BIG;
10655                         }
10656
10657                         /* hold the map. If the program is rejected by verifier,
10658                          * the map will be released by release_maps() or it
10659                          * will be used by the valid program until it's unloaded
10660                          * and all maps are released in free_used_maps()
10661                          */
10662                         bpf_map_inc(map);
10663
10664                         aux->map_index = env->used_map_cnt;
10665                         env->used_maps[env->used_map_cnt++] = map;
10666
10667                         if (bpf_map_is_cgroup_storage(map) &&
10668                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
10669                                 verbose(env, "only one cgroup storage of each type is allowed\n");
10670                                 fdput(f);
10671                                 return -EBUSY;
10672                         }
10673
10674                         fdput(f);
10675 next_insn:
10676                         insn++;
10677                         i++;
10678                         continue;
10679                 }
10680
10681                 /* Basic sanity check before we invest more work here. */
10682                 if (!bpf_opcode_in_insntable(insn->code)) {
10683                         verbose(env, "unknown opcode %02x\n", insn->code);
10684                         return -EINVAL;
10685                 }
10686         }
10687
10688         /* now all pseudo BPF_LD_IMM64 instructions load valid
10689          * 'struct bpf_map *' into a register instead of user map_fd.
10690          * These pointers will be used later by verifier to validate map access.
10691          */
10692         return 0;
10693 }
10694
10695 /* drop refcnt of maps used by the rejected program */
10696 static void release_maps(struct bpf_verifier_env *env)
10697 {
10698         __bpf_free_used_maps(env->prog->aux, env->used_maps,
10699                              env->used_map_cnt);
10700 }
10701
10702 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10703 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10704 {
10705         struct bpf_insn *insn = env->prog->insnsi;
10706         int insn_cnt = env->prog->len;
10707         int i;
10708
10709         for (i = 0; i < insn_cnt; i++, insn++)
10710                 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10711                         insn->src_reg = 0;
10712 }
10713
10714 /* single env->prog->insni[off] instruction was replaced with the range
10715  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
10716  * [0, off) and [off, end) to new locations, so the patched range stays zero
10717  */
10718 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
10719                                  struct bpf_insn_aux_data *new_data,
10720                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
10721 {
10722         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
10723         struct bpf_insn *insn = new_prog->insnsi;
10724         u32 old_seen = old_data[off].seen;
10725         u32 prog_len;
10726         int i;
10727
10728         /* aux info at OFF always needs adjustment, no matter fast path
10729          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10730          * original insn at old prog.
10731          */
10732         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10733
10734         if (cnt == 1)
10735                 return;
10736         prog_len = new_prog->len;
10737
10738         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10739         memcpy(new_data + off + cnt - 1, old_data + off,
10740                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10741         for (i = off; i < off + cnt - 1; i++) {
10742                 /* Expand insni[off]'s seen count to the patched range. */
10743                 new_data[i].seen = old_seen;
10744                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10745         }
10746         env->insn_aux_data = new_data;
10747         vfree(old_data);
10748 }
10749
10750 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10751 {
10752         int i;
10753
10754         if (len == 1)
10755                 return;
10756         /* NOTE: fake 'exit' subprog should be updated as well. */
10757         for (i = 0; i <= env->subprog_cnt; i++) {
10758                 if (env->subprog_info[i].start <= off)
10759                         continue;
10760                 env->subprog_info[i].start += len - 1;
10761         }
10762 }
10763
10764 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
10765 {
10766         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10767         int i, sz = prog->aux->size_poke_tab;
10768         struct bpf_jit_poke_descriptor *desc;
10769
10770         for (i = 0; i < sz; i++) {
10771                 desc = &tab[i];
10772                 if (desc->insn_idx <= off)
10773                         continue;
10774                 desc->insn_idx += len - 1;
10775         }
10776 }
10777
10778 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10779                                             const struct bpf_insn *patch, u32 len)
10780 {
10781         struct bpf_prog *new_prog;
10782         struct bpf_insn_aux_data *new_data = NULL;
10783
10784         if (len > 1) {
10785                 new_data = vzalloc(array_size(env->prog->len + len - 1,
10786                                               sizeof(struct bpf_insn_aux_data)));
10787                 if (!new_data)
10788                         return NULL;
10789         }
10790
10791         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10792         if (IS_ERR(new_prog)) {
10793                 if (PTR_ERR(new_prog) == -ERANGE)
10794                         verbose(env,
10795                                 "insn %d cannot be patched due to 16-bit range\n",
10796                                 env->insn_aux_data[off].orig_idx);
10797                 vfree(new_data);
10798                 return NULL;
10799         }
10800         adjust_insn_aux_data(env, new_data, new_prog, off, len);
10801         adjust_subprog_starts(env, off, len);
10802         adjust_poke_descs(new_prog, off, len);
10803         return new_prog;
10804 }
10805
10806 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10807                                               u32 off, u32 cnt)
10808 {
10809         int i, j;
10810
10811         /* find first prog starting at or after off (first to remove) */
10812         for (i = 0; i < env->subprog_cnt; i++)
10813                 if (env->subprog_info[i].start >= off)
10814                         break;
10815         /* find first prog starting at or after off + cnt (first to stay) */
10816         for (j = i; j < env->subprog_cnt; j++)
10817                 if (env->subprog_info[j].start >= off + cnt)
10818                         break;
10819         /* if j doesn't start exactly at off + cnt, we are just removing
10820          * the front of previous prog
10821          */
10822         if (env->subprog_info[j].start != off + cnt)
10823                 j--;
10824
10825         if (j > i) {
10826                 struct bpf_prog_aux *aux = env->prog->aux;
10827                 int move;
10828
10829                 /* move fake 'exit' subprog as well */
10830                 move = env->subprog_cnt + 1 - j;
10831
10832                 memmove(env->subprog_info + i,
10833                         env->subprog_info + j,
10834                         sizeof(*env->subprog_info) * move);
10835                 env->subprog_cnt -= j - i;
10836
10837                 /* remove func_info */
10838                 if (aux->func_info) {
10839                         move = aux->func_info_cnt - j;
10840
10841                         memmove(aux->func_info + i,
10842                                 aux->func_info + j,
10843                                 sizeof(*aux->func_info) * move);
10844                         aux->func_info_cnt -= j - i;
10845                         /* func_info->insn_off is set after all code rewrites,
10846                          * in adjust_btf_func() - no need to adjust
10847                          */
10848                 }
10849         } else {
10850                 /* convert i from "first prog to remove" to "first to adjust" */
10851                 if (env->subprog_info[i].start == off)
10852                         i++;
10853         }
10854
10855         /* update fake 'exit' subprog as well */
10856         for (; i <= env->subprog_cnt; i++)
10857                 env->subprog_info[i].start -= cnt;
10858
10859         return 0;
10860 }
10861
10862 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10863                                       u32 cnt)
10864 {
10865         struct bpf_prog *prog = env->prog;
10866         u32 i, l_off, l_cnt, nr_linfo;
10867         struct bpf_line_info *linfo;
10868
10869         nr_linfo = prog->aux->nr_linfo;
10870         if (!nr_linfo)
10871                 return 0;
10872
10873         linfo = prog->aux->linfo;
10874
10875         /* find first line info to remove, count lines to be removed */
10876         for (i = 0; i < nr_linfo; i++)
10877                 if (linfo[i].insn_off >= off)
10878                         break;
10879
10880         l_off = i;
10881         l_cnt = 0;
10882         for (; i < nr_linfo; i++)
10883                 if (linfo[i].insn_off < off + cnt)
10884                         l_cnt++;
10885                 else
10886                         break;
10887
10888         /* First live insn doesn't match first live linfo, it needs to "inherit"
10889          * last removed linfo.  prog is already modified, so prog->len == off
10890          * means no live instructions after (tail of the program was removed).
10891          */
10892         if (prog->len != off && l_cnt &&
10893             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10894                 l_cnt--;
10895                 linfo[--i].insn_off = off + cnt;
10896         }
10897
10898         /* remove the line info which refer to the removed instructions */
10899         if (l_cnt) {
10900                 memmove(linfo + l_off, linfo + i,
10901                         sizeof(*linfo) * (nr_linfo - i));
10902
10903                 prog->aux->nr_linfo -= l_cnt;
10904                 nr_linfo = prog->aux->nr_linfo;
10905         }
10906
10907         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10908         for (i = l_off; i < nr_linfo; i++)
10909                 linfo[i].insn_off -= cnt;
10910
10911         /* fix up all subprogs (incl. 'exit') which start >= off */
10912         for (i = 0; i <= env->subprog_cnt; i++)
10913                 if (env->subprog_info[i].linfo_idx > l_off) {
10914                         /* program may have started in the removed region but
10915                          * may not be fully removed
10916                          */
10917                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10918                                 env->subprog_info[i].linfo_idx -= l_cnt;
10919                         else
10920                                 env->subprog_info[i].linfo_idx = l_off;
10921                 }
10922
10923         return 0;
10924 }
10925
10926 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10927 {
10928         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10929         unsigned int orig_prog_len = env->prog->len;
10930         int err;
10931
10932         if (bpf_prog_is_dev_bound(env->prog->aux))
10933                 bpf_prog_offload_remove_insns(env, off, cnt);
10934
10935         err = bpf_remove_insns(env->prog, off, cnt);
10936         if (err)
10937                 return err;
10938
10939         err = adjust_subprog_starts_after_remove(env, off, cnt);
10940         if (err)
10941                 return err;
10942
10943         err = bpf_adj_linfo_after_remove(env, off, cnt);
10944         if (err)
10945                 return err;
10946
10947         memmove(aux_data + off, aux_data + off + cnt,
10948                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10949
10950         return 0;
10951 }
10952
10953 /* The verifier does more data flow analysis than llvm and will not
10954  * explore branches that are dead at run time. Malicious programs can
10955  * have dead code too. Therefore replace all dead at-run-time code
10956  * with 'ja -1'.
10957  *
10958  * Just nops are not optimal, e.g. if they would sit at the end of the
10959  * program and through another bug we would manage to jump there, then
10960  * we'd execute beyond program memory otherwise. Returning exception
10961  * code also wouldn't work since we can have subprogs where the dead
10962  * code could be located.
10963  */
10964 static void sanitize_dead_code(struct bpf_verifier_env *env)
10965 {
10966         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10967         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
10968         struct bpf_insn *insn = env->prog->insnsi;
10969         const int insn_cnt = env->prog->len;
10970         int i;
10971
10972         for (i = 0; i < insn_cnt; i++) {
10973                 if (aux_data[i].seen)
10974                         continue;
10975                 memcpy(insn + i, &trap, sizeof(trap));
10976                 aux_data[i].zext_dst = false;
10977         }
10978 }
10979
10980 static bool insn_is_cond_jump(u8 code)
10981 {
10982         u8 op;
10983
10984         if (BPF_CLASS(code) == BPF_JMP32)
10985                 return true;
10986
10987         if (BPF_CLASS(code) != BPF_JMP)
10988                 return false;
10989
10990         op = BPF_OP(code);
10991         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10992 }
10993
10994 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10995 {
10996         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10997         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10998         struct bpf_insn *insn = env->prog->insnsi;
10999         const int insn_cnt = env->prog->len;
11000         int i;
11001
11002         for (i = 0; i < insn_cnt; i++, insn++) {
11003                 if (!insn_is_cond_jump(insn->code))
11004                         continue;
11005
11006                 if (!aux_data[i + 1].seen)
11007                         ja.off = insn->off;
11008                 else if (!aux_data[i + 1 + insn->off].seen)
11009                         ja.off = 0;
11010                 else
11011                         continue;
11012
11013                 if (bpf_prog_is_dev_bound(env->prog->aux))
11014                         bpf_prog_offload_replace_insn(env, i, &ja);
11015
11016                 memcpy(insn, &ja, sizeof(ja));
11017         }
11018 }
11019
11020 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11021 {
11022         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11023         int insn_cnt = env->prog->len;
11024         int i, err;
11025
11026         for (i = 0; i < insn_cnt; i++) {
11027                 int j;
11028
11029                 j = 0;
11030                 while (i + j < insn_cnt && !aux_data[i + j].seen)
11031                         j++;
11032                 if (!j)
11033                         continue;
11034
11035                 err = verifier_remove_insns(env, i, j);
11036                 if (err)
11037                         return err;
11038                 insn_cnt = env->prog->len;
11039         }
11040
11041         return 0;
11042 }
11043
11044 static int opt_remove_nops(struct bpf_verifier_env *env)
11045 {
11046         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11047         struct bpf_insn *insn = env->prog->insnsi;
11048         int insn_cnt = env->prog->len;
11049         int i, err;
11050
11051         for (i = 0; i < insn_cnt; i++) {
11052                 if (memcmp(&insn[i], &ja, sizeof(ja)))
11053                         continue;
11054
11055                 err = verifier_remove_insns(env, i, 1);
11056                 if (err)
11057                         return err;
11058                 insn_cnt--;
11059                 i--;
11060         }
11061
11062         return 0;
11063 }
11064
11065 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11066                                          const union bpf_attr *attr)
11067 {
11068         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11069         struct bpf_insn_aux_data *aux = env->insn_aux_data;
11070         int i, patch_len, delta = 0, len = env->prog->len;
11071         struct bpf_insn *insns = env->prog->insnsi;
11072         struct bpf_prog *new_prog;
11073         bool rnd_hi32;
11074
11075         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11076         zext_patch[1] = BPF_ZEXT_REG(0);
11077         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11078         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11079         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11080         for (i = 0; i < len; i++) {
11081                 int adj_idx = i + delta;
11082                 struct bpf_insn insn;
11083
11084                 insn = insns[adj_idx];
11085                 if (!aux[adj_idx].zext_dst) {
11086                         u8 code, class;
11087                         u32 imm_rnd;
11088
11089                         if (!rnd_hi32)
11090                                 continue;
11091
11092                         code = insn.code;
11093                         class = BPF_CLASS(code);
11094                         if (insn_no_def(&insn))
11095                                 continue;
11096
11097                         /* NOTE: arg "reg" (the fourth one) is only used for
11098                          *       BPF_STX which has been ruled out in above
11099                          *       check, it is safe to pass NULL here.
11100                          */
11101                         if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11102                                 if (class == BPF_LD &&
11103                                     BPF_MODE(code) == BPF_IMM)
11104                                         i++;
11105                                 continue;
11106                         }
11107
11108                         /* ctx load could be transformed into wider load. */
11109                         if (class == BPF_LDX &&
11110                             aux[adj_idx].ptr_type == PTR_TO_CTX)
11111                                 continue;
11112
11113                         imm_rnd = get_random_int();
11114                         rnd_hi32_patch[0] = insn;
11115                         rnd_hi32_patch[1].imm = imm_rnd;
11116                         rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11117                         patch = rnd_hi32_patch;
11118                         patch_len = 4;
11119                         goto apply_patch_buffer;
11120                 }
11121
11122                 if (!bpf_jit_needs_zext())
11123                         continue;
11124
11125                 zext_patch[0] = insn;
11126                 zext_patch[1].dst_reg = insn.dst_reg;
11127                 zext_patch[1].src_reg = insn.dst_reg;
11128                 patch = zext_patch;
11129                 patch_len = 2;
11130 apply_patch_buffer:
11131                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11132                 if (!new_prog)
11133                         return -ENOMEM;
11134                 env->prog = new_prog;
11135                 insns = new_prog->insnsi;
11136                 aux = env->insn_aux_data;
11137                 delta += patch_len - 1;
11138         }
11139
11140         return 0;
11141 }
11142
11143 /* convert load instructions that access fields of a context type into a
11144  * sequence of instructions that access fields of the underlying structure:
11145  *     struct __sk_buff    -> struct sk_buff
11146  *     struct bpf_sock_ops -> struct sock
11147  */
11148 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11149 {
11150         const struct bpf_verifier_ops *ops = env->ops;
11151         int i, cnt, size, ctx_field_size, delta = 0;
11152         const int insn_cnt = env->prog->len;
11153         struct bpf_insn insn_buf[16], *insn;
11154         u32 target_size, size_default, off;
11155         struct bpf_prog *new_prog;
11156         enum bpf_access_type type;
11157         bool is_narrower_load;
11158
11159         if (ops->gen_prologue || env->seen_direct_write) {
11160                 if (!ops->gen_prologue) {
11161                         verbose(env, "bpf verifier is misconfigured\n");
11162                         return -EINVAL;
11163                 }
11164                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11165                                         env->prog);
11166                 if (cnt >= ARRAY_SIZE(insn_buf)) {
11167                         verbose(env, "bpf verifier is misconfigured\n");
11168                         return -EINVAL;
11169                 } else if (cnt) {
11170                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11171                         if (!new_prog)
11172                                 return -ENOMEM;
11173
11174                         env->prog = new_prog;
11175                         delta += cnt - 1;
11176                 }
11177         }
11178
11179         if (bpf_prog_is_dev_bound(env->prog->aux))
11180                 return 0;
11181
11182         insn = env->prog->insnsi + delta;
11183
11184         for (i = 0; i < insn_cnt; i++, insn++) {
11185                 bpf_convert_ctx_access_t convert_ctx_access;
11186                 bool ctx_access;
11187
11188                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11189                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11190                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11191                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
11192                         type = BPF_READ;
11193                         ctx_access = true;
11194                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11195                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11196                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11197                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
11198                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
11199                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
11200                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
11201                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
11202                         type = BPF_WRITE;
11203                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
11204                 } else {
11205                         continue;
11206                 }
11207
11208                 if (type == BPF_WRITE &&
11209                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
11210                         struct bpf_insn patch[] = {
11211                                 *insn,
11212                                 BPF_ST_NOSPEC(),
11213                         };
11214
11215                         cnt = ARRAY_SIZE(patch);
11216                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11217                         if (!new_prog)
11218                                 return -ENOMEM;
11219
11220                         delta    += cnt - 1;
11221                         env->prog = new_prog;
11222                         insn      = new_prog->insnsi + i + delta;
11223                         continue;
11224                 }
11225
11226                 if (!ctx_access)
11227                         continue;
11228
11229                 switch (env->insn_aux_data[i + delta].ptr_type) {
11230                 case PTR_TO_CTX:
11231                         if (!ops->convert_ctx_access)
11232                                 continue;
11233                         convert_ctx_access = ops->convert_ctx_access;
11234                         break;
11235                 case PTR_TO_SOCKET:
11236                 case PTR_TO_SOCK_COMMON:
11237                         convert_ctx_access = bpf_sock_convert_ctx_access;
11238                         break;
11239                 case PTR_TO_TCP_SOCK:
11240                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11241                         break;
11242                 case PTR_TO_XDP_SOCK:
11243                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11244                         break;
11245                 case PTR_TO_BTF_ID:
11246                         if (type == BPF_READ) {
11247                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
11248                                         BPF_SIZE((insn)->code);
11249                                 env->prog->aux->num_exentries++;
11250                         } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11251                                 verbose(env, "Writes through BTF pointers are not allowed\n");
11252                                 return -EINVAL;
11253                         }
11254                         continue;
11255                 default:
11256                         continue;
11257                 }
11258
11259                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11260                 size = BPF_LDST_BYTES(insn);
11261
11262                 /* If the read access is a narrower load of the field,
11263                  * convert to a 4/8-byte load, to minimum program type specific
11264                  * convert_ctx_access changes. If conversion is successful,
11265                  * we will apply proper mask to the result.
11266                  */
11267                 is_narrower_load = size < ctx_field_size;
11268                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11269                 off = insn->off;
11270                 if (is_narrower_load) {
11271                         u8 size_code;
11272
11273                         if (type == BPF_WRITE) {
11274                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11275                                 return -EINVAL;
11276                         }
11277
11278                         size_code = BPF_H;
11279                         if (ctx_field_size == 4)
11280                                 size_code = BPF_W;
11281                         else if (ctx_field_size == 8)
11282                                 size_code = BPF_DW;
11283
11284                         insn->off = off & ~(size_default - 1);
11285                         insn->code = BPF_LDX | BPF_MEM | size_code;
11286                 }
11287
11288                 target_size = 0;
11289                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11290                                          &target_size);
11291                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11292                     (ctx_field_size && !target_size)) {
11293                         verbose(env, "bpf verifier is misconfigured\n");
11294                         return -EINVAL;
11295                 }
11296
11297                 if (is_narrower_load && size < target_size) {
11298                         u8 shift = bpf_ctx_narrow_access_offset(
11299                                 off, size, size_default) * 8;
11300                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
11301                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
11302                                 return -EINVAL;
11303                         }
11304                         if (ctx_field_size <= 4) {
11305                                 if (shift)
11306                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11307                                                                         insn->dst_reg,
11308                                                                         shift);
11309                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11310                                                                 (1 << size * 8) - 1);
11311                         } else {
11312                                 if (shift)
11313                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11314                                                                         insn->dst_reg,
11315                                                                         shift);
11316                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11317                                                                 (1ULL << size * 8) - 1);
11318                         }
11319                 }
11320
11321                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11322                 if (!new_prog)
11323                         return -ENOMEM;
11324
11325                 delta += cnt - 1;
11326
11327                 /* keep walking new program and skip insns we just inserted */
11328                 env->prog = new_prog;
11329                 insn      = new_prog->insnsi + i + delta;
11330         }
11331
11332         return 0;
11333 }
11334
11335 static int jit_subprogs(struct bpf_verifier_env *env)
11336 {
11337         struct bpf_prog *prog = env->prog, **func, *tmp;
11338         int i, j, subprog_start, subprog_end = 0, len, subprog;
11339         struct bpf_map *map_ptr;
11340         struct bpf_insn *insn;
11341         void *old_bpf_func;
11342         int err, num_exentries;
11343
11344         if (env->subprog_cnt <= 1)
11345                 return 0;
11346
11347         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11348                 if (insn->code != (BPF_JMP | BPF_CALL) ||
11349                     insn->src_reg != BPF_PSEUDO_CALL)
11350                         continue;
11351                 /* Upon error here we cannot fall back to interpreter but
11352                  * need a hard reject of the program. Thus -EFAULT is
11353                  * propagated in any case.
11354                  */
11355                 subprog = find_subprog(env, i + insn->imm + 1);
11356                 if (subprog < 0) {
11357                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11358                                   i + insn->imm + 1);
11359                         return -EFAULT;
11360                 }
11361                 /* temporarily remember subprog id inside insn instead of
11362                  * aux_data, since next loop will split up all insns into funcs
11363                  */
11364                 insn->off = subprog;
11365                 /* remember original imm in case JIT fails and fallback
11366                  * to interpreter will be needed
11367                  */
11368                 env->insn_aux_data[i].call_imm = insn->imm;
11369                 /* point imm to __bpf_call_base+1 from JITs point of view */
11370                 insn->imm = 1;
11371         }
11372
11373         err = bpf_prog_alloc_jited_linfo(prog);
11374         if (err)
11375                 goto out_undo_insn;
11376
11377         err = -ENOMEM;
11378         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11379         if (!func)
11380                 goto out_undo_insn;
11381
11382         for (i = 0; i < env->subprog_cnt; i++) {
11383                 subprog_start = subprog_end;
11384                 subprog_end = env->subprog_info[i + 1].start;
11385
11386                 len = subprog_end - subprog_start;
11387                 /* BPF_PROG_RUN doesn't call subprogs directly,
11388                  * hence main prog stats include the runtime of subprogs.
11389                  * subprogs don't have IDs and not reachable via prog_get_next_id
11390                  * func[i]->aux->stats will never be accessed and stays NULL
11391                  */
11392                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11393                 if (!func[i])
11394                         goto out_free;
11395                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11396                        len * sizeof(struct bpf_insn));
11397                 func[i]->type = prog->type;
11398                 func[i]->len = len;
11399                 if (bpf_prog_calc_tag(func[i]))
11400                         goto out_free;
11401                 func[i]->is_func = 1;
11402                 func[i]->aux->func_idx = i;
11403                 /* Below members will be freed only at prog->aux */
11404                 func[i]->aux->btf = prog->aux->btf;
11405                 func[i]->aux->func_info = prog->aux->func_info;
11406                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
11407                 func[i]->aux->poke_tab = prog->aux->poke_tab;
11408                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
11409
11410                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11411                         struct bpf_jit_poke_descriptor *poke;
11412
11413                         poke = &prog->aux->poke_tab[j];
11414                         if (poke->insn_idx < subprog_end &&
11415                             poke->insn_idx >= subprog_start)
11416                                 poke->aux = func[i]->aux;
11417                 }
11418
11419                 func[i]->aux->name[0] = 'F';
11420                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11421                 func[i]->jit_requested = 1;
11422                 func[i]->aux->linfo = prog->aux->linfo;
11423                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11424                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11425                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11426                 num_exentries = 0;
11427                 insn = func[i]->insnsi;
11428                 for (j = 0; j < func[i]->len; j++, insn++) {
11429                         if (BPF_CLASS(insn->code) == BPF_LDX &&
11430                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
11431                                 num_exentries++;
11432                 }
11433                 func[i]->aux->num_exentries = num_exentries;
11434                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11435                 func[i] = bpf_int_jit_compile(func[i]);
11436                 if (!func[i]->jited) {
11437                         err = -ENOTSUPP;
11438                         goto out_free;
11439                 }
11440                 cond_resched();
11441         }
11442
11443         /* at this point all bpf functions were successfully JITed
11444          * now populate all bpf_calls with correct addresses and
11445          * run last pass of JIT
11446          */
11447         for (i = 0; i < env->subprog_cnt; i++) {
11448                 insn = func[i]->insnsi;
11449                 for (j = 0; j < func[i]->len; j++, insn++) {
11450                         if (insn->code != (BPF_JMP | BPF_CALL) ||
11451                             insn->src_reg != BPF_PSEUDO_CALL)
11452                                 continue;
11453                         subprog = insn->off;
11454                         insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11455                                     __bpf_call_base;
11456                 }
11457
11458                 /* we use the aux data to keep a list of the start addresses
11459                  * of the JITed images for each function in the program
11460                  *
11461                  * for some architectures, such as powerpc64, the imm field
11462                  * might not be large enough to hold the offset of the start
11463                  * address of the callee's JITed image from __bpf_call_base
11464                  *
11465                  * in such cases, we can lookup the start address of a callee
11466                  * by using its subprog id, available from the off field of
11467                  * the call instruction, as an index for this list
11468                  */
11469                 func[i]->aux->func = func;
11470                 func[i]->aux->func_cnt = env->subprog_cnt;
11471         }
11472         for (i = 0; i < env->subprog_cnt; i++) {
11473                 old_bpf_func = func[i]->bpf_func;
11474                 tmp = bpf_int_jit_compile(func[i]);
11475                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11476                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11477                         err = -ENOTSUPP;
11478                         goto out_free;
11479                 }
11480                 cond_resched();
11481         }
11482
11483         /* finally lock prog and jit images for all functions and
11484          * populate kallsysm
11485          */
11486         for (i = 0; i < env->subprog_cnt; i++) {
11487                 bpf_prog_lock_ro(func[i]);
11488                 bpf_prog_kallsyms_add(func[i]);
11489         }
11490
11491         /* Last step: make now unused interpreter insns from main
11492          * prog consistent for later dump requests, so they can
11493          * later look the same as if they were interpreted only.
11494          */
11495         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11496                 if (insn->code != (BPF_JMP | BPF_CALL) ||
11497                     insn->src_reg != BPF_PSEUDO_CALL)
11498                         continue;
11499                 insn->off = env->insn_aux_data[i].call_imm;
11500                 subprog = find_subprog(env, i + insn->off + 1);
11501                 insn->imm = subprog;
11502         }
11503
11504         prog->jited = 1;
11505         prog->bpf_func = func[0]->bpf_func;
11506         prog->aux->func = func;
11507         prog->aux->func_cnt = env->subprog_cnt;
11508         bpf_prog_free_unused_jited_linfo(prog);
11509         return 0;
11510 out_free:
11511         /* We failed JIT'ing, so at this point we need to unregister poke
11512          * descriptors from subprogs, so that kernel is not attempting to
11513          * patch it anymore as we're freeing the subprog JIT memory.
11514          */
11515         for (i = 0; i < prog->aux->size_poke_tab; i++) {
11516                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11517                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11518         }
11519         /* At this point we're guaranteed that poke descriptors are not
11520          * live anymore. We can just unlink its descriptor table as it's
11521          * released with the main prog.
11522          */
11523         for (i = 0; i < env->subprog_cnt; i++) {
11524                 if (!func[i])
11525                         continue;
11526                 func[i]->aux->poke_tab = NULL;
11527                 bpf_jit_free(func[i]);
11528         }
11529         kfree(func);
11530 out_undo_insn:
11531         /* cleanup main prog to be interpreted */
11532         prog->jit_requested = 0;
11533         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11534                 if (insn->code != (BPF_JMP | BPF_CALL) ||
11535                     insn->src_reg != BPF_PSEUDO_CALL)
11536                         continue;
11537                 insn->off = 0;
11538                 insn->imm = env->insn_aux_data[i].call_imm;
11539         }
11540         bpf_prog_free_jited_linfo(prog);
11541         return err;
11542 }
11543
11544 static int fixup_call_args(struct bpf_verifier_env *env)
11545 {
11546 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11547         struct bpf_prog *prog = env->prog;
11548         struct bpf_insn *insn = prog->insnsi;
11549         int i, depth;
11550 #endif
11551         int err = 0;
11552
11553         if (env->prog->jit_requested &&
11554             !bpf_prog_is_dev_bound(env->prog->aux)) {
11555                 err = jit_subprogs(env);
11556                 if (err == 0)
11557                         return 0;
11558                 if (err == -EFAULT)
11559                         return err;
11560         }
11561 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11562         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11563                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11564                  * have to be rejected, since interpreter doesn't support them yet.
11565                  */
11566                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11567                 return -EINVAL;
11568         }
11569         for (i = 0; i < prog->len; i++, insn++) {
11570                 if (insn->code != (BPF_JMP | BPF_CALL) ||
11571                     insn->src_reg != BPF_PSEUDO_CALL)
11572                         continue;
11573                 depth = get_callee_stack_depth(env, insn, i);
11574                 if (depth < 0)
11575                         return depth;
11576                 bpf_patch_call_args(insn, depth);
11577         }
11578         err = 0;
11579 #endif
11580         return err;
11581 }
11582
11583 /* fixup insn->imm field of bpf_call instructions
11584  * and inline eligible helpers as explicit sequence of BPF instructions
11585  *
11586  * this function is called after eBPF program passed verification
11587  */
11588 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11589 {
11590         struct bpf_prog *prog = env->prog;
11591         bool expect_blinding = bpf_jit_blinding_enabled(prog);
11592         struct bpf_insn *insn = prog->insnsi;
11593         const struct bpf_func_proto *fn;
11594         const int insn_cnt = prog->len;
11595         const struct bpf_map_ops *ops;
11596         struct bpf_insn_aux_data *aux;
11597         struct bpf_insn insn_buf[16];
11598         struct bpf_prog *new_prog;
11599         struct bpf_map *map_ptr;
11600         int i, ret, cnt, delta = 0;
11601
11602         for (i = 0; i < insn_cnt; i++, insn++) {
11603                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11604                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11605                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11606                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11607                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11608                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11609                         struct bpf_insn *patchlet;
11610                         struct bpf_insn chk_and_div[] = {
11611                                 /* [R,W]x div 0 -> 0 */
11612                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11613                                              BPF_JNE | BPF_K, insn->src_reg,
11614                                              0, 2, 0),
11615                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11616                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11617                                 *insn,
11618                         };
11619                         struct bpf_insn chk_and_mod[] = {
11620                                 /* [R,W]x mod 0 -> [R,W]x */
11621                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11622                                              BPF_JEQ | BPF_K, insn->src_reg,
11623                                              0, 1 + (is64 ? 0 : 1), 0),
11624                                 *insn,
11625                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11626                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11627                         };
11628
11629                         patchlet = isdiv ? chk_and_div : chk_and_mod;
11630                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11631                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11632
11633                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11634                         if (!new_prog)
11635                                 return -ENOMEM;
11636
11637                         delta    += cnt - 1;
11638                         env->prog = prog = new_prog;
11639                         insn      = new_prog->insnsi + i + delta;
11640                         continue;
11641                 }
11642
11643                 if (BPF_CLASS(insn->code) == BPF_LD &&
11644                     (BPF_MODE(insn->code) == BPF_ABS ||
11645                      BPF_MODE(insn->code) == BPF_IND)) {
11646                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
11647                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11648                                 verbose(env, "bpf verifier is misconfigured\n");
11649                                 return -EINVAL;
11650                         }
11651
11652                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11653                         if (!new_prog)
11654                                 return -ENOMEM;
11655
11656                         delta    += cnt - 1;
11657                         env->prog = prog = new_prog;
11658                         insn      = new_prog->insnsi + i + delta;
11659                         continue;
11660                 }
11661
11662                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11663                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11664                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11665                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11666                         struct bpf_insn insn_buf[16];
11667                         struct bpf_insn *patch = &insn_buf[0];
11668                         bool issrc, isneg, isimm;
11669                         u32 off_reg;
11670
11671                         aux = &env->insn_aux_data[i + delta];
11672                         if (!aux->alu_state ||
11673                             aux->alu_state == BPF_ALU_NON_POINTER)
11674                                 continue;
11675
11676                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11677                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11678                                 BPF_ALU_SANITIZE_SRC;
11679                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
11680
11681                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
11682                         if (isimm) {
11683                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11684                         } else {
11685                                 if (isneg)
11686                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11687                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11688                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11689                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11690                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11691                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11692                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
11693                         }
11694                         if (!issrc)
11695                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
11696                         insn->src_reg = BPF_REG_AX;
11697                         if (isneg)
11698                                 insn->code = insn->code == code_add ?
11699                                              code_sub : code_add;
11700                         *patch++ = *insn;
11701                         if (issrc && isneg && !isimm)
11702                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11703                         cnt = patch - insn_buf;
11704
11705                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11706                         if (!new_prog)
11707                                 return -ENOMEM;
11708
11709                         delta    += cnt - 1;
11710                         env->prog = prog = new_prog;
11711                         insn      = new_prog->insnsi + i + delta;
11712                         continue;
11713                 }
11714
11715                 if (insn->code != (BPF_JMP | BPF_CALL))
11716                         continue;
11717                 if (insn->src_reg == BPF_PSEUDO_CALL)
11718                         continue;
11719
11720                 if (insn->imm == BPF_FUNC_get_route_realm)
11721                         prog->dst_needed = 1;
11722                 if (insn->imm == BPF_FUNC_get_prandom_u32)
11723                         bpf_user_rnd_init_once();
11724                 if (insn->imm == BPF_FUNC_override_return)
11725                         prog->kprobe_override = 1;
11726                 if (insn->imm == BPF_FUNC_tail_call) {
11727                         /* If we tail call into other programs, we
11728                          * cannot make any assumptions since they can
11729                          * be replaced dynamically during runtime in
11730                          * the program array.
11731                          */
11732                         prog->cb_access = 1;
11733                         if (!allow_tail_call_in_subprogs(env))
11734                                 prog->aux->stack_depth = MAX_BPF_STACK;
11735                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11736
11737                         /* mark bpf_tail_call as different opcode to avoid
11738                          * conditional branch in the interpeter for every normal
11739                          * call and to prevent accidental JITing by JIT compiler
11740                          * that doesn't support bpf_tail_call yet
11741                          */
11742                         insn->imm = 0;
11743                         insn->code = BPF_JMP | BPF_TAIL_CALL;
11744
11745                         aux = &env->insn_aux_data[i + delta];
11746                         if (env->bpf_capable && !expect_blinding &&
11747                             prog->jit_requested &&
11748                             !bpf_map_key_poisoned(aux) &&
11749                             !bpf_map_ptr_poisoned(aux) &&
11750                             !bpf_map_ptr_unpriv(aux)) {
11751                                 struct bpf_jit_poke_descriptor desc = {
11752                                         .reason = BPF_POKE_REASON_TAIL_CALL,
11753                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11754                                         .tail_call.key = bpf_map_key_immediate(aux),
11755                                         .insn_idx = i + delta,
11756                                 };
11757
11758                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11759                                 if (ret < 0) {
11760                                         verbose(env, "adding tail call poke descriptor failed\n");
11761                                         return ret;
11762                                 }
11763
11764                                 insn->imm = ret + 1;
11765                                 continue;
11766                         }
11767
11768                         if (!bpf_map_ptr_unpriv(aux))
11769                                 continue;
11770
11771                         /* instead of changing every JIT dealing with tail_call
11772                          * emit two extra insns:
11773                          * if (index >= max_entries) goto out;
11774                          * index &= array->index_mask;
11775                          * to avoid out-of-bounds cpu speculation
11776                          */
11777                         if (bpf_map_ptr_poisoned(aux)) {
11778                                 verbose(env, "tail_call abusing map_ptr\n");
11779                                 return -EINVAL;
11780                         }
11781
11782                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11783                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11784                                                   map_ptr->max_entries, 2);
11785                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11786                                                     container_of(map_ptr,
11787                                                                  struct bpf_array,
11788                                                                  map)->index_mask);
11789                         insn_buf[2] = *insn;
11790                         cnt = 3;
11791                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11792                         if (!new_prog)
11793                                 return -ENOMEM;
11794
11795                         delta    += cnt - 1;
11796                         env->prog = prog = new_prog;
11797                         insn      = new_prog->insnsi + i + delta;
11798                         continue;
11799                 }
11800
11801                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11802                  * and other inlining handlers are currently limited to 64 bit
11803                  * only.
11804                  */
11805                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11806                     (insn->imm == BPF_FUNC_map_lookup_elem ||
11807                      insn->imm == BPF_FUNC_map_update_elem ||
11808                      insn->imm == BPF_FUNC_map_delete_elem ||
11809                      insn->imm == BPF_FUNC_map_push_elem   ||
11810                      insn->imm == BPF_FUNC_map_pop_elem    ||
11811                      insn->imm == BPF_FUNC_map_peek_elem)) {
11812                         aux = &env->insn_aux_data[i + delta];
11813                         if (bpf_map_ptr_poisoned(aux))
11814                                 goto patch_call_imm;
11815
11816                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11817                         ops = map_ptr->ops;
11818                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
11819                             ops->map_gen_lookup) {
11820                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11821                                 if (cnt == -EOPNOTSUPP)
11822                                         goto patch_map_ops_generic;
11823                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11824                                         verbose(env, "bpf verifier is misconfigured\n");
11825                                         return -EINVAL;
11826                                 }
11827
11828                                 new_prog = bpf_patch_insn_data(env, i + delta,
11829                                                                insn_buf, cnt);
11830                                 if (!new_prog)
11831                                         return -ENOMEM;
11832
11833                                 delta    += cnt - 1;
11834                                 env->prog = prog = new_prog;
11835                                 insn      = new_prog->insnsi + i + delta;
11836                                 continue;
11837                         }
11838
11839                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11840                                      (void *(*)(struct bpf_map *map, void *key))NULL));
11841                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11842                                      (int (*)(struct bpf_map *map, void *key))NULL));
11843                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11844                                      (int (*)(struct bpf_map *map, void *key, void *value,
11845                                               u64 flags))NULL));
11846                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11847                                      (int (*)(struct bpf_map *map, void *value,
11848                                               u64 flags))NULL));
11849                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11850                                      (int (*)(struct bpf_map *map, void *value))NULL));
11851                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11852                                      (int (*)(struct bpf_map *map, void *value))NULL));
11853 patch_map_ops_generic:
11854                         switch (insn->imm) {
11855                         case BPF_FUNC_map_lookup_elem:
11856                                 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11857                                             __bpf_call_base;
11858                                 continue;
11859                         case BPF_FUNC_map_update_elem:
11860                                 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11861                                             __bpf_call_base;
11862                                 continue;
11863                         case BPF_FUNC_map_delete_elem:
11864                                 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11865                                             __bpf_call_base;
11866                                 continue;
11867                         case BPF_FUNC_map_push_elem:
11868                                 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11869                                             __bpf_call_base;
11870                                 continue;
11871                         case BPF_FUNC_map_pop_elem:
11872                                 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11873                                             __bpf_call_base;
11874                                 continue;
11875                         case BPF_FUNC_map_peek_elem:
11876                                 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11877                                             __bpf_call_base;
11878                                 continue;
11879                         }
11880
11881                         goto patch_call_imm;
11882                 }
11883
11884                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11885                     insn->imm == BPF_FUNC_jiffies64) {
11886                         struct bpf_insn ld_jiffies_addr[2] = {
11887                                 BPF_LD_IMM64(BPF_REG_0,
11888                                              (unsigned long)&jiffies),
11889                         };
11890
11891                         insn_buf[0] = ld_jiffies_addr[0];
11892                         insn_buf[1] = ld_jiffies_addr[1];
11893                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11894                                                   BPF_REG_0, 0);
11895                         cnt = 3;
11896
11897                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11898                                                        cnt);
11899                         if (!new_prog)
11900                                 return -ENOMEM;
11901
11902                         delta    += cnt - 1;
11903                         env->prog = prog = new_prog;
11904                         insn      = new_prog->insnsi + i + delta;
11905                         continue;
11906                 }
11907
11908 patch_call_imm:
11909                 fn = env->ops->get_func_proto(insn->imm, env->prog);
11910                 /* all functions that have prototype and verifier allowed
11911                  * programs to call them, must be real in-kernel functions
11912                  */
11913                 if (!fn->func) {
11914                         verbose(env,
11915                                 "kernel subsystem misconfigured func %s#%d\n",
11916                                 func_id_name(insn->imm), insn->imm);
11917                         return -EFAULT;
11918                 }
11919                 insn->imm = fn->func - __bpf_call_base;
11920         }
11921
11922         /* Since poke tab is now finalized, publish aux to tracker. */
11923         for (i = 0; i < prog->aux->size_poke_tab; i++) {
11924                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11925                 if (!map_ptr->ops->map_poke_track ||
11926                     !map_ptr->ops->map_poke_untrack ||
11927                     !map_ptr->ops->map_poke_run) {
11928                         verbose(env, "bpf verifier is misconfigured\n");
11929                         return -EINVAL;
11930                 }
11931
11932                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11933                 if (ret < 0) {
11934                         verbose(env, "tracking tail call prog failed\n");
11935                         return ret;
11936                 }
11937         }
11938
11939         return 0;
11940 }
11941
11942 static void free_states(struct bpf_verifier_env *env)
11943 {
11944         struct bpf_verifier_state_list *sl, *sln;
11945         int i;
11946
11947         sl = env->free_list;
11948         while (sl) {
11949                 sln = sl->next;
11950                 free_verifier_state(&sl->state, false);
11951                 kfree(sl);
11952                 sl = sln;
11953         }
11954         env->free_list = NULL;
11955
11956         if (!env->explored_states)
11957                 return;
11958
11959         for (i = 0; i < state_htab_size(env); i++) {
11960                 sl = env->explored_states[i];
11961
11962                 while (sl) {
11963                         sln = sl->next;
11964                         free_verifier_state(&sl->state, false);
11965                         kfree(sl);
11966                         sl = sln;
11967                 }
11968                 env->explored_states[i] = NULL;
11969         }
11970 }
11971
11972 static int do_check_common(struct bpf_verifier_env *env, int subprog)
11973 {
11974         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11975         struct bpf_verifier_state *state;
11976         struct bpf_reg_state *regs;
11977         int ret, i;
11978
11979         env->prev_linfo = NULL;
11980         env->pass_cnt++;
11981
11982         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11983         if (!state)
11984                 return -ENOMEM;
11985         state->curframe = 0;
11986         state->speculative = false;
11987         state->branches = 1;
11988         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11989         if (!state->frame[0]) {
11990                 kfree(state);
11991                 return -ENOMEM;
11992         }
11993         env->cur_state = state;
11994         init_func_state(env, state->frame[0],
11995                         BPF_MAIN_FUNC /* callsite */,
11996                         0 /* frameno */,
11997                         subprog);
11998
11999         state->first_insn_idx = env->subprog_info[subprog].start;
12000         state->last_insn_idx = -1;
12001
12002         regs = state->frame[state->curframe]->regs;
12003         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12004                 ret = btf_prepare_func_args(env, subprog, regs);
12005                 if (ret)
12006                         goto out;
12007                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12008                         if (regs[i].type == PTR_TO_CTX)
12009                                 mark_reg_known_zero(env, regs, i);
12010                         else if (regs[i].type == SCALAR_VALUE)
12011                                 mark_reg_unknown(env, regs, i);
12012                 }
12013         } else {
12014                 /* 1st arg to a function */
12015                 regs[BPF_REG_1].type = PTR_TO_CTX;
12016                 mark_reg_known_zero(env, regs, BPF_REG_1);
12017                 ret = btf_check_func_arg_match(env, subprog, regs);
12018                 if (ret == -EFAULT)
12019                         /* unlikely verifier bug. abort.
12020                          * ret == 0 and ret < 0 are sadly acceptable for
12021                          * main() function due to backward compatibility.
12022                          * Like socket filter program may be written as:
12023                          * int bpf_prog(struct pt_regs *ctx)
12024                          * and never dereference that ctx in the program.
12025                          * 'struct pt_regs' is a type mismatch for socket
12026                          * filter that should be using 'struct __sk_buff'.
12027                          */
12028                         goto out;
12029         }
12030
12031         ret = do_check(env);
12032 out:
12033         /* check for NULL is necessary, since cur_state can be freed inside
12034          * do_check() under memory pressure.
12035          */
12036         if (env->cur_state) {
12037                 free_verifier_state(env->cur_state, true);
12038                 env->cur_state = NULL;
12039         }
12040         while (!pop_stack(env, NULL, NULL, false));
12041         if (!ret && pop_log)
12042                 bpf_vlog_reset(&env->log, 0);
12043         free_states(env);
12044         return ret;
12045 }
12046
12047 /* Verify all global functions in a BPF program one by one based on their BTF.
12048  * All global functions must pass verification. Otherwise the whole program is rejected.
12049  * Consider:
12050  * int bar(int);
12051  * int foo(int f)
12052  * {
12053  *    return bar(f);
12054  * }
12055  * int bar(int b)
12056  * {
12057  *    ...
12058  * }
12059  * foo() will be verified first for R1=any_scalar_value. During verification it
12060  * will be assumed that bar() already verified successfully and call to bar()
12061  * from foo() will be checked for type match only. Later bar() will be verified
12062  * independently to check that it's safe for R1=any_scalar_value.
12063  */
12064 static int do_check_subprogs(struct bpf_verifier_env *env)
12065 {
12066         struct bpf_prog_aux *aux = env->prog->aux;
12067         int i, ret;
12068
12069         if (!aux->func_info)
12070                 return 0;
12071
12072         for (i = 1; i < env->subprog_cnt; i++) {
12073                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12074                         continue;
12075                 env->insn_idx = env->subprog_info[i].start;
12076                 WARN_ON_ONCE(env->insn_idx == 0);
12077                 ret = do_check_common(env, i);
12078                 if (ret) {
12079                         return ret;
12080                 } else if (env->log.level & BPF_LOG_LEVEL) {
12081                         verbose(env,
12082                                 "Func#%d is safe for any args that match its prototype\n",
12083                                 i);
12084                 }
12085         }
12086         return 0;
12087 }
12088
12089 static int do_check_main(struct bpf_verifier_env *env)
12090 {
12091         int ret;
12092
12093         env->insn_idx = 0;
12094         ret = do_check_common(env, 0);
12095         if (!ret)
12096                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12097         return ret;
12098 }
12099
12100
12101 static void print_verification_stats(struct bpf_verifier_env *env)
12102 {
12103         int i;
12104
12105         if (env->log.level & BPF_LOG_STATS) {
12106                 verbose(env, "verification time %lld usec\n",
12107                         div_u64(env->verification_time, 1000));
12108                 verbose(env, "stack depth ");
12109                 for (i = 0; i < env->subprog_cnt; i++) {
12110                         u32 depth = env->subprog_info[i].stack_depth;
12111
12112                         verbose(env, "%d", depth);
12113                         if (i + 1 < env->subprog_cnt)
12114                                 verbose(env, "+");
12115                 }
12116                 verbose(env, "\n");
12117         }
12118         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12119                 "total_states %d peak_states %d mark_read %d\n",
12120                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12121                 env->max_states_per_insn, env->total_states,
12122                 env->peak_states, env->longest_mark_read_walk);
12123 }
12124
12125 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12126 {
12127         const struct btf_type *t, *func_proto;
12128         const struct bpf_struct_ops *st_ops;
12129         const struct btf_member *member;
12130         struct bpf_prog *prog = env->prog;
12131         u32 btf_id, member_idx;
12132         const char *mname;
12133
12134         if (!prog->gpl_compatible) {
12135                 verbose(env, "struct ops programs must have a GPL compatible license\n");
12136                 return -EINVAL;
12137         }
12138
12139         btf_id = prog->aux->attach_btf_id;
12140         st_ops = bpf_struct_ops_find(btf_id);
12141         if (!st_ops) {
12142                 verbose(env, "attach_btf_id %u is not a supported struct\n",
12143                         btf_id);
12144                 return -ENOTSUPP;
12145         }
12146
12147         t = st_ops->type;
12148         member_idx = prog->expected_attach_type;
12149         if (member_idx >= btf_type_vlen(t)) {
12150                 verbose(env, "attach to invalid member idx %u of struct %s\n",
12151                         member_idx, st_ops->name);
12152                 return -EINVAL;
12153         }
12154
12155         member = &btf_type_member(t)[member_idx];
12156         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12157         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12158                                                NULL);
12159         if (!func_proto) {
12160                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12161                         mname, member_idx, st_ops->name);
12162                 return -EINVAL;
12163         }
12164
12165         if (st_ops->check_member) {
12166                 int err = st_ops->check_member(t, member);
12167
12168                 if (err) {
12169                         verbose(env, "attach to unsupported member %s of struct %s\n",
12170                                 mname, st_ops->name);
12171                         return err;
12172                 }
12173         }
12174
12175         prog->aux->attach_func_proto = func_proto;
12176         prog->aux->attach_func_name = mname;
12177         env->ops = st_ops->verifier_ops;
12178
12179         return 0;
12180 }
12181 #define SECURITY_PREFIX "security_"
12182
12183 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12184 {
12185         if (within_error_injection_list(addr) ||
12186             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12187                 return 0;
12188
12189         return -EINVAL;
12190 }
12191
12192 /* non exhaustive list of sleepable bpf_lsm_*() functions */
12193 BTF_SET_START(btf_sleepable_lsm_hooks)
12194 #ifdef CONFIG_BPF_LSM
12195 BTF_ID(func, bpf_lsm_bprm_committed_creds)
12196 #else
12197 BTF_ID_UNUSED
12198 #endif
12199 BTF_SET_END(btf_sleepable_lsm_hooks)
12200
12201 static int check_sleepable_lsm_hook(u32 btf_id)
12202 {
12203         return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
12204 }
12205
12206 /* list of non-sleepable functions that are otherwise on
12207  * ALLOW_ERROR_INJECTION list
12208  */
12209 BTF_SET_START(btf_non_sleepable_error_inject)
12210 /* Three functions below can be called from sleepable and non-sleepable context.
12211  * Assume non-sleepable from bpf safety point of view.
12212  */
12213 BTF_ID(func, __add_to_page_cache_locked)
12214 BTF_ID(func, should_fail_alloc_page)
12215 BTF_ID(func, should_failslab)
12216 BTF_SET_END(btf_non_sleepable_error_inject)
12217
12218 static int check_non_sleepable_error_inject(u32 btf_id)
12219 {
12220         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12221 }
12222
12223 int bpf_check_attach_target(struct bpf_verifier_log *log,
12224                             const struct bpf_prog *prog,
12225                             const struct bpf_prog *tgt_prog,
12226                             u32 btf_id,
12227                             struct bpf_attach_target_info *tgt_info)
12228 {
12229         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12230         const char prefix[] = "btf_trace_";
12231         int ret = 0, subprog = -1, i;
12232         const struct btf_type *t;
12233         bool conservative = true;
12234         const char *tname;
12235         struct btf *btf;
12236         long addr = 0;
12237
12238         if (!btf_id) {
12239                 bpf_log(log, "Tracing programs must provide btf_id\n");
12240                 return -EINVAL;
12241         }
12242         btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
12243         if (!btf) {
12244                 bpf_log(log,
12245                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12246                 return -EINVAL;
12247         }
12248         t = btf_type_by_id(btf, btf_id);
12249         if (!t) {
12250                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12251                 return -EINVAL;
12252         }
12253         tname = btf_name_by_offset(btf, t->name_off);
12254         if (!tname) {
12255                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12256                 return -EINVAL;
12257         }
12258         if (tgt_prog) {
12259                 struct bpf_prog_aux *aux = tgt_prog->aux;
12260
12261                 for (i = 0; i < aux->func_info_cnt; i++)
12262                         if (aux->func_info[i].type_id == btf_id) {
12263                                 subprog = i;
12264                                 break;
12265                         }
12266                 if (subprog == -1) {
12267                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
12268                         return -EINVAL;
12269                 }
12270                 conservative = aux->func_info_aux[subprog].unreliable;
12271                 if (prog_extension) {
12272                         if (conservative) {
12273                                 bpf_log(log,
12274                                         "Cannot replace static functions\n");
12275                                 return -EINVAL;
12276                         }
12277                         if (!prog->jit_requested) {
12278                                 bpf_log(log,
12279                                         "Extension programs should be JITed\n");
12280                                 return -EINVAL;
12281                         }
12282                 }
12283                 if (!tgt_prog->jited) {
12284                         bpf_log(log, "Can attach to only JITed progs\n");
12285                         return -EINVAL;
12286                 }
12287                 if (tgt_prog->type == prog->type) {
12288                         /* Cannot fentry/fexit another fentry/fexit program.
12289                          * Cannot attach program extension to another extension.
12290                          * It's ok to attach fentry/fexit to extension program.
12291                          */
12292                         bpf_log(log, "Cannot recursively attach\n");
12293                         return -EINVAL;
12294                 }
12295                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12296                     prog_extension &&
12297                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12298                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12299                         /* Program extensions can extend all program types
12300                          * except fentry/fexit. The reason is the following.
12301                          * The fentry/fexit programs are used for performance
12302                          * analysis, stats and can be attached to any program
12303                          * type except themselves. When extension program is
12304                          * replacing XDP function it is necessary to allow
12305                          * performance analysis of all functions. Both original
12306                          * XDP program and its program extension. Hence
12307                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12308                          * allowed. If extending of fentry/fexit was allowed it
12309                          * would be possible to create long call chain
12310                          * fentry->extension->fentry->extension beyond
12311                          * reasonable stack size. Hence extending fentry is not
12312                          * allowed.
12313                          */
12314                         bpf_log(log, "Cannot extend fentry/fexit\n");
12315                         return -EINVAL;
12316                 }
12317         } else {
12318                 if (prog_extension) {
12319                         bpf_log(log, "Cannot replace kernel functions\n");
12320                         return -EINVAL;
12321                 }
12322         }
12323
12324         switch (prog->expected_attach_type) {
12325         case BPF_TRACE_RAW_TP:
12326                 if (tgt_prog) {
12327                         bpf_log(log,
12328                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12329                         return -EINVAL;
12330                 }
12331                 if (!btf_type_is_typedef(t)) {
12332                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
12333                                 btf_id);
12334                         return -EINVAL;
12335                 }
12336                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12337                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12338                                 btf_id, tname);
12339                         return -EINVAL;
12340                 }
12341                 tname += sizeof(prefix) - 1;
12342                 t = btf_type_by_id(btf, t->type);
12343                 if (!btf_type_is_ptr(t))
12344                         /* should never happen in valid vmlinux build */
12345                         return -EINVAL;
12346                 t = btf_type_by_id(btf, t->type);
12347                 if (!btf_type_is_func_proto(t))
12348                         /* should never happen in valid vmlinux build */
12349                         return -EINVAL;
12350
12351                 break;
12352         case BPF_TRACE_ITER:
12353                 if (!btf_type_is_func(t)) {
12354                         bpf_log(log, "attach_btf_id %u is not a function\n",
12355                                 btf_id);
12356                         return -EINVAL;
12357                 }
12358                 t = btf_type_by_id(btf, t->type);
12359                 if (!btf_type_is_func_proto(t))
12360                         return -EINVAL;
12361                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12362                 if (ret)
12363                         return ret;
12364                 break;
12365         default:
12366                 if (!prog_extension)
12367                         return -EINVAL;
12368                 fallthrough;
12369         case BPF_MODIFY_RETURN:
12370         case BPF_LSM_MAC:
12371         case BPF_TRACE_FENTRY:
12372         case BPF_TRACE_FEXIT:
12373                 if (!btf_type_is_func(t)) {
12374                         bpf_log(log, "attach_btf_id %u is not a function\n",
12375                                 btf_id);
12376                         return -EINVAL;
12377                 }
12378                 if (prog_extension &&
12379                     btf_check_type_match(log, prog, btf, t))
12380                         return -EINVAL;
12381                 t = btf_type_by_id(btf, t->type);
12382                 if (!btf_type_is_func_proto(t))
12383                         return -EINVAL;
12384
12385                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12386                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12387                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12388                         return -EINVAL;
12389
12390                 if (tgt_prog && conservative)
12391                         t = NULL;
12392
12393                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12394                 if (ret < 0)
12395                         return ret;
12396
12397                 if (tgt_prog) {
12398                         if (subprog == 0)
12399                                 addr = (long) tgt_prog->bpf_func;
12400                         else
12401                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12402                 } else {
12403                         addr = kallsyms_lookup_name(tname);
12404                         if (!addr) {
12405                                 bpf_log(log,
12406                                         "The address of function %s cannot be found\n",
12407                                         tname);
12408                                 return -ENOENT;
12409                         }
12410                 }
12411
12412                 if (prog->aux->sleepable) {
12413                         ret = -EINVAL;
12414                         switch (prog->type) {
12415                         case BPF_PROG_TYPE_TRACING:
12416                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12417                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12418                                  */
12419                                 if (!check_non_sleepable_error_inject(btf_id) &&
12420                                     within_error_injection_list(addr))
12421                                         ret = 0;
12422                                 break;
12423                         case BPF_PROG_TYPE_LSM:
12424                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12425                                  * Only some of them are sleepable.
12426                                  */
12427                                 if (check_sleepable_lsm_hook(btf_id))
12428                                         ret = 0;
12429                                 break;
12430                         default:
12431                                 break;
12432                         }
12433                         if (ret) {
12434                                 bpf_log(log, "%s is not sleepable\n", tname);
12435                                 return ret;
12436                         }
12437                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12438                         if (tgt_prog) {
12439                                 bpf_log(log, "can't modify return codes of BPF programs\n");
12440                                 return -EINVAL;
12441                         }
12442                         ret = check_attach_modify_return(addr, tname);
12443                         if (ret) {
12444                                 bpf_log(log, "%s() is not modifiable\n", tname);
12445                                 return ret;
12446                         }
12447                 }
12448
12449                 break;
12450         }
12451         tgt_info->tgt_addr = addr;
12452         tgt_info->tgt_name = tname;
12453         tgt_info->tgt_type = t;
12454         return 0;
12455 }
12456
12457 static int check_attach_btf_id(struct bpf_verifier_env *env)
12458 {
12459         struct bpf_prog *prog = env->prog;
12460         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12461         struct bpf_attach_target_info tgt_info = {};
12462         u32 btf_id = prog->aux->attach_btf_id;
12463         struct bpf_trampoline *tr;
12464         int ret;
12465         u64 key;
12466
12467         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12468             prog->type != BPF_PROG_TYPE_LSM) {
12469                 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12470                 return -EINVAL;
12471         }
12472
12473         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12474                 return check_struct_ops_btf_id(env);
12475
12476         if (prog->type != BPF_PROG_TYPE_TRACING &&
12477             prog->type != BPF_PROG_TYPE_LSM &&
12478             prog->type != BPF_PROG_TYPE_EXT)
12479                 return 0;
12480
12481         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12482         if (ret)
12483                 return ret;
12484
12485         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12486                 /* to make freplace equivalent to their targets, they need to
12487                  * inherit env->ops and expected_attach_type for the rest of the
12488                  * verification
12489                  */
12490                 env->ops = bpf_verifier_ops[tgt_prog->type];
12491                 prog->expected_attach_type = tgt_prog->expected_attach_type;
12492         }
12493
12494         /* store info about the attachment target that will be used later */
12495         prog->aux->attach_func_proto = tgt_info.tgt_type;
12496         prog->aux->attach_func_name = tgt_info.tgt_name;
12497
12498         if (tgt_prog) {
12499                 prog->aux->saved_dst_prog_type = tgt_prog->type;
12500                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12501         }
12502
12503         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12504                 prog->aux->attach_btf_trace = true;
12505                 return 0;
12506         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12507                 if (!bpf_iter_prog_supported(prog))
12508                         return -EINVAL;
12509                 return 0;
12510         }
12511
12512         if (prog->type == BPF_PROG_TYPE_LSM) {
12513                 ret = bpf_lsm_verify_prog(&env->log, prog);
12514                 if (ret < 0)
12515                         return ret;
12516         }
12517
12518         key = bpf_trampoline_compute_key(tgt_prog, btf_id);
12519         tr = bpf_trampoline_get(key, &tgt_info);
12520         if (!tr)
12521                 return -ENOMEM;
12522
12523         prog->aux->dst_trampoline = tr;
12524         return 0;
12525 }
12526
12527 struct btf *bpf_get_btf_vmlinux(void)
12528 {
12529         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12530                 mutex_lock(&bpf_verifier_lock);
12531                 if (!btf_vmlinux)
12532                         btf_vmlinux = btf_parse_vmlinux();
12533                 mutex_unlock(&bpf_verifier_lock);
12534         }
12535         return btf_vmlinux;
12536 }
12537
12538 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12539               union bpf_attr __user *uattr)
12540 {
12541         u64 start_time = ktime_get_ns();
12542         struct bpf_verifier_env *env;
12543         struct bpf_verifier_log *log;
12544         int i, len, ret = -EINVAL;
12545         bool is_priv;
12546
12547         /* no program is valid */
12548         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12549                 return -EINVAL;
12550
12551         /* 'struct bpf_verifier_env' can be global, but since it's not small,
12552          * allocate/free it every time bpf_check() is called
12553          */
12554         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12555         if (!env)
12556                 return -ENOMEM;
12557         log = &env->log;
12558
12559         len = (*prog)->len;
12560         env->insn_aux_data =
12561                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12562         ret = -ENOMEM;
12563         if (!env->insn_aux_data)
12564                 goto err_free_env;
12565         for (i = 0; i < len; i++)
12566                 env->insn_aux_data[i].orig_idx = i;
12567         env->prog = *prog;
12568         env->ops = bpf_verifier_ops[env->prog->type];
12569         is_priv = bpf_capable();
12570
12571         bpf_get_btf_vmlinux();
12572
12573         /* grab the mutex to protect few globals used by verifier */
12574         if (!is_priv)
12575                 mutex_lock(&bpf_verifier_lock);
12576
12577         if (attr->log_level || attr->log_buf || attr->log_size) {
12578                 /* user requested verbose verifier output
12579                  * and supplied buffer to store the verification trace
12580                  */
12581                 log->level = attr->log_level;
12582                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12583                 log->len_total = attr->log_size;
12584
12585                 /* log attributes have to be sane */
12586                 if (!bpf_verifier_log_attr_valid(log)) {
12587                         ret = -EINVAL;
12588                         goto err_unlock;
12589                 }
12590         }
12591
12592         if (IS_ERR(btf_vmlinux)) {
12593                 /* Either gcc or pahole or kernel are broken. */
12594                 verbose(env, "in-kernel BTF is malformed\n");
12595                 ret = PTR_ERR(btf_vmlinux);
12596                 goto skip_full_check;
12597         }
12598
12599         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12600         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12601                 env->strict_alignment = true;
12602         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12603                 env->strict_alignment = false;
12604
12605         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12606         env->allow_uninit_stack = bpf_allow_uninit_stack();
12607         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12608         env->bypass_spec_v1 = bpf_bypass_spec_v1();
12609         env->bypass_spec_v4 = bpf_bypass_spec_v4();
12610         env->bpf_capable = bpf_capable();
12611
12612         if (is_priv)
12613                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12614
12615         env->explored_states = kvcalloc(state_htab_size(env),
12616                                        sizeof(struct bpf_verifier_state_list *),
12617                                        GFP_USER);
12618         ret = -ENOMEM;
12619         if (!env->explored_states)
12620                 goto skip_full_check;
12621
12622         ret = check_subprogs(env);
12623         if (ret < 0)
12624                 goto skip_full_check;
12625
12626         ret = check_btf_info(env, attr, uattr);
12627         if (ret < 0)
12628                 goto skip_full_check;
12629
12630         ret = check_attach_btf_id(env);
12631         if (ret)
12632                 goto skip_full_check;
12633
12634         ret = resolve_pseudo_ldimm64(env);
12635         if (ret < 0)
12636                 goto skip_full_check;
12637
12638         if (bpf_prog_is_dev_bound(env->prog->aux)) {
12639                 ret = bpf_prog_offload_verifier_prep(env->prog);
12640                 if (ret)
12641                         goto skip_full_check;
12642         }
12643
12644         ret = check_cfg(env);
12645         if (ret < 0)
12646                 goto skip_full_check;
12647
12648         ret = do_check_subprogs(env);
12649         ret = ret ?: do_check_main(env);
12650
12651         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12652                 ret = bpf_prog_offload_finalize(env);
12653
12654 skip_full_check:
12655         kvfree(env->explored_states);
12656
12657         if (ret == 0)
12658                 ret = check_max_stack_depth(env);
12659
12660         /* instruction rewrites happen after this point */
12661         if (is_priv) {
12662                 if (ret == 0)
12663                         opt_hard_wire_dead_code_branches(env);
12664                 if (ret == 0)
12665                         ret = opt_remove_dead_code(env);
12666                 if (ret == 0)
12667                         ret = opt_remove_nops(env);
12668         } else {
12669                 if (ret == 0)
12670                         sanitize_dead_code(env);
12671         }
12672
12673         if (ret == 0)
12674                 /* program is valid, convert *(u32*)(ctx + off) accesses */
12675                 ret = convert_ctx_accesses(env);
12676
12677         if (ret == 0)
12678                 ret = fixup_bpf_calls(env);
12679
12680         /* do 32-bit optimization after insn patching has done so those patched
12681          * insns could be handled correctly.
12682          */
12683         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12684                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12685                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12686                                                                      : false;
12687         }
12688
12689         if (ret == 0)
12690                 ret = fixup_call_args(env);
12691
12692         env->verification_time = ktime_get_ns() - start_time;
12693         print_verification_stats(env);
12694
12695         if (log->level && bpf_verifier_log_full(log))
12696                 ret = -ENOSPC;
12697         if (log->level && !log->ubuf) {
12698                 ret = -EFAULT;
12699                 goto err_release_maps;
12700         }
12701
12702         if (ret == 0 && env->used_map_cnt) {
12703                 /* if program passed verifier, update used_maps in bpf_prog_info */
12704                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12705                                                           sizeof(env->used_maps[0]),
12706                                                           GFP_KERNEL);
12707
12708                 if (!env->prog->aux->used_maps) {
12709                         ret = -ENOMEM;
12710                         goto err_release_maps;
12711                 }
12712
12713                 memcpy(env->prog->aux->used_maps, env->used_maps,
12714                        sizeof(env->used_maps[0]) * env->used_map_cnt);
12715                 env->prog->aux->used_map_cnt = env->used_map_cnt;
12716
12717                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12718                  * bpf_ld_imm64 instructions
12719                  */
12720                 convert_pseudo_ld_imm64(env);
12721         }
12722
12723         if (ret == 0)
12724                 adjust_btf_func(env);
12725
12726 err_release_maps:
12727         if (!env->prog->aux->used_maps)
12728                 /* if we didn't copy map pointers into bpf_prog_info, release
12729                  * them now. Otherwise free_used_maps() will release them.
12730                  */
12731                 release_maps(env);
12732
12733         /* extension progs temporarily inherit the attach_type of their targets
12734            for verification purposes, so set it back to zero before returning
12735          */
12736         if (env->prog->type == BPF_PROG_TYPE_EXT)
12737                 env->prog->expected_attach_type = 0;
12738
12739         *prog = env->prog;
12740 err_unlock:
12741         if (!is_priv)
12742                 mutex_unlock(&bpf_verifier_lock);
12743         vfree(env->insn_aux_data);
12744 err_free_env:
12745         kfree(env);
12746         return ret;
12747 }