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