GNU Linux-libre 5.13.14-gnu1
[releases.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
25
26 #include "disasm.h"
27
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30         [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
34 #undef BPF_PROG_TYPE
35 #undef BPF_MAP_TYPE
36 #undef BPF_LINK_TYPE
37 };
38
39 /* bpf_check() is a static code analyzer that walks eBPF program
40  * instruction by instruction and updates register/stack state.
41  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42  *
43  * The first pass is depth-first-search to check that the program is a DAG.
44  * It rejects the following programs:
45  * - larger than BPF_MAXINSNS insns
46  * - if loop is present (detected via back-edge)
47  * - unreachable insns exist (shouldn't be a forest. program = one function)
48  * - out of bounds or malformed jumps
49  * The second pass is all possible path descent from the 1st insn.
50  * Since it's analyzing all pathes through the program, the length of the
51  * analysis is limited to 64k insn, which may be hit even if total number of
52  * insn is less then 4K, but there are too many branches that change stack/regs.
53  * Number of 'branches to be analyzed' is limited to 1k
54  *
55  * On entry to each instruction, each register has a type, and the instruction
56  * changes the types of the registers depending on instruction semantics.
57  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58  * copied to R1.
59  *
60  * All registers are 64-bit.
61  * R0 - return register
62  * R1-R5 argument passing registers
63  * R6-R9 callee saved registers
64  * R10 - frame pointer read-only
65  *
66  * At the start of BPF program the register R1 contains a pointer to bpf_context
67  * and has type PTR_TO_CTX.
68  *
69  * Verifier tracks arithmetic operations on pointers in case:
70  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72  * 1st insn copies R10 (which has FRAME_PTR) type into R1
73  * and 2nd arithmetic instruction is pattern matched to recognize
74  * that it wants to construct a pointer to some element within stack.
75  * So after 2nd insn, the register R1 has type PTR_TO_STACK
76  * (and -20 constant is saved for further stack bounds checking).
77  * Meaning that this reg is a pointer to stack plus known immediate constant.
78  *
79  * Most of the time the registers have SCALAR_VALUE type, which
80  * means the register has some value, but it's not a valid pointer.
81  * (like pointer plus pointer becomes SCALAR_VALUE type)
82  *
83  * When verifier sees load or store instructions the type of base register
84  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85  * four pointer types recognized by check_mem_access() function.
86  *
87  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88  * and the range of [ptr, ptr + map's value_size) is accessible.
89  *
90  * registers used to pass values to function calls are checked against
91  * function argument constraints.
92  *
93  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94  * It means that the register type passed to this function must be
95  * PTR_TO_STACK and it will be used inside the function as
96  * 'pointer to map element key'
97  *
98  * For example the argument constraints for bpf_map_lookup_elem():
99  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100  *   .arg1_type = ARG_CONST_MAP_PTR,
101  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
102  *
103  * ret_type says that this function returns 'pointer to map elem value or null'
104  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105  * 2nd argument should be a pointer to stack, which will be used inside
106  * the helper function as a pointer to map element key.
107  *
108  * On the kernel side the helper function looks like:
109  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110  * {
111  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112  *    void *key = (void *) (unsigned long) r2;
113  *    void *value;
114  *
115  *    here kernel can access 'key' and 'map' pointers safely, knowing that
116  *    [key, key + map->key_size) bytes are valid and were initialized on
117  *    the stack of eBPF program.
118  * }
119  *
120  * Corresponding eBPF program may look like:
121  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
122  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
124  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125  * here verifier looks at prototype of map_lookup_elem() and sees:
126  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128  *
129  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131  * and were initialized prior to this call.
132  * If it's ok, then verifier allows this BPF_CALL insn and looks at
133  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135  * returns ether pointer to map value or NULL.
136  *
137  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138  * insn, the register holding that pointer in the true branch changes state to
139  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140  * branch. See check_cond_jmp_op().
141  *
142  * After the call R0 is set to return type of the function and registers R1-R5
143  * are set to NOT_INIT to indicate that they are no longer readable.
144  *
145  * The following reference types represent a potential reference to a kernel
146  * resource which, after first being allocated, must be checked and freed by
147  * the BPF program:
148  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149  *
150  * When the verifier sees a helper call return a reference type, it allocates a
151  * pointer id for the reference and stores it in the current function state.
152  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154  * passes through a NULL-check conditional. For the branch wherein the state is
155  * changed to CONST_IMM, the verifier releases the reference.
156  *
157  * For each helper function that allocates a reference, such as
158  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159  * bpf_sk_release(). When a reference type passes into the release function,
160  * the verifier also releases the reference. If any unchecked or unreleased
161  * reference remains at the end of the program, the verifier rejects it.
162  */
163
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem {
166         /* verifer state is 'st'
167          * before processing instruction 'insn_idx'
168          * and after processing instruction 'prev_insn_idx'
169          */
170         struct bpf_verifier_state st;
171         int insn_idx;
172         int prev_insn_idx;
173         struct bpf_verifier_stack_elem *next;
174         /* length of verifier log at the time this state was pushed on stack */
175         u32 log_pos;
176 };
177
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
179 #define BPF_COMPLEXITY_LIMIT_STATES     64
180
181 #define BPF_MAP_KEY_POISON      (1ULL << 63)
182 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
183
184 #define BPF_MAP_PTR_UNPRIV      1UL
185 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
186                                           POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188
189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190 {
191         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
192 }
193
194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195 {
196         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
197 }
198
199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200                               const struct bpf_map *map, bool unpriv)
201 {
202         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203         unpriv |= bpf_map_ptr_unpriv(aux);
204         aux->map_ptr_state = (unsigned long)map |
205                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206 }
207
208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209 {
210         return aux->map_key_state & BPF_MAP_KEY_POISON;
211 }
212
213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214 {
215         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216 }
217
218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219 {
220         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221 }
222
223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224 {
225         bool poisoned = bpf_map_key_poisoned(aux);
226
227         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
229 }
230
231 static bool bpf_pseudo_call(const struct bpf_insn *insn)
232 {
233         return insn->code == (BPF_JMP | BPF_CALL) &&
234                insn->src_reg == BPF_PSEUDO_CALL;
235 }
236
237 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
238 {
239         return insn->code == (BPF_JMP | BPF_CALL) &&
240                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
241 }
242
243 static bool bpf_pseudo_func(const struct bpf_insn *insn)
244 {
245         return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
246                insn->src_reg == BPF_PSEUDO_FUNC;
247 }
248
249 struct bpf_call_arg_meta {
250         struct bpf_map *map_ptr;
251         bool raw_mode;
252         bool pkt_access;
253         int regno;
254         int access_size;
255         int mem_size;
256         u64 msize_max_value;
257         int ref_obj_id;
258         int func_id;
259         struct btf *btf;
260         u32 btf_id;
261         struct btf *ret_btf;
262         u32 ret_btf_id;
263         u32 subprogno;
264 };
265
266 struct btf *btf_vmlinux;
267
268 static DEFINE_MUTEX(bpf_verifier_lock);
269
270 static const struct bpf_line_info *
271 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
272 {
273         const struct bpf_line_info *linfo;
274         const struct bpf_prog *prog;
275         u32 i, nr_linfo;
276
277         prog = env->prog;
278         nr_linfo = prog->aux->nr_linfo;
279
280         if (!nr_linfo || insn_off >= prog->len)
281                 return NULL;
282
283         linfo = prog->aux->linfo;
284         for (i = 1; i < nr_linfo; i++)
285                 if (insn_off < linfo[i].insn_off)
286                         break;
287
288         return &linfo[i - 1];
289 }
290
291 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
292                        va_list args)
293 {
294         unsigned int n;
295
296         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
297
298         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
299                   "verifier log line truncated - local buffer too short\n");
300
301         n = min(log->len_total - log->len_used - 1, n);
302         log->kbuf[n] = '\0';
303
304         if (log->level == BPF_LOG_KERNEL) {
305                 pr_err("BPF:%s\n", log->kbuf);
306                 return;
307         }
308         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
309                 log->len_used += n;
310         else
311                 log->ubuf = NULL;
312 }
313
314 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
315 {
316         char zero = 0;
317
318         if (!bpf_verifier_log_needed(log))
319                 return;
320
321         log->len_used = new_pos;
322         if (put_user(zero, log->ubuf + new_pos))
323                 log->ubuf = NULL;
324 }
325
326 /* log_level controls verbosity level of eBPF verifier.
327  * bpf_verifier_log_write() is used to dump the verification trace to the log,
328  * so the user can figure out what's wrong with the program
329  */
330 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
331                                            const char *fmt, ...)
332 {
333         va_list args;
334
335         if (!bpf_verifier_log_needed(&env->log))
336                 return;
337
338         va_start(args, fmt);
339         bpf_verifier_vlog(&env->log, fmt, args);
340         va_end(args);
341 }
342 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
343
344 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
345 {
346         struct bpf_verifier_env *env = private_data;
347         va_list args;
348
349         if (!bpf_verifier_log_needed(&env->log))
350                 return;
351
352         va_start(args, fmt);
353         bpf_verifier_vlog(&env->log, fmt, args);
354         va_end(args);
355 }
356
357 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
358                             const char *fmt, ...)
359 {
360         va_list args;
361
362         if (!bpf_verifier_log_needed(log))
363                 return;
364
365         va_start(args, fmt);
366         bpf_verifier_vlog(log, fmt, args);
367         va_end(args);
368 }
369
370 static const char *ltrim(const char *s)
371 {
372         while (isspace(*s))
373                 s++;
374
375         return s;
376 }
377
378 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
379                                          u32 insn_off,
380                                          const char *prefix_fmt, ...)
381 {
382         const struct bpf_line_info *linfo;
383
384         if (!bpf_verifier_log_needed(&env->log))
385                 return;
386
387         linfo = find_linfo(env, insn_off);
388         if (!linfo || linfo == env->prev_linfo)
389                 return;
390
391         if (prefix_fmt) {
392                 va_list args;
393
394                 va_start(args, prefix_fmt);
395                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
396                 va_end(args);
397         }
398
399         verbose(env, "%s\n",
400                 ltrim(btf_name_by_offset(env->prog->aux->btf,
401                                          linfo->line_off)));
402
403         env->prev_linfo = linfo;
404 }
405
406 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
407                                    struct bpf_reg_state *reg,
408                                    struct tnum *range, const char *ctx,
409                                    const char *reg_name)
410 {
411         char tn_buf[48];
412
413         verbose(env, "At %s the register %s ", ctx, reg_name);
414         if (!tnum_is_unknown(reg->var_off)) {
415                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
416                 verbose(env, "has value %s", tn_buf);
417         } else {
418                 verbose(env, "has unknown scalar value");
419         }
420         tnum_strn(tn_buf, sizeof(tn_buf), *range);
421         verbose(env, " should have been in %s\n", tn_buf);
422 }
423
424 static bool type_is_pkt_pointer(enum bpf_reg_type type)
425 {
426         return type == PTR_TO_PACKET ||
427                type == PTR_TO_PACKET_META;
428 }
429
430 static bool type_is_sk_pointer(enum bpf_reg_type type)
431 {
432         return type == PTR_TO_SOCKET ||
433                 type == PTR_TO_SOCK_COMMON ||
434                 type == PTR_TO_TCP_SOCK ||
435                 type == PTR_TO_XDP_SOCK;
436 }
437
438 static bool reg_type_not_null(enum bpf_reg_type type)
439 {
440         return type == PTR_TO_SOCKET ||
441                 type == PTR_TO_TCP_SOCK ||
442                 type == PTR_TO_MAP_VALUE ||
443                 type == PTR_TO_MAP_KEY ||
444                 type == PTR_TO_SOCK_COMMON;
445 }
446
447 static bool reg_type_may_be_null(enum bpf_reg_type type)
448 {
449         return type == PTR_TO_MAP_VALUE_OR_NULL ||
450                type == PTR_TO_SOCKET_OR_NULL ||
451                type == PTR_TO_SOCK_COMMON_OR_NULL ||
452                type == PTR_TO_TCP_SOCK_OR_NULL ||
453                type == PTR_TO_BTF_ID_OR_NULL ||
454                type == PTR_TO_MEM_OR_NULL ||
455                type == PTR_TO_RDONLY_BUF_OR_NULL ||
456                type == PTR_TO_RDWR_BUF_OR_NULL;
457 }
458
459 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
460 {
461         return reg->type == PTR_TO_MAP_VALUE &&
462                 map_value_has_spin_lock(reg->map_ptr);
463 }
464
465 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
466 {
467         return type == PTR_TO_SOCKET ||
468                 type == PTR_TO_SOCKET_OR_NULL ||
469                 type == PTR_TO_TCP_SOCK ||
470                 type == PTR_TO_TCP_SOCK_OR_NULL ||
471                 type == PTR_TO_MEM ||
472                 type == PTR_TO_MEM_OR_NULL;
473 }
474
475 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
476 {
477         return type == ARG_PTR_TO_SOCK_COMMON;
478 }
479
480 static bool arg_type_may_be_null(enum bpf_arg_type type)
481 {
482         return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
483                type == ARG_PTR_TO_MEM_OR_NULL ||
484                type == ARG_PTR_TO_CTX_OR_NULL ||
485                type == ARG_PTR_TO_SOCKET_OR_NULL ||
486                type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
487                type == ARG_PTR_TO_STACK_OR_NULL;
488 }
489
490 /* Determine whether the function releases some resources allocated by another
491  * function call. The first reference type argument will be assumed to be
492  * released by release_reference().
493  */
494 static bool is_release_function(enum bpf_func_id func_id)
495 {
496         return func_id == BPF_FUNC_sk_release ||
497                func_id == BPF_FUNC_ringbuf_submit ||
498                func_id == BPF_FUNC_ringbuf_discard;
499 }
500
501 static bool may_be_acquire_function(enum bpf_func_id func_id)
502 {
503         return func_id == BPF_FUNC_sk_lookup_tcp ||
504                 func_id == BPF_FUNC_sk_lookup_udp ||
505                 func_id == BPF_FUNC_skc_lookup_tcp ||
506                 func_id == BPF_FUNC_map_lookup_elem ||
507                 func_id == BPF_FUNC_ringbuf_reserve;
508 }
509
510 static bool is_acquire_function(enum bpf_func_id func_id,
511                                 const struct bpf_map *map)
512 {
513         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
514
515         if (func_id == BPF_FUNC_sk_lookup_tcp ||
516             func_id == BPF_FUNC_sk_lookup_udp ||
517             func_id == BPF_FUNC_skc_lookup_tcp ||
518             func_id == BPF_FUNC_ringbuf_reserve)
519                 return true;
520
521         if (func_id == BPF_FUNC_map_lookup_elem &&
522             (map_type == BPF_MAP_TYPE_SOCKMAP ||
523              map_type == BPF_MAP_TYPE_SOCKHASH))
524                 return true;
525
526         return false;
527 }
528
529 static bool is_ptr_cast_function(enum bpf_func_id func_id)
530 {
531         return func_id == BPF_FUNC_tcp_sock ||
532                 func_id == BPF_FUNC_sk_fullsock ||
533                 func_id == BPF_FUNC_skc_to_tcp_sock ||
534                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
535                 func_id == BPF_FUNC_skc_to_udp6_sock ||
536                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539
540 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
541 {
542         return BPF_CLASS(insn->code) == BPF_STX &&
543                BPF_MODE(insn->code) == BPF_ATOMIC &&
544                insn->imm == BPF_CMPXCHG;
545 }
546
547 /* string representation of 'enum bpf_reg_type' */
548 static const char * const reg_type_str[] = {
549         [NOT_INIT]              = "?",
550         [SCALAR_VALUE]          = "inv",
551         [PTR_TO_CTX]            = "ctx",
552         [CONST_PTR_TO_MAP]      = "map_ptr",
553         [PTR_TO_MAP_VALUE]      = "map_value",
554         [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
555         [PTR_TO_STACK]          = "fp",
556         [PTR_TO_PACKET]         = "pkt",
557         [PTR_TO_PACKET_META]    = "pkt_meta",
558         [PTR_TO_PACKET_END]     = "pkt_end",
559         [PTR_TO_FLOW_KEYS]      = "flow_keys",
560         [PTR_TO_SOCKET]         = "sock",
561         [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
562         [PTR_TO_SOCK_COMMON]    = "sock_common",
563         [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
564         [PTR_TO_TCP_SOCK]       = "tcp_sock",
565         [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
566         [PTR_TO_TP_BUFFER]      = "tp_buffer",
567         [PTR_TO_XDP_SOCK]       = "xdp_sock",
568         [PTR_TO_BTF_ID]         = "ptr_",
569         [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
570         [PTR_TO_PERCPU_BTF_ID]  = "percpu_ptr_",
571         [PTR_TO_MEM]            = "mem",
572         [PTR_TO_MEM_OR_NULL]    = "mem_or_null",
573         [PTR_TO_RDONLY_BUF]     = "rdonly_buf",
574         [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
575         [PTR_TO_RDWR_BUF]       = "rdwr_buf",
576         [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
577         [PTR_TO_FUNC]           = "func",
578         [PTR_TO_MAP_KEY]        = "map_key",
579 };
580
581 static char slot_type_char[] = {
582         [STACK_INVALID] = '?',
583         [STACK_SPILL]   = 'r',
584         [STACK_MISC]    = 'm',
585         [STACK_ZERO]    = '0',
586 };
587
588 static void print_liveness(struct bpf_verifier_env *env,
589                            enum bpf_reg_liveness live)
590 {
591         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
592             verbose(env, "_");
593         if (live & REG_LIVE_READ)
594                 verbose(env, "r");
595         if (live & REG_LIVE_WRITTEN)
596                 verbose(env, "w");
597         if (live & REG_LIVE_DONE)
598                 verbose(env, "D");
599 }
600
601 static struct bpf_func_state *func(struct bpf_verifier_env *env,
602                                    const struct bpf_reg_state *reg)
603 {
604         struct bpf_verifier_state *cur = env->cur_state;
605
606         return cur->frame[reg->frameno];
607 }
608
609 static const char *kernel_type_name(const struct btf* btf, u32 id)
610 {
611         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
612 }
613
614 static void print_verifier_state(struct bpf_verifier_env *env,
615                                  const struct bpf_func_state *state)
616 {
617         const struct bpf_reg_state *reg;
618         enum bpf_reg_type t;
619         int i;
620
621         if (state->frameno)
622                 verbose(env, " frame%d:", state->frameno);
623         for (i = 0; i < MAX_BPF_REG; i++) {
624                 reg = &state->regs[i];
625                 t = reg->type;
626                 if (t == NOT_INIT)
627                         continue;
628                 verbose(env, " R%d", i);
629                 print_liveness(env, reg->live);
630                 verbose(env, "=%s", reg_type_str[t]);
631                 if (t == SCALAR_VALUE && reg->precise)
632                         verbose(env, "P");
633                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
634                     tnum_is_const(reg->var_off)) {
635                         /* reg->off should be 0 for SCALAR_VALUE */
636                         verbose(env, "%lld", reg->var_off.value + reg->off);
637                 } else {
638                         if (t == PTR_TO_BTF_ID ||
639                             t == PTR_TO_BTF_ID_OR_NULL ||
640                             t == PTR_TO_PERCPU_BTF_ID)
641                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
642                         verbose(env, "(id=%d", reg->id);
643                         if (reg_type_may_be_refcounted_or_null(t))
644                                 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
645                         if (t != SCALAR_VALUE)
646                                 verbose(env, ",off=%d", reg->off);
647                         if (type_is_pkt_pointer(t))
648                                 verbose(env, ",r=%d", reg->range);
649                         else if (t == CONST_PTR_TO_MAP ||
650                                  t == PTR_TO_MAP_KEY ||
651                                  t == PTR_TO_MAP_VALUE ||
652                                  t == PTR_TO_MAP_VALUE_OR_NULL)
653                                 verbose(env, ",ks=%d,vs=%d",
654                                         reg->map_ptr->key_size,
655                                         reg->map_ptr->value_size);
656                         if (tnum_is_const(reg->var_off)) {
657                                 /* Typically an immediate SCALAR_VALUE, but
658                                  * could be a pointer whose offset is too big
659                                  * for reg->off
660                                  */
661                                 verbose(env, ",imm=%llx", reg->var_off.value);
662                         } else {
663                                 if (reg->smin_value != reg->umin_value &&
664                                     reg->smin_value != S64_MIN)
665                                         verbose(env, ",smin_value=%lld",
666                                                 (long long)reg->smin_value);
667                                 if (reg->smax_value != reg->umax_value &&
668                                     reg->smax_value != S64_MAX)
669                                         verbose(env, ",smax_value=%lld",
670                                                 (long long)reg->smax_value);
671                                 if (reg->umin_value != 0)
672                                         verbose(env, ",umin_value=%llu",
673                                                 (unsigned long long)reg->umin_value);
674                                 if (reg->umax_value != U64_MAX)
675                                         verbose(env, ",umax_value=%llu",
676                                                 (unsigned long long)reg->umax_value);
677                                 if (!tnum_is_unknown(reg->var_off)) {
678                                         char tn_buf[48];
679
680                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
681                                         verbose(env, ",var_off=%s", tn_buf);
682                                 }
683                                 if (reg->s32_min_value != reg->smin_value &&
684                                     reg->s32_min_value != S32_MIN)
685                                         verbose(env, ",s32_min_value=%d",
686                                                 (int)(reg->s32_min_value));
687                                 if (reg->s32_max_value != reg->smax_value &&
688                                     reg->s32_max_value != S32_MAX)
689                                         verbose(env, ",s32_max_value=%d",
690                                                 (int)(reg->s32_max_value));
691                                 if (reg->u32_min_value != reg->umin_value &&
692                                     reg->u32_min_value != U32_MIN)
693                                         verbose(env, ",u32_min_value=%d",
694                                                 (int)(reg->u32_min_value));
695                                 if (reg->u32_max_value != reg->umax_value &&
696                                     reg->u32_max_value != U32_MAX)
697                                         verbose(env, ",u32_max_value=%d",
698                                                 (int)(reg->u32_max_value));
699                         }
700                         verbose(env, ")");
701                 }
702         }
703         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
704                 char types_buf[BPF_REG_SIZE + 1];
705                 bool valid = false;
706                 int j;
707
708                 for (j = 0; j < BPF_REG_SIZE; j++) {
709                         if (state->stack[i].slot_type[j] != STACK_INVALID)
710                                 valid = true;
711                         types_buf[j] = slot_type_char[
712                                         state->stack[i].slot_type[j]];
713                 }
714                 types_buf[BPF_REG_SIZE] = 0;
715                 if (!valid)
716                         continue;
717                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
718                 print_liveness(env, state->stack[i].spilled_ptr.live);
719                 if (state->stack[i].slot_type[0] == STACK_SPILL) {
720                         reg = &state->stack[i].spilled_ptr;
721                         t = reg->type;
722                         verbose(env, "=%s", reg_type_str[t]);
723                         if (t == SCALAR_VALUE && reg->precise)
724                                 verbose(env, "P");
725                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
726                                 verbose(env, "%lld", reg->var_off.value + reg->off);
727                 } else {
728                         verbose(env, "=%s", types_buf);
729                 }
730         }
731         if (state->acquired_refs && state->refs[0].id) {
732                 verbose(env, " refs=%d", state->refs[0].id);
733                 for (i = 1; i < state->acquired_refs; i++)
734                         if (state->refs[i].id)
735                                 verbose(env, ",%d", state->refs[i].id);
736         }
737         verbose(env, "\n");
738 }
739
740 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)                         \
741 static int copy_##NAME##_state(struct bpf_func_state *dst,              \
742                                const struct bpf_func_state *src)        \
743 {                                                                       \
744         if (!src->FIELD)                                                \
745                 return 0;                                               \
746         if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {                    \
747                 /* internal bug, make state invalid to reject the program */ \
748                 memset(dst, 0, sizeof(*dst));                           \
749                 return -EFAULT;                                         \
750         }                                                               \
751         memcpy(dst->FIELD, src->FIELD,                                  \
752                sizeof(*src->FIELD) * (src->COUNT / SIZE));              \
753         return 0;                                                       \
754 }
755 /* copy_reference_state() */
756 COPY_STATE_FN(reference, acquired_refs, refs, 1)
757 /* copy_stack_state() */
758 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
759 #undef COPY_STATE_FN
760
761 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)                      \
762 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
763                                   bool copy_old)                        \
764 {                                                                       \
765         u32 old_size = state->COUNT;                                    \
766         struct bpf_##NAME##_state *new_##FIELD;                         \
767         int slot = size / SIZE;                                         \
768                                                                         \
769         if (size <= old_size || !size) {                                \
770                 if (copy_old)                                           \
771                         return 0;                                       \
772                 state->COUNT = slot * SIZE;                             \
773                 if (!size && old_size) {                                \
774                         kfree(state->FIELD);                            \
775                         state->FIELD = NULL;                            \
776                 }                                                       \
777                 return 0;                                               \
778         }                                                               \
779         new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
780                                     GFP_KERNEL);                        \
781         if (!new_##FIELD)                                               \
782                 return -ENOMEM;                                         \
783         if (copy_old) {                                                 \
784                 if (state->FIELD)                                       \
785                         memcpy(new_##FIELD, state->FIELD,               \
786                                sizeof(*new_##FIELD) * (old_size / SIZE)); \
787                 memset(new_##FIELD + old_size / SIZE, 0,                \
788                        sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
789         }                                                               \
790         state->COUNT = slot * SIZE;                                     \
791         kfree(state->FIELD);                                            \
792         state->FIELD = new_##FIELD;                                     \
793         return 0;                                                       \
794 }
795 /* realloc_reference_state() */
796 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
797 /* realloc_stack_state() */
798 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
799 #undef REALLOC_STATE_FN
800
801 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
802  * make it consume minimal amount of memory. check_stack_write() access from
803  * the program calls into realloc_func_state() to grow the stack size.
804  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
805  * which realloc_stack_state() copies over. It points to previous
806  * bpf_verifier_state which is never reallocated.
807  */
808 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
809                               int refs_size, bool copy_old)
810 {
811         int err = realloc_reference_state(state, refs_size, copy_old);
812         if (err)
813                 return err;
814         return realloc_stack_state(state, stack_size, copy_old);
815 }
816
817 /* Acquire a pointer id from the env and update the state->refs to include
818  * this new pointer reference.
819  * On success, returns a valid pointer id to associate with the register
820  * On failure, returns a negative errno.
821  */
822 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
823 {
824         struct bpf_func_state *state = cur_func(env);
825         int new_ofs = state->acquired_refs;
826         int id, err;
827
828         err = realloc_reference_state(state, state->acquired_refs + 1, true);
829         if (err)
830                 return err;
831         id = ++env->id_gen;
832         state->refs[new_ofs].id = id;
833         state->refs[new_ofs].insn_idx = insn_idx;
834
835         return id;
836 }
837
838 /* release function corresponding to acquire_reference_state(). Idempotent. */
839 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
840 {
841         int i, last_idx;
842
843         last_idx = state->acquired_refs - 1;
844         for (i = 0; i < state->acquired_refs; i++) {
845                 if (state->refs[i].id == ptr_id) {
846                         if (last_idx && i != last_idx)
847                                 memcpy(&state->refs[i], &state->refs[last_idx],
848                                        sizeof(*state->refs));
849                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
850                         state->acquired_refs--;
851                         return 0;
852                 }
853         }
854         return -EINVAL;
855 }
856
857 static int transfer_reference_state(struct bpf_func_state *dst,
858                                     struct bpf_func_state *src)
859 {
860         int err = realloc_reference_state(dst, src->acquired_refs, false);
861         if (err)
862                 return err;
863         err = copy_reference_state(dst, src);
864         if (err)
865                 return err;
866         return 0;
867 }
868
869 static void free_func_state(struct bpf_func_state *state)
870 {
871         if (!state)
872                 return;
873         kfree(state->refs);
874         kfree(state->stack);
875         kfree(state);
876 }
877
878 static void clear_jmp_history(struct bpf_verifier_state *state)
879 {
880         kfree(state->jmp_history);
881         state->jmp_history = NULL;
882         state->jmp_history_cnt = 0;
883 }
884
885 static void free_verifier_state(struct bpf_verifier_state *state,
886                                 bool free_self)
887 {
888         int i;
889
890         for (i = 0; i <= state->curframe; i++) {
891                 free_func_state(state->frame[i]);
892                 state->frame[i] = NULL;
893         }
894         clear_jmp_history(state);
895         if (free_self)
896                 kfree(state);
897 }
898
899 /* copy verifier state from src to dst growing dst stack space
900  * when necessary to accommodate larger src stack
901  */
902 static int copy_func_state(struct bpf_func_state *dst,
903                            const struct bpf_func_state *src)
904 {
905         int err;
906
907         err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
908                                  false);
909         if (err)
910                 return err;
911         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
912         err = copy_reference_state(dst, src);
913         if (err)
914                 return err;
915         return copy_stack_state(dst, src);
916 }
917
918 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
919                                const struct bpf_verifier_state *src)
920 {
921         struct bpf_func_state *dst;
922         u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
923         int i, err;
924
925         if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
926                 kfree(dst_state->jmp_history);
927                 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
928                 if (!dst_state->jmp_history)
929                         return -ENOMEM;
930         }
931         memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
932         dst_state->jmp_history_cnt = src->jmp_history_cnt;
933
934         /* if dst has more stack frames then src frame, free them */
935         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
936                 free_func_state(dst_state->frame[i]);
937                 dst_state->frame[i] = NULL;
938         }
939         dst_state->speculative = src->speculative;
940         dst_state->curframe = src->curframe;
941         dst_state->active_spin_lock = src->active_spin_lock;
942         dst_state->branches = src->branches;
943         dst_state->parent = src->parent;
944         dst_state->first_insn_idx = src->first_insn_idx;
945         dst_state->last_insn_idx = src->last_insn_idx;
946         for (i = 0; i <= src->curframe; i++) {
947                 dst = dst_state->frame[i];
948                 if (!dst) {
949                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
950                         if (!dst)
951                                 return -ENOMEM;
952                         dst_state->frame[i] = dst;
953                 }
954                 err = copy_func_state(dst, src->frame[i]);
955                 if (err)
956                         return err;
957         }
958         return 0;
959 }
960
961 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
962 {
963         while (st) {
964                 u32 br = --st->branches;
965
966                 /* WARN_ON(br > 1) technically makes sense here,
967                  * but see comment in push_stack(), hence:
968                  */
969                 WARN_ONCE((int)br < 0,
970                           "BUG update_branch_counts:branches_to_explore=%d\n",
971                           br);
972                 if (br)
973                         break;
974                 st = st->parent;
975         }
976 }
977
978 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
979                      int *insn_idx, bool pop_log)
980 {
981         struct bpf_verifier_state *cur = env->cur_state;
982         struct bpf_verifier_stack_elem *elem, *head = env->head;
983         int err;
984
985         if (env->head == NULL)
986                 return -ENOENT;
987
988         if (cur) {
989                 err = copy_verifier_state(cur, &head->st);
990                 if (err)
991                         return err;
992         }
993         if (pop_log)
994                 bpf_vlog_reset(&env->log, head->log_pos);
995         if (insn_idx)
996                 *insn_idx = head->insn_idx;
997         if (prev_insn_idx)
998                 *prev_insn_idx = head->prev_insn_idx;
999         elem = head->next;
1000         free_verifier_state(&head->st, false);
1001         kfree(head);
1002         env->head = elem;
1003         env->stack_size--;
1004         return 0;
1005 }
1006
1007 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1008                                              int insn_idx, int prev_insn_idx,
1009                                              bool speculative)
1010 {
1011         struct bpf_verifier_state *cur = env->cur_state;
1012         struct bpf_verifier_stack_elem *elem;
1013         int err;
1014
1015         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1016         if (!elem)
1017                 goto err;
1018
1019         elem->insn_idx = insn_idx;
1020         elem->prev_insn_idx = prev_insn_idx;
1021         elem->next = env->head;
1022         elem->log_pos = env->log.len_used;
1023         env->head = elem;
1024         env->stack_size++;
1025         err = copy_verifier_state(&elem->st, cur);
1026         if (err)
1027                 goto err;
1028         elem->st.speculative |= speculative;
1029         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1030                 verbose(env, "The sequence of %d jumps is too complex.\n",
1031                         env->stack_size);
1032                 goto err;
1033         }
1034         if (elem->st.parent) {
1035                 ++elem->st.parent->branches;
1036                 /* WARN_ON(branches > 2) technically makes sense here,
1037                  * but
1038                  * 1. speculative states will bump 'branches' for non-branch
1039                  * instructions
1040                  * 2. is_state_visited() heuristics may decide not to create
1041                  * a new state for a sequence of branches and all such current
1042                  * and cloned states will be pointing to a single parent state
1043                  * which might have large 'branches' count.
1044                  */
1045         }
1046         return &elem->st;
1047 err:
1048         free_verifier_state(env->cur_state, true);
1049         env->cur_state = NULL;
1050         /* pop all elements and return */
1051         while (!pop_stack(env, NULL, NULL, false));
1052         return NULL;
1053 }
1054
1055 #define CALLER_SAVED_REGS 6
1056 static const int caller_saved[CALLER_SAVED_REGS] = {
1057         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1058 };
1059
1060 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1061                                 struct bpf_reg_state *reg);
1062
1063 /* This helper doesn't clear reg->id */
1064 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1065 {
1066         reg->var_off = tnum_const(imm);
1067         reg->smin_value = (s64)imm;
1068         reg->smax_value = (s64)imm;
1069         reg->umin_value = imm;
1070         reg->umax_value = imm;
1071
1072         reg->s32_min_value = (s32)imm;
1073         reg->s32_max_value = (s32)imm;
1074         reg->u32_min_value = (u32)imm;
1075         reg->u32_max_value = (u32)imm;
1076 }
1077
1078 /* Mark the unknown part of a register (variable offset or scalar value) as
1079  * known to have the value @imm.
1080  */
1081 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1082 {
1083         /* Clear id, off, and union(map_ptr, range) */
1084         memset(((u8 *)reg) + sizeof(reg->type), 0,
1085                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1086         ___mark_reg_known(reg, imm);
1087 }
1088
1089 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1090 {
1091         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1092         reg->s32_min_value = (s32)imm;
1093         reg->s32_max_value = (s32)imm;
1094         reg->u32_min_value = (u32)imm;
1095         reg->u32_max_value = (u32)imm;
1096 }
1097
1098 /* Mark the 'variable offset' part of a register as zero.  This should be
1099  * used only on registers holding a pointer type.
1100  */
1101 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1102 {
1103         __mark_reg_known(reg, 0);
1104 }
1105
1106 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1107 {
1108         __mark_reg_known(reg, 0);
1109         reg->type = SCALAR_VALUE;
1110 }
1111
1112 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1113                                 struct bpf_reg_state *regs, u32 regno)
1114 {
1115         if (WARN_ON(regno >= MAX_BPF_REG)) {
1116                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1117                 /* Something bad happened, let's kill all regs */
1118                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1119                         __mark_reg_not_init(env, regs + regno);
1120                 return;
1121         }
1122         __mark_reg_known_zero(regs + regno);
1123 }
1124
1125 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1126 {
1127         switch (reg->type) {
1128         case PTR_TO_MAP_VALUE_OR_NULL: {
1129                 const struct bpf_map *map = reg->map_ptr;
1130
1131                 if (map->inner_map_meta) {
1132                         reg->type = CONST_PTR_TO_MAP;
1133                         reg->map_ptr = map->inner_map_meta;
1134                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1135                         reg->type = PTR_TO_XDP_SOCK;
1136                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1137                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1138                         reg->type = PTR_TO_SOCKET;
1139                 } else {
1140                         reg->type = PTR_TO_MAP_VALUE;
1141                 }
1142                 break;
1143         }
1144         case PTR_TO_SOCKET_OR_NULL:
1145                 reg->type = PTR_TO_SOCKET;
1146                 break;
1147         case PTR_TO_SOCK_COMMON_OR_NULL:
1148                 reg->type = PTR_TO_SOCK_COMMON;
1149                 break;
1150         case PTR_TO_TCP_SOCK_OR_NULL:
1151                 reg->type = PTR_TO_TCP_SOCK;
1152                 break;
1153         case PTR_TO_BTF_ID_OR_NULL:
1154                 reg->type = PTR_TO_BTF_ID;
1155                 break;
1156         case PTR_TO_MEM_OR_NULL:
1157                 reg->type = PTR_TO_MEM;
1158                 break;
1159         case PTR_TO_RDONLY_BUF_OR_NULL:
1160                 reg->type = PTR_TO_RDONLY_BUF;
1161                 break;
1162         case PTR_TO_RDWR_BUF_OR_NULL:
1163                 reg->type = PTR_TO_RDWR_BUF;
1164                 break;
1165         default:
1166                 WARN_ONCE(1, "unknown nullable register type");
1167         }
1168 }
1169
1170 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1171 {
1172         return type_is_pkt_pointer(reg->type);
1173 }
1174
1175 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1176 {
1177         return reg_is_pkt_pointer(reg) ||
1178                reg->type == PTR_TO_PACKET_END;
1179 }
1180
1181 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1182 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1183                                     enum bpf_reg_type which)
1184 {
1185         /* The register can already have a range from prior markings.
1186          * This is fine as long as it hasn't been advanced from its
1187          * origin.
1188          */
1189         return reg->type == which &&
1190                reg->id == 0 &&
1191                reg->off == 0 &&
1192                tnum_equals_const(reg->var_off, 0);
1193 }
1194
1195 /* Reset the min/max bounds of a register */
1196 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1197 {
1198         reg->smin_value = S64_MIN;
1199         reg->smax_value = S64_MAX;
1200         reg->umin_value = 0;
1201         reg->umax_value = U64_MAX;
1202
1203         reg->s32_min_value = S32_MIN;
1204         reg->s32_max_value = S32_MAX;
1205         reg->u32_min_value = 0;
1206         reg->u32_max_value = U32_MAX;
1207 }
1208
1209 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1210 {
1211         reg->smin_value = S64_MIN;
1212         reg->smax_value = S64_MAX;
1213         reg->umin_value = 0;
1214         reg->umax_value = U64_MAX;
1215 }
1216
1217 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1218 {
1219         reg->s32_min_value = S32_MIN;
1220         reg->s32_max_value = S32_MAX;
1221         reg->u32_min_value = 0;
1222         reg->u32_max_value = U32_MAX;
1223 }
1224
1225 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1226 {
1227         struct tnum var32_off = tnum_subreg(reg->var_off);
1228
1229         /* min signed is max(sign bit) | min(other bits) */
1230         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1231                         var32_off.value | (var32_off.mask & S32_MIN));
1232         /* max signed is min(sign bit) | max(other bits) */
1233         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1234                         var32_off.value | (var32_off.mask & S32_MAX));
1235         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1236         reg->u32_max_value = min(reg->u32_max_value,
1237                                  (u32)(var32_off.value | var32_off.mask));
1238 }
1239
1240 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1241 {
1242         /* min signed is max(sign bit) | min(other bits) */
1243         reg->smin_value = max_t(s64, reg->smin_value,
1244                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1245         /* max signed is min(sign bit) | max(other bits) */
1246         reg->smax_value = min_t(s64, reg->smax_value,
1247                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1248         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1249         reg->umax_value = min(reg->umax_value,
1250                               reg->var_off.value | reg->var_off.mask);
1251 }
1252
1253 static void __update_reg_bounds(struct bpf_reg_state *reg)
1254 {
1255         __update_reg32_bounds(reg);
1256         __update_reg64_bounds(reg);
1257 }
1258
1259 /* Uses signed min/max values to inform unsigned, and vice-versa */
1260 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1261 {
1262         /* Learn sign from signed bounds.
1263          * If we cannot cross the sign boundary, then signed and unsigned bounds
1264          * are the same, so combine.  This works even in the negative case, e.g.
1265          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1266          */
1267         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1268                 reg->s32_min_value = reg->u32_min_value =
1269                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1270                 reg->s32_max_value = reg->u32_max_value =
1271                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1272                 return;
1273         }
1274         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1275          * boundary, so we must be careful.
1276          */
1277         if ((s32)reg->u32_max_value >= 0) {
1278                 /* Positive.  We can't learn anything from the smin, but smax
1279                  * is positive, hence safe.
1280                  */
1281                 reg->s32_min_value = reg->u32_min_value;
1282                 reg->s32_max_value = reg->u32_max_value =
1283                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1284         } else if ((s32)reg->u32_min_value < 0) {
1285                 /* Negative.  We can't learn anything from the smax, but smin
1286                  * is negative, hence safe.
1287                  */
1288                 reg->s32_min_value = reg->u32_min_value =
1289                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1290                 reg->s32_max_value = reg->u32_max_value;
1291         }
1292 }
1293
1294 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1295 {
1296         /* Learn sign from signed bounds.
1297          * If we cannot cross the sign boundary, then signed and unsigned bounds
1298          * are the same, so combine.  This works even in the negative case, e.g.
1299          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1300          */
1301         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1302                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1303                                                           reg->umin_value);
1304                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1305                                                           reg->umax_value);
1306                 return;
1307         }
1308         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1309          * boundary, so we must be careful.
1310          */
1311         if ((s64)reg->umax_value >= 0) {
1312                 /* Positive.  We can't learn anything from the smin, but smax
1313                  * is positive, hence safe.
1314                  */
1315                 reg->smin_value = reg->umin_value;
1316                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1317                                                           reg->umax_value);
1318         } else if ((s64)reg->umin_value < 0) {
1319                 /* Negative.  We can't learn anything from the smax, but smin
1320                  * is negative, hence safe.
1321                  */
1322                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1323                                                           reg->umin_value);
1324                 reg->smax_value = reg->umax_value;
1325         }
1326 }
1327
1328 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1329 {
1330         __reg32_deduce_bounds(reg);
1331         __reg64_deduce_bounds(reg);
1332 }
1333
1334 /* Attempts to improve var_off based on unsigned min/max information */
1335 static void __reg_bound_offset(struct bpf_reg_state *reg)
1336 {
1337         struct tnum var64_off = tnum_intersect(reg->var_off,
1338                                                tnum_range(reg->umin_value,
1339                                                           reg->umax_value));
1340         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1341                                                 tnum_range(reg->u32_min_value,
1342                                                            reg->u32_max_value));
1343
1344         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1345 }
1346
1347 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1348 {
1349         reg->umin_value = reg->u32_min_value;
1350         reg->umax_value = reg->u32_max_value;
1351         /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1352          * but must be positive otherwise set to worse case bounds
1353          * and refine later from tnum.
1354          */
1355         if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1356                 reg->smax_value = reg->s32_max_value;
1357         else
1358                 reg->smax_value = U32_MAX;
1359         if (reg->s32_min_value >= 0)
1360                 reg->smin_value = reg->s32_min_value;
1361         else
1362                 reg->smin_value = 0;
1363 }
1364
1365 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1366 {
1367         /* special case when 64-bit register has upper 32-bit register
1368          * zeroed. Typically happens after zext or <<32, >>32 sequence
1369          * allowing us to use 32-bit bounds directly,
1370          */
1371         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1372                 __reg_assign_32_into_64(reg);
1373         } else {
1374                 /* Otherwise the best we can do is push lower 32bit known and
1375                  * unknown bits into register (var_off set from jmp logic)
1376                  * then learn as much as possible from the 64-bit tnum
1377                  * known and unknown bits. The previous smin/smax bounds are
1378                  * invalid here because of jmp32 compare so mark them unknown
1379                  * so they do not impact tnum bounds calculation.
1380                  */
1381                 __mark_reg64_unbounded(reg);
1382                 __update_reg_bounds(reg);
1383         }
1384
1385         /* Intersecting with the old var_off might have improved our bounds
1386          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1387          * then new var_off is (0; 0x7f...fc) which improves our umax.
1388          */
1389         __reg_deduce_bounds(reg);
1390         __reg_bound_offset(reg);
1391         __update_reg_bounds(reg);
1392 }
1393
1394 static bool __reg64_bound_s32(s64 a)
1395 {
1396         return a > S32_MIN && a < S32_MAX;
1397 }
1398
1399 static bool __reg64_bound_u32(u64 a)
1400 {
1401         return a > U32_MIN && a < U32_MAX;
1402 }
1403
1404 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1405 {
1406         __mark_reg32_unbounded(reg);
1407
1408         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1409                 reg->s32_min_value = (s32)reg->smin_value;
1410                 reg->s32_max_value = (s32)reg->smax_value;
1411         }
1412         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1413                 reg->u32_min_value = (u32)reg->umin_value;
1414                 reg->u32_max_value = (u32)reg->umax_value;
1415         }
1416
1417         /* Intersecting with the old var_off might have improved our bounds
1418          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1419          * then new var_off is (0; 0x7f...fc) which improves our umax.
1420          */
1421         __reg_deduce_bounds(reg);
1422         __reg_bound_offset(reg);
1423         __update_reg_bounds(reg);
1424 }
1425
1426 /* Mark a register as having a completely unknown (scalar) value. */
1427 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1428                                struct bpf_reg_state *reg)
1429 {
1430         /*
1431          * Clear type, id, off, and union(map_ptr, range) and
1432          * padding between 'type' and union
1433          */
1434         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1435         reg->type = SCALAR_VALUE;
1436         reg->var_off = tnum_unknown;
1437         reg->frameno = 0;
1438         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1439         __mark_reg_unbounded(reg);
1440 }
1441
1442 static void mark_reg_unknown(struct bpf_verifier_env *env,
1443                              struct bpf_reg_state *regs, u32 regno)
1444 {
1445         if (WARN_ON(regno >= MAX_BPF_REG)) {
1446                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1447                 /* Something bad happened, let's kill all regs except FP */
1448                 for (regno = 0; regno < BPF_REG_FP; regno++)
1449                         __mark_reg_not_init(env, regs + regno);
1450                 return;
1451         }
1452         __mark_reg_unknown(env, regs + regno);
1453 }
1454
1455 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1456                                 struct bpf_reg_state *reg)
1457 {
1458         __mark_reg_unknown(env, reg);
1459         reg->type = NOT_INIT;
1460 }
1461
1462 static void mark_reg_not_init(struct bpf_verifier_env *env,
1463                               struct bpf_reg_state *regs, u32 regno)
1464 {
1465         if (WARN_ON(regno >= MAX_BPF_REG)) {
1466                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1467                 /* Something bad happened, let's kill all regs except FP */
1468                 for (regno = 0; regno < BPF_REG_FP; regno++)
1469                         __mark_reg_not_init(env, regs + regno);
1470                 return;
1471         }
1472         __mark_reg_not_init(env, regs + regno);
1473 }
1474
1475 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1476                             struct bpf_reg_state *regs, u32 regno,
1477                             enum bpf_reg_type reg_type,
1478                             struct btf *btf, u32 btf_id)
1479 {
1480         if (reg_type == SCALAR_VALUE) {
1481                 mark_reg_unknown(env, regs, regno);
1482                 return;
1483         }
1484         mark_reg_known_zero(env, regs, regno);
1485         regs[regno].type = PTR_TO_BTF_ID;
1486         regs[regno].btf = btf;
1487         regs[regno].btf_id = btf_id;
1488 }
1489
1490 #define DEF_NOT_SUBREG  (0)
1491 static void init_reg_state(struct bpf_verifier_env *env,
1492                            struct bpf_func_state *state)
1493 {
1494         struct bpf_reg_state *regs = state->regs;
1495         int i;
1496
1497         for (i = 0; i < MAX_BPF_REG; i++) {
1498                 mark_reg_not_init(env, regs, i);
1499                 regs[i].live = REG_LIVE_NONE;
1500                 regs[i].parent = NULL;
1501                 regs[i].subreg_def = DEF_NOT_SUBREG;
1502         }
1503
1504         /* frame pointer */
1505         regs[BPF_REG_FP].type = PTR_TO_STACK;
1506         mark_reg_known_zero(env, regs, BPF_REG_FP);
1507         regs[BPF_REG_FP].frameno = state->frameno;
1508 }
1509
1510 #define BPF_MAIN_FUNC (-1)
1511 static void init_func_state(struct bpf_verifier_env *env,
1512                             struct bpf_func_state *state,
1513                             int callsite, int frameno, int subprogno)
1514 {
1515         state->callsite = callsite;
1516         state->frameno = frameno;
1517         state->subprogno = subprogno;
1518         init_reg_state(env, state);
1519 }
1520
1521 enum reg_arg_type {
1522         SRC_OP,         /* register is used as source operand */
1523         DST_OP,         /* register is used as destination operand */
1524         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1525 };
1526
1527 static int cmp_subprogs(const void *a, const void *b)
1528 {
1529         return ((struct bpf_subprog_info *)a)->start -
1530                ((struct bpf_subprog_info *)b)->start;
1531 }
1532
1533 static int find_subprog(struct bpf_verifier_env *env, int off)
1534 {
1535         struct bpf_subprog_info *p;
1536
1537         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1538                     sizeof(env->subprog_info[0]), cmp_subprogs);
1539         if (!p)
1540                 return -ENOENT;
1541         return p - env->subprog_info;
1542
1543 }
1544
1545 static int add_subprog(struct bpf_verifier_env *env, int off)
1546 {
1547         int insn_cnt = env->prog->len;
1548         int ret;
1549
1550         if (off >= insn_cnt || off < 0) {
1551                 verbose(env, "call to invalid destination\n");
1552                 return -EINVAL;
1553         }
1554         ret = find_subprog(env, off);
1555         if (ret >= 0)
1556                 return ret;
1557         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1558                 verbose(env, "too many subprograms\n");
1559                 return -E2BIG;
1560         }
1561         /* determine subprog starts. The end is one before the next starts */
1562         env->subprog_info[env->subprog_cnt++].start = off;
1563         sort(env->subprog_info, env->subprog_cnt,
1564              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1565         return env->subprog_cnt - 1;
1566 }
1567
1568 struct bpf_kfunc_desc {
1569         struct btf_func_model func_model;
1570         u32 func_id;
1571         s32 imm;
1572 };
1573
1574 #define MAX_KFUNC_DESCS 256
1575 struct bpf_kfunc_desc_tab {
1576         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1577         u32 nr_descs;
1578 };
1579
1580 static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1581 {
1582         const struct bpf_kfunc_desc *d0 = a;
1583         const struct bpf_kfunc_desc *d1 = b;
1584
1585         /* func_id is not greater than BTF_MAX_TYPE */
1586         return d0->func_id - d1->func_id;
1587 }
1588
1589 static const struct bpf_kfunc_desc *
1590 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1591 {
1592         struct bpf_kfunc_desc desc = {
1593                 .func_id = func_id,
1594         };
1595         struct bpf_kfunc_desc_tab *tab;
1596
1597         tab = prog->aux->kfunc_tab;
1598         return bsearch(&desc, tab->descs, tab->nr_descs,
1599                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1600 }
1601
1602 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1603 {
1604         const struct btf_type *func, *func_proto;
1605         struct bpf_kfunc_desc_tab *tab;
1606         struct bpf_prog_aux *prog_aux;
1607         struct bpf_kfunc_desc *desc;
1608         const char *func_name;
1609         unsigned long addr;
1610         int err;
1611
1612         prog_aux = env->prog->aux;
1613         tab = prog_aux->kfunc_tab;
1614         if (!tab) {
1615                 if (!btf_vmlinux) {
1616                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1617                         return -ENOTSUPP;
1618                 }
1619
1620                 if (!env->prog->jit_requested) {
1621                         verbose(env, "JIT is required for calling kernel function\n");
1622                         return -ENOTSUPP;
1623                 }
1624
1625                 if (!bpf_jit_supports_kfunc_call()) {
1626                         verbose(env, "JIT does not support calling kernel function\n");
1627                         return -ENOTSUPP;
1628                 }
1629
1630                 if (!env->prog->gpl_compatible) {
1631                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1632                         return -EINVAL;
1633                 }
1634
1635                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1636                 if (!tab)
1637                         return -ENOMEM;
1638                 prog_aux->kfunc_tab = tab;
1639         }
1640
1641         if (find_kfunc_desc(env->prog, func_id))
1642                 return 0;
1643
1644         if (tab->nr_descs == MAX_KFUNC_DESCS) {
1645                 verbose(env, "too many different kernel function calls\n");
1646                 return -E2BIG;
1647         }
1648
1649         func = btf_type_by_id(btf_vmlinux, func_id);
1650         if (!func || !btf_type_is_func(func)) {
1651                 verbose(env, "kernel btf_id %u is not a function\n",
1652                         func_id);
1653                 return -EINVAL;
1654         }
1655         func_proto = btf_type_by_id(btf_vmlinux, func->type);
1656         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1657                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1658                         func_id);
1659                 return -EINVAL;
1660         }
1661
1662         func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1663         addr = kallsyms_lookup_name(func_name);
1664         if (!addr) {
1665                 verbose(env, "cannot find address for kernel function %s\n",
1666                         func_name);
1667                 return -EINVAL;
1668         }
1669
1670         desc = &tab->descs[tab->nr_descs++];
1671         desc->func_id = func_id;
1672         desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1673         err = btf_distill_func_proto(&env->log, btf_vmlinux,
1674                                      func_proto, func_name,
1675                                      &desc->func_model);
1676         if (!err)
1677                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1678                      kfunc_desc_cmp_by_id, NULL);
1679         return err;
1680 }
1681
1682 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1683 {
1684         const struct bpf_kfunc_desc *d0 = a;
1685         const struct bpf_kfunc_desc *d1 = b;
1686
1687         if (d0->imm > d1->imm)
1688                 return 1;
1689         else if (d0->imm < d1->imm)
1690                 return -1;
1691         return 0;
1692 }
1693
1694 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1695 {
1696         struct bpf_kfunc_desc_tab *tab;
1697
1698         tab = prog->aux->kfunc_tab;
1699         if (!tab)
1700                 return;
1701
1702         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1703              kfunc_desc_cmp_by_imm, NULL);
1704 }
1705
1706 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1707 {
1708         return !!prog->aux->kfunc_tab;
1709 }
1710
1711 const struct btf_func_model *
1712 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1713                          const struct bpf_insn *insn)
1714 {
1715         const struct bpf_kfunc_desc desc = {
1716                 .imm = insn->imm,
1717         };
1718         const struct bpf_kfunc_desc *res;
1719         struct bpf_kfunc_desc_tab *tab;
1720
1721         tab = prog->aux->kfunc_tab;
1722         res = bsearch(&desc, tab->descs, tab->nr_descs,
1723                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1724
1725         return res ? &res->func_model : NULL;
1726 }
1727
1728 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1729 {
1730         struct bpf_subprog_info *subprog = env->subprog_info;
1731         struct bpf_insn *insn = env->prog->insnsi;
1732         int i, ret, insn_cnt = env->prog->len;
1733
1734         /* Add entry function. */
1735         ret = add_subprog(env, 0);
1736         if (ret)
1737                 return ret;
1738
1739         for (i = 0; i < insn_cnt; i++, insn++) {
1740                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1741                     !bpf_pseudo_kfunc_call(insn))
1742                         continue;
1743
1744                 if (!env->bpf_capable) {
1745                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1746                         return -EPERM;
1747                 }
1748
1749                 if (bpf_pseudo_func(insn)) {
1750                         ret = add_subprog(env, i + insn->imm + 1);
1751                         if (ret >= 0)
1752                                 /* remember subprog */
1753                                 insn[1].imm = ret;
1754                 } else if (bpf_pseudo_call(insn)) {
1755                         ret = add_subprog(env, i + insn->imm + 1);
1756                 } else {
1757                         ret = add_kfunc_call(env, insn->imm);
1758                 }
1759
1760                 if (ret < 0)
1761                         return ret;
1762         }
1763
1764         /* Add a fake 'exit' subprog which could simplify subprog iteration
1765          * logic. 'subprog_cnt' should not be increased.
1766          */
1767         subprog[env->subprog_cnt].start = insn_cnt;
1768
1769         if (env->log.level & BPF_LOG_LEVEL2)
1770                 for (i = 0; i < env->subprog_cnt; i++)
1771                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
1772
1773         return 0;
1774 }
1775
1776 static int check_subprogs(struct bpf_verifier_env *env)
1777 {
1778         int i, subprog_start, subprog_end, off, cur_subprog = 0;
1779         struct bpf_subprog_info *subprog = env->subprog_info;
1780         struct bpf_insn *insn = env->prog->insnsi;
1781         int insn_cnt = env->prog->len;
1782
1783         /* now check that all jumps are within the same subprog */
1784         subprog_start = subprog[cur_subprog].start;
1785         subprog_end = subprog[cur_subprog + 1].start;
1786         for (i = 0; i < insn_cnt; i++) {
1787                 u8 code = insn[i].code;
1788
1789                 if (code == (BPF_JMP | BPF_CALL) &&
1790                     insn[i].imm == BPF_FUNC_tail_call &&
1791                     insn[i].src_reg != BPF_PSEUDO_CALL)
1792                         subprog[cur_subprog].has_tail_call = true;
1793                 if (BPF_CLASS(code) == BPF_LD &&
1794                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1795                         subprog[cur_subprog].has_ld_abs = true;
1796                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1797                         goto next;
1798                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1799                         goto next;
1800                 off = i + insn[i].off + 1;
1801                 if (off < subprog_start || off >= subprog_end) {
1802                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
1803                         return -EINVAL;
1804                 }
1805 next:
1806                 if (i == subprog_end - 1) {
1807                         /* to avoid fall-through from one subprog into another
1808                          * the last insn of the subprog should be either exit
1809                          * or unconditional jump back
1810                          */
1811                         if (code != (BPF_JMP | BPF_EXIT) &&
1812                             code != (BPF_JMP | BPF_JA)) {
1813                                 verbose(env, "last insn is not an exit or jmp\n");
1814                                 return -EINVAL;
1815                         }
1816                         subprog_start = subprog_end;
1817                         cur_subprog++;
1818                         if (cur_subprog < env->subprog_cnt)
1819                                 subprog_end = subprog[cur_subprog + 1].start;
1820                 }
1821         }
1822         return 0;
1823 }
1824
1825 /* Parentage chain of this register (or stack slot) should take care of all
1826  * issues like callee-saved registers, stack slot allocation time, etc.
1827  */
1828 static int mark_reg_read(struct bpf_verifier_env *env,
1829                          const struct bpf_reg_state *state,
1830                          struct bpf_reg_state *parent, u8 flag)
1831 {
1832         bool writes = parent == state->parent; /* Observe write marks */
1833         int cnt = 0;
1834
1835         while (parent) {
1836                 /* if read wasn't screened by an earlier write ... */
1837                 if (writes && state->live & REG_LIVE_WRITTEN)
1838                         break;
1839                 if (parent->live & REG_LIVE_DONE) {
1840                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1841                                 reg_type_str[parent->type],
1842                                 parent->var_off.value, parent->off);
1843                         return -EFAULT;
1844                 }
1845                 /* The first condition is more likely to be true than the
1846                  * second, checked it first.
1847                  */
1848                 if ((parent->live & REG_LIVE_READ) == flag ||
1849                     parent->live & REG_LIVE_READ64)
1850                         /* The parentage chain never changes and
1851                          * this parent was already marked as LIVE_READ.
1852                          * There is no need to keep walking the chain again and
1853                          * keep re-marking all parents as LIVE_READ.
1854                          * This case happens when the same register is read
1855                          * multiple times without writes into it in-between.
1856                          * Also, if parent has the stronger REG_LIVE_READ64 set,
1857                          * then no need to set the weak REG_LIVE_READ32.
1858                          */
1859                         break;
1860                 /* ... then we depend on parent's value */
1861                 parent->live |= flag;
1862                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1863                 if (flag == REG_LIVE_READ64)
1864                         parent->live &= ~REG_LIVE_READ32;
1865                 state = parent;
1866                 parent = state->parent;
1867                 writes = true;
1868                 cnt++;
1869         }
1870
1871         if (env->longest_mark_read_walk < cnt)
1872                 env->longest_mark_read_walk = cnt;
1873         return 0;
1874 }
1875
1876 /* This function is supposed to be used by the following 32-bit optimization
1877  * code only. It returns TRUE if the source or destination register operates
1878  * on 64-bit, otherwise return FALSE.
1879  */
1880 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1881                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1882 {
1883         u8 code, class, op;
1884
1885         code = insn->code;
1886         class = BPF_CLASS(code);
1887         op = BPF_OP(code);
1888         if (class == BPF_JMP) {
1889                 /* BPF_EXIT for "main" will reach here. Return TRUE
1890                  * conservatively.
1891                  */
1892                 if (op == BPF_EXIT)
1893                         return true;
1894                 if (op == BPF_CALL) {
1895                         /* BPF to BPF call will reach here because of marking
1896                          * caller saved clobber with DST_OP_NO_MARK for which we
1897                          * don't care the register def because they are anyway
1898                          * marked as NOT_INIT already.
1899                          */
1900                         if (insn->src_reg == BPF_PSEUDO_CALL)
1901                                 return false;
1902                         /* Helper call will reach here because of arg type
1903                          * check, conservatively return TRUE.
1904                          */
1905                         if (t == SRC_OP)
1906                                 return true;
1907
1908                         return false;
1909                 }
1910         }
1911
1912         if (class == BPF_ALU64 || class == BPF_JMP ||
1913             /* BPF_END always use BPF_ALU class. */
1914             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1915                 return true;
1916
1917         if (class == BPF_ALU || class == BPF_JMP32)
1918                 return false;
1919
1920         if (class == BPF_LDX) {
1921                 if (t != SRC_OP)
1922                         return BPF_SIZE(code) == BPF_DW;
1923                 /* LDX source must be ptr. */
1924                 return true;
1925         }
1926
1927         if (class == BPF_STX) {
1928                 /* BPF_STX (including atomic variants) has multiple source
1929                  * operands, one of which is a ptr. Check whether the caller is
1930                  * asking about it.
1931                  */
1932                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
1933                         return true;
1934                 return BPF_SIZE(code) == BPF_DW;
1935         }
1936
1937         if (class == BPF_LD) {
1938                 u8 mode = BPF_MODE(code);
1939
1940                 /* LD_IMM64 */
1941                 if (mode == BPF_IMM)
1942                         return true;
1943
1944                 /* Both LD_IND and LD_ABS return 32-bit data. */
1945                 if (t != SRC_OP)
1946                         return  false;
1947
1948                 /* Implicit ctx ptr. */
1949                 if (regno == BPF_REG_6)
1950                         return true;
1951
1952                 /* Explicit source could be any width. */
1953                 return true;
1954         }
1955
1956         if (class == BPF_ST)
1957                 /* The only source register for BPF_ST is a ptr. */
1958                 return true;
1959
1960         /* Conservatively return true at default. */
1961         return true;
1962 }
1963
1964 /* Return the regno defined by the insn, or -1. */
1965 static int insn_def_regno(const struct bpf_insn *insn)
1966 {
1967         switch (BPF_CLASS(insn->code)) {
1968         case BPF_JMP:
1969         case BPF_JMP32:
1970         case BPF_ST:
1971                 return -1;
1972         case BPF_STX:
1973                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1974                     (insn->imm & BPF_FETCH)) {
1975                         if (insn->imm == BPF_CMPXCHG)
1976                                 return BPF_REG_0;
1977                         else
1978                                 return insn->src_reg;
1979                 } else {
1980                         return -1;
1981                 }
1982         default:
1983                 return insn->dst_reg;
1984         }
1985 }
1986
1987 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1988 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1989 {
1990         int dst_reg = insn_def_regno(insn);
1991
1992         if (dst_reg == -1)
1993                 return false;
1994
1995         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
1996 }
1997
1998 static void mark_insn_zext(struct bpf_verifier_env *env,
1999                            struct bpf_reg_state *reg)
2000 {
2001         s32 def_idx = reg->subreg_def;
2002
2003         if (def_idx == DEF_NOT_SUBREG)
2004                 return;
2005
2006         env->insn_aux_data[def_idx - 1].zext_dst = true;
2007         /* The dst will be zero extended, so won't be sub-register anymore. */
2008         reg->subreg_def = DEF_NOT_SUBREG;
2009 }
2010
2011 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2012                          enum reg_arg_type t)
2013 {
2014         struct bpf_verifier_state *vstate = env->cur_state;
2015         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2016         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2017         struct bpf_reg_state *reg, *regs = state->regs;
2018         bool rw64;
2019
2020         if (regno >= MAX_BPF_REG) {
2021                 verbose(env, "R%d is invalid\n", regno);
2022                 return -EINVAL;
2023         }
2024
2025         reg = &regs[regno];
2026         rw64 = is_reg64(env, insn, regno, reg, t);
2027         if (t == SRC_OP) {
2028                 /* check whether register used as source operand can be read */
2029                 if (reg->type == NOT_INIT) {
2030                         verbose(env, "R%d !read_ok\n", regno);
2031                         return -EACCES;
2032                 }
2033                 /* We don't need to worry about FP liveness because it's read-only */
2034                 if (regno == BPF_REG_FP)
2035                         return 0;
2036
2037                 if (rw64)
2038                         mark_insn_zext(env, reg);
2039
2040                 return mark_reg_read(env, reg, reg->parent,
2041                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2042         } else {
2043                 /* check whether register used as dest operand can be written to */
2044                 if (regno == BPF_REG_FP) {
2045                         verbose(env, "frame pointer is read only\n");
2046                         return -EACCES;
2047                 }
2048                 reg->live |= REG_LIVE_WRITTEN;
2049                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2050                 if (t == DST_OP)
2051                         mark_reg_unknown(env, regs, regno);
2052         }
2053         return 0;
2054 }
2055
2056 /* for any branch, call, exit record the history of jmps in the given state */
2057 static int push_jmp_history(struct bpf_verifier_env *env,
2058                             struct bpf_verifier_state *cur)
2059 {
2060         u32 cnt = cur->jmp_history_cnt;
2061         struct bpf_idx_pair *p;
2062
2063         cnt++;
2064         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2065         if (!p)
2066                 return -ENOMEM;
2067         p[cnt - 1].idx = env->insn_idx;
2068         p[cnt - 1].prev_idx = env->prev_insn_idx;
2069         cur->jmp_history = p;
2070         cur->jmp_history_cnt = cnt;
2071         return 0;
2072 }
2073
2074 /* Backtrack one insn at a time. If idx is not at the top of recorded
2075  * history then previous instruction came from straight line execution.
2076  */
2077 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2078                              u32 *history)
2079 {
2080         u32 cnt = *history;
2081
2082         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2083                 i = st->jmp_history[cnt - 1].prev_idx;
2084                 (*history)--;
2085         } else {
2086                 i--;
2087         }
2088         return i;
2089 }
2090
2091 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2092 {
2093         const struct btf_type *func;
2094
2095         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2096                 return NULL;
2097
2098         func = btf_type_by_id(btf_vmlinux, insn->imm);
2099         return btf_name_by_offset(btf_vmlinux, func->name_off);
2100 }
2101
2102 /* For given verifier state backtrack_insn() is called from the last insn to
2103  * the first insn. Its purpose is to compute a bitmask of registers and
2104  * stack slots that needs precision in the parent verifier state.
2105  */
2106 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2107                           u32 *reg_mask, u64 *stack_mask)
2108 {
2109         const struct bpf_insn_cbs cbs = {
2110                 .cb_call        = disasm_kfunc_name,
2111                 .cb_print       = verbose,
2112                 .private_data   = env,
2113         };
2114         struct bpf_insn *insn = env->prog->insnsi + idx;
2115         u8 class = BPF_CLASS(insn->code);
2116         u8 opcode = BPF_OP(insn->code);
2117         u8 mode = BPF_MODE(insn->code);
2118         u32 dreg = 1u << insn->dst_reg;
2119         u32 sreg = 1u << insn->src_reg;
2120         u32 spi;
2121
2122         if (insn->code == 0)
2123                 return 0;
2124         if (env->log.level & BPF_LOG_LEVEL) {
2125                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2126                 verbose(env, "%d: ", idx);
2127                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2128         }
2129
2130         if (class == BPF_ALU || class == BPF_ALU64) {
2131                 if (!(*reg_mask & dreg))
2132                         return 0;
2133                 if (opcode == BPF_MOV) {
2134                         if (BPF_SRC(insn->code) == BPF_X) {
2135                                 /* dreg = sreg
2136                                  * dreg needs precision after this insn
2137                                  * sreg needs precision before this insn
2138                                  */
2139                                 *reg_mask &= ~dreg;
2140                                 *reg_mask |= sreg;
2141                         } else {
2142                                 /* dreg = K
2143                                  * dreg needs precision after this insn.
2144                                  * Corresponding register is already marked
2145                                  * as precise=true in this verifier state.
2146                                  * No further markings in parent are necessary
2147                                  */
2148                                 *reg_mask &= ~dreg;
2149                         }
2150                 } else {
2151                         if (BPF_SRC(insn->code) == BPF_X) {
2152                                 /* dreg += sreg
2153                                  * both dreg and sreg need precision
2154                                  * before this insn
2155                                  */
2156                                 *reg_mask |= sreg;
2157                         } /* else dreg += K
2158                            * dreg still needs precision before this insn
2159                            */
2160                 }
2161         } else if (class == BPF_LDX) {
2162                 if (!(*reg_mask & dreg))
2163                         return 0;
2164                 *reg_mask &= ~dreg;
2165
2166                 /* scalars can only be spilled into stack w/o losing precision.
2167                  * Load from any other memory can be zero extended.
2168                  * The desire to keep that precision is already indicated
2169                  * by 'precise' mark in corresponding register of this state.
2170                  * No further tracking necessary.
2171                  */
2172                 if (insn->src_reg != BPF_REG_FP)
2173                         return 0;
2174                 if (BPF_SIZE(insn->code) != BPF_DW)
2175                         return 0;
2176
2177                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2178                  * that [fp - off] slot contains scalar that needs to be
2179                  * tracked with precision
2180                  */
2181                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2182                 if (spi >= 64) {
2183                         verbose(env, "BUG spi %d\n", spi);
2184                         WARN_ONCE(1, "verifier backtracking bug");
2185                         return -EFAULT;
2186                 }
2187                 *stack_mask |= 1ull << spi;
2188         } else if (class == BPF_STX || class == BPF_ST) {
2189                 if (*reg_mask & dreg)
2190                         /* stx & st shouldn't be using _scalar_ dst_reg
2191                          * to access memory. It means backtracking
2192                          * encountered a case of pointer subtraction.
2193                          */
2194                         return -ENOTSUPP;
2195                 /* scalars can only be spilled into stack */
2196                 if (insn->dst_reg != BPF_REG_FP)
2197                         return 0;
2198                 if (BPF_SIZE(insn->code) != BPF_DW)
2199                         return 0;
2200                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2201                 if (spi >= 64) {
2202                         verbose(env, "BUG spi %d\n", spi);
2203                         WARN_ONCE(1, "verifier backtracking bug");
2204                         return -EFAULT;
2205                 }
2206                 if (!(*stack_mask & (1ull << spi)))
2207                         return 0;
2208                 *stack_mask &= ~(1ull << spi);
2209                 if (class == BPF_STX)
2210                         *reg_mask |= sreg;
2211         } else if (class == BPF_JMP || class == BPF_JMP32) {
2212                 if (opcode == BPF_CALL) {
2213                         if (insn->src_reg == BPF_PSEUDO_CALL)
2214                                 return -ENOTSUPP;
2215                         /* regular helper call sets R0 */
2216                         *reg_mask &= ~1;
2217                         if (*reg_mask & 0x3f) {
2218                                 /* if backtracing was looking for registers R1-R5
2219                                  * they should have been found already.
2220                                  */
2221                                 verbose(env, "BUG regs %x\n", *reg_mask);
2222                                 WARN_ONCE(1, "verifier backtracking bug");
2223                                 return -EFAULT;
2224                         }
2225                 } else if (opcode == BPF_EXIT) {
2226                         return -ENOTSUPP;
2227                 }
2228         } else if (class == BPF_LD) {
2229                 if (!(*reg_mask & dreg))
2230                         return 0;
2231                 *reg_mask &= ~dreg;
2232                 /* It's ld_imm64 or ld_abs or ld_ind.
2233                  * For ld_imm64 no further tracking of precision
2234                  * into parent is necessary
2235                  */
2236                 if (mode == BPF_IND || mode == BPF_ABS)
2237                         /* to be analyzed */
2238                         return -ENOTSUPP;
2239         }
2240         return 0;
2241 }
2242
2243 /* the scalar precision tracking algorithm:
2244  * . at the start all registers have precise=false.
2245  * . scalar ranges are tracked as normal through alu and jmp insns.
2246  * . once precise value of the scalar register is used in:
2247  *   .  ptr + scalar alu
2248  *   . if (scalar cond K|scalar)
2249  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2250  *   backtrack through the verifier states and mark all registers and
2251  *   stack slots with spilled constants that these scalar regisers
2252  *   should be precise.
2253  * . during state pruning two registers (or spilled stack slots)
2254  *   are equivalent if both are not precise.
2255  *
2256  * Note the verifier cannot simply walk register parentage chain,
2257  * since many different registers and stack slots could have been
2258  * used to compute single precise scalar.
2259  *
2260  * The approach of starting with precise=true for all registers and then
2261  * backtrack to mark a register as not precise when the verifier detects
2262  * that program doesn't care about specific value (e.g., when helper
2263  * takes register as ARG_ANYTHING parameter) is not safe.
2264  *
2265  * It's ok to walk single parentage chain of the verifier states.
2266  * It's possible that this backtracking will go all the way till 1st insn.
2267  * All other branches will be explored for needing precision later.
2268  *
2269  * The backtracking needs to deal with cases like:
2270  *   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)
2271  * r9 -= r8
2272  * r5 = r9
2273  * if r5 > 0x79f goto pc+7
2274  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2275  * r5 += 1
2276  * ...
2277  * call bpf_perf_event_output#25
2278  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2279  *
2280  * and this case:
2281  * r6 = 1
2282  * call foo // uses callee's r6 inside to compute r0
2283  * r0 += r6
2284  * if r0 == 0 goto
2285  *
2286  * to track above reg_mask/stack_mask needs to be independent for each frame.
2287  *
2288  * Also if parent's curframe > frame where backtracking started,
2289  * the verifier need to mark registers in both frames, otherwise callees
2290  * may incorrectly prune callers. This is similar to
2291  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2292  *
2293  * For now backtracking falls back into conservative marking.
2294  */
2295 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2296                                      struct bpf_verifier_state *st)
2297 {
2298         struct bpf_func_state *func;
2299         struct bpf_reg_state *reg;
2300         int i, j;
2301
2302         /* big hammer: mark all scalars precise in this path.
2303          * pop_stack may still get !precise scalars.
2304          */
2305         for (; st; st = st->parent)
2306                 for (i = 0; i <= st->curframe; i++) {
2307                         func = st->frame[i];
2308                         for (j = 0; j < BPF_REG_FP; j++) {
2309                                 reg = &func->regs[j];
2310                                 if (reg->type != SCALAR_VALUE)
2311                                         continue;
2312                                 reg->precise = true;
2313                         }
2314                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2315                                 if (func->stack[j].slot_type[0] != STACK_SPILL)
2316                                         continue;
2317                                 reg = &func->stack[j].spilled_ptr;
2318                                 if (reg->type != SCALAR_VALUE)
2319                                         continue;
2320                                 reg->precise = true;
2321                         }
2322                 }
2323 }
2324
2325 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2326                                   int spi)
2327 {
2328         struct bpf_verifier_state *st = env->cur_state;
2329         int first_idx = st->first_insn_idx;
2330         int last_idx = env->insn_idx;
2331         struct bpf_func_state *func;
2332         struct bpf_reg_state *reg;
2333         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2334         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2335         bool skip_first = true;
2336         bool new_marks = false;
2337         int i, err;
2338
2339         if (!env->bpf_capable)
2340                 return 0;
2341
2342         func = st->frame[st->curframe];
2343         if (regno >= 0) {
2344                 reg = &func->regs[regno];
2345                 if (reg->type != SCALAR_VALUE) {
2346                         WARN_ONCE(1, "backtracing misuse");
2347                         return -EFAULT;
2348                 }
2349                 if (!reg->precise)
2350                         new_marks = true;
2351                 else
2352                         reg_mask = 0;
2353                 reg->precise = true;
2354         }
2355
2356         while (spi >= 0) {
2357                 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2358                         stack_mask = 0;
2359                         break;
2360                 }
2361                 reg = &func->stack[spi].spilled_ptr;
2362                 if (reg->type != SCALAR_VALUE) {
2363                         stack_mask = 0;
2364                         break;
2365                 }
2366                 if (!reg->precise)
2367                         new_marks = true;
2368                 else
2369                         stack_mask = 0;
2370                 reg->precise = true;
2371                 break;
2372         }
2373
2374         if (!new_marks)
2375                 return 0;
2376         if (!reg_mask && !stack_mask)
2377                 return 0;
2378         for (;;) {
2379                 DECLARE_BITMAP(mask, 64);
2380                 u32 history = st->jmp_history_cnt;
2381
2382                 if (env->log.level & BPF_LOG_LEVEL)
2383                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2384                 for (i = last_idx;;) {
2385                         if (skip_first) {
2386                                 err = 0;
2387                                 skip_first = false;
2388                         } else {
2389                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2390                         }
2391                         if (err == -ENOTSUPP) {
2392                                 mark_all_scalars_precise(env, st);
2393                                 return 0;
2394                         } else if (err) {
2395                                 return err;
2396                         }
2397                         if (!reg_mask && !stack_mask)
2398                                 /* Found assignment(s) into tracked register in this state.
2399                                  * Since this state is already marked, just return.
2400                                  * Nothing to be tracked further in the parent state.
2401                                  */
2402                                 return 0;
2403                         if (i == first_idx)
2404                                 break;
2405                         i = get_prev_insn_idx(st, i, &history);
2406                         if (i >= env->prog->len) {
2407                                 /* This can happen if backtracking reached insn 0
2408                                  * and there are still reg_mask or stack_mask
2409                                  * to backtrack.
2410                                  * It means the backtracking missed the spot where
2411                                  * particular register was initialized with a constant.
2412                                  */
2413                                 verbose(env, "BUG backtracking idx %d\n", i);
2414                                 WARN_ONCE(1, "verifier backtracking bug");
2415                                 return -EFAULT;
2416                         }
2417                 }
2418                 st = st->parent;
2419                 if (!st)
2420                         break;
2421
2422                 new_marks = false;
2423                 func = st->frame[st->curframe];
2424                 bitmap_from_u64(mask, reg_mask);
2425                 for_each_set_bit(i, mask, 32) {
2426                         reg = &func->regs[i];
2427                         if (reg->type != SCALAR_VALUE) {
2428                                 reg_mask &= ~(1u << i);
2429                                 continue;
2430                         }
2431                         if (!reg->precise)
2432                                 new_marks = true;
2433                         reg->precise = true;
2434                 }
2435
2436                 bitmap_from_u64(mask, stack_mask);
2437                 for_each_set_bit(i, mask, 64) {
2438                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2439                                 /* the sequence of instructions:
2440                                  * 2: (bf) r3 = r10
2441                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2442                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2443                                  * doesn't contain jmps. It's backtracked
2444                                  * as a single block.
2445                                  * During backtracking insn 3 is not recognized as
2446                                  * stack access, so at the end of backtracking
2447                                  * stack slot fp-8 is still marked in stack_mask.
2448                                  * However the parent state may not have accessed
2449                                  * fp-8 and it's "unallocated" stack space.
2450                                  * In such case fallback to conservative.
2451                                  */
2452                                 mark_all_scalars_precise(env, st);
2453                                 return 0;
2454                         }
2455
2456                         if (func->stack[i].slot_type[0] != STACK_SPILL) {
2457                                 stack_mask &= ~(1ull << i);
2458                                 continue;
2459                         }
2460                         reg = &func->stack[i].spilled_ptr;
2461                         if (reg->type != SCALAR_VALUE) {
2462                                 stack_mask &= ~(1ull << i);
2463                                 continue;
2464                         }
2465                         if (!reg->precise)
2466                                 new_marks = true;
2467                         reg->precise = true;
2468                 }
2469                 if (env->log.level & BPF_LOG_LEVEL) {
2470                         print_verifier_state(env, func);
2471                         verbose(env, "parent %s regs=%x stack=%llx marks\n",
2472                                 new_marks ? "didn't have" : "already had",
2473                                 reg_mask, stack_mask);
2474                 }
2475
2476                 if (!reg_mask && !stack_mask)
2477                         break;
2478                 if (!new_marks)
2479                         break;
2480
2481                 last_idx = st->last_insn_idx;
2482                 first_idx = st->first_insn_idx;
2483         }
2484         return 0;
2485 }
2486
2487 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2488 {
2489         return __mark_chain_precision(env, regno, -1);
2490 }
2491
2492 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2493 {
2494         return __mark_chain_precision(env, -1, spi);
2495 }
2496
2497 static bool is_spillable_regtype(enum bpf_reg_type type)
2498 {
2499         switch (type) {
2500         case PTR_TO_MAP_VALUE:
2501         case PTR_TO_MAP_VALUE_OR_NULL:
2502         case PTR_TO_STACK:
2503         case PTR_TO_CTX:
2504         case PTR_TO_PACKET:
2505         case PTR_TO_PACKET_META:
2506         case PTR_TO_PACKET_END:
2507         case PTR_TO_FLOW_KEYS:
2508         case CONST_PTR_TO_MAP:
2509         case PTR_TO_SOCKET:
2510         case PTR_TO_SOCKET_OR_NULL:
2511         case PTR_TO_SOCK_COMMON:
2512         case PTR_TO_SOCK_COMMON_OR_NULL:
2513         case PTR_TO_TCP_SOCK:
2514         case PTR_TO_TCP_SOCK_OR_NULL:
2515         case PTR_TO_XDP_SOCK:
2516         case PTR_TO_BTF_ID:
2517         case PTR_TO_BTF_ID_OR_NULL:
2518         case PTR_TO_RDONLY_BUF:
2519         case PTR_TO_RDONLY_BUF_OR_NULL:
2520         case PTR_TO_RDWR_BUF:
2521         case PTR_TO_RDWR_BUF_OR_NULL:
2522         case PTR_TO_PERCPU_BTF_ID:
2523         case PTR_TO_MEM:
2524         case PTR_TO_MEM_OR_NULL:
2525         case PTR_TO_FUNC:
2526         case PTR_TO_MAP_KEY:
2527                 return true;
2528         default:
2529                 return false;
2530         }
2531 }
2532
2533 /* Does this register contain a constant zero? */
2534 static bool register_is_null(struct bpf_reg_state *reg)
2535 {
2536         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2537 }
2538
2539 static bool register_is_const(struct bpf_reg_state *reg)
2540 {
2541         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2542 }
2543
2544 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2545 {
2546         return tnum_is_unknown(reg->var_off) &&
2547                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2548                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2549                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2550                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2551 }
2552
2553 static bool register_is_bounded(struct bpf_reg_state *reg)
2554 {
2555         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2556 }
2557
2558 static bool __is_pointer_value(bool allow_ptr_leaks,
2559                                const struct bpf_reg_state *reg)
2560 {
2561         if (allow_ptr_leaks)
2562                 return false;
2563
2564         return reg->type != SCALAR_VALUE;
2565 }
2566
2567 static void save_register_state(struct bpf_func_state *state,
2568                                 int spi, struct bpf_reg_state *reg)
2569 {
2570         int i;
2571
2572         state->stack[spi].spilled_ptr = *reg;
2573         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2574
2575         for (i = 0; i < BPF_REG_SIZE; i++)
2576                 state->stack[spi].slot_type[i] = STACK_SPILL;
2577 }
2578
2579 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2580  * stack boundary and alignment are checked in check_mem_access()
2581  */
2582 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2583                                        /* stack frame we're writing to */
2584                                        struct bpf_func_state *state,
2585                                        int off, int size, int value_regno,
2586                                        int insn_idx)
2587 {
2588         struct bpf_func_state *cur; /* state of the current function */
2589         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2590         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2591         struct bpf_reg_state *reg = NULL;
2592
2593         err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2594                                  state->acquired_refs, true);
2595         if (err)
2596                 return err;
2597         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2598          * so it's aligned access and [off, off + size) are within stack limits
2599          */
2600         if (!env->allow_ptr_leaks &&
2601             state->stack[spi].slot_type[0] == STACK_SPILL &&
2602             size != BPF_REG_SIZE) {
2603                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2604                 return -EACCES;
2605         }
2606
2607         cur = env->cur_state->frame[env->cur_state->curframe];
2608         if (value_regno >= 0)
2609                 reg = &cur->regs[value_regno];
2610         if (!env->bypass_spec_v4) {
2611                 bool sanitize = reg && is_spillable_regtype(reg->type);
2612
2613                 for (i = 0; i < size; i++) {
2614                         if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2615                                 sanitize = true;
2616                                 break;
2617                         }
2618                 }
2619
2620                 if (sanitize)
2621                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2622         }
2623
2624         if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2625             !register_is_null(reg) && env->bpf_capable) {
2626                 if (dst_reg != BPF_REG_FP) {
2627                         /* The backtracking logic can only recognize explicit
2628                          * stack slot address like [fp - 8]. Other spill of
2629                          * scalar via different register has to be conervative.
2630                          * Backtrack from here and mark all registers as precise
2631                          * that contributed into 'reg' being a constant.
2632                          */
2633                         err = mark_chain_precision(env, value_regno);
2634                         if (err)
2635                                 return err;
2636                 }
2637                 save_register_state(state, spi, reg);
2638         } else if (reg && is_spillable_regtype(reg->type)) {
2639                 /* register containing pointer is being spilled into stack */
2640                 if (size != BPF_REG_SIZE) {
2641                         verbose_linfo(env, insn_idx, "; ");
2642                         verbose(env, "invalid size of register spill\n");
2643                         return -EACCES;
2644                 }
2645                 if (state != cur && reg->type == PTR_TO_STACK) {
2646                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2647                         return -EINVAL;
2648                 }
2649                 save_register_state(state, spi, reg);
2650         } else {
2651                 u8 type = STACK_MISC;
2652
2653                 /* regular write of data into stack destroys any spilled ptr */
2654                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2655                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2656                 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2657                         for (i = 0; i < BPF_REG_SIZE; i++)
2658                                 state->stack[spi].slot_type[i] = STACK_MISC;
2659
2660                 /* only mark the slot as written if all 8 bytes were written
2661                  * otherwise read propagation may incorrectly stop too soon
2662                  * when stack slots are partially written.
2663                  * This heuristic means that read propagation will be
2664                  * conservative, since it will add reg_live_read marks
2665                  * to stack slots all the way to first state when programs
2666                  * writes+reads less than 8 bytes
2667                  */
2668                 if (size == BPF_REG_SIZE)
2669                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2670
2671                 /* when we zero initialize stack slots mark them as such */
2672                 if (reg && register_is_null(reg)) {
2673                         /* backtracking doesn't work for STACK_ZERO yet. */
2674                         err = mark_chain_precision(env, value_regno);
2675                         if (err)
2676                                 return err;
2677                         type = STACK_ZERO;
2678                 }
2679
2680                 /* Mark slots affected by this stack write. */
2681                 for (i = 0; i < size; i++)
2682                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2683                                 type;
2684         }
2685         return 0;
2686 }
2687
2688 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2689  * known to contain a variable offset.
2690  * This function checks whether the write is permitted and conservatively
2691  * tracks the effects of the write, considering that each stack slot in the
2692  * dynamic range is potentially written to.
2693  *
2694  * 'off' includes 'regno->off'.
2695  * 'value_regno' can be -1, meaning that an unknown value is being written to
2696  * the stack.
2697  *
2698  * Spilled pointers in range are not marked as written because we don't know
2699  * what's going to be actually written. This means that read propagation for
2700  * future reads cannot be terminated by this write.
2701  *
2702  * For privileged programs, uninitialized stack slots are considered
2703  * initialized by this write (even though we don't know exactly what offsets
2704  * are going to be written to). The idea is that we don't want the verifier to
2705  * reject future reads that access slots written to through variable offsets.
2706  */
2707 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2708                                      /* func where register points to */
2709                                      struct bpf_func_state *state,
2710                                      int ptr_regno, int off, int size,
2711                                      int value_regno, int insn_idx)
2712 {
2713         struct bpf_func_state *cur; /* state of the current function */
2714         int min_off, max_off;
2715         int i, err;
2716         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2717         bool writing_zero = false;
2718         /* set if the fact that we're writing a zero is used to let any
2719          * stack slots remain STACK_ZERO
2720          */
2721         bool zero_used = false;
2722
2723         cur = env->cur_state->frame[env->cur_state->curframe];
2724         ptr_reg = &cur->regs[ptr_regno];
2725         min_off = ptr_reg->smin_value + off;
2726         max_off = ptr_reg->smax_value + off + size;
2727         if (value_regno >= 0)
2728                 value_reg = &cur->regs[value_regno];
2729         if (value_reg && register_is_null(value_reg))
2730                 writing_zero = true;
2731
2732         err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2733                                  state->acquired_refs, true);
2734         if (err)
2735                 return err;
2736
2737
2738         /* Variable offset writes destroy any spilled pointers in range. */
2739         for (i = min_off; i < max_off; i++) {
2740                 u8 new_type, *stype;
2741                 int slot, spi;
2742
2743                 slot = -i - 1;
2744                 spi = slot / BPF_REG_SIZE;
2745                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2746
2747                 if (!env->allow_ptr_leaks
2748                                 && *stype != NOT_INIT
2749                                 && *stype != SCALAR_VALUE) {
2750                         /* Reject the write if there's are spilled pointers in
2751                          * range. If we didn't reject here, the ptr status
2752                          * would be erased below (even though not all slots are
2753                          * actually overwritten), possibly opening the door to
2754                          * leaks.
2755                          */
2756                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2757                                 insn_idx, i);
2758                         return -EINVAL;
2759                 }
2760
2761                 /* Erase all spilled pointers. */
2762                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2763
2764                 /* Update the slot type. */
2765                 new_type = STACK_MISC;
2766                 if (writing_zero && *stype == STACK_ZERO) {
2767                         new_type = STACK_ZERO;
2768                         zero_used = true;
2769                 }
2770                 /* If the slot is STACK_INVALID, we check whether it's OK to
2771                  * pretend that it will be initialized by this write. The slot
2772                  * might not actually be written to, and so if we mark it as
2773                  * initialized future reads might leak uninitialized memory.
2774                  * For privileged programs, we will accept such reads to slots
2775                  * that may or may not be written because, if we're reject
2776                  * them, the error would be too confusing.
2777                  */
2778                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2779                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2780                                         insn_idx, i);
2781                         return -EINVAL;
2782                 }
2783                 *stype = new_type;
2784         }
2785         if (zero_used) {
2786                 /* backtracking doesn't work for STACK_ZERO yet. */
2787                 err = mark_chain_precision(env, value_regno);
2788                 if (err)
2789                         return err;
2790         }
2791         return 0;
2792 }
2793
2794 /* When register 'dst_regno' is assigned some values from stack[min_off,
2795  * max_off), we set the register's type according to the types of the
2796  * respective stack slots. If all the stack values are known to be zeros, then
2797  * so is the destination reg. Otherwise, the register is considered to be
2798  * SCALAR. This function does not deal with register filling; the caller must
2799  * ensure that all spilled registers in the stack range have been marked as
2800  * read.
2801  */
2802 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2803                                 /* func where src register points to */
2804                                 struct bpf_func_state *ptr_state,
2805                                 int min_off, int max_off, int dst_regno)
2806 {
2807         struct bpf_verifier_state *vstate = env->cur_state;
2808         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2809         int i, slot, spi;
2810         u8 *stype;
2811         int zeros = 0;
2812
2813         for (i = min_off; i < max_off; i++) {
2814                 slot = -i - 1;
2815                 spi = slot / BPF_REG_SIZE;
2816                 stype = ptr_state->stack[spi].slot_type;
2817                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2818                         break;
2819                 zeros++;
2820         }
2821         if (zeros == max_off - min_off) {
2822                 /* any access_size read into register is zero extended,
2823                  * so the whole register == const_zero
2824                  */
2825                 __mark_reg_const_zero(&state->regs[dst_regno]);
2826                 /* backtracking doesn't support STACK_ZERO yet,
2827                  * so mark it precise here, so that later
2828                  * backtracking can stop here.
2829                  * Backtracking may not need this if this register
2830                  * doesn't participate in pointer adjustment.
2831                  * Forward propagation of precise flag is not
2832                  * necessary either. This mark is only to stop
2833                  * backtracking. Any register that contributed
2834                  * to const 0 was marked precise before spill.
2835                  */
2836                 state->regs[dst_regno].precise = true;
2837         } else {
2838                 /* have read misc data from the stack */
2839                 mark_reg_unknown(env, state->regs, dst_regno);
2840         }
2841         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2842 }
2843
2844 /* Read the stack at 'off' and put the results into the register indicated by
2845  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2846  * spilled reg.
2847  *
2848  * 'dst_regno' can be -1, meaning that the read value is not going to a
2849  * register.
2850  *
2851  * The access is assumed to be within the current stack bounds.
2852  */
2853 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2854                                       /* func where src register points to */
2855                                       struct bpf_func_state *reg_state,
2856                                       int off, int size, int dst_regno)
2857 {
2858         struct bpf_verifier_state *vstate = env->cur_state;
2859         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2860         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2861         struct bpf_reg_state *reg;
2862         u8 *stype;
2863
2864         stype = reg_state->stack[spi].slot_type;
2865         reg = &reg_state->stack[spi].spilled_ptr;
2866
2867         if (stype[0] == STACK_SPILL) {
2868                 if (size != BPF_REG_SIZE) {
2869                         if (reg->type != SCALAR_VALUE) {
2870                                 verbose_linfo(env, env->insn_idx, "; ");
2871                                 verbose(env, "invalid size of register fill\n");
2872                                 return -EACCES;
2873                         }
2874                         if (dst_regno >= 0) {
2875                                 mark_reg_unknown(env, state->regs, dst_regno);
2876                                 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2877                         }
2878                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2879                         return 0;
2880                 }
2881                 for (i = 1; i < BPF_REG_SIZE; i++) {
2882                         if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2883                                 verbose(env, "corrupted spill memory\n");
2884                                 return -EACCES;
2885                         }
2886                 }
2887
2888                 if (dst_regno >= 0) {
2889                         /* restore register state from stack */
2890                         state->regs[dst_regno] = *reg;
2891                         /* mark reg as written since spilled pointer state likely
2892                          * has its liveness marks cleared by is_state_visited()
2893                          * which resets stack/reg liveness for state transitions
2894                          */
2895                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2896                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2897                         /* If dst_regno==-1, the caller is asking us whether
2898                          * it is acceptable to use this value as a SCALAR_VALUE
2899                          * (e.g. for XADD).
2900                          * We must not allow unprivileged callers to do that
2901                          * with spilled pointers.
2902                          */
2903                         verbose(env, "leaking pointer from stack off %d\n",
2904                                 off);
2905                         return -EACCES;
2906                 }
2907                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2908         } else {
2909                 u8 type;
2910
2911                 for (i = 0; i < size; i++) {
2912                         type = stype[(slot - i) % BPF_REG_SIZE];
2913                         if (type == STACK_MISC)
2914                                 continue;
2915                         if (type == STACK_ZERO)
2916                                 continue;
2917                         verbose(env, "invalid read from stack off %d+%d size %d\n",
2918                                 off, i, size);
2919                         return -EACCES;
2920                 }
2921                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2922                 if (dst_regno >= 0)
2923                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2924         }
2925         return 0;
2926 }
2927
2928 enum stack_access_src {
2929         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2930         ACCESS_HELPER = 2,  /* the access is performed by a helper */
2931 };
2932
2933 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2934                                          int regno, int off, int access_size,
2935                                          bool zero_size_allowed,
2936                                          enum stack_access_src type,
2937                                          struct bpf_call_arg_meta *meta);
2938
2939 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2940 {
2941         return cur_regs(env) + regno;
2942 }
2943
2944 /* Read the stack at 'ptr_regno + off' and put the result into the register
2945  * 'dst_regno'.
2946  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2947  * but not its variable offset.
2948  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2949  *
2950  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2951  * filling registers (i.e. reads of spilled register cannot be detected when
2952  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2953  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2954  * offset; for a fixed offset check_stack_read_fixed_off should be used
2955  * instead.
2956  */
2957 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2958                                     int ptr_regno, int off, int size, int dst_regno)
2959 {
2960         /* The state of the source register. */
2961         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2962         struct bpf_func_state *ptr_state = func(env, reg);
2963         int err;
2964         int min_off, max_off;
2965
2966         /* Note that we pass a NULL meta, so raw access will not be permitted.
2967          */
2968         err = check_stack_range_initialized(env, ptr_regno, off, size,
2969                                             false, ACCESS_DIRECT, NULL);
2970         if (err)
2971                 return err;
2972
2973         min_off = reg->smin_value + off;
2974         max_off = reg->smax_value + off;
2975         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2976         return 0;
2977 }
2978
2979 /* check_stack_read dispatches to check_stack_read_fixed_off or
2980  * check_stack_read_var_off.
2981  *
2982  * The caller must ensure that the offset falls within the allocated stack
2983  * bounds.
2984  *
2985  * 'dst_regno' is a register which will receive the value from the stack. It
2986  * can be -1, meaning that the read value is not going to a register.
2987  */
2988 static int check_stack_read(struct bpf_verifier_env *env,
2989                             int ptr_regno, int off, int size,
2990                             int dst_regno)
2991 {
2992         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2993         struct bpf_func_state *state = func(env, reg);
2994         int err;
2995         /* Some accesses are only permitted with a static offset. */
2996         bool var_off = !tnum_is_const(reg->var_off);
2997
2998         /* The offset is required to be static when reads don't go to a
2999          * register, in order to not leak pointers (see
3000          * check_stack_read_fixed_off).
3001          */
3002         if (dst_regno < 0 && var_off) {
3003                 char tn_buf[48];
3004
3005                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3006                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3007                         tn_buf, off, size);
3008                 return -EACCES;
3009         }
3010         /* Variable offset is prohibited for unprivileged mode for simplicity
3011          * since it requires corresponding support in Spectre masking for stack
3012          * ALU. See also retrieve_ptr_limit().
3013          */
3014         if (!env->bypass_spec_v1 && var_off) {
3015                 char tn_buf[48];
3016
3017                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3018                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3019                                 ptr_regno, tn_buf);
3020                 return -EACCES;
3021         }
3022
3023         if (!var_off) {
3024                 off += reg->var_off.value;
3025                 err = check_stack_read_fixed_off(env, state, off, size,
3026                                                  dst_regno);
3027         } else {
3028                 /* Variable offset stack reads need more conservative handling
3029                  * than fixed offset ones. Note that dst_regno >= 0 on this
3030                  * branch.
3031                  */
3032                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3033                                                dst_regno);
3034         }
3035         return err;
3036 }
3037
3038
3039 /* check_stack_write dispatches to check_stack_write_fixed_off or
3040  * check_stack_write_var_off.
3041  *
3042  * 'ptr_regno' is the register used as a pointer into the stack.
3043  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3044  * 'value_regno' is the register whose value we're writing to the stack. It can
3045  * be -1, meaning that we're not writing from a register.
3046  *
3047  * The caller must ensure that the offset falls within the maximum stack size.
3048  */
3049 static int check_stack_write(struct bpf_verifier_env *env,
3050                              int ptr_regno, int off, int size,
3051                              int value_regno, int insn_idx)
3052 {
3053         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3054         struct bpf_func_state *state = func(env, reg);
3055         int err;
3056
3057         if (tnum_is_const(reg->var_off)) {
3058                 off += reg->var_off.value;
3059                 err = check_stack_write_fixed_off(env, state, off, size,
3060                                                   value_regno, insn_idx);
3061         } else {
3062                 /* Variable offset stack reads need more conservative handling
3063                  * than fixed offset ones.
3064                  */
3065                 err = check_stack_write_var_off(env, state,
3066                                                 ptr_regno, off, size,
3067                                                 value_regno, insn_idx);
3068         }
3069         return err;
3070 }
3071
3072 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3073                                  int off, int size, enum bpf_access_type type)
3074 {
3075         struct bpf_reg_state *regs = cur_regs(env);
3076         struct bpf_map *map = regs[regno].map_ptr;
3077         u32 cap = bpf_map_flags_to_cap(map);
3078
3079         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3080                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3081                         map->value_size, off, size);
3082                 return -EACCES;
3083         }
3084
3085         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3086                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3087                         map->value_size, off, size);
3088                 return -EACCES;
3089         }
3090
3091         return 0;
3092 }
3093
3094 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3095 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3096                               int off, int size, u32 mem_size,
3097                               bool zero_size_allowed)
3098 {
3099         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3100         struct bpf_reg_state *reg;
3101
3102         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3103                 return 0;
3104
3105         reg = &cur_regs(env)[regno];
3106         switch (reg->type) {
3107         case PTR_TO_MAP_KEY:
3108                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3109                         mem_size, off, size);
3110                 break;
3111         case PTR_TO_MAP_VALUE:
3112                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3113                         mem_size, off, size);
3114                 break;
3115         case PTR_TO_PACKET:
3116         case PTR_TO_PACKET_META:
3117         case PTR_TO_PACKET_END:
3118                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3119                         off, size, regno, reg->id, off, mem_size);
3120                 break;
3121         case PTR_TO_MEM:
3122         default:
3123                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3124                         mem_size, off, size);
3125         }
3126
3127         return -EACCES;
3128 }
3129
3130 /* check read/write into a memory region with possible variable offset */
3131 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3132                                    int off, int size, u32 mem_size,
3133                                    bool zero_size_allowed)
3134 {
3135         struct bpf_verifier_state *vstate = env->cur_state;
3136         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3137         struct bpf_reg_state *reg = &state->regs[regno];
3138         int err;
3139
3140         /* We may have adjusted the register pointing to memory region, so we
3141          * need to try adding each of min_value and max_value to off
3142          * to make sure our theoretical access will be safe.
3143          */
3144         if (env->log.level & BPF_LOG_LEVEL)
3145                 print_verifier_state(env, state);
3146
3147         /* The minimum value is only important with signed
3148          * comparisons where we can't assume the floor of a
3149          * value is 0.  If we are using signed variables for our
3150          * index'es we need to make sure that whatever we use
3151          * will have a set floor within our range.
3152          */
3153         if (reg->smin_value < 0 &&
3154             (reg->smin_value == S64_MIN ||
3155              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3156               reg->smin_value + off < 0)) {
3157                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3158                         regno);
3159                 return -EACCES;
3160         }
3161         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3162                                  mem_size, zero_size_allowed);
3163         if (err) {
3164                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3165                         regno);
3166                 return err;
3167         }
3168
3169         /* If we haven't set a max value then we need to bail since we can't be
3170          * sure we won't do bad things.
3171          * If reg->umax_value + off could overflow, treat that as unbounded too.
3172          */
3173         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3174                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3175                         regno);
3176                 return -EACCES;
3177         }
3178         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3179                                  mem_size, zero_size_allowed);
3180         if (err) {
3181                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3182                         regno);
3183                 return err;
3184         }
3185
3186         return 0;
3187 }
3188
3189 /* check read/write into a map element with possible variable offset */
3190 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3191                             int off, int size, bool zero_size_allowed)
3192 {
3193         struct bpf_verifier_state *vstate = env->cur_state;
3194         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3195         struct bpf_reg_state *reg = &state->regs[regno];
3196         struct bpf_map *map = reg->map_ptr;
3197         int err;
3198
3199         err = check_mem_region_access(env, regno, off, size, map->value_size,
3200                                       zero_size_allowed);
3201         if (err)
3202                 return err;
3203
3204         if (map_value_has_spin_lock(map)) {
3205                 u32 lock = map->spin_lock_off;
3206
3207                 /* if any part of struct bpf_spin_lock can be touched by
3208                  * load/store reject this program.
3209                  * To check that [x1, x2) overlaps with [y1, y2)
3210                  * it is sufficient to check x1 < y2 && y1 < x2.
3211                  */
3212                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3213                      lock < reg->umax_value + off + size) {
3214                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3215                         return -EACCES;
3216                 }
3217         }
3218         return err;
3219 }
3220
3221 #define MAX_PACKET_OFF 0xffff
3222
3223 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3224 {
3225         return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3226 }
3227
3228 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3229                                        const struct bpf_call_arg_meta *meta,
3230                                        enum bpf_access_type t)
3231 {
3232         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3233
3234         switch (prog_type) {
3235         /* Program types only with direct read access go here! */
3236         case BPF_PROG_TYPE_LWT_IN:
3237         case BPF_PROG_TYPE_LWT_OUT:
3238         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3239         case BPF_PROG_TYPE_SK_REUSEPORT:
3240         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3241         case BPF_PROG_TYPE_CGROUP_SKB:
3242                 if (t == BPF_WRITE)
3243                         return false;
3244                 fallthrough;
3245
3246         /* Program types with direct read + write access go here! */
3247         case BPF_PROG_TYPE_SCHED_CLS:
3248         case BPF_PROG_TYPE_SCHED_ACT:
3249         case BPF_PROG_TYPE_XDP:
3250         case BPF_PROG_TYPE_LWT_XMIT:
3251         case BPF_PROG_TYPE_SK_SKB:
3252         case BPF_PROG_TYPE_SK_MSG:
3253                 if (meta)
3254                         return meta->pkt_access;
3255
3256                 env->seen_direct_write = true;
3257                 return true;
3258
3259         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3260                 if (t == BPF_WRITE)
3261                         env->seen_direct_write = true;
3262
3263                 return true;
3264
3265         default:
3266                 return false;
3267         }
3268 }
3269
3270 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3271                                int size, bool zero_size_allowed)
3272 {
3273         struct bpf_reg_state *regs = cur_regs(env);
3274         struct bpf_reg_state *reg = &regs[regno];
3275         int err;
3276
3277         /* We may have added a variable offset to the packet pointer; but any
3278          * reg->range we have comes after that.  We are only checking the fixed
3279          * offset.
3280          */
3281
3282         /* We don't allow negative numbers, because we aren't tracking enough
3283          * detail to prove they're safe.
3284          */
3285         if (reg->smin_value < 0) {
3286                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3287                         regno);
3288                 return -EACCES;
3289         }
3290
3291         err = reg->range < 0 ? -EINVAL :
3292               __check_mem_access(env, regno, off, size, reg->range,
3293                                  zero_size_allowed);
3294         if (err) {
3295                 verbose(env, "R%d offset is outside of the packet\n", regno);
3296                 return err;
3297         }
3298
3299         /* __check_mem_access has made sure "off + size - 1" is within u16.
3300          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3301          * otherwise find_good_pkt_pointers would have refused to set range info
3302          * that __check_mem_access would have rejected this pkt access.
3303          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3304          */
3305         env->prog->aux->max_pkt_offset =
3306                 max_t(u32, env->prog->aux->max_pkt_offset,
3307                       off + reg->umax_value + size - 1);
3308
3309         return err;
3310 }
3311
3312 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3313 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3314                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
3315                             struct btf **btf, u32 *btf_id)
3316 {
3317         struct bpf_insn_access_aux info = {
3318                 .reg_type = *reg_type,
3319                 .log = &env->log,
3320         };
3321
3322         if (env->ops->is_valid_access &&
3323             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3324                 /* A non zero info.ctx_field_size indicates that this field is a
3325                  * candidate for later verifier transformation to load the whole
3326                  * field and then apply a mask when accessed with a narrower
3327                  * access than actual ctx access size. A zero info.ctx_field_size
3328                  * will only allow for whole field access and rejects any other
3329                  * type of narrower access.
3330                  */
3331                 *reg_type = info.reg_type;
3332
3333                 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3334                         *btf = info.btf;
3335                         *btf_id = info.btf_id;
3336                 } else {
3337                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3338                 }
3339                 /* remember the offset of last byte accessed in ctx */
3340                 if (env->prog->aux->max_ctx_offset < off + size)
3341                         env->prog->aux->max_ctx_offset = off + size;
3342                 return 0;
3343         }
3344
3345         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3346         return -EACCES;
3347 }
3348
3349 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3350                                   int size)
3351 {
3352         if (size < 0 || off < 0 ||
3353             (u64)off + size > sizeof(struct bpf_flow_keys)) {
3354                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3355                         off, size);
3356                 return -EACCES;
3357         }
3358         return 0;
3359 }
3360
3361 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3362                              u32 regno, int off, int size,
3363                              enum bpf_access_type t)
3364 {
3365         struct bpf_reg_state *regs = cur_regs(env);
3366         struct bpf_reg_state *reg = &regs[regno];
3367         struct bpf_insn_access_aux info = {};
3368         bool valid;
3369
3370         if (reg->smin_value < 0) {
3371                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3372                         regno);
3373                 return -EACCES;
3374         }
3375
3376         switch (reg->type) {
3377         case PTR_TO_SOCK_COMMON:
3378                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3379                 break;
3380         case PTR_TO_SOCKET:
3381                 valid = bpf_sock_is_valid_access(off, size, t, &info);
3382                 break;
3383         case PTR_TO_TCP_SOCK:
3384                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3385                 break;
3386         case PTR_TO_XDP_SOCK:
3387                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3388                 break;
3389         default:
3390                 valid = false;
3391         }
3392
3393
3394         if (valid) {
3395                 env->insn_aux_data[insn_idx].ctx_field_size =
3396                         info.ctx_field_size;
3397                 return 0;
3398         }
3399
3400         verbose(env, "R%d invalid %s access off=%d size=%d\n",
3401                 regno, reg_type_str[reg->type], off, size);
3402
3403         return -EACCES;
3404 }
3405
3406 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3407 {
3408         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3409 }
3410
3411 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3412 {
3413         const struct bpf_reg_state *reg = reg_state(env, regno);
3414
3415         return reg->type == PTR_TO_CTX;
3416 }
3417
3418 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3419 {
3420         const struct bpf_reg_state *reg = reg_state(env, regno);
3421
3422         return type_is_sk_pointer(reg->type);
3423 }
3424
3425 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3426 {
3427         const struct bpf_reg_state *reg = reg_state(env, regno);
3428
3429         return type_is_pkt_pointer(reg->type);
3430 }
3431
3432 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3433 {
3434         const struct bpf_reg_state *reg = reg_state(env, regno);
3435
3436         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3437         return reg->type == PTR_TO_FLOW_KEYS;
3438 }
3439
3440 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3441                                    const struct bpf_reg_state *reg,
3442                                    int off, int size, bool strict)
3443 {
3444         struct tnum reg_off;
3445         int ip_align;
3446
3447         /* Byte size accesses are always allowed. */
3448         if (!strict || size == 1)
3449                 return 0;
3450
3451         /* For platforms that do not have a Kconfig enabling
3452          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3453          * NET_IP_ALIGN is universally set to '2'.  And on platforms
3454          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3455          * to this code only in strict mode where we want to emulate
3456          * the NET_IP_ALIGN==2 checking.  Therefore use an
3457          * unconditional IP align value of '2'.
3458          */
3459         ip_align = 2;
3460
3461         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3462         if (!tnum_is_aligned(reg_off, size)) {
3463                 char tn_buf[48];
3464
3465                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3466                 verbose(env,
3467                         "misaligned packet access off %d+%s+%d+%d size %d\n",
3468                         ip_align, tn_buf, reg->off, off, size);
3469                 return -EACCES;
3470         }
3471
3472         return 0;
3473 }
3474
3475 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3476                                        const struct bpf_reg_state *reg,
3477                                        const char *pointer_desc,
3478                                        int off, int size, bool strict)
3479 {
3480         struct tnum reg_off;
3481
3482         /* Byte size accesses are always allowed. */
3483         if (!strict || size == 1)
3484                 return 0;
3485
3486         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3487         if (!tnum_is_aligned(reg_off, size)) {
3488                 char tn_buf[48];
3489
3490                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3491                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3492                         pointer_desc, tn_buf, reg->off, off, size);
3493                 return -EACCES;
3494         }
3495
3496         return 0;
3497 }
3498
3499 static int check_ptr_alignment(struct bpf_verifier_env *env,
3500                                const struct bpf_reg_state *reg, int off,
3501                                int size, bool strict_alignment_once)
3502 {
3503         bool strict = env->strict_alignment || strict_alignment_once;
3504         const char *pointer_desc = "";
3505
3506         switch (reg->type) {
3507         case PTR_TO_PACKET:
3508         case PTR_TO_PACKET_META:
3509                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3510                  * right in front, treat it the very same way.
3511                  */
3512                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3513         case PTR_TO_FLOW_KEYS:
3514                 pointer_desc = "flow keys ";
3515                 break;
3516         case PTR_TO_MAP_KEY:
3517                 pointer_desc = "key ";
3518                 break;
3519         case PTR_TO_MAP_VALUE:
3520                 pointer_desc = "value ";
3521                 break;
3522         case PTR_TO_CTX:
3523                 pointer_desc = "context ";
3524                 break;
3525         case PTR_TO_STACK:
3526                 pointer_desc = "stack ";
3527                 /* The stack spill tracking logic in check_stack_write_fixed_off()
3528                  * and check_stack_read_fixed_off() relies on stack accesses being
3529                  * aligned.
3530                  */
3531                 strict = true;
3532                 break;
3533         case PTR_TO_SOCKET:
3534                 pointer_desc = "sock ";
3535                 break;
3536         case PTR_TO_SOCK_COMMON:
3537                 pointer_desc = "sock_common ";
3538                 break;
3539         case PTR_TO_TCP_SOCK:
3540                 pointer_desc = "tcp_sock ";
3541                 break;
3542         case PTR_TO_XDP_SOCK:
3543                 pointer_desc = "xdp_sock ";
3544                 break;
3545         default:
3546                 break;
3547         }
3548         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3549                                            strict);
3550 }
3551
3552 static int update_stack_depth(struct bpf_verifier_env *env,
3553                               const struct bpf_func_state *func,
3554                               int off)
3555 {
3556         u16 stack = env->subprog_info[func->subprogno].stack_depth;
3557
3558         if (stack >= -off)
3559                 return 0;
3560
3561         /* update known max for given subprogram */
3562         env->subprog_info[func->subprogno].stack_depth = -off;
3563         return 0;
3564 }
3565
3566 /* starting from main bpf function walk all instructions of the function
3567  * and recursively walk all callees that given function can call.
3568  * Ignore jump and exit insns.
3569  * Since recursion is prevented by check_cfg() this algorithm
3570  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3571  */
3572 static int check_max_stack_depth(struct bpf_verifier_env *env)
3573 {
3574         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3575         struct bpf_subprog_info *subprog = env->subprog_info;
3576         struct bpf_insn *insn = env->prog->insnsi;
3577         bool tail_call_reachable = false;
3578         int ret_insn[MAX_CALL_FRAMES];
3579         int ret_prog[MAX_CALL_FRAMES];
3580         int j;
3581
3582 process_func:
3583         /* protect against potential stack overflow that might happen when
3584          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3585          * depth for such case down to 256 so that the worst case scenario
3586          * would result in 8k stack size (32 which is tailcall limit * 256 =
3587          * 8k).
3588          *
3589          * To get the idea what might happen, see an example:
3590          * func1 -> sub rsp, 128
3591          *  subfunc1 -> sub rsp, 256
3592          *  tailcall1 -> add rsp, 256
3593          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3594          *   subfunc2 -> sub rsp, 64
3595          *   subfunc22 -> sub rsp, 128
3596          *   tailcall2 -> add rsp, 128
3597          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3598          *
3599          * tailcall will unwind the current stack frame but it will not get rid
3600          * of caller's stack as shown on the example above.
3601          */
3602         if (idx && subprog[idx].has_tail_call && depth >= 256) {
3603                 verbose(env,
3604                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3605                         depth);
3606                 return -EACCES;
3607         }
3608         /* round up to 32-bytes, since this is granularity
3609          * of interpreter stack size
3610          */
3611         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3612         if (depth > MAX_BPF_STACK) {
3613                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3614                         frame + 1, depth);
3615                 return -EACCES;
3616         }
3617 continue_func:
3618         subprog_end = subprog[idx + 1].start;
3619         for (; i < subprog_end; i++) {
3620                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3621                         continue;
3622                 /* remember insn and function to return to */
3623                 ret_insn[frame] = i + 1;
3624                 ret_prog[frame] = idx;
3625
3626                 /* find the callee */
3627                 i = i + insn[i].imm + 1;
3628                 idx = find_subprog(env, i);
3629                 if (idx < 0) {
3630                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3631                                   i);
3632                         return -EFAULT;
3633                 }
3634
3635                 if (subprog[idx].has_tail_call)
3636                         tail_call_reachable = true;
3637
3638                 frame++;
3639                 if (frame >= MAX_CALL_FRAMES) {
3640                         verbose(env, "the call stack of %d frames is too deep !\n",
3641                                 frame);
3642                         return -E2BIG;
3643                 }
3644                 goto process_func;
3645         }
3646         /* if tail call got detected across bpf2bpf calls then mark each of the
3647          * currently present subprog frames as tail call reachable subprogs;
3648          * this info will be utilized by JIT so that we will be preserving the
3649          * tail call counter throughout bpf2bpf calls combined with tailcalls
3650          */
3651         if (tail_call_reachable)
3652                 for (j = 0; j < frame; j++)
3653                         subprog[ret_prog[j]].tail_call_reachable = true;
3654         if (subprog[0].tail_call_reachable)
3655                 env->prog->aux->tail_call_reachable = true;
3656
3657         /* end of for() loop means the last insn of the 'subprog'
3658          * was reached. Doesn't matter whether it was JA or EXIT
3659          */
3660         if (frame == 0)
3661                 return 0;
3662         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3663         frame--;
3664         i = ret_insn[frame];
3665         idx = ret_prog[frame];
3666         goto continue_func;
3667 }
3668
3669 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3670 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3671                                   const struct bpf_insn *insn, int idx)
3672 {
3673         int start = idx + insn->imm + 1, subprog;
3674
3675         subprog = find_subprog(env, start);
3676         if (subprog < 0) {
3677                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3678                           start);
3679                 return -EFAULT;
3680         }
3681         return env->subprog_info[subprog].stack_depth;
3682 }
3683 #endif
3684
3685 int check_ctx_reg(struct bpf_verifier_env *env,
3686                   const struct bpf_reg_state *reg, int regno)
3687 {
3688         /* Access to ctx or passing it to a helper is only allowed in
3689          * its original, unmodified form.
3690          */
3691
3692         if (reg->off) {
3693                 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3694                         regno, reg->off);
3695                 return -EACCES;
3696         }
3697
3698         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3699                 char tn_buf[48];
3700
3701                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3702                 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3703                 return -EACCES;
3704         }
3705
3706         return 0;
3707 }
3708
3709 static int __check_buffer_access(struct bpf_verifier_env *env,
3710                                  const char *buf_info,
3711                                  const struct bpf_reg_state *reg,
3712                                  int regno, int off, int size)
3713 {
3714         if (off < 0) {
3715                 verbose(env,
3716                         "R%d invalid %s buffer access: off=%d, size=%d\n",
3717                         regno, buf_info, off, size);
3718                 return -EACCES;
3719         }
3720         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3721                 char tn_buf[48];
3722
3723                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3724                 verbose(env,
3725                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3726                         regno, off, tn_buf);
3727                 return -EACCES;
3728         }
3729
3730         return 0;
3731 }
3732
3733 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3734                                   const struct bpf_reg_state *reg,
3735                                   int regno, int off, int size)
3736 {
3737         int err;
3738
3739         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3740         if (err)
3741                 return err;
3742
3743         if (off + size > env->prog->aux->max_tp_access)
3744                 env->prog->aux->max_tp_access = off + size;
3745
3746         return 0;
3747 }
3748
3749 static int check_buffer_access(struct bpf_verifier_env *env,
3750                                const struct bpf_reg_state *reg,
3751                                int regno, int off, int size,
3752                                bool zero_size_allowed,
3753                                const char *buf_info,
3754                                u32 *max_access)
3755 {
3756         int err;
3757
3758         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3759         if (err)
3760                 return err;
3761
3762         if (off + size > *max_access)
3763                 *max_access = off + size;
3764
3765         return 0;
3766 }
3767
3768 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3769 static void zext_32_to_64(struct bpf_reg_state *reg)
3770 {
3771         reg->var_off = tnum_subreg(reg->var_off);
3772         __reg_assign_32_into_64(reg);
3773 }
3774
3775 /* truncate register to smaller size (in bytes)
3776  * must be called with size < BPF_REG_SIZE
3777  */
3778 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3779 {
3780         u64 mask;
3781
3782         /* clear high bits in bit representation */
3783         reg->var_off = tnum_cast(reg->var_off, size);
3784
3785         /* fix arithmetic bounds */
3786         mask = ((u64)1 << (size * 8)) - 1;
3787         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3788                 reg->umin_value &= mask;
3789                 reg->umax_value &= mask;
3790         } else {
3791                 reg->umin_value = 0;
3792                 reg->umax_value = mask;
3793         }
3794         reg->smin_value = reg->umin_value;
3795         reg->smax_value = reg->umax_value;
3796
3797         /* If size is smaller than 32bit register the 32bit register
3798          * values are also truncated so we push 64-bit bounds into
3799          * 32-bit bounds. Above were truncated < 32-bits already.
3800          */
3801         if (size >= 4)
3802                 return;
3803         __reg_combine_64_into_32(reg);
3804 }
3805
3806 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3807 {
3808         return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3809 }
3810
3811 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3812 {
3813         void *ptr;
3814         u64 addr;
3815         int err;
3816
3817         err = map->ops->map_direct_value_addr(map, &addr, off);
3818         if (err)
3819                 return err;
3820         ptr = (void *)(long)addr + off;
3821
3822         switch (size) {
3823         case sizeof(u8):
3824                 *val = (u64)*(u8 *)ptr;
3825                 break;
3826         case sizeof(u16):
3827                 *val = (u64)*(u16 *)ptr;
3828                 break;
3829         case sizeof(u32):
3830                 *val = (u64)*(u32 *)ptr;
3831                 break;
3832         case sizeof(u64):
3833                 *val = *(u64 *)ptr;
3834                 break;
3835         default:
3836                 return -EINVAL;
3837         }
3838         return 0;
3839 }
3840
3841 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3842                                    struct bpf_reg_state *regs,
3843                                    int regno, int off, int size,
3844                                    enum bpf_access_type atype,
3845                                    int value_regno)
3846 {
3847         struct bpf_reg_state *reg = regs + regno;
3848         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3849         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3850         u32 btf_id;
3851         int ret;
3852
3853         if (off < 0) {
3854                 verbose(env,
3855                         "R%d is ptr_%s invalid negative access: off=%d\n",
3856                         regno, tname, off);
3857                 return -EACCES;
3858         }
3859         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3860                 char tn_buf[48];
3861
3862                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3863                 verbose(env,
3864                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3865                         regno, tname, off, tn_buf);
3866                 return -EACCES;
3867         }
3868
3869         if (env->ops->btf_struct_access) {
3870                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3871                                                   off, size, atype, &btf_id);
3872         } else {
3873                 if (atype != BPF_READ) {
3874                         verbose(env, "only read is supported\n");
3875                         return -EACCES;
3876                 }
3877
3878                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3879                                         atype, &btf_id);
3880         }
3881
3882         if (ret < 0)
3883                 return ret;
3884
3885         if (atype == BPF_READ && value_regno >= 0)
3886                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3887
3888         return 0;
3889 }
3890
3891 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3892                                    struct bpf_reg_state *regs,
3893                                    int regno, int off, int size,
3894                                    enum bpf_access_type atype,
3895                                    int value_regno)
3896 {
3897         struct bpf_reg_state *reg = regs + regno;
3898         struct bpf_map *map = reg->map_ptr;
3899         const struct btf_type *t;
3900         const char *tname;
3901         u32 btf_id;
3902         int ret;
3903
3904         if (!btf_vmlinux) {
3905                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3906                 return -ENOTSUPP;
3907         }
3908
3909         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3910                 verbose(env, "map_ptr access not supported for map type %d\n",
3911                         map->map_type);
3912                 return -ENOTSUPP;
3913         }
3914
3915         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3916         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3917
3918         if (!env->allow_ptr_to_map_access) {
3919                 verbose(env,
3920                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3921                         tname);
3922                 return -EPERM;
3923         }
3924
3925         if (off < 0) {
3926                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3927                         regno, tname, off);
3928                 return -EACCES;
3929         }
3930
3931         if (atype != BPF_READ) {
3932                 verbose(env, "only read from %s is supported\n", tname);
3933                 return -EACCES;
3934         }
3935
3936         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
3937         if (ret < 0)
3938                 return ret;
3939
3940         if (value_regno >= 0)
3941                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
3942
3943         return 0;
3944 }
3945
3946 /* Check that the stack access at the given offset is within bounds. The
3947  * maximum valid offset is -1.
3948  *
3949  * The minimum valid offset is -MAX_BPF_STACK for writes, and
3950  * -state->allocated_stack for reads.
3951  */
3952 static int check_stack_slot_within_bounds(int off,
3953                                           struct bpf_func_state *state,
3954                                           enum bpf_access_type t)
3955 {
3956         int min_valid_off;
3957
3958         if (t == BPF_WRITE)
3959                 min_valid_off = -MAX_BPF_STACK;
3960         else
3961                 min_valid_off = -state->allocated_stack;
3962
3963         if (off < min_valid_off || off > -1)
3964                 return -EACCES;
3965         return 0;
3966 }
3967
3968 /* Check that the stack access at 'regno + off' falls within the maximum stack
3969  * bounds.
3970  *
3971  * 'off' includes `regno->offset`, but not its dynamic part (if any).
3972  */
3973 static int check_stack_access_within_bounds(
3974                 struct bpf_verifier_env *env,
3975                 int regno, int off, int access_size,
3976                 enum stack_access_src src, enum bpf_access_type type)
3977 {
3978         struct bpf_reg_state *regs = cur_regs(env);
3979         struct bpf_reg_state *reg = regs + regno;
3980         struct bpf_func_state *state = func(env, reg);
3981         int min_off, max_off;
3982         int err;
3983         char *err_extra;
3984
3985         if (src == ACCESS_HELPER)
3986                 /* We don't know if helpers are reading or writing (or both). */
3987                 err_extra = " indirect access to";
3988         else if (type == BPF_READ)
3989                 err_extra = " read from";
3990         else
3991                 err_extra = " write to";
3992
3993         if (tnum_is_const(reg->var_off)) {
3994                 min_off = reg->var_off.value + off;
3995                 if (access_size > 0)
3996                         max_off = min_off + access_size - 1;
3997                 else
3998                         max_off = min_off;
3999         } else {
4000                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4001                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4002                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4003                                 err_extra, regno);
4004                         return -EACCES;
4005                 }
4006                 min_off = reg->smin_value + off;
4007                 if (access_size > 0)
4008                         max_off = reg->smax_value + off + access_size - 1;
4009                 else
4010                         max_off = min_off;
4011         }
4012
4013         err = check_stack_slot_within_bounds(min_off, state, type);
4014         if (!err)
4015                 err = check_stack_slot_within_bounds(max_off, state, type);
4016
4017         if (err) {
4018                 if (tnum_is_const(reg->var_off)) {
4019                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4020                                 err_extra, regno, off, access_size);
4021                 } else {
4022                         char tn_buf[48];
4023
4024                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4025                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4026                                 err_extra, regno, tn_buf, access_size);
4027                 }
4028         }
4029         return err;
4030 }
4031
4032 /* check whether memory at (regno + off) is accessible for t = (read | write)
4033  * if t==write, value_regno is a register which value is stored into memory
4034  * if t==read, value_regno is a register which will receive the value from memory
4035  * if t==write && value_regno==-1, some unknown value is stored into memory
4036  * if t==read && value_regno==-1, don't care what we read from memory
4037  */
4038 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4039                             int off, int bpf_size, enum bpf_access_type t,
4040                             int value_regno, bool strict_alignment_once)
4041 {
4042         struct bpf_reg_state *regs = cur_regs(env);
4043         struct bpf_reg_state *reg = regs + regno;
4044         struct bpf_func_state *state;
4045         int size, err = 0;
4046
4047         size = bpf_size_to_bytes(bpf_size);
4048         if (size < 0)
4049                 return size;
4050
4051         /* alignment checks will add in reg->off themselves */
4052         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4053         if (err)
4054                 return err;
4055
4056         /* for access checks, reg->off is just part of off */
4057         off += reg->off;
4058
4059         if (reg->type == PTR_TO_MAP_KEY) {
4060                 if (t == BPF_WRITE) {
4061                         verbose(env, "write to change key R%d not allowed\n", regno);
4062                         return -EACCES;
4063                 }
4064
4065                 err = check_mem_region_access(env, regno, off, size,
4066                                               reg->map_ptr->key_size, false);
4067                 if (err)
4068                         return err;
4069                 if (value_regno >= 0)
4070                         mark_reg_unknown(env, regs, value_regno);
4071         } else if (reg->type == PTR_TO_MAP_VALUE) {
4072                 if (t == BPF_WRITE && value_regno >= 0 &&
4073                     is_pointer_value(env, value_regno)) {
4074                         verbose(env, "R%d leaks addr into map\n", value_regno);
4075                         return -EACCES;
4076                 }
4077                 err = check_map_access_type(env, regno, off, size, t);
4078                 if (err)
4079                         return err;
4080                 err = check_map_access(env, regno, off, size, false);
4081                 if (!err && t == BPF_READ && value_regno >= 0) {
4082                         struct bpf_map *map = reg->map_ptr;
4083
4084                         /* if map is read-only, track its contents as scalars */
4085                         if (tnum_is_const(reg->var_off) &&
4086                             bpf_map_is_rdonly(map) &&
4087                             map->ops->map_direct_value_addr) {
4088                                 int map_off = off + reg->var_off.value;
4089                                 u64 val = 0;
4090
4091                                 err = bpf_map_direct_read(map, map_off, size,
4092                                                           &val);
4093                                 if (err)
4094                                         return err;
4095
4096                                 regs[value_regno].type = SCALAR_VALUE;
4097                                 __mark_reg_known(&regs[value_regno], val);
4098                         } else {
4099                                 mark_reg_unknown(env, regs, value_regno);
4100                         }
4101                 }
4102         } else if (reg->type == PTR_TO_MEM) {
4103                 if (t == BPF_WRITE && value_regno >= 0 &&
4104                     is_pointer_value(env, value_regno)) {
4105                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4106                         return -EACCES;
4107                 }
4108                 err = check_mem_region_access(env, regno, off, size,
4109                                               reg->mem_size, false);
4110                 if (!err && t == BPF_READ && value_regno >= 0)
4111                         mark_reg_unknown(env, regs, value_regno);
4112         } else if (reg->type == PTR_TO_CTX) {
4113                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4114                 struct btf *btf = NULL;
4115                 u32 btf_id = 0;
4116
4117                 if (t == BPF_WRITE && value_regno >= 0 &&
4118                     is_pointer_value(env, value_regno)) {
4119                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4120                         return -EACCES;
4121                 }
4122
4123                 err = check_ctx_reg(env, reg, regno);
4124                 if (err < 0)
4125                         return err;
4126
4127                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4128                 if (err)
4129                         verbose_linfo(env, insn_idx, "; ");
4130                 if (!err && t == BPF_READ && value_regno >= 0) {
4131                         /* ctx access returns either a scalar, or a
4132                          * PTR_TO_PACKET[_META,_END]. In the latter
4133                          * case, we know the offset is zero.
4134                          */
4135                         if (reg_type == SCALAR_VALUE) {
4136                                 mark_reg_unknown(env, regs, value_regno);
4137                         } else {
4138                                 mark_reg_known_zero(env, regs,
4139                                                     value_regno);
4140                                 if (reg_type_may_be_null(reg_type))
4141                                         regs[value_regno].id = ++env->id_gen;
4142                                 /* A load of ctx field could have different
4143                                  * actual load size with the one encoded in the
4144                                  * insn. When the dst is PTR, it is for sure not
4145                                  * a sub-register.
4146                                  */
4147                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4148                                 if (reg_type == PTR_TO_BTF_ID ||
4149                                     reg_type == PTR_TO_BTF_ID_OR_NULL) {
4150                                         regs[value_regno].btf = btf;
4151                                         regs[value_regno].btf_id = btf_id;
4152                                 }
4153                         }
4154                         regs[value_regno].type = reg_type;
4155                 }
4156
4157         } else if (reg->type == PTR_TO_STACK) {
4158                 /* Basic bounds checks. */
4159                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4160                 if (err)
4161                         return err;
4162
4163                 state = func(env, reg);
4164                 err = update_stack_depth(env, state, off);
4165                 if (err)
4166                         return err;
4167
4168                 if (t == BPF_READ)
4169                         err = check_stack_read(env, regno, off, size,
4170                                                value_regno);
4171                 else
4172                         err = check_stack_write(env, regno, off, size,
4173                                                 value_regno, insn_idx);
4174         } else if (reg_is_pkt_pointer(reg)) {
4175                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4176                         verbose(env, "cannot write into packet\n");
4177                         return -EACCES;
4178                 }
4179                 if (t == BPF_WRITE && value_regno >= 0 &&
4180                     is_pointer_value(env, value_regno)) {
4181                         verbose(env, "R%d leaks addr into packet\n",
4182                                 value_regno);
4183                         return -EACCES;
4184                 }
4185                 err = check_packet_access(env, regno, off, size, false);
4186                 if (!err && t == BPF_READ && value_regno >= 0)
4187                         mark_reg_unknown(env, regs, value_regno);
4188         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4189                 if (t == BPF_WRITE && value_regno >= 0 &&
4190                     is_pointer_value(env, value_regno)) {
4191                         verbose(env, "R%d leaks addr into flow keys\n",
4192                                 value_regno);
4193                         return -EACCES;
4194                 }
4195
4196                 err = check_flow_keys_access(env, off, size);
4197                 if (!err && t == BPF_READ && value_regno >= 0)
4198                         mark_reg_unknown(env, regs, value_regno);
4199         } else if (type_is_sk_pointer(reg->type)) {
4200                 if (t == BPF_WRITE) {
4201                         verbose(env, "R%d cannot write into %s\n",
4202                                 regno, reg_type_str[reg->type]);
4203                         return -EACCES;
4204                 }
4205                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4206                 if (!err && value_regno >= 0)
4207                         mark_reg_unknown(env, regs, value_regno);
4208         } else if (reg->type == PTR_TO_TP_BUFFER) {
4209                 err = check_tp_buffer_access(env, reg, regno, off, size);
4210                 if (!err && t == BPF_READ && value_regno >= 0)
4211                         mark_reg_unknown(env, regs, value_regno);
4212         } else if (reg->type == PTR_TO_BTF_ID) {
4213                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4214                                               value_regno);
4215         } else if (reg->type == CONST_PTR_TO_MAP) {
4216                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4217                                               value_regno);
4218         } else if (reg->type == PTR_TO_RDONLY_BUF) {
4219                 if (t == BPF_WRITE) {
4220                         verbose(env, "R%d cannot write into %s\n",
4221                                 regno, reg_type_str[reg->type]);
4222                         return -EACCES;
4223                 }
4224                 err = check_buffer_access(env, reg, regno, off, size, false,
4225                                           "rdonly",
4226                                           &env->prog->aux->max_rdonly_access);
4227                 if (!err && value_regno >= 0)
4228                         mark_reg_unknown(env, regs, value_regno);
4229         } else if (reg->type == PTR_TO_RDWR_BUF) {
4230                 err = check_buffer_access(env, reg, regno, off, size, false,
4231                                           "rdwr",
4232                                           &env->prog->aux->max_rdwr_access);
4233                 if (!err && t == BPF_READ && value_regno >= 0)
4234                         mark_reg_unknown(env, regs, value_regno);
4235         } else {
4236                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4237                         reg_type_str[reg->type]);
4238                 return -EACCES;
4239         }
4240
4241         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4242             regs[value_regno].type == SCALAR_VALUE) {
4243                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4244                 coerce_reg_to_size(&regs[value_regno], size);
4245         }
4246         return err;
4247 }
4248
4249 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4250 {
4251         int load_reg;
4252         int err;
4253
4254         switch (insn->imm) {
4255         case BPF_ADD:
4256         case BPF_ADD | BPF_FETCH:
4257         case BPF_AND:
4258         case BPF_AND | BPF_FETCH:
4259         case BPF_OR:
4260         case BPF_OR | BPF_FETCH:
4261         case BPF_XOR:
4262         case BPF_XOR | BPF_FETCH:
4263         case BPF_XCHG:
4264         case BPF_CMPXCHG:
4265                 break;
4266         default:
4267                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4268                 return -EINVAL;
4269         }
4270
4271         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4272                 verbose(env, "invalid atomic operand size\n");
4273                 return -EINVAL;
4274         }
4275
4276         /* check src1 operand */
4277         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4278         if (err)
4279                 return err;
4280
4281         /* check src2 operand */
4282         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4283         if (err)
4284                 return err;
4285
4286         if (insn->imm == BPF_CMPXCHG) {
4287                 /* Check comparison of R0 with memory location */
4288                 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4289                 if (err)
4290                         return err;
4291         }
4292
4293         if (is_pointer_value(env, insn->src_reg)) {
4294                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4295                 return -EACCES;
4296         }
4297
4298         if (is_ctx_reg(env, insn->dst_reg) ||
4299             is_pkt_reg(env, insn->dst_reg) ||
4300             is_flow_key_reg(env, insn->dst_reg) ||
4301             is_sk_reg(env, insn->dst_reg)) {
4302                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4303                         insn->dst_reg,
4304                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
4305                 return -EACCES;
4306         }
4307
4308         if (insn->imm & BPF_FETCH) {
4309                 if (insn->imm == BPF_CMPXCHG)
4310                         load_reg = BPF_REG_0;
4311                 else
4312                         load_reg = insn->src_reg;
4313
4314                 /* check and record load of old value */
4315                 err = check_reg_arg(env, load_reg, DST_OP);
4316                 if (err)
4317                         return err;
4318         } else {
4319                 /* This instruction accesses a memory location but doesn't
4320                  * actually load it into a register.
4321                  */
4322                 load_reg = -1;
4323         }
4324
4325         /* check whether we can read the memory */
4326         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4327                                BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4328         if (err)
4329                 return err;
4330
4331         /* check whether we can write into the same memory */
4332         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4333                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4334         if (err)
4335                 return err;
4336
4337         return 0;
4338 }
4339
4340 /* When register 'regno' is used to read the stack (either directly or through
4341  * a helper function) make sure that it's within stack boundary and, depending
4342  * on the access type, that all elements of the stack are initialized.
4343  *
4344  * 'off' includes 'regno->off', but not its dynamic part (if any).
4345  *
4346  * All registers that have been spilled on the stack in the slots within the
4347  * read offsets are marked as read.
4348  */
4349 static int check_stack_range_initialized(
4350                 struct bpf_verifier_env *env, int regno, int off,
4351                 int access_size, bool zero_size_allowed,
4352                 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4353 {
4354         struct bpf_reg_state *reg = reg_state(env, regno);
4355         struct bpf_func_state *state = func(env, reg);
4356         int err, min_off, max_off, i, j, slot, spi;
4357         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4358         enum bpf_access_type bounds_check_type;
4359         /* Some accesses can write anything into the stack, others are
4360          * read-only.
4361          */
4362         bool clobber = false;
4363
4364         if (access_size == 0 && !zero_size_allowed) {
4365                 verbose(env, "invalid zero-sized read\n");
4366                 return -EACCES;
4367         }
4368
4369         if (type == ACCESS_HELPER) {
4370                 /* The bounds checks for writes are more permissive than for
4371                  * reads. However, if raw_mode is not set, we'll do extra
4372                  * checks below.
4373                  */
4374                 bounds_check_type = BPF_WRITE;
4375                 clobber = true;
4376         } else {
4377                 bounds_check_type = BPF_READ;
4378         }
4379         err = check_stack_access_within_bounds(env, regno, off, access_size,
4380                                                type, bounds_check_type);
4381         if (err)
4382                 return err;
4383
4384
4385         if (tnum_is_const(reg->var_off)) {
4386                 min_off = max_off = reg->var_off.value + off;
4387         } else {
4388                 /* Variable offset is prohibited for unprivileged mode for
4389                  * simplicity since it requires corresponding support in
4390                  * Spectre masking for stack ALU.
4391                  * See also retrieve_ptr_limit().
4392                  */
4393                 if (!env->bypass_spec_v1) {
4394                         char tn_buf[48];
4395
4396                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4397                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4398                                 regno, err_extra, tn_buf);
4399                         return -EACCES;
4400                 }
4401                 /* Only initialized buffer on stack is allowed to be accessed
4402                  * with variable offset. With uninitialized buffer it's hard to
4403                  * guarantee that whole memory is marked as initialized on
4404                  * helper return since specific bounds are unknown what may
4405                  * cause uninitialized stack leaking.
4406                  */
4407                 if (meta && meta->raw_mode)
4408                         meta = NULL;
4409
4410                 min_off = reg->smin_value + off;
4411                 max_off = reg->smax_value + off;
4412         }
4413
4414         if (meta && meta->raw_mode) {
4415                 meta->access_size = access_size;
4416                 meta->regno = regno;
4417                 return 0;
4418         }
4419
4420         for (i = min_off; i < max_off + access_size; i++) {
4421                 u8 *stype;
4422
4423                 slot = -i - 1;
4424                 spi = slot / BPF_REG_SIZE;
4425                 if (state->allocated_stack <= slot)
4426                         goto err;
4427                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4428                 if (*stype == STACK_MISC)
4429                         goto mark;
4430                 if (*stype == STACK_ZERO) {
4431                         if (clobber) {
4432                                 /* helper can write anything into the stack */
4433                                 *stype = STACK_MISC;
4434                         }
4435                         goto mark;
4436                 }
4437
4438                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4439                     state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4440                         goto mark;
4441
4442                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4443                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4444                      env->allow_ptr_leaks)) {
4445                         if (clobber) {
4446                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4447                                 for (j = 0; j < BPF_REG_SIZE; j++)
4448                                         state->stack[spi].slot_type[j] = STACK_MISC;
4449                         }
4450                         goto mark;
4451                 }
4452
4453 err:
4454                 if (tnum_is_const(reg->var_off)) {
4455                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4456                                 err_extra, regno, min_off, i - min_off, access_size);
4457                 } else {
4458                         char tn_buf[48];
4459
4460                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4461                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4462                                 err_extra, regno, tn_buf, i - min_off, access_size);
4463                 }
4464                 return -EACCES;
4465 mark:
4466                 /* reading any byte out of 8-byte 'spill_slot' will cause
4467                  * the whole slot to be marked as 'read'
4468                  */
4469                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4470                               state->stack[spi].spilled_ptr.parent,
4471                               REG_LIVE_READ64);
4472         }
4473         return update_stack_depth(env, state, min_off);
4474 }
4475
4476 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4477                                    int access_size, bool zero_size_allowed,
4478                                    struct bpf_call_arg_meta *meta)
4479 {
4480         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4481
4482         switch (reg->type) {
4483         case PTR_TO_PACKET:
4484         case PTR_TO_PACKET_META:
4485                 return check_packet_access(env, regno, reg->off, access_size,
4486                                            zero_size_allowed);
4487         case PTR_TO_MAP_KEY:
4488                 return check_mem_region_access(env, regno, reg->off, access_size,
4489                                                reg->map_ptr->key_size, false);
4490         case PTR_TO_MAP_VALUE:
4491                 if (check_map_access_type(env, regno, reg->off, access_size,
4492                                           meta && meta->raw_mode ? BPF_WRITE :
4493                                           BPF_READ))
4494                         return -EACCES;
4495                 return check_map_access(env, regno, reg->off, access_size,
4496                                         zero_size_allowed);
4497         case PTR_TO_MEM:
4498                 return check_mem_region_access(env, regno, reg->off,
4499                                                access_size, reg->mem_size,
4500                                                zero_size_allowed);
4501         case PTR_TO_RDONLY_BUF:
4502                 if (meta && meta->raw_mode)
4503                         return -EACCES;
4504                 return check_buffer_access(env, reg, regno, reg->off,
4505                                            access_size, zero_size_allowed,
4506                                            "rdonly",
4507                                            &env->prog->aux->max_rdonly_access);
4508         case PTR_TO_RDWR_BUF:
4509                 return check_buffer_access(env, reg, regno, reg->off,
4510                                            access_size, zero_size_allowed,
4511                                            "rdwr",
4512                                            &env->prog->aux->max_rdwr_access);
4513         case PTR_TO_STACK:
4514                 return check_stack_range_initialized(
4515                                 env,
4516                                 regno, reg->off, access_size,
4517                                 zero_size_allowed, ACCESS_HELPER, meta);
4518         default: /* scalar_value or invalid ptr */
4519                 /* Allow zero-byte read from NULL, regardless of pointer type */
4520                 if (zero_size_allowed && access_size == 0 &&
4521                     register_is_null(reg))
4522                         return 0;
4523
4524                 verbose(env, "R%d type=%s expected=%s\n", regno,
4525                         reg_type_str[reg->type],
4526                         reg_type_str[PTR_TO_STACK]);
4527                 return -EACCES;
4528         }
4529 }
4530
4531 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4532                    u32 regno, u32 mem_size)
4533 {
4534         if (register_is_null(reg))
4535                 return 0;
4536
4537         if (reg_type_may_be_null(reg->type)) {
4538                 /* Assuming that the register contains a value check if the memory
4539                  * access is safe. Temporarily save and restore the register's state as
4540                  * the conversion shouldn't be visible to a caller.
4541                  */
4542                 const struct bpf_reg_state saved_reg = *reg;
4543                 int rv;
4544
4545                 mark_ptr_not_null_reg(reg);
4546                 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4547                 *reg = saved_reg;
4548                 return rv;
4549         }
4550
4551         return check_helper_mem_access(env, regno, mem_size, true, NULL);
4552 }
4553
4554 /* Implementation details:
4555  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4556  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4557  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4558  * value_or_null->value transition, since the verifier only cares about
4559  * the range of access to valid map value pointer and doesn't care about actual
4560  * address of the map element.
4561  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4562  * reg->id > 0 after value_or_null->value transition. By doing so
4563  * two bpf_map_lookups will be considered two different pointers that
4564  * point to different bpf_spin_locks.
4565  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4566  * dead-locks.
4567  * Since only one bpf_spin_lock is allowed the checks are simpler than
4568  * reg_is_refcounted() logic. The verifier needs to remember only
4569  * one spin_lock instead of array of acquired_refs.
4570  * cur_state->active_spin_lock remembers which map value element got locked
4571  * and clears it after bpf_spin_unlock.
4572  */
4573 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4574                              bool is_lock)
4575 {
4576         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4577         struct bpf_verifier_state *cur = env->cur_state;
4578         bool is_const = tnum_is_const(reg->var_off);
4579         struct bpf_map *map = reg->map_ptr;
4580         u64 val = reg->var_off.value;
4581
4582         if (!is_const) {
4583                 verbose(env,
4584                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4585                         regno);
4586                 return -EINVAL;
4587         }
4588         if (!map->btf) {
4589                 verbose(env,
4590                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4591                         map->name);
4592                 return -EINVAL;
4593         }
4594         if (!map_value_has_spin_lock(map)) {
4595                 if (map->spin_lock_off == -E2BIG)
4596                         verbose(env,
4597                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4598                                 map->name);
4599                 else if (map->spin_lock_off == -ENOENT)
4600                         verbose(env,
4601                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4602                                 map->name);
4603                 else
4604                         verbose(env,
4605                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4606                                 map->name);
4607                 return -EINVAL;
4608         }
4609         if (map->spin_lock_off != val + reg->off) {
4610                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4611                         val + reg->off);
4612                 return -EINVAL;
4613         }
4614         if (is_lock) {
4615                 if (cur->active_spin_lock) {
4616                         verbose(env,
4617                                 "Locking two bpf_spin_locks are not allowed\n");
4618                         return -EINVAL;
4619                 }
4620                 cur->active_spin_lock = reg->id;
4621         } else {
4622                 if (!cur->active_spin_lock) {
4623                         verbose(env, "bpf_spin_unlock without taking a lock\n");
4624                         return -EINVAL;
4625                 }
4626                 if (cur->active_spin_lock != reg->id) {
4627                         verbose(env, "bpf_spin_unlock of different lock\n");
4628                         return -EINVAL;
4629                 }
4630                 cur->active_spin_lock = 0;
4631         }
4632         return 0;
4633 }
4634
4635 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4636 {
4637         return type == ARG_PTR_TO_MEM ||
4638                type == ARG_PTR_TO_MEM_OR_NULL ||
4639                type == ARG_PTR_TO_UNINIT_MEM;
4640 }
4641
4642 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4643 {
4644         return type == ARG_CONST_SIZE ||
4645                type == ARG_CONST_SIZE_OR_ZERO;
4646 }
4647
4648 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4649 {
4650         return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4651 }
4652
4653 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4654 {
4655         return type == ARG_PTR_TO_INT ||
4656                type == ARG_PTR_TO_LONG;
4657 }
4658
4659 static int int_ptr_type_to_size(enum bpf_arg_type type)
4660 {
4661         if (type == ARG_PTR_TO_INT)
4662                 return sizeof(u32);
4663         else if (type == ARG_PTR_TO_LONG)
4664                 return sizeof(u64);
4665
4666         return -EINVAL;
4667 }
4668
4669 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4670                                  const struct bpf_call_arg_meta *meta,
4671                                  enum bpf_arg_type *arg_type)
4672 {
4673         if (!meta->map_ptr) {
4674                 /* kernel subsystem misconfigured verifier */
4675                 verbose(env, "invalid map_ptr to access map->type\n");
4676                 return -EACCES;
4677         }
4678
4679         switch (meta->map_ptr->map_type) {
4680         case BPF_MAP_TYPE_SOCKMAP:
4681         case BPF_MAP_TYPE_SOCKHASH:
4682                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4683                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4684                 } else {
4685                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
4686                         return -EINVAL;
4687                 }
4688                 break;
4689
4690         default:
4691                 break;
4692         }
4693         return 0;
4694 }
4695
4696 struct bpf_reg_types {
4697         const enum bpf_reg_type types[10];
4698         u32 *btf_id;
4699 };
4700
4701 static const struct bpf_reg_types map_key_value_types = {
4702         .types = {
4703                 PTR_TO_STACK,
4704                 PTR_TO_PACKET,
4705                 PTR_TO_PACKET_META,
4706                 PTR_TO_MAP_KEY,
4707                 PTR_TO_MAP_VALUE,
4708         },
4709 };
4710
4711 static const struct bpf_reg_types sock_types = {
4712         .types = {
4713                 PTR_TO_SOCK_COMMON,
4714                 PTR_TO_SOCKET,
4715                 PTR_TO_TCP_SOCK,
4716                 PTR_TO_XDP_SOCK,
4717         },
4718 };
4719
4720 #ifdef CONFIG_NET
4721 static const struct bpf_reg_types btf_id_sock_common_types = {
4722         .types = {
4723                 PTR_TO_SOCK_COMMON,
4724                 PTR_TO_SOCKET,
4725                 PTR_TO_TCP_SOCK,
4726                 PTR_TO_XDP_SOCK,
4727                 PTR_TO_BTF_ID,
4728         },
4729         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4730 };
4731 #endif
4732
4733 static const struct bpf_reg_types mem_types = {
4734         .types = {
4735                 PTR_TO_STACK,
4736                 PTR_TO_PACKET,
4737                 PTR_TO_PACKET_META,
4738                 PTR_TO_MAP_KEY,
4739                 PTR_TO_MAP_VALUE,
4740                 PTR_TO_MEM,
4741                 PTR_TO_RDONLY_BUF,
4742                 PTR_TO_RDWR_BUF,
4743         },
4744 };
4745
4746 static const struct bpf_reg_types int_ptr_types = {
4747         .types = {
4748                 PTR_TO_STACK,
4749                 PTR_TO_PACKET,
4750                 PTR_TO_PACKET_META,
4751                 PTR_TO_MAP_KEY,
4752                 PTR_TO_MAP_VALUE,
4753         },
4754 };
4755
4756 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4757 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4758 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4759 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4760 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4761 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4762 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4763 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4764 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4765 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
4766 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
4767
4768 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4769         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
4770         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
4771         [ARG_PTR_TO_UNINIT_MAP_VALUE]   = &map_key_value_types,
4772         [ARG_PTR_TO_MAP_VALUE_OR_NULL]  = &map_key_value_types,
4773         [ARG_CONST_SIZE]                = &scalar_types,
4774         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
4775         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
4776         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
4777         [ARG_PTR_TO_CTX]                = &context_types,
4778         [ARG_PTR_TO_CTX_OR_NULL]        = &context_types,
4779         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
4780 #ifdef CONFIG_NET
4781         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4782 #endif
4783         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
4784         [ARG_PTR_TO_SOCKET_OR_NULL]     = &fullsock_types,
4785         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
4786         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
4787         [ARG_PTR_TO_MEM]                = &mem_types,
4788         [ARG_PTR_TO_MEM_OR_NULL]        = &mem_types,
4789         [ARG_PTR_TO_UNINIT_MEM]         = &mem_types,
4790         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
4791         [ARG_PTR_TO_ALLOC_MEM_OR_NULL]  = &alloc_mem_types,
4792         [ARG_PTR_TO_INT]                = &int_ptr_types,
4793         [ARG_PTR_TO_LONG]               = &int_ptr_types,
4794         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
4795         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
4796         [ARG_PTR_TO_STACK_OR_NULL]      = &stack_ptr_types,
4797         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
4798 };
4799
4800 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4801                           enum bpf_arg_type arg_type,
4802                           const u32 *arg_btf_id)
4803 {
4804         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4805         enum bpf_reg_type expected, type = reg->type;
4806         const struct bpf_reg_types *compatible;
4807         int i, j;
4808
4809         compatible = compatible_reg_types[arg_type];
4810         if (!compatible) {
4811                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4812                 return -EFAULT;
4813         }
4814
4815         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4816                 expected = compatible->types[i];
4817                 if (expected == NOT_INIT)
4818                         break;
4819
4820                 if (type == expected)
4821                         goto found;
4822         }
4823
4824         verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4825         for (j = 0; j + 1 < i; j++)
4826                 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4827         verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4828         return -EACCES;
4829
4830 found:
4831         if (type == PTR_TO_BTF_ID) {
4832                 if (!arg_btf_id) {
4833                         if (!compatible->btf_id) {
4834                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4835                                 return -EFAULT;
4836                         }
4837                         arg_btf_id = compatible->btf_id;
4838                 }
4839
4840                 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4841                                           btf_vmlinux, *arg_btf_id)) {
4842                         verbose(env, "R%d is of type %s but %s is expected\n",
4843                                 regno, kernel_type_name(reg->btf, reg->btf_id),
4844                                 kernel_type_name(btf_vmlinux, *arg_btf_id));
4845                         return -EACCES;
4846                 }
4847
4848                 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4849                         verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4850                                 regno);
4851                         return -EACCES;
4852                 }
4853         }
4854
4855         return 0;
4856 }
4857
4858 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4859                           struct bpf_call_arg_meta *meta,
4860                           const struct bpf_func_proto *fn)
4861 {
4862         u32 regno = BPF_REG_1 + arg;
4863         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4864         enum bpf_arg_type arg_type = fn->arg_type[arg];
4865         enum bpf_reg_type type = reg->type;
4866         int err = 0;
4867
4868         if (arg_type == ARG_DONTCARE)
4869                 return 0;
4870
4871         err = check_reg_arg(env, regno, SRC_OP);
4872         if (err)
4873                 return err;
4874
4875         if (arg_type == ARG_ANYTHING) {
4876                 if (is_pointer_value(env, regno)) {
4877                         verbose(env, "R%d leaks addr into helper function\n",
4878                                 regno);
4879                         return -EACCES;
4880                 }
4881                 return 0;
4882         }
4883
4884         if (type_is_pkt_pointer(type) &&
4885             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4886                 verbose(env, "helper access to the packet is not allowed\n");
4887                 return -EACCES;
4888         }
4889
4890         if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4891             arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4892             arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4893                 err = resolve_map_arg_type(env, meta, &arg_type);
4894                 if (err)
4895                         return err;
4896         }
4897
4898         if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4899                 /* A NULL register has a SCALAR_VALUE type, so skip
4900                  * type checking.
4901                  */
4902                 goto skip_type_check;
4903
4904         err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4905         if (err)
4906                 return err;
4907
4908         if (type == PTR_TO_CTX) {
4909                 err = check_ctx_reg(env, reg, regno);
4910                 if (err < 0)
4911                         return err;
4912         }
4913
4914 skip_type_check:
4915         if (reg->ref_obj_id) {
4916                 if (meta->ref_obj_id) {
4917                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4918                                 regno, reg->ref_obj_id,
4919                                 meta->ref_obj_id);
4920                         return -EFAULT;
4921                 }
4922                 meta->ref_obj_id = reg->ref_obj_id;
4923         }
4924
4925         if (arg_type == ARG_CONST_MAP_PTR) {
4926                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4927                 meta->map_ptr = reg->map_ptr;
4928         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4929                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4930                  * check that [key, key + map->key_size) are within
4931                  * stack limits and initialized
4932                  */
4933                 if (!meta->map_ptr) {
4934                         /* in function declaration map_ptr must come before
4935                          * map_key, so that it's verified and known before
4936                          * we have to check map_key here. Otherwise it means
4937                          * that kernel subsystem misconfigured verifier
4938                          */
4939                         verbose(env, "invalid map_ptr to access map->key\n");
4940                         return -EACCES;
4941                 }
4942                 err = check_helper_mem_access(env, regno,
4943                                               meta->map_ptr->key_size, false,
4944                                               NULL);
4945         } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4946                    (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4947                     !register_is_null(reg)) ||
4948                    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4949                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4950                  * check [value, value + map->value_size) validity
4951                  */
4952                 if (!meta->map_ptr) {
4953                         /* kernel subsystem misconfigured verifier */
4954                         verbose(env, "invalid map_ptr to access map->value\n");
4955                         return -EACCES;
4956                 }
4957                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4958                 err = check_helper_mem_access(env, regno,
4959                                               meta->map_ptr->value_size, false,
4960                                               meta);
4961         } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4962                 if (!reg->btf_id) {
4963                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4964                         return -EACCES;
4965                 }
4966                 meta->ret_btf = reg->btf;
4967                 meta->ret_btf_id = reg->btf_id;
4968         } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4969                 if (meta->func_id == BPF_FUNC_spin_lock) {
4970                         if (process_spin_lock(env, regno, true))
4971                                 return -EACCES;
4972                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4973                         if (process_spin_lock(env, regno, false))
4974                                 return -EACCES;
4975                 } else {
4976                         verbose(env, "verifier internal error\n");
4977                         return -EFAULT;
4978                 }
4979         } else if (arg_type == ARG_PTR_TO_FUNC) {
4980                 meta->subprogno = reg->subprogno;
4981         } else if (arg_type_is_mem_ptr(arg_type)) {
4982                 /* The access to this pointer is only checked when we hit the
4983                  * next is_mem_size argument below.
4984                  */
4985                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4986         } else if (arg_type_is_mem_size(arg_type)) {
4987                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4988
4989                 /* This is used to refine r0 return value bounds for helpers
4990                  * that enforce this value as an upper bound on return values.
4991                  * See do_refine_retval_range() for helpers that can refine
4992                  * the return value. C type of helper is u32 so we pull register
4993                  * bound from umax_value however, if negative verifier errors
4994                  * out. Only upper bounds can be learned because retval is an
4995                  * int type and negative retvals are allowed.
4996                  */
4997                 meta->msize_max_value = reg->umax_value;
4998
4999                 /* The register is SCALAR_VALUE; the access check
5000                  * happens using its boundaries.
5001                  */
5002                 if (!tnum_is_const(reg->var_off))
5003                         /* For unprivileged variable accesses, disable raw
5004                          * mode so that the program is required to
5005                          * initialize all the memory that the helper could
5006                          * just partially fill up.
5007                          */
5008                         meta = NULL;
5009
5010                 if (reg->smin_value < 0) {
5011                         verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5012                                 regno);
5013                         return -EACCES;
5014                 }
5015
5016                 if (reg->umin_value == 0) {
5017                         err = check_helper_mem_access(env, regno - 1, 0,
5018                                                       zero_size_allowed,
5019                                                       meta);
5020                         if (err)
5021                                 return err;
5022                 }
5023
5024                 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5025                         verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5026                                 regno);
5027                         return -EACCES;
5028                 }
5029                 err = check_helper_mem_access(env, regno - 1,
5030                                               reg->umax_value,
5031                                               zero_size_allowed, meta);
5032                 if (!err)
5033                         err = mark_chain_precision(env, regno);
5034         } else if (arg_type_is_alloc_size(arg_type)) {
5035                 if (!tnum_is_const(reg->var_off)) {
5036                         verbose(env, "R%d is not a known constant'\n",
5037                                 regno);
5038                         return -EACCES;
5039                 }
5040                 meta->mem_size = reg->var_off.value;
5041         } else if (arg_type_is_int_ptr(arg_type)) {
5042                 int size = int_ptr_type_to_size(arg_type);
5043
5044                 err = check_helper_mem_access(env, regno, size, false, meta);
5045                 if (err)
5046                         return err;
5047                 err = check_ptr_alignment(env, reg, 0, size, true);
5048         } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5049                 struct bpf_map *map = reg->map_ptr;
5050                 int map_off;
5051                 u64 map_addr;
5052                 char *str_ptr;
5053
5054                 if (!bpf_map_is_rdonly(map)) {
5055                         verbose(env, "R%d does not point to a readonly map'\n", regno);
5056                         return -EACCES;
5057                 }
5058
5059                 if (!tnum_is_const(reg->var_off)) {
5060                         verbose(env, "R%d is not a constant address'\n", regno);
5061                         return -EACCES;
5062                 }
5063
5064                 if (!map->ops->map_direct_value_addr) {
5065                         verbose(env, "no direct value access support for this map type\n");
5066                         return -EACCES;
5067                 }
5068
5069                 err = check_map_access(env, regno, reg->off,
5070                                        map->value_size - reg->off, false);
5071                 if (err)
5072                         return err;
5073
5074                 map_off = reg->off + reg->var_off.value;
5075                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5076                 if (err) {
5077                         verbose(env, "direct value access on string failed\n");
5078                         return err;
5079                 }
5080
5081                 str_ptr = (char *)(long)(map_addr);
5082                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5083                         verbose(env, "string is not zero-terminated\n");
5084                         return -EINVAL;
5085                 }
5086         }
5087
5088         return err;
5089 }
5090
5091 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5092 {
5093         enum bpf_attach_type eatype = env->prog->expected_attach_type;
5094         enum bpf_prog_type type = resolve_prog_type(env->prog);
5095
5096         if (func_id != BPF_FUNC_map_update_elem)
5097                 return false;
5098
5099         /* It's not possible to get access to a locked struct sock in these
5100          * contexts, so updating is safe.
5101          */
5102         switch (type) {
5103         case BPF_PROG_TYPE_TRACING:
5104                 if (eatype == BPF_TRACE_ITER)
5105                         return true;
5106                 break;
5107         case BPF_PROG_TYPE_SOCKET_FILTER:
5108         case BPF_PROG_TYPE_SCHED_CLS:
5109         case BPF_PROG_TYPE_SCHED_ACT:
5110         case BPF_PROG_TYPE_XDP:
5111         case BPF_PROG_TYPE_SK_REUSEPORT:
5112         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5113         case BPF_PROG_TYPE_SK_LOOKUP:
5114                 return true;
5115         default:
5116                 break;
5117         }
5118
5119         verbose(env, "cannot update sockmap in this context\n");
5120         return false;
5121 }
5122
5123 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5124 {
5125         return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5126 }
5127
5128 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5129                                         struct bpf_map *map, int func_id)
5130 {
5131         if (!map)
5132                 return 0;
5133
5134         /* We need a two way check, first is from map perspective ... */
5135         switch (map->map_type) {
5136         case BPF_MAP_TYPE_PROG_ARRAY:
5137                 if (func_id != BPF_FUNC_tail_call)
5138                         goto error;
5139                 break;
5140         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5141                 if (func_id != BPF_FUNC_perf_event_read &&
5142                     func_id != BPF_FUNC_perf_event_output &&
5143                     func_id != BPF_FUNC_skb_output &&
5144                     func_id != BPF_FUNC_perf_event_read_value &&
5145                     func_id != BPF_FUNC_xdp_output)
5146                         goto error;
5147                 break;
5148         case BPF_MAP_TYPE_RINGBUF:
5149                 if (func_id != BPF_FUNC_ringbuf_output &&
5150                     func_id != BPF_FUNC_ringbuf_reserve &&
5151                     func_id != BPF_FUNC_ringbuf_query)
5152                         goto error;
5153                 break;
5154         case BPF_MAP_TYPE_STACK_TRACE:
5155                 if (func_id != BPF_FUNC_get_stackid)
5156                         goto error;
5157                 break;
5158         case BPF_MAP_TYPE_CGROUP_ARRAY:
5159                 if (func_id != BPF_FUNC_skb_under_cgroup &&
5160                     func_id != BPF_FUNC_current_task_under_cgroup)
5161                         goto error;
5162                 break;
5163         case BPF_MAP_TYPE_CGROUP_STORAGE:
5164         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5165                 if (func_id != BPF_FUNC_get_local_storage)
5166                         goto error;
5167                 break;
5168         case BPF_MAP_TYPE_DEVMAP:
5169         case BPF_MAP_TYPE_DEVMAP_HASH:
5170                 if (func_id != BPF_FUNC_redirect_map &&
5171                     func_id != BPF_FUNC_map_lookup_elem)
5172                         goto error;
5173                 break;
5174         /* Restrict bpf side of cpumap and xskmap, open when use-cases
5175          * appear.
5176          */
5177         case BPF_MAP_TYPE_CPUMAP:
5178                 if (func_id != BPF_FUNC_redirect_map)
5179                         goto error;
5180                 break;
5181         case BPF_MAP_TYPE_XSKMAP:
5182                 if (func_id != BPF_FUNC_redirect_map &&
5183                     func_id != BPF_FUNC_map_lookup_elem)
5184                         goto error;
5185                 break;
5186         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5187         case BPF_MAP_TYPE_HASH_OF_MAPS:
5188                 if (func_id != BPF_FUNC_map_lookup_elem)
5189                         goto error;
5190                 break;
5191         case BPF_MAP_TYPE_SOCKMAP:
5192                 if (func_id != BPF_FUNC_sk_redirect_map &&
5193                     func_id != BPF_FUNC_sock_map_update &&
5194                     func_id != BPF_FUNC_map_delete_elem &&
5195                     func_id != BPF_FUNC_msg_redirect_map &&
5196                     func_id != BPF_FUNC_sk_select_reuseport &&
5197                     func_id != BPF_FUNC_map_lookup_elem &&
5198                     !may_update_sockmap(env, func_id))
5199                         goto error;
5200                 break;
5201         case BPF_MAP_TYPE_SOCKHASH:
5202                 if (func_id != BPF_FUNC_sk_redirect_hash &&
5203                     func_id != BPF_FUNC_sock_hash_update &&
5204                     func_id != BPF_FUNC_map_delete_elem &&
5205                     func_id != BPF_FUNC_msg_redirect_hash &&
5206                     func_id != BPF_FUNC_sk_select_reuseport &&
5207                     func_id != BPF_FUNC_map_lookup_elem &&
5208                     !may_update_sockmap(env, func_id))
5209                         goto error;
5210                 break;
5211         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5212                 if (func_id != BPF_FUNC_sk_select_reuseport)
5213                         goto error;
5214                 break;
5215         case BPF_MAP_TYPE_QUEUE:
5216         case BPF_MAP_TYPE_STACK:
5217                 if (func_id != BPF_FUNC_map_peek_elem &&
5218                     func_id != BPF_FUNC_map_pop_elem &&
5219                     func_id != BPF_FUNC_map_push_elem)
5220                         goto error;
5221                 break;
5222         case BPF_MAP_TYPE_SK_STORAGE:
5223                 if (func_id != BPF_FUNC_sk_storage_get &&
5224                     func_id != BPF_FUNC_sk_storage_delete)
5225                         goto error;
5226                 break;
5227         case BPF_MAP_TYPE_INODE_STORAGE:
5228                 if (func_id != BPF_FUNC_inode_storage_get &&
5229                     func_id != BPF_FUNC_inode_storage_delete)
5230                         goto error;
5231                 break;
5232         case BPF_MAP_TYPE_TASK_STORAGE:
5233                 if (func_id != BPF_FUNC_task_storage_get &&
5234                     func_id != BPF_FUNC_task_storage_delete)
5235                         goto error;
5236                 break;
5237         default:
5238                 break;
5239         }
5240
5241         /* ... and second from the function itself. */
5242         switch (func_id) {
5243         case BPF_FUNC_tail_call:
5244                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5245                         goto error;
5246                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5247                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5248                         return -EINVAL;
5249                 }
5250                 break;
5251         case BPF_FUNC_perf_event_read:
5252         case BPF_FUNC_perf_event_output:
5253         case BPF_FUNC_perf_event_read_value:
5254         case BPF_FUNC_skb_output:
5255         case BPF_FUNC_xdp_output:
5256                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5257                         goto error;
5258                 break;
5259         case BPF_FUNC_ringbuf_output:
5260         case BPF_FUNC_ringbuf_reserve:
5261         case BPF_FUNC_ringbuf_query:
5262                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5263                         goto error;
5264                 break;
5265         case BPF_FUNC_get_stackid:
5266                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5267                         goto error;
5268                 break;
5269         case BPF_FUNC_current_task_under_cgroup:
5270         case BPF_FUNC_skb_under_cgroup:
5271                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5272                         goto error;
5273                 break;
5274         case BPF_FUNC_redirect_map:
5275                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5276                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5277                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
5278                     map->map_type != BPF_MAP_TYPE_XSKMAP)
5279                         goto error;
5280                 break;
5281         case BPF_FUNC_sk_redirect_map:
5282         case BPF_FUNC_msg_redirect_map:
5283         case BPF_FUNC_sock_map_update:
5284                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5285                         goto error;
5286                 break;
5287         case BPF_FUNC_sk_redirect_hash:
5288         case BPF_FUNC_msg_redirect_hash:
5289         case BPF_FUNC_sock_hash_update:
5290                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5291                         goto error;
5292                 break;
5293         case BPF_FUNC_get_local_storage:
5294                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5295                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5296                         goto error;
5297                 break;
5298         case BPF_FUNC_sk_select_reuseport:
5299                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5300                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5301                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
5302                         goto error;
5303                 break;
5304         case BPF_FUNC_map_peek_elem:
5305         case BPF_FUNC_map_pop_elem:
5306         case BPF_FUNC_map_push_elem:
5307                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5308                     map->map_type != BPF_MAP_TYPE_STACK)
5309                         goto error;
5310                 break;
5311         case BPF_FUNC_sk_storage_get:
5312         case BPF_FUNC_sk_storage_delete:
5313                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5314                         goto error;
5315                 break;
5316         case BPF_FUNC_inode_storage_get:
5317         case BPF_FUNC_inode_storage_delete:
5318                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5319                         goto error;
5320                 break;
5321         case BPF_FUNC_task_storage_get:
5322         case BPF_FUNC_task_storage_delete:
5323                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5324                         goto error;
5325                 break;
5326         default:
5327                 break;
5328         }
5329
5330         return 0;
5331 error:
5332         verbose(env, "cannot pass map_type %d into func %s#%d\n",
5333                 map->map_type, func_id_name(func_id), func_id);
5334         return -EINVAL;
5335 }
5336
5337 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5338 {
5339         int count = 0;
5340
5341         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5342                 count++;
5343         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5344                 count++;
5345         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5346                 count++;
5347         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5348                 count++;
5349         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5350                 count++;
5351
5352         /* We only support one arg being in raw mode at the moment,
5353          * which is sufficient for the helper functions we have
5354          * right now.
5355          */
5356         return count <= 1;
5357 }
5358
5359 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5360                                     enum bpf_arg_type arg_next)
5361 {
5362         return (arg_type_is_mem_ptr(arg_curr) &&
5363                 !arg_type_is_mem_size(arg_next)) ||
5364                (!arg_type_is_mem_ptr(arg_curr) &&
5365                 arg_type_is_mem_size(arg_next));
5366 }
5367
5368 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5369 {
5370         /* bpf_xxx(..., buf, len) call will access 'len'
5371          * bytes from memory 'buf'. Both arg types need
5372          * to be paired, so make sure there's no buggy
5373          * helper function specification.
5374          */
5375         if (arg_type_is_mem_size(fn->arg1_type) ||
5376             arg_type_is_mem_ptr(fn->arg5_type)  ||
5377             check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5378             check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5379             check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5380             check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5381                 return false;
5382
5383         return true;
5384 }
5385
5386 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5387 {
5388         int count = 0;
5389
5390         if (arg_type_may_be_refcounted(fn->arg1_type))
5391                 count++;
5392         if (arg_type_may_be_refcounted(fn->arg2_type))
5393                 count++;
5394         if (arg_type_may_be_refcounted(fn->arg3_type))
5395                 count++;
5396         if (arg_type_may_be_refcounted(fn->arg4_type))
5397                 count++;
5398         if (arg_type_may_be_refcounted(fn->arg5_type))
5399                 count++;
5400
5401         /* A reference acquiring function cannot acquire
5402          * another refcounted ptr.
5403          */
5404         if (may_be_acquire_function(func_id) && count)
5405                 return false;
5406
5407         /* We only support one arg being unreferenced at the moment,
5408          * which is sufficient for the helper functions we have right now.
5409          */
5410         return count <= 1;
5411 }
5412
5413 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5414 {
5415         int i;
5416
5417         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5418                 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5419                         return false;
5420
5421                 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5422                         return false;
5423         }
5424
5425         return true;
5426 }
5427
5428 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5429 {
5430         return check_raw_mode_ok(fn) &&
5431                check_arg_pair_ok(fn) &&
5432                check_btf_id_ok(fn) &&
5433                check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5434 }
5435
5436 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5437  * are now invalid, so turn them into unknown SCALAR_VALUE.
5438  */
5439 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5440                                      struct bpf_func_state *state)
5441 {
5442         struct bpf_reg_state *regs = state->regs, *reg;
5443         int i;
5444
5445         for (i = 0; i < MAX_BPF_REG; i++)
5446                 if (reg_is_pkt_pointer_any(&regs[i]))
5447                         mark_reg_unknown(env, regs, i);
5448
5449         bpf_for_each_spilled_reg(i, state, reg) {
5450                 if (!reg)
5451                         continue;
5452                 if (reg_is_pkt_pointer_any(reg))
5453                         __mark_reg_unknown(env, reg);
5454         }
5455 }
5456
5457 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5458 {
5459         struct bpf_verifier_state *vstate = env->cur_state;
5460         int i;
5461
5462         for (i = 0; i <= vstate->curframe; i++)
5463                 __clear_all_pkt_pointers(env, vstate->frame[i]);
5464 }
5465
5466 enum {
5467         AT_PKT_END = -1,
5468         BEYOND_PKT_END = -2,
5469 };
5470
5471 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5472 {
5473         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5474         struct bpf_reg_state *reg = &state->regs[regn];
5475
5476         if (reg->type != PTR_TO_PACKET)
5477                 /* PTR_TO_PACKET_META is not supported yet */
5478                 return;
5479
5480         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5481          * How far beyond pkt_end it goes is unknown.
5482          * if (!range_open) it's the case of pkt >= pkt_end
5483          * if (range_open) it's the case of pkt > pkt_end
5484          * hence this pointer is at least 1 byte bigger than pkt_end
5485          */
5486         if (range_open)
5487                 reg->range = BEYOND_PKT_END;
5488         else
5489                 reg->range = AT_PKT_END;
5490 }
5491
5492 static void release_reg_references(struct bpf_verifier_env *env,
5493                                    struct bpf_func_state *state,
5494                                    int ref_obj_id)
5495 {
5496         struct bpf_reg_state *regs = state->regs, *reg;
5497         int i;
5498
5499         for (i = 0; i < MAX_BPF_REG; i++)
5500                 if (regs[i].ref_obj_id == ref_obj_id)
5501                         mark_reg_unknown(env, regs, i);
5502
5503         bpf_for_each_spilled_reg(i, state, reg) {
5504                 if (!reg)
5505                         continue;
5506                 if (reg->ref_obj_id == ref_obj_id)
5507                         __mark_reg_unknown(env, reg);
5508         }
5509 }
5510
5511 /* The pointer with the specified id has released its reference to kernel
5512  * resources. Identify all copies of the same pointer and clear the reference.
5513  */
5514 static int release_reference(struct bpf_verifier_env *env,
5515                              int ref_obj_id)
5516 {
5517         struct bpf_verifier_state *vstate = env->cur_state;
5518         int err;
5519         int i;
5520
5521         err = release_reference_state(cur_func(env), ref_obj_id);
5522         if (err)
5523                 return err;
5524
5525         for (i = 0; i <= vstate->curframe; i++)
5526                 release_reg_references(env, vstate->frame[i], ref_obj_id);
5527
5528         return 0;
5529 }
5530
5531 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5532                                     struct bpf_reg_state *regs)
5533 {
5534         int i;
5535
5536         /* after the call registers r0 - r5 were scratched */
5537         for (i = 0; i < CALLER_SAVED_REGS; i++) {
5538                 mark_reg_not_init(env, regs, caller_saved[i]);
5539                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5540         }
5541 }
5542
5543 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5544                                    struct bpf_func_state *caller,
5545                                    struct bpf_func_state *callee,
5546                                    int insn_idx);
5547
5548 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5549                              int *insn_idx, int subprog,
5550                              set_callee_state_fn set_callee_state_cb)
5551 {
5552         struct bpf_verifier_state *state = env->cur_state;
5553         struct bpf_func_info_aux *func_info_aux;
5554         struct bpf_func_state *caller, *callee;
5555         int err;
5556         bool is_global = false;
5557
5558         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5559                 verbose(env, "the call stack of %d frames is too deep\n",
5560                         state->curframe + 2);
5561                 return -E2BIG;
5562         }
5563
5564         caller = state->frame[state->curframe];
5565         if (state->frame[state->curframe + 1]) {
5566                 verbose(env, "verifier bug. Frame %d already allocated\n",
5567                         state->curframe + 1);
5568                 return -EFAULT;
5569         }
5570
5571         func_info_aux = env->prog->aux->func_info_aux;
5572         if (func_info_aux)
5573                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5574         err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5575         if (err == -EFAULT)
5576                 return err;
5577         if (is_global) {
5578                 if (err) {
5579                         verbose(env, "Caller passes invalid args into func#%d\n",
5580                                 subprog);
5581                         return err;
5582                 } else {
5583                         if (env->log.level & BPF_LOG_LEVEL)
5584                                 verbose(env,
5585                                         "Func#%d is global and valid. Skipping.\n",
5586                                         subprog);
5587                         clear_caller_saved_regs(env, caller->regs);
5588
5589                         /* All global functions return a 64-bit SCALAR_VALUE */
5590                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
5591                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5592
5593                         /* continue with next insn after call */
5594                         return 0;
5595                 }
5596         }
5597
5598         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5599         if (!callee)
5600                 return -ENOMEM;
5601         state->frame[state->curframe + 1] = callee;
5602
5603         /* callee cannot access r0, r6 - r9 for reading and has to write
5604          * into its own stack before reading from it.
5605          * callee can read/write into caller's stack
5606          */
5607         init_func_state(env, callee,
5608                         /* remember the callsite, it will be used by bpf_exit */
5609                         *insn_idx /* callsite */,
5610                         state->curframe + 1 /* frameno within this callchain */,
5611                         subprog /* subprog number within this prog */);
5612
5613         /* Transfer references to the callee */
5614         err = transfer_reference_state(callee, caller);
5615         if (err)
5616                 return err;
5617
5618         err = set_callee_state_cb(env, caller, callee, *insn_idx);
5619         if (err)
5620                 return err;
5621
5622         clear_caller_saved_regs(env, caller->regs);
5623
5624         /* only increment it after check_reg_arg() finished */
5625         state->curframe++;
5626
5627         /* and go analyze first insn of the callee */
5628         *insn_idx = env->subprog_info[subprog].start - 1;
5629
5630         if (env->log.level & BPF_LOG_LEVEL) {
5631                 verbose(env, "caller:\n");
5632                 print_verifier_state(env, caller);
5633                 verbose(env, "callee:\n");
5634                 print_verifier_state(env, callee);
5635         }
5636         return 0;
5637 }
5638
5639 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5640                                    struct bpf_func_state *caller,
5641                                    struct bpf_func_state *callee)
5642 {
5643         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5644          *      void *callback_ctx, u64 flags);
5645          * callback_fn(struct bpf_map *map, void *key, void *value,
5646          *      void *callback_ctx);
5647          */
5648         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5649
5650         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5651         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5652         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5653
5654         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5655         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5656         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5657
5658         /* pointer to stack or null */
5659         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5660
5661         /* unused */
5662         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5663         return 0;
5664 }
5665
5666 static int set_callee_state(struct bpf_verifier_env *env,
5667                             struct bpf_func_state *caller,
5668                             struct bpf_func_state *callee, int insn_idx)
5669 {
5670         int i;
5671
5672         /* copy r1 - r5 args that callee can access.  The copy includes parent
5673          * pointers, which connects us up to the liveness chain
5674          */
5675         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5676                 callee->regs[i] = caller->regs[i];
5677         return 0;
5678 }
5679
5680 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5681                            int *insn_idx)
5682 {
5683         int subprog, target_insn;
5684
5685         target_insn = *insn_idx + insn->imm + 1;
5686         subprog = find_subprog(env, target_insn);
5687         if (subprog < 0) {
5688                 verbose(env, "verifier bug. No program starts at insn %d\n",
5689                         target_insn);
5690                 return -EFAULT;
5691         }
5692
5693         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5694 }
5695
5696 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5697                                        struct bpf_func_state *caller,
5698                                        struct bpf_func_state *callee,
5699                                        int insn_idx)
5700 {
5701         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5702         struct bpf_map *map;
5703         int err;
5704
5705         if (bpf_map_ptr_poisoned(insn_aux)) {
5706                 verbose(env, "tail_call abusing map_ptr\n");
5707                 return -EINVAL;
5708         }
5709
5710         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5711         if (!map->ops->map_set_for_each_callback_args ||
5712             !map->ops->map_for_each_callback) {
5713                 verbose(env, "callback function not allowed for map\n");
5714                 return -ENOTSUPP;
5715         }
5716
5717         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5718         if (err)
5719                 return err;
5720
5721         callee->in_callback_fn = true;
5722         return 0;
5723 }
5724
5725 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5726 {
5727         struct bpf_verifier_state *state = env->cur_state;
5728         struct bpf_func_state *caller, *callee;
5729         struct bpf_reg_state *r0;
5730         int err;
5731
5732         callee = state->frame[state->curframe];
5733         r0 = &callee->regs[BPF_REG_0];
5734         if (r0->type == PTR_TO_STACK) {
5735                 /* technically it's ok to return caller's stack pointer
5736                  * (or caller's caller's pointer) back to the caller,
5737                  * since these pointers are valid. Only current stack
5738                  * pointer will be invalid as soon as function exits,
5739                  * but let's be conservative
5740                  */
5741                 verbose(env, "cannot return stack pointer to the caller\n");
5742                 return -EINVAL;
5743         }
5744
5745         state->curframe--;
5746         caller = state->frame[state->curframe];
5747         if (callee->in_callback_fn) {
5748                 /* enforce R0 return value range [0, 1]. */
5749                 struct tnum range = tnum_range(0, 1);
5750
5751                 if (r0->type != SCALAR_VALUE) {
5752                         verbose(env, "R0 not a scalar value\n");
5753                         return -EACCES;
5754                 }
5755                 if (!tnum_in(range, r0->var_off)) {
5756                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5757                         return -EINVAL;
5758                 }
5759         } else {
5760                 /* return to the caller whatever r0 had in the callee */
5761                 caller->regs[BPF_REG_0] = *r0;
5762         }
5763
5764         /* Transfer references to the caller */
5765         err = transfer_reference_state(caller, callee);
5766         if (err)
5767                 return err;
5768
5769         *insn_idx = callee->callsite + 1;
5770         if (env->log.level & BPF_LOG_LEVEL) {
5771                 verbose(env, "returning from callee:\n");
5772                 print_verifier_state(env, callee);
5773                 verbose(env, "to caller at %d:\n", *insn_idx);
5774                 print_verifier_state(env, caller);
5775         }
5776         /* clear everything in the callee */
5777         free_func_state(callee);
5778         state->frame[state->curframe + 1] = NULL;
5779         return 0;
5780 }
5781
5782 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5783                                    int func_id,
5784                                    struct bpf_call_arg_meta *meta)
5785 {
5786         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5787
5788         if (ret_type != RET_INTEGER ||
5789             (func_id != BPF_FUNC_get_stack &&
5790              func_id != BPF_FUNC_get_task_stack &&
5791              func_id != BPF_FUNC_probe_read_str &&
5792              func_id != BPF_FUNC_probe_read_kernel_str &&
5793              func_id != BPF_FUNC_probe_read_user_str))
5794                 return;
5795
5796         ret_reg->smax_value = meta->msize_max_value;
5797         ret_reg->s32_max_value = meta->msize_max_value;
5798         ret_reg->smin_value = -MAX_ERRNO;
5799         ret_reg->s32_min_value = -MAX_ERRNO;
5800         __reg_deduce_bounds(ret_reg);
5801         __reg_bound_offset(ret_reg);
5802         __update_reg_bounds(ret_reg);
5803 }
5804
5805 static int
5806 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5807                 int func_id, int insn_idx)
5808 {
5809         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5810         struct bpf_map *map = meta->map_ptr;
5811
5812         if (func_id != BPF_FUNC_tail_call &&
5813             func_id != BPF_FUNC_map_lookup_elem &&
5814             func_id != BPF_FUNC_map_update_elem &&
5815             func_id != BPF_FUNC_map_delete_elem &&
5816             func_id != BPF_FUNC_map_push_elem &&
5817             func_id != BPF_FUNC_map_pop_elem &&
5818             func_id != BPF_FUNC_map_peek_elem &&
5819             func_id != BPF_FUNC_for_each_map_elem &&
5820             func_id != BPF_FUNC_redirect_map)
5821                 return 0;
5822
5823         if (map == NULL) {
5824                 verbose(env, "kernel subsystem misconfigured verifier\n");
5825                 return -EINVAL;
5826         }
5827
5828         /* In case of read-only, some additional restrictions
5829          * need to be applied in order to prevent altering the
5830          * state of the map from program side.
5831          */
5832         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5833             (func_id == BPF_FUNC_map_delete_elem ||
5834              func_id == BPF_FUNC_map_update_elem ||
5835              func_id == BPF_FUNC_map_push_elem ||
5836              func_id == BPF_FUNC_map_pop_elem)) {
5837                 verbose(env, "write into map forbidden\n");
5838                 return -EACCES;
5839         }
5840
5841         if (!BPF_MAP_PTR(aux->map_ptr_state))
5842                 bpf_map_ptr_store(aux, meta->map_ptr,
5843                                   !meta->map_ptr->bypass_spec_v1);
5844         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5845                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5846                                   !meta->map_ptr->bypass_spec_v1);
5847         return 0;
5848 }
5849
5850 static int
5851 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5852                 int func_id, int insn_idx)
5853 {
5854         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5855         struct bpf_reg_state *regs = cur_regs(env), *reg;
5856         struct bpf_map *map = meta->map_ptr;
5857         struct tnum range;
5858         u64 val;
5859         int err;
5860
5861         if (func_id != BPF_FUNC_tail_call)
5862                 return 0;
5863         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5864                 verbose(env, "kernel subsystem misconfigured verifier\n");
5865                 return -EINVAL;
5866         }
5867
5868         range = tnum_range(0, map->max_entries - 1);
5869         reg = &regs[BPF_REG_3];
5870
5871         if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5872                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5873                 return 0;
5874         }
5875
5876         err = mark_chain_precision(env, BPF_REG_3);
5877         if (err)
5878                 return err;
5879
5880         val = reg->var_off.value;
5881         if (bpf_map_key_unseen(aux))
5882                 bpf_map_key_store(aux, val);
5883         else if (!bpf_map_key_poisoned(aux) &&
5884                   bpf_map_key_immediate(aux) != val)
5885                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5886         return 0;
5887 }
5888
5889 static int check_reference_leak(struct bpf_verifier_env *env)
5890 {
5891         struct bpf_func_state *state = cur_func(env);
5892         int i;
5893
5894         for (i = 0; i < state->acquired_refs; i++) {
5895                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5896                         state->refs[i].id, state->refs[i].insn_idx);
5897         }
5898         return state->acquired_refs ? -EINVAL : 0;
5899 }
5900
5901 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
5902                                    struct bpf_reg_state *regs)
5903 {
5904         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
5905         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
5906         struct bpf_map *fmt_map = fmt_reg->map_ptr;
5907         int err, fmt_map_off, num_args;
5908         u64 fmt_addr;
5909         char *fmt;
5910
5911         /* data must be an array of u64 */
5912         if (data_len_reg->var_off.value % 8)
5913                 return -EINVAL;
5914         num_args = data_len_reg->var_off.value / 8;
5915
5916         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
5917          * and map_direct_value_addr is set.
5918          */
5919         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
5920         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
5921                                                   fmt_map_off);
5922         if (err) {
5923                 verbose(env, "verifier bug\n");
5924                 return -EFAULT;
5925         }
5926         fmt = (char *)(long)fmt_addr + fmt_map_off;
5927
5928         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
5929          * can focus on validating the format specifiers.
5930          */
5931         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
5932         if (err < 0)
5933                 verbose(env, "Invalid format string\n");
5934
5935         return err;
5936 }
5937
5938 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5939                              int *insn_idx_p)
5940 {
5941         const struct bpf_func_proto *fn = NULL;
5942         struct bpf_reg_state *regs;
5943         struct bpf_call_arg_meta meta;
5944         int insn_idx = *insn_idx_p;
5945         bool changes_data;
5946         int i, err, func_id;
5947
5948         /* find function prototype */
5949         func_id = insn->imm;
5950         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5951                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5952                         func_id);
5953                 return -EINVAL;
5954         }
5955
5956         if (env->ops->get_func_proto)
5957                 fn = env->ops->get_func_proto(func_id, env->prog);
5958         if (!fn) {
5959                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5960                         func_id);
5961                 return -EINVAL;
5962         }
5963
5964         /* eBPF programs must be GPL compatible to use GPL-ed functions */
5965         if (!env->prog->gpl_compatible && fn->gpl_only) {
5966                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5967                 return -EINVAL;
5968         }
5969
5970         if (fn->allowed && !fn->allowed(env->prog)) {
5971                 verbose(env, "helper call is not allowed in probe\n");
5972                 return -EINVAL;
5973         }
5974
5975         /* With LD_ABS/IND some JITs save/restore skb from r1. */
5976         changes_data = bpf_helper_changes_pkt_data(fn->func);
5977         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5978                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5979                         func_id_name(func_id), func_id);
5980                 return -EINVAL;
5981         }
5982
5983         memset(&meta, 0, sizeof(meta));
5984         meta.pkt_access = fn->pkt_access;
5985
5986         err = check_func_proto(fn, func_id);
5987         if (err) {
5988                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5989                         func_id_name(func_id), func_id);
5990                 return err;
5991         }
5992
5993         meta.func_id = func_id;
5994         /* check args */
5995         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
5996                 err = check_func_arg(env, i, &meta, fn);
5997                 if (err)
5998                         return err;
5999         }
6000
6001         err = record_func_map(env, &meta, func_id, insn_idx);
6002         if (err)
6003                 return err;
6004
6005         err = record_func_key(env, &meta, func_id, insn_idx);
6006         if (err)
6007                 return err;
6008
6009         /* Mark slots with STACK_MISC in case of raw mode, stack offset
6010          * is inferred from register state.
6011          */
6012         for (i = 0; i < meta.access_size; i++) {
6013                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6014                                        BPF_WRITE, -1, false);
6015                 if (err)
6016                         return err;
6017         }
6018
6019         if (func_id == BPF_FUNC_tail_call) {
6020                 err = check_reference_leak(env);
6021                 if (err) {
6022                         verbose(env, "tail_call would lead to reference leak\n");
6023                         return err;
6024                 }
6025         } else if (is_release_function(func_id)) {
6026                 err = release_reference(env, meta.ref_obj_id);
6027                 if (err) {
6028                         verbose(env, "func %s#%d reference has not been acquired before\n",
6029                                 func_id_name(func_id), func_id);
6030                         return err;
6031                 }
6032         }
6033
6034         regs = cur_regs(env);
6035
6036         /* check that flags argument in get_local_storage(map, flags) is 0,
6037          * this is required because get_local_storage() can't return an error.
6038          */
6039         if (func_id == BPF_FUNC_get_local_storage &&
6040             !register_is_null(&regs[BPF_REG_2])) {
6041                 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6042                 return -EINVAL;
6043         }
6044
6045         if (func_id == BPF_FUNC_for_each_map_elem) {
6046                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6047                                         set_map_elem_callback_state);
6048                 if (err < 0)
6049                         return -EINVAL;
6050         }
6051
6052         if (func_id == BPF_FUNC_snprintf) {
6053                 err = check_bpf_snprintf_call(env, regs);
6054                 if (err < 0)
6055                         return err;
6056         }
6057
6058         /* reset caller saved regs */
6059         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6060                 mark_reg_not_init(env, regs, caller_saved[i]);
6061                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6062         }
6063
6064         /* helper call returns 64-bit value. */
6065         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6066
6067         /* update return register (already marked as written above) */
6068         if (fn->ret_type == RET_INTEGER) {
6069                 /* sets type to SCALAR_VALUE */
6070                 mark_reg_unknown(env, regs, BPF_REG_0);
6071         } else if (fn->ret_type == RET_VOID) {
6072                 regs[BPF_REG_0].type = NOT_INIT;
6073         } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6074                    fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6075                 /* There is no offset yet applied, variable or fixed */
6076                 mark_reg_known_zero(env, regs, BPF_REG_0);
6077                 /* remember map_ptr, so that check_map_access()
6078                  * can check 'value_size' boundary of memory access
6079                  * to map element returned from bpf_map_lookup_elem()
6080                  */
6081                 if (meta.map_ptr == NULL) {
6082                         verbose(env,
6083                                 "kernel subsystem misconfigured verifier\n");
6084                         return -EINVAL;
6085                 }
6086                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
6087                 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6088                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
6089                         if (map_value_has_spin_lock(meta.map_ptr))
6090                                 regs[BPF_REG_0].id = ++env->id_gen;
6091                 } else {
6092                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
6093                 }
6094         } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6095                 mark_reg_known_zero(env, regs, BPF_REG_0);
6096                 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
6097         } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6098                 mark_reg_known_zero(env, regs, BPF_REG_0);
6099                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
6100         } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6101                 mark_reg_known_zero(env, regs, BPF_REG_0);
6102                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
6103         } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6104                 mark_reg_known_zero(env, regs, BPF_REG_0);
6105                 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
6106                 regs[BPF_REG_0].mem_size = meta.mem_size;
6107         } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6108                    fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
6109                 const struct btf_type *t;
6110
6111                 mark_reg_known_zero(env, regs, BPF_REG_0);
6112                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6113                 if (!btf_type_is_struct(t)) {
6114                         u32 tsize;
6115                         const struct btf_type *ret;
6116                         const char *tname;
6117
6118                         /* resolve the type size of ksym. */
6119                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6120                         if (IS_ERR(ret)) {
6121                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6122                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6123                                         tname, PTR_ERR(ret));
6124                                 return -EINVAL;
6125                         }
6126                         regs[BPF_REG_0].type =
6127                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6128                                 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
6129                         regs[BPF_REG_0].mem_size = tsize;
6130                 } else {
6131                         regs[BPF_REG_0].type =
6132                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6133                                 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
6134                         regs[BPF_REG_0].btf = meta.ret_btf;
6135                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6136                 }
6137         } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6138                    fn->ret_type == RET_PTR_TO_BTF_ID) {
6139                 int ret_btf_id;
6140
6141                 mark_reg_known_zero(env, regs, BPF_REG_0);
6142                 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6143                                                      PTR_TO_BTF_ID :
6144                                                      PTR_TO_BTF_ID_OR_NULL;
6145                 ret_btf_id = *fn->ret_btf_id;
6146                 if (ret_btf_id == 0) {
6147                         verbose(env, "invalid return type %d of func %s#%d\n",
6148                                 fn->ret_type, func_id_name(func_id), func_id);
6149                         return -EINVAL;
6150                 }
6151                 /* current BPF helper definitions are only coming from
6152                  * built-in code with type IDs from  vmlinux BTF
6153                  */
6154                 regs[BPF_REG_0].btf = btf_vmlinux;
6155                 regs[BPF_REG_0].btf_id = ret_btf_id;
6156         } else {
6157                 verbose(env, "unknown return type %d of func %s#%d\n",
6158                         fn->ret_type, func_id_name(func_id), func_id);
6159                 return -EINVAL;
6160         }
6161
6162         if (reg_type_may_be_null(regs[BPF_REG_0].type))
6163                 regs[BPF_REG_0].id = ++env->id_gen;
6164
6165         if (is_ptr_cast_function(func_id)) {
6166                 /* For release_reference() */
6167                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6168         } else if (is_acquire_function(func_id, meta.map_ptr)) {
6169                 int id = acquire_reference_state(env, insn_idx);
6170
6171                 if (id < 0)
6172                         return id;
6173                 /* For mark_ptr_or_null_reg() */
6174                 regs[BPF_REG_0].id = id;
6175                 /* For release_reference() */
6176                 regs[BPF_REG_0].ref_obj_id = id;
6177         }
6178
6179         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6180
6181         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6182         if (err)
6183                 return err;
6184
6185         if ((func_id == BPF_FUNC_get_stack ||
6186              func_id == BPF_FUNC_get_task_stack) &&
6187             !env->prog->has_callchain_buf) {
6188                 const char *err_str;
6189
6190 #ifdef CONFIG_PERF_EVENTS
6191                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6192                 err_str = "cannot get callchain buffer for func %s#%d\n";
6193 #else
6194                 err = -ENOTSUPP;
6195                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6196 #endif
6197                 if (err) {
6198                         verbose(env, err_str, func_id_name(func_id), func_id);
6199                         return err;
6200                 }
6201
6202                 env->prog->has_callchain_buf = true;
6203         }
6204
6205         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6206                 env->prog->call_get_stack = true;
6207
6208         if (changes_data)
6209                 clear_all_pkt_pointers(env);
6210         return 0;
6211 }
6212
6213 /* mark_btf_func_reg_size() is used when the reg size is determined by
6214  * the BTF func_proto's return value size and argument.
6215  */
6216 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6217                                    size_t reg_size)
6218 {
6219         struct bpf_reg_state *reg = &cur_regs(env)[regno];
6220
6221         if (regno == BPF_REG_0) {
6222                 /* Function return value */
6223                 reg->live |= REG_LIVE_WRITTEN;
6224                 reg->subreg_def = reg_size == sizeof(u64) ?
6225                         DEF_NOT_SUBREG : env->insn_idx + 1;
6226         } else {
6227                 /* Function argument */
6228                 if (reg_size == sizeof(u64)) {
6229                         mark_insn_zext(env, reg);
6230                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6231                 } else {
6232                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6233                 }
6234         }
6235 }
6236
6237 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6238 {
6239         const struct btf_type *t, *func, *func_proto, *ptr_type;
6240         struct bpf_reg_state *regs = cur_regs(env);
6241         const char *func_name, *ptr_type_name;
6242         u32 i, nargs, func_id, ptr_type_id;
6243         const struct btf_param *args;
6244         int err;
6245
6246         func_id = insn->imm;
6247         func = btf_type_by_id(btf_vmlinux, func_id);
6248         func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6249         func_proto = btf_type_by_id(btf_vmlinux, func->type);
6250
6251         if (!env->ops->check_kfunc_call ||
6252             !env->ops->check_kfunc_call(func_id)) {
6253                 verbose(env, "calling kernel function %s is not allowed\n",
6254                         func_name);
6255                 return -EACCES;
6256         }
6257
6258         /* Check the arguments */
6259         err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6260         if (err)
6261                 return err;
6262
6263         for (i = 0; i < CALLER_SAVED_REGS; i++)
6264                 mark_reg_not_init(env, regs, caller_saved[i]);
6265
6266         /* Check return type */
6267         t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6268         if (btf_type_is_scalar(t)) {
6269                 mark_reg_unknown(env, regs, BPF_REG_0);
6270                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6271         } else if (btf_type_is_ptr(t)) {
6272                 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6273                                                    &ptr_type_id);
6274                 if (!btf_type_is_struct(ptr_type)) {
6275                         ptr_type_name = btf_name_by_offset(btf_vmlinux,
6276                                                            ptr_type->name_off);
6277                         verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6278                                 func_name, btf_type_str(ptr_type),
6279                                 ptr_type_name);
6280                         return -EINVAL;
6281                 }
6282                 mark_reg_known_zero(env, regs, BPF_REG_0);
6283                 regs[BPF_REG_0].btf = btf_vmlinux;
6284                 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6285                 regs[BPF_REG_0].btf_id = ptr_type_id;
6286                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6287         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6288
6289         nargs = btf_type_vlen(func_proto);
6290         args = (const struct btf_param *)(func_proto + 1);
6291         for (i = 0; i < nargs; i++) {
6292                 u32 regno = i + 1;
6293
6294                 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6295                 if (btf_type_is_ptr(t))
6296                         mark_btf_func_reg_size(env, regno, sizeof(void *));
6297                 else
6298                         /* scalar. ensured by btf_check_kfunc_arg_match() */
6299                         mark_btf_func_reg_size(env, regno, t->size);
6300         }
6301
6302         return 0;
6303 }
6304
6305 static bool signed_add_overflows(s64 a, s64 b)
6306 {
6307         /* Do the add in u64, where overflow is well-defined */
6308         s64 res = (s64)((u64)a + (u64)b);
6309
6310         if (b < 0)
6311                 return res > a;
6312         return res < a;
6313 }
6314
6315 static bool signed_add32_overflows(s32 a, s32 b)
6316 {
6317         /* Do the add in u32, where overflow is well-defined */
6318         s32 res = (s32)((u32)a + (u32)b);
6319
6320         if (b < 0)
6321                 return res > a;
6322         return res < a;
6323 }
6324
6325 static bool signed_sub_overflows(s64 a, s64 b)
6326 {
6327         /* Do the sub in u64, where overflow is well-defined */
6328         s64 res = (s64)((u64)a - (u64)b);
6329
6330         if (b < 0)
6331                 return res < a;
6332         return res > a;
6333 }
6334
6335 static bool signed_sub32_overflows(s32 a, s32 b)
6336 {
6337         /* Do the sub in u32, where overflow is well-defined */
6338         s32 res = (s32)((u32)a - (u32)b);
6339
6340         if (b < 0)
6341                 return res < a;
6342         return res > a;
6343 }
6344
6345 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6346                                   const struct bpf_reg_state *reg,
6347                                   enum bpf_reg_type type)
6348 {
6349         bool known = tnum_is_const(reg->var_off);
6350         s64 val = reg->var_off.value;
6351         s64 smin = reg->smin_value;
6352
6353         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6354                 verbose(env, "math between %s pointer and %lld is not allowed\n",
6355                         reg_type_str[type], val);
6356                 return false;
6357         }
6358
6359         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6360                 verbose(env, "%s pointer offset %d is not allowed\n",
6361                         reg_type_str[type], reg->off);
6362                 return false;
6363         }
6364
6365         if (smin == S64_MIN) {
6366                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6367                         reg_type_str[type]);
6368                 return false;
6369         }
6370
6371         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6372                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6373                         smin, reg_type_str[type]);
6374                 return false;
6375         }
6376
6377         return true;
6378 }
6379
6380 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6381 {
6382         return &env->insn_aux_data[env->insn_idx];
6383 }
6384
6385 enum {
6386         REASON_BOUNDS   = -1,
6387         REASON_TYPE     = -2,
6388         REASON_PATHS    = -3,
6389         REASON_LIMIT    = -4,
6390         REASON_STACK    = -5,
6391 };
6392
6393 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6394                               u32 *alu_limit, bool mask_to_left)
6395 {
6396         u32 max = 0, ptr_limit = 0;
6397
6398         switch (ptr_reg->type) {
6399         case PTR_TO_STACK:
6400                 /* Offset 0 is out-of-bounds, but acceptable start for the
6401                  * left direction, see BPF_REG_FP. Also, unknown scalar
6402                  * offset where we would need to deal with min/max bounds is
6403                  * currently prohibited for unprivileged.
6404                  */
6405                 max = MAX_BPF_STACK + mask_to_left;
6406                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6407                 break;
6408         case PTR_TO_MAP_VALUE:
6409                 max = ptr_reg->map_ptr->value_size;
6410                 ptr_limit = (mask_to_left ?
6411                              ptr_reg->smin_value :
6412                              ptr_reg->umax_value) + ptr_reg->off;
6413                 break;
6414         default:
6415                 return REASON_TYPE;
6416         }
6417
6418         if (ptr_limit >= max)
6419                 return REASON_LIMIT;
6420         *alu_limit = ptr_limit;
6421         return 0;
6422 }
6423
6424 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6425                                     const struct bpf_insn *insn)
6426 {
6427         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6428 }
6429
6430 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6431                                        u32 alu_state, u32 alu_limit)
6432 {
6433         /* If we arrived here from different branches with different
6434          * state or limits to sanitize, then this won't work.
6435          */
6436         if (aux->alu_state &&
6437             (aux->alu_state != alu_state ||
6438              aux->alu_limit != alu_limit))
6439                 return REASON_PATHS;
6440
6441         /* Corresponding fixup done in do_misc_fixups(). */
6442         aux->alu_state = alu_state;
6443         aux->alu_limit = alu_limit;
6444         return 0;
6445 }
6446
6447 static int sanitize_val_alu(struct bpf_verifier_env *env,
6448                             struct bpf_insn *insn)
6449 {
6450         struct bpf_insn_aux_data *aux = cur_aux(env);
6451
6452         if (can_skip_alu_sanitation(env, insn))
6453                 return 0;
6454
6455         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6456 }
6457
6458 static bool sanitize_needed(u8 opcode)
6459 {
6460         return opcode == BPF_ADD || opcode == BPF_SUB;
6461 }
6462
6463 struct bpf_sanitize_info {
6464         struct bpf_insn_aux_data aux;
6465         bool mask_to_left;
6466 };
6467
6468 static struct bpf_verifier_state *
6469 sanitize_speculative_path(struct bpf_verifier_env *env,
6470                           const struct bpf_insn *insn,
6471                           u32 next_idx, u32 curr_idx)
6472 {
6473         struct bpf_verifier_state *branch;
6474         struct bpf_reg_state *regs;
6475
6476         branch = push_stack(env, next_idx, curr_idx, true);
6477         if (branch && insn) {
6478                 regs = branch->frame[branch->curframe]->regs;
6479                 if (BPF_SRC(insn->code) == BPF_K) {
6480                         mark_reg_unknown(env, regs, insn->dst_reg);
6481                 } else if (BPF_SRC(insn->code) == BPF_X) {
6482                         mark_reg_unknown(env, regs, insn->dst_reg);
6483                         mark_reg_unknown(env, regs, insn->src_reg);
6484                 }
6485         }
6486         return branch;
6487 }
6488
6489 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6490                             struct bpf_insn *insn,
6491                             const struct bpf_reg_state *ptr_reg,
6492                             const struct bpf_reg_state *off_reg,
6493                             struct bpf_reg_state *dst_reg,
6494                             struct bpf_sanitize_info *info,
6495                             const bool commit_window)
6496 {
6497         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6498         struct bpf_verifier_state *vstate = env->cur_state;
6499         bool off_is_imm = tnum_is_const(off_reg->var_off);
6500         bool off_is_neg = off_reg->smin_value < 0;
6501         bool ptr_is_dst_reg = ptr_reg == dst_reg;
6502         u8 opcode = BPF_OP(insn->code);
6503         u32 alu_state, alu_limit;
6504         struct bpf_reg_state tmp;
6505         bool ret;
6506         int err;
6507
6508         if (can_skip_alu_sanitation(env, insn))
6509                 return 0;
6510
6511         /* We already marked aux for masking from non-speculative
6512          * paths, thus we got here in the first place. We only care
6513          * to explore bad access from here.
6514          */
6515         if (vstate->speculative)
6516                 goto do_sim;
6517
6518         if (!commit_window) {
6519                 if (!tnum_is_const(off_reg->var_off) &&
6520                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6521                         return REASON_BOUNDS;
6522
6523                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6524                                      (opcode == BPF_SUB && !off_is_neg);
6525         }
6526
6527         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6528         if (err < 0)
6529                 return err;
6530
6531         if (commit_window) {
6532                 /* In commit phase we narrow the masking window based on
6533                  * the observed pointer move after the simulated operation.
6534                  */
6535                 alu_state = info->aux.alu_state;
6536                 alu_limit = abs(info->aux.alu_limit - alu_limit);
6537         } else {
6538                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6539                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6540                 alu_state |= ptr_is_dst_reg ?
6541                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6542
6543                 /* Limit pruning on unknown scalars to enable deep search for
6544                  * potential masking differences from other program paths.
6545                  */
6546                 if (!off_is_imm)
6547                         env->explore_alu_limits = true;
6548         }
6549
6550         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6551         if (err < 0)
6552                 return err;
6553 do_sim:
6554         /* If we're in commit phase, we're done here given we already
6555          * pushed the truncated dst_reg into the speculative verification
6556          * stack.
6557          *
6558          * Also, when register is a known constant, we rewrite register-based
6559          * operation to immediate-based, and thus do not need masking (and as
6560          * a consequence, do not need to simulate the zero-truncation either).
6561          */
6562         if (commit_window || off_is_imm)
6563                 return 0;
6564
6565         /* Simulate and find potential out-of-bounds access under
6566          * speculative execution from truncation as a result of
6567          * masking when off was not within expected range. If off
6568          * sits in dst, then we temporarily need to move ptr there
6569          * to simulate dst (== 0) +/-= ptr. Needed, for example,
6570          * for cases where we use K-based arithmetic in one direction
6571          * and truncated reg-based in the other in order to explore
6572          * bad access.
6573          */
6574         if (!ptr_is_dst_reg) {
6575                 tmp = *dst_reg;
6576                 *dst_reg = *ptr_reg;
6577         }
6578         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6579                                         env->insn_idx);
6580         if (!ptr_is_dst_reg && ret)
6581                 *dst_reg = tmp;
6582         return !ret ? REASON_STACK : 0;
6583 }
6584
6585 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6586 {
6587         struct bpf_verifier_state *vstate = env->cur_state;
6588
6589         /* If we simulate paths under speculation, we don't update the
6590          * insn as 'seen' such that when we verify unreachable paths in
6591          * the non-speculative domain, sanitize_dead_code() can still
6592          * rewrite/sanitize them.
6593          */
6594         if (!vstate->speculative)
6595                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6596 }
6597
6598 static int sanitize_err(struct bpf_verifier_env *env,
6599                         const struct bpf_insn *insn, int reason,
6600                         const struct bpf_reg_state *off_reg,
6601                         const struct bpf_reg_state *dst_reg)
6602 {
6603         static const char *err = "pointer arithmetic with it prohibited for !root";
6604         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6605         u32 dst = insn->dst_reg, src = insn->src_reg;
6606
6607         switch (reason) {
6608         case REASON_BOUNDS:
6609                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6610                         off_reg == dst_reg ? dst : src, err);
6611                 break;
6612         case REASON_TYPE:
6613                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6614                         off_reg == dst_reg ? src : dst, err);
6615                 break;
6616         case REASON_PATHS:
6617                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6618                         dst, op, err);
6619                 break;
6620         case REASON_LIMIT:
6621                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6622                         dst, op, err);
6623                 break;
6624         case REASON_STACK:
6625                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6626                         dst, err);
6627                 break;
6628         default:
6629                 verbose(env, "verifier internal error: unknown reason (%d)\n",
6630                         reason);
6631                 break;
6632         }
6633
6634         return -EACCES;
6635 }
6636
6637 /* check that stack access falls within stack limits and that 'reg' doesn't
6638  * have a variable offset.
6639  *
6640  * Variable offset is prohibited for unprivileged mode for simplicity since it
6641  * requires corresponding support in Spectre masking for stack ALU.  See also
6642  * retrieve_ptr_limit().
6643  *
6644  *
6645  * 'off' includes 'reg->off'.
6646  */
6647 static int check_stack_access_for_ptr_arithmetic(
6648                                 struct bpf_verifier_env *env,
6649                                 int regno,
6650                                 const struct bpf_reg_state *reg,
6651                                 int off)
6652 {
6653         if (!tnum_is_const(reg->var_off)) {
6654                 char tn_buf[48];
6655
6656                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6657                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6658                         regno, tn_buf, off);
6659                 return -EACCES;
6660         }
6661
6662         if (off >= 0 || off < -MAX_BPF_STACK) {
6663                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6664                         "prohibited for !root; off=%d\n", regno, off);
6665                 return -EACCES;
6666         }
6667
6668         return 0;
6669 }
6670
6671 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6672                                  const struct bpf_insn *insn,
6673                                  const struct bpf_reg_state *dst_reg)
6674 {
6675         u32 dst = insn->dst_reg;
6676
6677         /* For unprivileged we require that resulting offset must be in bounds
6678          * in order to be able to sanitize access later on.
6679          */
6680         if (env->bypass_spec_v1)
6681                 return 0;
6682
6683         switch (dst_reg->type) {
6684         case PTR_TO_STACK:
6685                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6686                                         dst_reg->off + dst_reg->var_off.value))
6687                         return -EACCES;
6688                 break;
6689         case PTR_TO_MAP_VALUE:
6690                 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6691                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6692                                 "prohibited for !root\n", dst);
6693                         return -EACCES;
6694                 }
6695                 break;
6696         default:
6697                 break;
6698         }
6699
6700         return 0;
6701 }
6702
6703 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6704  * Caller should also handle BPF_MOV case separately.
6705  * If we return -EACCES, caller may want to try again treating pointer as a
6706  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6707  */
6708 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6709                                    struct bpf_insn *insn,
6710                                    const struct bpf_reg_state *ptr_reg,
6711                                    const struct bpf_reg_state *off_reg)
6712 {
6713         struct bpf_verifier_state *vstate = env->cur_state;
6714         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6715         struct bpf_reg_state *regs = state->regs, *dst_reg;
6716         bool known = tnum_is_const(off_reg->var_off);
6717         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6718             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6719         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6720             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6721         struct bpf_sanitize_info info = {};
6722         u8 opcode = BPF_OP(insn->code);
6723         u32 dst = insn->dst_reg;
6724         int ret;
6725
6726         dst_reg = &regs[dst];
6727
6728         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6729             smin_val > smax_val || umin_val > umax_val) {
6730                 /* Taint dst register if offset had invalid bounds derived from
6731                  * e.g. dead branches.
6732                  */
6733                 __mark_reg_unknown(env, dst_reg);
6734                 return 0;
6735         }
6736
6737         if (BPF_CLASS(insn->code) != BPF_ALU64) {
6738                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6739                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6740                         __mark_reg_unknown(env, dst_reg);
6741                         return 0;
6742                 }
6743
6744                 verbose(env,
6745                         "R%d 32-bit pointer arithmetic prohibited\n",
6746                         dst);
6747                 return -EACCES;
6748         }
6749
6750         switch (ptr_reg->type) {
6751         case PTR_TO_MAP_VALUE_OR_NULL:
6752                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6753                         dst, reg_type_str[ptr_reg->type]);
6754                 return -EACCES;
6755         case CONST_PTR_TO_MAP:
6756                 /* smin_val represents the known value */
6757                 if (known && smin_val == 0 && opcode == BPF_ADD)
6758                         break;
6759                 fallthrough;
6760         case PTR_TO_PACKET_END:
6761         case PTR_TO_SOCKET:
6762         case PTR_TO_SOCKET_OR_NULL:
6763         case PTR_TO_SOCK_COMMON:
6764         case PTR_TO_SOCK_COMMON_OR_NULL:
6765         case PTR_TO_TCP_SOCK:
6766         case PTR_TO_TCP_SOCK_OR_NULL:
6767         case PTR_TO_XDP_SOCK:
6768                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6769                         dst, reg_type_str[ptr_reg->type]);
6770                 return -EACCES;
6771         default:
6772                 break;
6773         }
6774
6775         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6776          * The id may be overwritten later if we create a new variable offset.
6777          */
6778         dst_reg->type = ptr_reg->type;
6779         dst_reg->id = ptr_reg->id;
6780
6781         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6782             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6783                 return -EINVAL;
6784
6785         /* pointer types do not carry 32-bit bounds at the moment. */
6786         __mark_reg32_unbounded(dst_reg);
6787
6788         if (sanitize_needed(opcode)) {
6789                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6790                                        &info, false);
6791                 if (ret < 0)
6792                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
6793         }
6794
6795         switch (opcode) {
6796         case BPF_ADD:
6797                 /* We can take a fixed offset as long as it doesn't overflow
6798                  * the s32 'off' field
6799                  */
6800                 if (known && (ptr_reg->off + smin_val ==
6801                               (s64)(s32)(ptr_reg->off + smin_val))) {
6802                         /* pointer += K.  Accumulate it into fixed offset */
6803                         dst_reg->smin_value = smin_ptr;
6804                         dst_reg->smax_value = smax_ptr;
6805                         dst_reg->umin_value = umin_ptr;
6806                         dst_reg->umax_value = umax_ptr;
6807                         dst_reg->var_off = ptr_reg->var_off;
6808                         dst_reg->off = ptr_reg->off + smin_val;
6809                         dst_reg->raw = ptr_reg->raw;
6810                         break;
6811                 }
6812                 /* A new variable offset is created.  Note that off_reg->off
6813                  * == 0, since it's a scalar.
6814                  * dst_reg gets the pointer type and since some positive
6815                  * integer value was added to the pointer, give it a new 'id'
6816                  * if it's a PTR_TO_PACKET.
6817                  * this creates a new 'base' pointer, off_reg (variable) gets
6818                  * added into the variable offset, and we copy the fixed offset
6819                  * from ptr_reg.
6820                  */
6821                 if (signed_add_overflows(smin_ptr, smin_val) ||
6822                     signed_add_overflows(smax_ptr, smax_val)) {
6823                         dst_reg->smin_value = S64_MIN;
6824                         dst_reg->smax_value = S64_MAX;
6825                 } else {
6826                         dst_reg->smin_value = smin_ptr + smin_val;
6827                         dst_reg->smax_value = smax_ptr + smax_val;
6828                 }
6829                 if (umin_ptr + umin_val < umin_ptr ||
6830                     umax_ptr + umax_val < umax_ptr) {
6831                         dst_reg->umin_value = 0;
6832                         dst_reg->umax_value = U64_MAX;
6833                 } else {
6834                         dst_reg->umin_value = umin_ptr + umin_val;
6835                         dst_reg->umax_value = umax_ptr + umax_val;
6836                 }
6837                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6838                 dst_reg->off = ptr_reg->off;
6839                 dst_reg->raw = ptr_reg->raw;
6840                 if (reg_is_pkt_pointer(ptr_reg)) {
6841                         dst_reg->id = ++env->id_gen;
6842                         /* something was added to pkt_ptr, set range to zero */
6843                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6844                 }
6845                 break;
6846         case BPF_SUB:
6847                 if (dst_reg == off_reg) {
6848                         /* scalar -= pointer.  Creates an unknown scalar */
6849                         verbose(env, "R%d tried to subtract pointer from scalar\n",
6850                                 dst);
6851                         return -EACCES;
6852                 }
6853                 /* We don't allow subtraction from FP, because (according to
6854                  * test_verifier.c test "invalid fp arithmetic", JITs might not
6855                  * be able to deal with it.
6856                  */
6857                 if (ptr_reg->type == PTR_TO_STACK) {
6858                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
6859                                 dst);
6860                         return -EACCES;
6861                 }
6862                 if (known && (ptr_reg->off - smin_val ==
6863                               (s64)(s32)(ptr_reg->off - smin_val))) {
6864                         /* pointer -= K.  Subtract it from fixed offset */
6865                         dst_reg->smin_value = smin_ptr;
6866                         dst_reg->smax_value = smax_ptr;
6867                         dst_reg->umin_value = umin_ptr;
6868                         dst_reg->umax_value = umax_ptr;
6869                         dst_reg->var_off = ptr_reg->var_off;
6870                         dst_reg->id = ptr_reg->id;
6871                         dst_reg->off = ptr_reg->off - smin_val;
6872                         dst_reg->raw = ptr_reg->raw;
6873                         break;
6874                 }
6875                 /* A new variable offset is created.  If the subtrahend is known
6876                  * nonnegative, then any reg->range we had before is still good.
6877                  */
6878                 if (signed_sub_overflows(smin_ptr, smax_val) ||
6879                     signed_sub_overflows(smax_ptr, smin_val)) {
6880                         /* Overflow possible, we know nothing */
6881                         dst_reg->smin_value = S64_MIN;
6882                         dst_reg->smax_value = S64_MAX;
6883                 } else {
6884                         dst_reg->smin_value = smin_ptr - smax_val;
6885                         dst_reg->smax_value = smax_ptr - smin_val;
6886                 }
6887                 if (umin_ptr < umax_val) {
6888                         /* Overflow possible, we know nothing */
6889                         dst_reg->umin_value = 0;
6890                         dst_reg->umax_value = U64_MAX;
6891                 } else {
6892                         /* Cannot overflow (as long as bounds are consistent) */
6893                         dst_reg->umin_value = umin_ptr - umax_val;
6894                         dst_reg->umax_value = umax_ptr - umin_val;
6895                 }
6896                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6897                 dst_reg->off = ptr_reg->off;
6898                 dst_reg->raw = ptr_reg->raw;
6899                 if (reg_is_pkt_pointer(ptr_reg)) {
6900                         dst_reg->id = ++env->id_gen;
6901                         /* something was added to pkt_ptr, set range to zero */
6902                         if (smin_val < 0)
6903                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6904                 }
6905                 break;
6906         case BPF_AND:
6907         case BPF_OR:
6908         case BPF_XOR:
6909                 /* bitwise ops on pointers are troublesome, prohibit. */
6910                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6911                         dst, bpf_alu_string[opcode >> 4]);
6912                 return -EACCES;
6913         default:
6914                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6915                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6916                         dst, bpf_alu_string[opcode >> 4]);
6917                 return -EACCES;
6918         }
6919
6920         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6921                 return -EINVAL;
6922
6923         __update_reg_bounds(dst_reg);
6924         __reg_deduce_bounds(dst_reg);
6925         __reg_bound_offset(dst_reg);
6926
6927         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6928                 return -EACCES;
6929         if (sanitize_needed(opcode)) {
6930                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6931                                        &info, true);
6932                 if (ret < 0)
6933                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
6934         }
6935
6936         return 0;
6937 }
6938
6939 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6940                                  struct bpf_reg_state *src_reg)
6941 {
6942         s32 smin_val = src_reg->s32_min_value;
6943         s32 smax_val = src_reg->s32_max_value;
6944         u32 umin_val = src_reg->u32_min_value;
6945         u32 umax_val = src_reg->u32_max_value;
6946
6947         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6948             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6949                 dst_reg->s32_min_value = S32_MIN;
6950                 dst_reg->s32_max_value = S32_MAX;
6951         } else {
6952                 dst_reg->s32_min_value += smin_val;
6953                 dst_reg->s32_max_value += smax_val;
6954         }
6955         if (dst_reg->u32_min_value + umin_val < umin_val ||
6956             dst_reg->u32_max_value + umax_val < umax_val) {
6957                 dst_reg->u32_min_value = 0;
6958                 dst_reg->u32_max_value = U32_MAX;
6959         } else {
6960                 dst_reg->u32_min_value += umin_val;
6961                 dst_reg->u32_max_value += umax_val;
6962         }
6963 }
6964
6965 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6966                                struct bpf_reg_state *src_reg)
6967 {
6968         s64 smin_val = src_reg->smin_value;
6969         s64 smax_val = src_reg->smax_value;
6970         u64 umin_val = src_reg->umin_value;
6971         u64 umax_val = src_reg->umax_value;
6972
6973         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6974             signed_add_overflows(dst_reg->smax_value, smax_val)) {
6975                 dst_reg->smin_value = S64_MIN;
6976                 dst_reg->smax_value = S64_MAX;
6977         } else {
6978                 dst_reg->smin_value += smin_val;
6979                 dst_reg->smax_value += smax_val;
6980         }
6981         if (dst_reg->umin_value + umin_val < umin_val ||
6982             dst_reg->umax_value + umax_val < umax_val) {
6983                 dst_reg->umin_value = 0;
6984                 dst_reg->umax_value = U64_MAX;
6985         } else {
6986                 dst_reg->umin_value += umin_val;
6987                 dst_reg->umax_value += umax_val;
6988         }
6989 }
6990
6991 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6992                                  struct bpf_reg_state *src_reg)
6993 {
6994         s32 smin_val = src_reg->s32_min_value;
6995         s32 smax_val = src_reg->s32_max_value;
6996         u32 umin_val = src_reg->u32_min_value;
6997         u32 umax_val = src_reg->u32_max_value;
6998
6999         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7000             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7001                 /* Overflow possible, we know nothing */
7002                 dst_reg->s32_min_value = S32_MIN;
7003                 dst_reg->s32_max_value = S32_MAX;
7004         } else {
7005                 dst_reg->s32_min_value -= smax_val;
7006                 dst_reg->s32_max_value -= smin_val;
7007         }
7008         if (dst_reg->u32_min_value < umax_val) {
7009                 /* Overflow possible, we know nothing */
7010                 dst_reg->u32_min_value = 0;
7011                 dst_reg->u32_max_value = U32_MAX;
7012         } else {
7013                 /* Cannot overflow (as long as bounds are consistent) */
7014                 dst_reg->u32_min_value -= umax_val;
7015                 dst_reg->u32_max_value -= umin_val;
7016         }
7017 }
7018
7019 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7020                                struct bpf_reg_state *src_reg)
7021 {
7022         s64 smin_val = src_reg->smin_value;
7023         s64 smax_val = src_reg->smax_value;
7024         u64 umin_val = src_reg->umin_value;
7025         u64 umax_val = src_reg->umax_value;
7026
7027         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7028             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7029                 /* Overflow possible, we know nothing */
7030                 dst_reg->smin_value = S64_MIN;
7031                 dst_reg->smax_value = S64_MAX;
7032         } else {
7033                 dst_reg->smin_value -= smax_val;
7034                 dst_reg->smax_value -= smin_val;
7035         }
7036         if (dst_reg->umin_value < umax_val) {
7037                 /* Overflow possible, we know nothing */
7038                 dst_reg->umin_value = 0;
7039                 dst_reg->umax_value = U64_MAX;
7040         } else {
7041                 /* Cannot overflow (as long as bounds are consistent) */
7042                 dst_reg->umin_value -= umax_val;
7043                 dst_reg->umax_value -= umin_val;
7044         }
7045 }
7046
7047 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7048                                  struct bpf_reg_state *src_reg)
7049 {
7050         s32 smin_val = src_reg->s32_min_value;
7051         u32 umin_val = src_reg->u32_min_value;
7052         u32 umax_val = src_reg->u32_max_value;
7053
7054         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7055                 /* Ain't nobody got time to multiply that sign */
7056                 __mark_reg32_unbounded(dst_reg);
7057                 return;
7058         }
7059         /* Both values are positive, so we can work with unsigned and
7060          * copy the result to signed (unless it exceeds S32_MAX).
7061          */
7062         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7063                 /* Potential overflow, we know nothing */
7064                 __mark_reg32_unbounded(dst_reg);
7065                 return;
7066         }
7067         dst_reg->u32_min_value *= umin_val;
7068         dst_reg->u32_max_value *= umax_val;
7069         if (dst_reg->u32_max_value > S32_MAX) {
7070                 /* Overflow possible, we know nothing */
7071                 dst_reg->s32_min_value = S32_MIN;
7072                 dst_reg->s32_max_value = S32_MAX;
7073         } else {
7074                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7075                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7076         }
7077 }
7078
7079 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7080                                struct bpf_reg_state *src_reg)
7081 {
7082         s64 smin_val = src_reg->smin_value;
7083         u64 umin_val = src_reg->umin_value;
7084         u64 umax_val = src_reg->umax_value;
7085
7086         if (smin_val < 0 || dst_reg->smin_value < 0) {
7087                 /* Ain't nobody got time to multiply that sign */
7088                 __mark_reg64_unbounded(dst_reg);
7089                 return;
7090         }
7091         /* Both values are positive, so we can work with unsigned and
7092          * copy the result to signed (unless it exceeds S64_MAX).
7093          */
7094         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7095                 /* Potential overflow, we know nothing */
7096                 __mark_reg64_unbounded(dst_reg);
7097                 return;
7098         }
7099         dst_reg->umin_value *= umin_val;
7100         dst_reg->umax_value *= umax_val;
7101         if (dst_reg->umax_value > S64_MAX) {
7102                 /* Overflow possible, we know nothing */
7103                 dst_reg->smin_value = S64_MIN;
7104                 dst_reg->smax_value = S64_MAX;
7105         } else {
7106                 dst_reg->smin_value = dst_reg->umin_value;
7107                 dst_reg->smax_value = dst_reg->umax_value;
7108         }
7109 }
7110
7111 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7112                                  struct bpf_reg_state *src_reg)
7113 {
7114         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7115         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7116         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7117         s32 smin_val = src_reg->s32_min_value;
7118         u32 umax_val = src_reg->u32_max_value;
7119
7120         if (src_known && dst_known) {
7121                 __mark_reg32_known(dst_reg, var32_off.value);
7122                 return;
7123         }
7124
7125         /* We get our minimum from the var_off, since that's inherently
7126          * bitwise.  Our maximum is the minimum of the operands' maxima.
7127          */
7128         dst_reg->u32_min_value = var32_off.value;
7129         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7130         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7131                 /* Lose signed bounds when ANDing negative numbers,
7132                  * ain't nobody got time for that.
7133                  */
7134                 dst_reg->s32_min_value = S32_MIN;
7135                 dst_reg->s32_max_value = S32_MAX;
7136         } else {
7137                 /* ANDing two positives gives a positive, so safe to
7138                  * cast result into s64.
7139                  */
7140                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7141                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7142         }
7143 }
7144
7145 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7146                                struct bpf_reg_state *src_reg)
7147 {
7148         bool src_known = tnum_is_const(src_reg->var_off);
7149         bool dst_known = tnum_is_const(dst_reg->var_off);
7150         s64 smin_val = src_reg->smin_value;
7151         u64 umax_val = src_reg->umax_value;
7152
7153         if (src_known && dst_known) {
7154                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7155                 return;
7156         }
7157
7158         /* We get our minimum from the var_off, since that's inherently
7159          * bitwise.  Our maximum is the minimum of the operands' maxima.
7160          */
7161         dst_reg->umin_value = dst_reg->var_off.value;
7162         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7163         if (dst_reg->smin_value < 0 || smin_val < 0) {
7164                 /* Lose signed bounds when ANDing negative numbers,
7165                  * ain't nobody got time for that.
7166                  */
7167                 dst_reg->smin_value = S64_MIN;
7168                 dst_reg->smax_value = S64_MAX;
7169         } else {
7170                 /* ANDing two positives gives a positive, so safe to
7171                  * cast result into s64.
7172                  */
7173                 dst_reg->smin_value = dst_reg->umin_value;
7174                 dst_reg->smax_value = dst_reg->umax_value;
7175         }
7176         /* We may learn something more from the var_off */
7177         __update_reg_bounds(dst_reg);
7178 }
7179
7180 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7181                                 struct bpf_reg_state *src_reg)
7182 {
7183         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7184         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7185         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7186         s32 smin_val = src_reg->s32_min_value;
7187         u32 umin_val = src_reg->u32_min_value;
7188
7189         if (src_known && dst_known) {
7190                 __mark_reg32_known(dst_reg, var32_off.value);
7191                 return;
7192         }
7193
7194         /* We get our maximum from the var_off, and our minimum is the
7195          * maximum of the operands' minima
7196          */
7197         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7198         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7199         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7200                 /* Lose signed bounds when ORing negative numbers,
7201                  * ain't nobody got time for that.
7202                  */
7203                 dst_reg->s32_min_value = S32_MIN;
7204                 dst_reg->s32_max_value = S32_MAX;
7205         } else {
7206                 /* ORing two positives gives a positive, so safe to
7207                  * cast result into s64.
7208                  */
7209                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7210                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7211         }
7212 }
7213
7214 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7215                               struct bpf_reg_state *src_reg)
7216 {
7217         bool src_known = tnum_is_const(src_reg->var_off);
7218         bool dst_known = tnum_is_const(dst_reg->var_off);
7219         s64 smin_val = src_reg->smin_value;
7220         u64 umin_val = src_reg->umin_value;
7221
7222         if (src_known && dst_known) {
7223                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7224                 return;
7225         }
7226
7227         /* We get our maximum from the var_off, and our minimum is the
7228          * maximum of the operands' minima
7229          */
7230         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7231         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7232         if (dst_reg->smin_value < 0 || smin_val < 0) {
7233                 /* Lose signed bounds when ORing negative numbers,
7234                  * ain't nobody got time for that.
7235                  */
7236                 dst_reg->smin_value = S64_MIN;
7237                 dst_reg->smax_value = S64_MAX;
7238         } else {
7239                 /* ORing two positives gives a positive, so safe to
7240                  * cast result into s64.
7241                  */
7242                 dst_reg->smin_value = dst_reg->umin_value;
7243                 dst_reg->smax_value = dst_reg->umax_value;
7244         }
7245         /* We may learn something more from the var_off */
7246         __update_reg_bounds(dst_reg);
7247 }
7248
7249 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7250                                  struct bpf_reg_state *src_reg)
7251 {
7252         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7253         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7254         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7255         s32 smin_val = src_reg->s32_min_value;
7256
7257         if (src_known && dst_known) {
7258                 __mark_reg32_known(dst_reg, var32_off.value);
7259                 return;
7260         }
7261
7262         /* We get both minimum and maximum from the var32_off. */
7263         dst_reg->u32_min_value = var32_off.value;
7264         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7265
7266         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7267                 /* XORing two positive sign numbers gives a positive,
7268                  * so safe to cast u32 result into s32.
7269                  */
7270                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7271                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7272         } else {
7273                 dst_reg->s32_min_value = S32_MIN;
7274                 dst_reg->s32_max_value = S32_MAX;
7275         }
7276 }
7277
7278 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7279                                struct bpf_reg_state *src_reg)
7280 {
7281         bool src_known = tnum_is_const(src_reg->var_off);
7282         bool dst_known = tnum_is_const(dst_reg->var_off);
7283         s64 smin_val = src_reg->smin_value;
7284
7285         if (src_known && dst_known) {
7286                 /* dst_reg->var_off.value has been updated earlier */
7287                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7288                 return;
7289         }
7290
7291         /* We get both minimum and maximum from the var_off. */
7292         dst_reg->umin_value = dst_reg->var_off.value;
7293         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7294
7295         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7296                 /* XORing two positive sign numbers gives a positive,
7297                  * so safe to cast u64 result into s64.
7298                  */
7299                 dst_reg->smin_value = dst_reg->umin_value;
7300                 dst_reg->smax_value = dst_reg->umax_value;
7301         } else {
7302                 dst_reg->smin_value = S64_MIN;
7303                 dst_reg->smax_value = S64_MAX;
7304         }
7305
7306         __update_reg_bounds(dst_reg);
7307 }
7308
7309 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7310                                    u64 umin_val, u64 umax_val)
7311 {
7312         /* We lose all sign bit information (except what we can pick
7313          * up from var_off)
7314          */
7315         dst_reg->s32_min_value = S32_MIN;
7316         dst_reg->s32_max_value = S32_MAX;
7317         /* If we might shift our top bit out, then we know nothing */
7318         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7319                 dst_reg->u32_min_value = 0;
7320                 dst_reg->u32_max_value = U32_MAX;
7321         } else {
7322                 dst_reg->u32_min_value <<= umin_val;
7323                 dst_reg->u32_max_value <<= umax_val;
7324         }
7325 }
7326
7327 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7328                                  struct bpf_reg_state *src_reg)
7329 {
7330         u32 umax_val = src_reg->u32_max_value;
7331         u32 umin_val = src_reg->u32_min_value;
7332         /* u32 alu operation will zext upper bits */
7333         struct tnum subreg = tnum_subreg(dst_reg->var_off);
7334
7335         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7336         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7337         /* Not required but being careful mark reg64 bounds as unknown so
7338          * that we are forced to pick them up from tnum and zext later and
7339          * if some path skips this step we are still safe.
7340          */
7341         __mark_reg64_unbounded(dst_reg);
7342         __update_reg32_bounds(dst_reg);
7343 }
7344
7345 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7346                                    u64 umin_val, u64 umax_val)
7347 {
7348         /* Special case <<32 because it is a common compiler pattern to sign
7349          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7350          * positive we know this shift will also be positive so we can track
7351          * bounds correctly. Otherwise we lose all sign bit information except
7352          * what we can pick up from var_off. Perhaps we can generalize this
7353          * later to shifts of any length.
7354          */
7355         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7356                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7357         else
7358                 dst_reg->smax_value = S64_MAX;
7359
7360         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7361                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7362         else
7363                 dst_reg->smin_value = S64_MIN;
7364
7365         /* If we might shift our top bit out, then we know nothing */
7366         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7367                 dst_reg->umin_value = 0;
7368                 dst_reg->umax_value = U64_MAX;
7369         } else {
7370                 dst_reg->umin_value <<= umin_val;
7371                 dst_reg->umax_value <<= umax_val;
7372         }
7373 }
7374
7375 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7376                                struct bpf_reg_state *src_reg)
7377 {
7378         u64 umax_val = src_reg->umax_value;
7379         u64 umin_val = src_reg->umin_value;
7380
7381         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7382         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7383         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7384
7385         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7386         /* We may learn something more from the var_off */
7387         __update_reg_bounds(dst_reg);
7388 }
7389
7390 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7391                                  struct bpf_reg_state *src_reg)
7392 {
7393         struct tnum subreg = tnum_subreg(dst_reg->var_off);
7394         u32 umax_val = src_reg->u32_max_value;
7395         u32 umin_val = src_reg->u32_min_value;
7396
7397         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7398          * be negative, then either:
7399          * 1) src_reg might be zero, so the sign bit of the result is
7400          *    unknown, so we lose our signed bounds
7401          * 2) it's known negative, thus the unsigned bounds capture the
7402          *    signed bounds
7403          * 3) the signed bounds cross zero, so they tell us nothing
7404          *    about the result
7405          * If the value in dst_reg is known nonnegative, then again the
7406          * unsigned bounds capture the signed bounds.
7407          * Thus, in all cases it suffices to blow away our signed bounds
7408          * and rely on inferring new ones from the unsigned bounds and
7409          * var_off of the result.
7410          */
7411         dst_reg->s32_min_value = S32_MIN;
7412         dst_reg->s32_max_value = S32_MAX;
7413
7414         dst_reg->var_off = tnum_rshift(subreg, umin_val);
7415         dst_reg->u32_min_value >>= umax_val;
7416         dst_reg->u32_max_value >>= umin_val;
7417
7418         __mark_reg64_unbounded(dst_reg);
7419         __update_reg32_bounds(dst_reg);
7420 }
7421
7422 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7423                                struct bpf_reg_state *src_reg)
7424 {
7425         u64 umax_val = src_reg->umax_value;
7426         u64 umin_val = src_reg->umin_value;
7427
7428         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7429          * be negative, then either:
7430          * 1) src_reg might be zero, so the sign bit of the result is
7431          *    unknown, so we lose our signed bounds
7432          * 2) it's known negative, thus the unsigned bounds capture the
7433          *    signed bounds
7434          * 3) the signed bounds cross zero, so they tell us nothing
7435          *    about the result
7436          * If the value in dst_reg is known nonnegative, then again the
7437          * unsigned bounds capture the signed bounds.
7438          * Thus, in all cases it suffices to blow away our signed bounds
7439          * and rely on inferring new ones from the unsigned bounds and
7440          * var_off of the result.
7441          */
7442         dst_reg->smin_value = S64_MIN;
7443         dst_reg->smax_value = S64_MAX;
7444         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7445         dst_reg->umin_value >>= umax_val;
7446         dst_reg->umax_value >>= umin_val;
7447
7448         /* Its not easy to operate on alu32 bounds here because it depends
7449          * on bits being shifted in. Take easy way out and mark unbounded
7450          * so we can recalculate later from tnum.
7451          */
7452         __mark_reg32_unbounded(dst_reg);
7453         __update_reg_bounds(dst_reg);
7454 }
7455
7456 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7457                                   struct bpf_reg_state *src_reg)
7458 {
7459         u64 umin_val = src_reg->u32_min_value;
7460
7461         /* Upon reaching here, src_known is true and
7462          * umax_val is equal to umin_val.
7463          */
7464         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7465         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7466
7467         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7468
7469         /* blow away the dst_reg umin_value/umax_value and rely on
7470          * dst_reg var_off to refine the result.
7471          */
7472         dst_reg->u32_min_value = 0;
7473         dst_reg->u32_max_value = U32_MAX;
7474
7475         __mark_reg64_unbounded(dst_reg);
7476         __update_reg32_bounds(dst_reg);
7477 }
7478
7479 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7480                                 struct bpf_reg_state *src_reg)
7481 {
7482         u64 umin_val = src_reg->umin_value;
7483
7484         /* Upon reaching here, src_known is true and umax_val is equal
7485          * to umin_val.
7486          */
7487         dst_reg->smin_value >>= umin_val;
7488         dst_reg->smax_value >>= umin_val;
7489
7490         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7491
7492         /* blow away the dst_reg umin_value/umax_value and rely on
7493          * dst_reg var_off to refine the result.
7494          */
7495         dst_reg->umin_value = 0;
7496         dst_reg->umax_value = U64_MAX;
7497
7498         /* Its not easy to operate on alu32 bounds here because it depends
7499          * on bits being shifted in from upper 32-bits. Take easy way out
7500          * and mark unbounded so we can recalculate later from tnum.
7501          */
7502         __mark_reg32_unbounded(dst_reg);
7503         __update_reg_bounds(dst_reg);
7504 }
7505
7506 /* WARNING: This function does calculations on 64-bit values, but the actual
7507  * execution may occur on 32-bit values. Therefore, things like bitshifts
7508  * need extra checks in the 32-bit case.
7509  */
7510 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7511                                       struct bpf_insn *insn,
7512                                       struct bpf_reg_state *dst_reg,
7513                                       struct bpf_reg_state src_reg)
7514 {
7515         struct bpf_reg_state *regs = cur_regs(env);
7516         u8 opcode = BPF_OP(insn->code);
7517         bool src_known;
7518         s64 smin_val, smax_val;
7519         u64 umin_val, umax_val;
7520         s32 s32_min_val, s32_max_val;
7521         u32 u32_min_val, u32_max_val;
7522         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7523         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7524         int ret;
7525
7526         smin_val = src_reg.smin_value;
7527         smax_val = src_reg.smax_value;
7528         umin_val = src_reg.umin_value;
7529         umax_val = src_reg.umax_value;
7530
7531         s32_min_val = src_reg.s32_min_value;
7532         s32_max_val = src_reg.s32_max_value;
7533         u32_min_val = src_reg.u32_min_value;
7534         u32_max_val = src_reg.u32_max_value;
7535
7536         if (alu32) {
7537                 src_known = tnum_subreg_is_const(src_reg.var_off);
7538                 if ((src_known &&
7539                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7540                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7541                         /* Taint dst register if offset had invalid bounds
7542                          * derived from e.g. dead branches.
7543                          */
7544                         __mark_reg_unknown(env, dst_reg);
7545                         return 0;
7546                 }
7547         } else {
7548                 src_known = tnum_is_const(src_reg.var_off);
7549                 if ((src_known &&
7550                      (smin_val != smax_val || umin_val != umax_val)) ||
7551                     smin_val > smax_val || umin_val > umax_val) {
7552                         /* Taint dst register if offset had invalid bounds
7553                          * derived from e.g. dead branches.
7554                          */
7555                         __mark_reg_unknown(env, dst_reg);
7556                         return 0;
7557                 }
7558         }
7559
7560         if (!src_known &&
7561             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7562                 __mark_reg_unknown(env, dst_reg);
7563                 return 0;
7564         }
7565
7566         if (sanitize_needed(opcode)) {
7567                 ret = sanitize_val_alu(env, insn);
7568                 if (ret < 0)
7569                         return sanitize_err(env, insn, ret, NULL, NULL);
7570         }
7571
7572         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7573          * There are two classes of instructions: The first class we track both
7574          * alu32 and alu64 sign/unsigned bounds independently this provides the
7575          * greatest amount of precision when alu operations are mixed with jmp32
7576          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7577          * and BPF_OR. This is possible because these ops have fairly easy to
7578          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7579          * See alu32 verifier tests for examples. The second class of
7580          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7581          * with regards to tracking sign/unsigned bounds because the bits may
7582          * cross subreg boundaries in the alu64 case. When this happens we mark
7583          * the reg unbounded in the subreg bound space and use the resulting
7584          * tnum to calculate an approximation of the sign/unsigned bounds.
7585          */
7586         switch (opcode) {
7587         case BPF_ADD:
7588                 scalar32_min_max_add(dst_reg, &src_reg);
7589                 scalar_min_max_add(dst_reg, &src_reg);
7590                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7591                 break;
7592         case BPF_SUB:
7593                 scalar32_min_max_sub(dst_reg, &src_reg);
7594                 scalar_min_max_sub(dst_reg, &src_reg);
7595                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7596                 break;
7597         case BPF_MUL:
7598                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7599                 scalar32_min_max_mul(dst_reg, &src_reg);
7600                 scalar_min_max_mul(dst_reg, &src_reg);
7601                 break;
7602         case BPF_AND:
7603                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7604                 scalar32_min_max_and(dst_reg, &src_reg);
7605                 scalar_min_max_and(dst_reg, &src_reg);
7606                 break;
7607         case BPF_OR:
7608                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7609                 scalar32_min_max_or(dst_reg, &src_reg);
7610                 scalar_min_max_or(dst_reg, &src_reg);
7611                 break;
7612         case BPF_XOR:
7613                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7614                 scalar32_min_max_xor(dst_reg, &src_reg);
7615                 scalar_min_max_xor(dst_reg, &src_reg);
7616                 break;
7617         case BPF_LSH:
7618                 if (umax_val >= insn_bitness) {
7619                         /* Shifts greater than 31 or 63 are undefined.
7620                          * This includes shifts by a negative number.
7621                          */
7622                         mark_reg_unknown(env, regs, insn->dst_reg);
7623                         break;
7624                 }
7625                 if (alu32)
7626                         scalar32_min_max_lsh(dst_reg, &src_reg);
7627                 else
7628                         scalar_min_max_lsh(dst_reg, &src_reg);
7629                 break;
7630         case BPF_RSH:
7631                 if (umax_val >= insn_bitness) {
7632                         /* Shifts greater than 31 or 63 are undefined.
7633                          * This includes shifts by a negative number.
7634                          */
7635                         mark_reg_unknown(env, regs, insn->dst_reg);
7636                         break;
7637                 }
7638                 if (alu32)
7639                         scalar32_min_max_rsh(dst_reg, &src_reg);
7640                 else
7641                         scalar_min_max_rsh(dst_reg, &src_reg);
7642                 break;
7643         case BPF_ARSH:
7644                 if (umax_val >= insn_bitness) {
7645                         /* Shifts greater than 31 or 63 are undefined.
7646                          * This includes shifts by a negative number.
7647                          */
7648                         mark_reg_unknown(env, regs, insn->dst_reg);
7649                         break;
7650                 }
7651                 if (alu32)
7652                         scalar32_min_max_arsh(dst_reg, &src_reg);
7653                 else
7654                         scalar_min_max_arsh(dst_reg, &src_reg);
7655                 break;
7656         default:
7657                 mark_reg_unknown(env, regs, insn->dst_reg);
7658                 break;
7659         }
7660
7661         /* ALU32 ops are zero extended into 64bit register */
7662         if (alu32)
7663                 zext_32_to_64(dst_reg);
7664
7665         __update_reg_bounds(dst_reg);
7666         __reg_deduce_bounds(dst_reg);
7667         __reg_bound_offset(dst_reg);
7668         return 0;
7669 }
7670
7671 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7672  * and var_off.
7673  */
7674 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7675                                    struct bpf_insn *insn)
7676 {
7677         struct bpf_verifier_state *vstate = env->cur_state;
7678         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7679         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7680         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7681         u8 opcode = BPF_OP(insn->code);
7682         int err;
7683
7684         dst_reg = &regs[insn->dst_reg];
7685         src_reg = NULL;
7686         if (dst_reg->type != SCALAR_VALUE)
7687                 ptr_reg = dst_reg;
7688         else
7689                 /* Make sure ID is cleared otherwise dst_reg min/max could be
7690                  * incorrectly propagated into other registers by find_equal_scalars()
7691                  */
7692                 dst_reg->id = 0;
7693         if (BPF_SRC(insn->code) == BPF_X) {
7694                 src_reg = &regs[insn->src_reg];
7695                 if (src_reg->type != SCALAR_VALUE) {
7696                         if (dst_reg->type != SCALAR_VALUE) {
7697                                 /* Combining two pointers by any ALU op yields
7698                                  * an arbitrary scalar. Disallow all math except
7699                                  * pointer subtraction
7700                                  */
7701                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7702                                         mark_reg_unknown(env, regs, insn->dst_reg);
7703                                         return 0;
7704                                 }
7705                                 verbose(env, "R%d pointer %s pointer prohibited\n",
7706                                         insn->dst_reg,
7707                                         bpf_alu_string[opcode >> 4]);
7708                                 return -EACCES;
7709                         } else {
7710                                 /* scalar += pointer
7711                                  * This is legal, but we have to reverse our
7712                                  * src/dest handling in computing the range
7713                                  */
7714                                 err = mark_chain_precision(env, insn->dst_reg);
7715                                 if (err)
7716                                         return err;
7717                                 return adjust_ptr_min_max_vals(env, insn,
7718                                                                src_reg, dst_reg);
7719                         }
7720                 } else if (ptr_reg) {
7721                         /* pointer += scalar */
7722                         err = mark_chain_precision(env, insn->src_reg);
7723                         if (err)
7724                                 return err;
7725                         return adjust_ptr_min_max_vals(env, insn,
7726                                                        dst_reg, src_reg);
7727                 }
7728         } else {
7729                 /* Pretend the src is a reg with a known value, since we only
7730                  * need to be able to read from this state.
7731                  */
7732                 off_reg.type = SCALAR_VALUE;
7733                 __mark_reg_known(&off_reg, insn->imm);
7734                 src_reg = &off_reg;
7735                 if (ptr_reg) /* pointer += K */
7736                         return adjust_ptr_min_max_vals(env, insn,
7737                                                        ptr_reg, src_reg);
7738         }
7739
7740         /* Got here implies adding two SCALAR_VALUEs */
7741         if (WARN_ON_ONCE(ptr_reg)) {
7742                 print_verifier_state(env, state);
7743                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7744                 return -EINVAL;
7745         }
7746         if (WARN_ON(!src_reg)) {
7747                 print_verifier_state(env, state);
7748                 verbose(env, "verifier internal error: no src_reg\n");
7749                 return -EINVAL;
7750         }
7751         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7752 }
7753
7754 /* check validity of 32-bit and 64-bit arithmetic operations */
7755 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7756 {
7757         struct bpf_reg_state *regs = cur_regs(env);
7758         u8 opcode = BPF_OP(insn->code);
7759         int err;
7760
7761         if (opcode == BPF_END || opcode == BPF_NEG) {
7762                 if (opcode == BPF_NEG) {
7763                         if (BPF_SRC(insn->code) != 0 ||
7764                             insn->src_reg != BPF_REG_0 ||
7765                             insn->off != 0 || insn->imm != 0) {
7766                                 verbose(env, "BPF_NEG uses reserved fields\n");
7767                                 return -EINVAL;
7768                         }
7769                 } else {
7770                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7771                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7772                             BPF_CLASS(insn->code) == BPF_ALU64) {
7773                                 verbose(env, "BPF_END uses reserved fields\n");
7774                                 return -EINVAL;
7775                         }
7776                 }
7777
7778                 /* check src operand */
7779                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7780                 if (err)
7781                         return err;
7782
7783                 if (is_pointer_value(env, insn->dst_reg)) {
7784                         verbose(env, "R%d pointer arithmetic prohibited\n",
7785                                 insn->dst_reg);
7786                         return -EACCES;
7787                 }
7788
7789                 /* check dest operand */
7790                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7791                 if (err)
7792                         return err;
7793
7794         } else if (opcode == BPF_MOV) {
7795
7796                 if (BPF_SRC(insn->code) == BPF_X) {
7797                         if (insn->imm != 0 || insn->off != 0) {
7798                                 verbose(env, "BPF_MOV uses reserved fields\n");
7799                                 return -EINVAL;
7800                         }
7801
7802                         /* check src operand */
7803                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
7804                         if (err)
7805                                 return err;
7806                 } else {
7807                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7808                                 verbose(env, "BPF_MOV uses reserved fields\n");
7809                                 return -EINVAL;
7810                         }
7811                 }
7812
7813                 /* check dest operand, mark as required later */
7814                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7815                 if (err)
7816                         return err;
7817
7818                 if (BPF_SRC(insn->code) == BPF_X) {
7819                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
7820                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7821
7822                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
7823                                 /* case: R1 = R2
7824                                  * copy register state to dest reg
7825                                  */
7826                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7827                                         /* Assign src and dst registers the same ID
7828                                          * that will be used by find_equal_scalars()
7829                                          * to propagate min/max range.
7830                                          */
7831                                         src_reg->id = ++env->id_gen;
7832                                 *dst_reg = *src_reg;
7833                                 dst_reg->live |= REG_LIVE_WRITTEN;
7834                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
7835                         } else {
7836                                 /* R1 = (u32) R2 */
7837                                 if (is_pointer_value(env, insn->src_reg)) {
7838                                         verbose(env,
7839                                                 "R%d partial copy of pointer\n",
7840                                                 insn->src_reg);
7841                                         return -EACCES;
7842                                 } else if (src_reg->type == SCALAR_VALUE) {
7843                                         *dst_reg = *src_reg;
7844                                         /* Make sure ID is cleared otherwise
7845                                          * dst_reg min/max could be incorrectly
7846                                          * propagated into src_reg by find_equal_scalars()
7847                                          */
7848                                         dst_reg->id = 0;
7849                                         dst_reg->live |= REG_LIVE_WRITTEN;
7850                                         dst_reg->subreg_def = env->insn_idx + 1;
7851                                 } else {
7852                                         mark_reg_unknown(env, regs,
7853                                                          insn->dst_reg);
7854                                 }
7855                                 zext_32_to_64(dst_reg);
7856                         }
7857                 } else {
7858                         /* case: R = imm
7859                          * remember the value we stored into this reg
7860                          */
7861                         /* clear any state __mark_reg_known doesn't set */
7862                         mark_reg_unknown(env, regs, insn->dst_reg);
7863                         regs[insn->dst_reg].type = SCALAR_VALUE;
7864                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
7865                                 __mark_reg_known(regs + insn->dst_reg,
7866                                                  insn->imm);
7867                         } else {
7868                                 __mark_reg_known(regs + insn->dst_reg,
7869                                                  (u32)insn->imm);
7870                         }
7871                 }
7872
7873         } else if (opcode > BPF_END) {
7874                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7875                 return -EINVAL;
7876
7877         } else {        /* all other ALU ops: and, sub, xor, add, ... */
7878
7879                 if (BPF_SRC(insn->code) == BPF_X) {
7880                         if (insn->imm != 0 || insn->off != 0) {
7881                                 verbose(env, "BPF_ALU uses reserved fields\n");
7882                                 return -EINVAL;
7883                         }
7884                         /* check src1 operand */
7885                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
7886                         if (err)
7887                                 return err;
7888                 } else {
7889                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7890                                 verbose(env, "BPF_ALU uses reserved fields\n");
7891                                 return -EINVAL;
7892                         }
7893                 }
7894
7895                 /* check src2 operand */
7896                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7897                 if (err)
7898                         return err;
7899
7900                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7901                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7902                         verbose(env, "div by zero\n");
7903                         return -EINVAL;
7904                 }
7905
7906                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7907                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7908                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7909
7910                         if (insn->imm < 0 || insn->imm >= size) {
7911                                 verbose(env, "invalid shift %d\n", insn->imm);
7912                                 return -EINVAL;
7913                         }
7914                 }
7915
7916                 /* check dest operand */
7917                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7918                 if (err)
7919                         return err;
7920
7921                 return adjust_reg_min_max_vals(env, insn);
7922         }
7923
7924         return 0;
7925 }
7926
7927 static void __find_good_pkt_pointers(struct bpf_func_state *state,
7928                                      struct bpf_reg_state *dst_reg,
7929                                      enum bpf_reg_type type, int new_range)
7930 {
7931         struct bpf_reg_state *reg;
7932         int i;
7933
7934         for (i = 0; i < MAX_BPF_REG; i++) {
7935                 reg = &state->regs[i];
7936                 if (reg->type == type && reg->id == dst_reg->id)
7937                         /* keep the maximum range already checked */
7938                         reg->range = max(reg->range, new_range);
7939         }
7940
7941         bpf_for_each_spilled_reg(i, state, reg) {
7942                 if (!reg)
7943                         continue;
7944                 if (reg->type == type && reg->id == dst_reg->id)
7945                         reg->range = max(reg->range, new_range);
7946         }
7947 }
7948
7949 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7950                                    struct bpf_reg_state *dst_reg,
7951                                    enum bpf_reg_type type,
7952                                    bool range_right_open)
7953 {
7954         int new_range, i;
7955
7956         if (dst_reg->off < 0 ||
7957             (dst_reg->off == 0 && range_right_open))
7958                 /* This doesn't give us any range */
7959                 return;
7960
7961         if (dst_reg->umax_value > MAX_PACKET_OFF ||
7962             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7963                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
7964                  * than pkt_end, but that's because it's also less than pkt.
7965                  */
7966                 return;
7967
7968         new_range = dst_reg->off;
7969         if (range_right_open)
7970                 new_range--;
7971
7972         /* Examples for register markings:
7973          *
7974          * pkt_data in dst register:
7975          *
7976          *   r2 = r3;
7977          *   r2 += 8;
7978          *   if (r2 > pkt_end) goto <handle exception>
7979          *   <access okay>
7980          *
7981          *   r2 = r3;
7982          *   r2 += 8;
7983          *   if (r2 < pkt_end) goto <access okay>
7984          *   <handle exception>
7985          *
7986          *   Where:
7987          *     r2 == dst_reg, pkt_end == src_reg
7988          *     r2=pkt(id=n,off=8,r=0)
7989          *     r3=pkt(id=n,off=0,r=0)
7990          *
7991          * pkt_data in src register:
7992          *
7993          *   r2 = r3;
7994          *   r2 += 8;
7995          *   if (pkt_end >= r2) goto <access okay>
7996          *   <handle exception>
7997          *
7998          *   r2 = r3;
7999          *   r2 += 8;
8000          *   if (pkt_end <= r2) goto <handle exception>
8001          *   <access okay>
8002          *
8003          *   Where:
8004          *     pkt_end == dst_reg, r2 == src_reg
8005          *     r2=pkt(id=n,off=8,r=0)
8006          *     r3=pkt(id=n,off=0,r=0)
8007          *
8008          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8009          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8010          * and [r3, r3 + 8-1) respectively is safe to access depending on
8011          * the check.
8012          */
8013
8014         /* If our ids match, then we must have the same max_value.  And we
8015          * don't care about the other reg's fixed offset, since if it's too big
8016          * the range won't allow anything.
8017          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8018          */
8019         for (i = 0; i <= vstate->curframe; i++)
8020                 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8021                                          new_range);
8022 }
8023
8024 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8025 {
8026         struct tnum subreg = tnum_subreg(reg->var_off);
8027         s32 sval = (s32)val;
8028
8029         switch (opcode) {
8030         case BPF_JEQ:
8031                 if (tnum_is_const(subreg))
8032                         return !!tnum_equals_const(subreg, val);
8033                 break;
8034         case BPF_JNE:
8035                 if (tnum_is_const(subreg))
8036                         return !tnum_equals_const(subreg, val);
8037                 break;
8038         case BPF_JSET:
8039                 if ((~subreg.mask & subreg.value) & val)
8040                         return 1;
8041                 if (!((subreg.mask | subreg.value) & val))
8042                         return 0;
8043                 break;
8044         case BPF_JGT:
8045                 if (reg->u32_min_value > val)
8046                         return 1;
8047                 else if (reg->u32_max_value <= val)
8048                         return 0;
8049                 break;
8050         case BPF_JSGT:
8051                 if (reg->s32_min_value > sval)
8052                         return 1;
8053                 else if (reg->s32_max_value <= sval)
8054                         return 0;
8055                 break;
8056         case BPF_JLT:
8057                 if (reg->u32_max_value < val)
8058                         return 1;
8059                 else if (reg->u32_min_value >= val)
8060                         return 0;
8061                 break;
8062         case BPF_JSLT:
8063                 if (reg->s32_max_value < sval)
8064                         return 1;
8065                 else if (reg->s32_min_value >= sval)
8066                         return 0;
8067                 break;
8068         case BPF_JGE:
8069                 if (reg->u32_min_value >= val)
8070                         return 1;
8071                 else if (reg->u32_max_value < val)
8072                         return 0;
8073                 break;
8074         case BPF_JSGE:
8075                 if (reg->s32_min_value >= sval)
8076                         return 1;
8077                 else if (reg->s32_max_value < sval)
8078                         return 0;
8079                 break;
8080         case BPF_JLE:
8081                 if (reg->u32_max_value <= val)
8082                         return 1;
8083                 else if (reg->u32_min_value > val)
8084                         return 0;
8085                 break;
8086         case BPF_JSLE:
8087                 if (reg->s32_max_value <= sval)
8088                         return 1;
8089                 else if (reg->s32_min_value > sval)
8090                         return 0;
8091                 break;
8092         }
8093
8094         return -1;
8095 }
8096
8097
8098 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8099 {
8100         s64 sval = (s64)val;
8101
8102         switch (opcode) {
8103         case BPF_JEQ:
8104                 if (tnum_is_const(reg->var_off))
8105                         return !!tnum_equals_const(reg->var_off, val);
8106                 break;
8107         case BPF_JNE:
8108                 if (tnum_is_const(reg->var_off))
8109                         return !tnum_equals_const(reg->var_off, val);
8110                 break;
8111         case BPF_JSET:
8112                 if ((~reg->var_off.mask & reg->var_off.value) & val)
8113                         return 1;
8114                 if (!((reg->var_off.mask | reg->var_off.value) & val))
8115                         return 0;
8116                 break;
8117         case BPF_JGT:
8118                 if (reg->umin_value > val)
8119                         return 1;
8120                 else if (reg->umax_value <= val)
8121                         return 0;
8122                 break;
8123         case BPF_JSGT:
8124                 if (reg->smin_value > sval)
8125                         return 1;
8126                 else if (reg->smax_value <= sval)
8127                         return 0;
8128                 break;
8129         case BPF_JLT:
8130                 if (reg->umax_value < val)
8131                         return 1;
8132                 else if (reg->umin_value >= val)
8133                         return 0;
8134                 break;
8135         case BPF_JSLT:
8136                 if (reg->smax_value < sval)
8137                         return 1;
8138                 else if (reg->smin_value >= sval)
8139                         return 0;
8140                 break;
8141         case BPF_JGE:
8142                 if (reg->umin_value >= val)
8143                         return 1;
8144                 else if (reg->umax_value < val)
8145                         return 0;
8146                 break;
8147         case BPF_JSGE:
8148                 if (reg->smin_value >= sval)
8149                         return 1;
8150                 else if (reg->smax_value < sval)
8151                         return 0;
8152                 break;
8153         case BPF_JLE:
8154                 if (reg->umax_value <= val)
8155                         return 1;
8156                 else if (reg->umin_value > val)
8157                         return 0;
8158                 break;
8159         case BPF_JSLE:
8160                 if (reg->smax_value <= sval)
8161                         return 1;
8162                 else if (reg->smin_value > sval)
8163                         return 0;
8164                 break;
8165         }
8166
8167         return -1;
8168 }
8169
8170 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8171  * and return:
8172  *  1 - branch will be taken and "goto target" will be executed
8173  *  0 - branch will not be taken and fall-through to next insn
8174  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8175  *      range [0,10]
8176  */
8177 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8178                            bool is_jmp32)
8179 {
8180         if (__is_pointer_value(false, reg)) {
8181                 if (!reg_type_not_null(reg->type))
8182                         return -1;
8183
8184                 /* If pointer is valid tests against zero will fail so we can
8185                  * use this to direct branch taken.
8186                  */
8187                 if (val != 0)
8188                         return -1;
8189
8190                 switch (opcode) {
8191                 case BPF_JEQ:
8192                         return 0;
8193                 case BPF_JNE:
8194                         return 1;
8195                 default:
8196                         return -1;
8197                 }
8198         }
8199
8200         if (is_jmp32)
8201                 return is_branch32_taken(reg, val, opcode);
8202         return is_branch64_taken(reg, val, opcode);
8203 }
8204
8205 static int flip_opcode(u32 opcode)
8206 {
8207         /* How can we transform "a <op> b" into "b <op> a"? */
8208         static const u8 opcode_flip[16] = {
8209                 /* these stay the same */
8210                 [BPF_JEQ  >> 4] = BPF_JEQ,
8211                 [BPF_JNE  >> 4] = BPF_JNE,
8212                 [BPF_JSET >> 4] = BPF_JSET,
8213                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8214                 [BPF_JGE  >> 4] = BPF_JLE,
8215                 [BPF_JGT  >> 4] = BPF_JLT,
8216                 [BPF_JLE  >> 4] = BPF_JGE,
8217                 [BPF_JLT  >> 4] = BPF_JGT,
8218                 [BPF_JSGE >> 4] = BPF_JSLE,
8219                 [BPF_JSGT >> 4] = BPF_JSLT,
8220                 [BPF_JSLE >> 4] = BPF_JSGE,
8221                 [BPF_JSLT >> 4] = BPF_JSGT
8222         };
8223         return opcode_flip[opcode >> 4];
8224 }
8225
8226 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8227                                    struct bpf_reg_state *src_reg,
8228                                    u8 opcode)
8229 {
8230         struct bpf_reg_state *pkt;
8231
8232         if (src_reg->type == PTR_TO_PACKET_END) {
8233                 pkt = dst_reg;
8234         } else if (dst_reg->type == PTR_TO_PACKET_END) {
8235                 pkt = src_reg;
8236                 opcode = flip_opcode(opcode);
8237         } else {
8238                 return -1;
8239         }
8240
8241         if (pkt->range >= 0)
8242                 return -1;
8243
8244         switch (opcode) {
8245         case BPF_JLE:
8246                 /* pkt <= pkt_end */
8247                 fallthrough;
8248         case BPF_JGT:
8249                 /* pkt > pkt_end */
8250                 if (pkt->range == BEYOND_PKT_END)
8251                         /* pkt has at last one extra byte beyond pkt_end */
8252                         return opcode == BPF_JGT;
8253                 break;
8254         case BPF_JLT:
8255                 /* pkt < pkt_end */
8256                 fallthrough;
8257         case BPF_JGE:
8258                 /* pkt >= pkt_end */
8259                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8260                         return opcode == BPF_JGE;
8261                 break;
8262         }
8263         return -1;
8264 }
8265
8266 /* Adjusts the register min/max values in the case that the dst_reg is the
8267  * variable register that we are working on, and src_reg is a constant or we're
8268  * simply doing a BPF_K check.
8269  * In JEQ/JNE cases we also adjust the var_off values.
8270  */
8271 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8272                             struct bpf_reg_state *false_reg,
8273                             u64 val, u32 val32,
8274                             u8 opcode, bool is_jmp32)
8275 {
8276         struct tnum false_32off = tnum_subreg(false_reg->var_off);
8277         struct tnum false_64off = false_reg->var_off;
8278         struct tnum true_32off = tnum_subreg(true_reg->var_off);
8279         struct tnum true_64off = true_reg->var_off;
8280         s64 sval = (s64)val;
8281         s32 sval32 = (s32)val32;
8282
8283         /* If the dst_reg is a pointer, we can't learn anything about its
8284          * variable offset from the compare (unless src_reg were a pointer into
8285          * the same object, but we don't bother with that.
8286          * Since false_reg and true_reg have the same type by construction, we
8287          * only need to check one of them for pointerness.
8288          */
8289         if (__is_pointer_value(false, false_reg))
8290                 return;
8291
8292         switch (opcode) {
8293         case BPF_JEQ:
8294         case BPF_JNE:
8295         {
8296                 struct bpf_reg_state *reg =
8297                         opcode == BPF_JEQ ? true_reg : false_reg;
8298
8299                 /* JEQ/JNE comparison doesn't change the register equivalence.
8300                  * r1 = r2;
8301                  * if (r1 == 42) goto label;
8302                  * ...
8303                  * label: // here both r1 and r2 are known to be 42.
8304                  *
8305                  * Hence when marking register as known preserve it's ID.
8306                  */
8307                 if (is_jmp32)
8308                         __mark_reg32_known(reg, val32);
8309                 else
8310                         ___mark_reg_known(reg, val);
8311                 break;
8312         }
8313         case BPF_JSET:
8314                 if (is_jmp32) {
8315                         false_32off = tnum_and(false_32off, tnum_const(~val32));
8316                         if (is_power_of_2(val32))
8317                                 true_32off = tnum_or(true_32off,
8318                                                      tnum_const(val32));
8319                 } else {
8320                         false_64off = tnum_and(false_64off, tnum_const(~val));
8321                         if (is_power_of_2(val))
8322                                 true_64off = tnum_or(true_64off,
8323                                                      tnum_const(val));
8324                 }
8325                 break;
8326         case BPF_JGE:
8327         case BPF_JGT:
8328         {
8329                 if (is_jmp32) {
8330                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8331                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8332
8333                         false_reg->u32_max_value = min(false_reg->u32_max_value,
8334                                                        false_umax);
8335                         true_reg->u32_min_value = max(true_reg->u32_min_value,
8336                                                       true_umin);
8337                 } else {
8338                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8339                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8340
8341                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
8342                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
8343                 }
8344                 break;
8345         }
8346         case BPF_JSGE:
8347         case BPF_JSGT:
8348         {
8349                 if (is_jmp32) {
8350                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8351                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8352
8353                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8354                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8355                 } else {
8356                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8357                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8358
8359                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
8360                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
8361                 }
8362                 break;
8363         }
8364         case BPF_JLE:
8365         case BPF_JLT:
8366         {
8367                 if (is_jmp32) {
8368                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8369                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8370
8371                         false_reg->u32_min_value = max(false_reg->u32_min_value,
8372                                                        false_umin);
8373                         true_reg->u32_max_value = min(true_reg->u32_max_value,
8374                                                       true_umax);
8375                 } else {
8376                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8377                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8378
8379                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
8380                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
8381                 }
8382                 break;
8383         }
8384         case BPF_JSLE:
8385         case BPF_JSLT:
8386         {
8387                 if (is_jmp32) {
8388                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8389                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8390
8391                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8392                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8393                 } else {
8394                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8395                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8396
8397                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
8398                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
8399                 }
8400                 break;
8401         }
8402         default:
8403                 return;
8404         }
8405
8406         if (is_jmp32) {
8407                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8408                                              tnum_subreg(false_32off));
8409                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8410                                             tnum_subreg(true_32off));
8411                 __reg_combine_32_into_64(false_reg);
8412                 __reg_combine_32_into_64(true_reg);
8413         } else {
8414                 false_reg->var_off = false_64off;
8415                 true_reg->var_off = true_64off;
8416                 __reg_combine_64_into_32(false_reg);
8417                 __reg_combine_64_into_32(true_reg);
8418         }
8419 }
8420
8421 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8422  * the variable reg.
8423  */
8424 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8425                                 struct bpf_reg_state *false_reg,
8426                                 u64 val, u32 val32,
8427                                 u8 opcode, bool is_jmp32)
8428 {
8429         opcode = flip_opcode(opcode);
8430         /* This uses zero as "not present in table"; luckily the zero opcode,
8431          * BPF_JA, can't get here.
8432          */
8433         if (opcode)
8434                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8435 }
8436
8437 /* Regs are known to be equal, so intersect their min/max/var_off */
8438 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8439                                   struct bpf_reg_state *dst_reg)
8440 {
8441         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8442                                                         dst_reg->umin_value);
8443         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8444                                                         dst_reg->umax_value);
8445         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8446                                                         dst_reg->smin_value);
8447         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8448                                                         dst_reg->smax_value);
8449         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8450                                                              dst_reg->var_off);
8451         /* We might have learned new bounds from the var_off. */
8452         __update_reg_bounds(src_reg);
8453         __update_reg_bounds(dst_reg);
8454         /* We might have learned something about the sign bit. */
8455         __reg_deduce_bounds(src_reg);
8456         __reg_deduce_bounds(dst_reg);
8457         /* We might have learned some bits from the bounds. */
8458         __reg_bound_offset(src_reg);
8459         __reg_bound_offset(dst_reg);
8460         /* Intersecting with the old var_off might have improved our bounds
8461          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8462          * then new var_off is (0; 0x7f...fc) which improves our umax.
8463          */
8464         __update_reg_bounds(src_reg);
8465         __update_reg_bounds(dst_reg);
8466 }
8467
8468 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8469                                 struct bpf_reg_state *true_dst,
8470                                 struct bpf_reg_state *false_src,
8471                                 struct bpf_reg_state *false_dst,
8472                                 u8 opcode)
8473 {
8474         switch (opcode) {
8475         case BPF_JEQ:
8476                 __reg_combine_min_max(true_src, true_dst);
8477                 break;
8478         case BPF_JNE:
8479                 __reg_combine_min_max(false_src, false_dst);
8480                 break;
8481         }
8482 }
8483
8484 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8485                                  struct bpf_reg_state *reg, u32 id,
8486                                  bool is_null)
8487 {
8488         if (reg_type_may_be_null(reg->type) && reg->id == id &&
8489             !WARN_ON_ONCE(!reg->id)) {
8490                 /* Old offset (both fixed and variable parts) should
8491                  * have been known-zero, because we don't allow pointer
8492                  * arithmetic on pointers that might be NULL.
8493                  */
8494                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8495                                  !tnum_equals_const(reg->var_off, 0) ||
8496                                  reg->off)) {
8497                         __mark_reg_known_zero(reg);
8498                         reg->off = 0;
8499                 }
8500                 if (is_null) {
8501                         reg->type = SCALAR_VALUE;
8502                         /* We don't need id and ref_obj_id from this point
8503                          * onwards anymore, thus we should better reset it,
8504                          * so that state pruning has chances to take effect.
8505                          */
8506                         reg->id = 0;
8507                         reg->ref_obj_id = 0;
8508
8509                         return;
8510                 }
8511
8512                 mark_ptr_not_null_reg(reg);
8513
8514                 if (!reg_may_point_to_spin_lock(reg)) {
8515                         /* For not-NULL ptr, reg->ref_obj_id will be reset
8516                          * in release_reg_references().
8517                          *
8518                          * reg->id is still used by spin_lock ptr. Other
8519                          * than spin_lock ptr type, reg->id can be reset.
8520                          */
8521                         reg->id = 0;
8522                 }
8523         }
8524 }
8525
8526 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8527                                     bool is_null)
8528 {
8529         struct bpf_reg_state *reg;
8530         int i;
8531
8532         for (i = 0; i < MAX_BPF_REG; i++)
8533                 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8534
8535         bpf_for_each_spilled_reg(i, state, reg) {
8536                 if (!reg)
8537                         continue;
8538                 mark_ptr_or_null_reg(state, reg, id, is_null);
8539         }
8540 }
8541
8542 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8543  * be folded together at some point.
8544  */
8545 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8546                                   bool is_null)
8547 {
8548         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8549         struct bpf_reg_state *regs = state->regs;
8550         u32 ref_obj_id = regs[regno].ref_obj_id;
8551         u32 id = regs[regno].id;
8552         int i;
8553
8554         if (ref_obj_id && ref_obj_id == id && is_null)
8555                 /* regs[regno] is in the " == NULL" branch.
8556                  * No one could have freed the reference state before
8557                  * doing the NULL check.
8558                  */
8559                 WARN_ON_ONCE(release_reference_state(state, id));
8560
8561         for (i = 0; i <= vstate->curframe; i++)
8562                 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
8563 }
8564
8565 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8566                                    struct bpf_reg_state *dst_reg,
8567                                    struct bpf_reg_state *src_reg,
8568                                    struct bpf_verifier_state *this_branch,
8569                                    struct bpf_verifier_state *other_branch)
8570 {
8571         if (BPF_SRC(insn->code) != BPF_X)
8572                 return false;
8573
8574         /* Pointers are always 64-bit. */
8575         if (BPF_CLASS(insn->code) == BPF_JMP32)
8576                 return false;
8577
8578         switch (BPF_OP(insn->code)) {
8579         case BPF_JGT:
8580                 if ((dst_reg->type == PTR_TO_PACKET &&
8581                      src_reg->type == PTR_TO_PACKET_END) ||
8582                     (dst_reg->type == PTR_TO_PACKET_META &&
8583                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8584                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8585                         find_good_pkt_pointers(this_branch, dst_reg,
8586                                                dst_reg->type, false);
8587                         mark_pkt_end(other_branch, insn->dst_reg, true);
8588                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8589                             src_reg->type == PTR_TO_PACKET) ||
8590                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8591                             src_reg->type == PTR_TO_PACKET_META)) {
8592                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8593                         find_good_pkt_pointers(other_branch, src_reg,
8594                                                src_reg->type, true);
8595                         mark_pkt_end(this_branch, insn->src_reg, false);
8596                 } else {
8597                         return false;
8598                 }
8599                 break;
8600         case BPF_JLT:
8601                 if ((dst_reg->type == PTR_TO_PACKET &&
8602                      src_reg->type == PTR_TO_PACKET_END) ||
8603                     (dst_reg->type == PTR_TO_PACKET_META &&
8604                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8605                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8606                         find_good_pkt_pointers(other_branch, dst_reg,
8607                                                dst_reg->type, true);
8608                         mark_pkt_end(this_branch, insn->dst_reg, false);
8609                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8610                             src_reg->type == PTR_TO_PACKET) ||
8611                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8612                             src_reg->type == PTR_TO_PACKET_META)) {
8613                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8614                         find_good_pkt_pointers(this_branch, src_reg,
8615                                                src_reg->type, false);
8616                         mark_pkt_end(other_branch, insn->src_reg, true);
8617                 } else {
8618                         return false;
8619                 }
8620                 break;
8621         case BPF_JGE:
8622                 if ((dst_reg->type == PTR_TO_PACKET &&
8623                      src_reg->type == PTR_TO_PACKET_END) ||
8624                     (dst_reg->type == PTR_TO_PACKET_META &&
8625                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8626                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8627                         find_good_pkt_pointers(this_branch, dst_reg,
8628                                                dst_reg->type, true);
8629                         mark_pkt_end(other_branch, insn->dst_reg, false);
8630                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8631                             src_reg->type == PTR_TO_PACKET) ||
8632                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8633                             src_reg->type == PTR_TO_PACKET_META)) {
8634                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8635                         find_good_pkt_pointers(other_branch, src_reg,
8636                                                src_reg->type, false);
8637                         mark_pkt_end(this_branch, insn->src_reg, true);
8638                 } else {
8639                         return false;
8640                 }
8641                 break;
8642         case BPF_JLE:
8643                 if ((dst_reg->type == PTR_TO_PACKET &&
8644                      src_reg->type == PTR_TO_PACKET_END) ||
8645                     (dst_reg->type == PTR_TO_PACKET_META &&
8646                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8647                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8648                         find_good_pkt_pointers(other_branch, dst_reg,
8649                                                dst_reg->type, false);
8650                         mark_pkt_end(this_branch, insn->dst_reg, true);
8651                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8652                             src_reg->type == PTR_TO_PACKET) ||
8653                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8654                             src_reg->type == PTR_TO_PACKET_META)) {
8655                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8656                         find_good_pkt_pointers(this_branch, src_reg,
8657                                                src_reg->type, true);
8658                         mark_pkt_end(other_branch, insn->src_reg, false);
8659                 } else {
8660                         return false;
8661                 }
8662                 break;
8663         default:
8664                 return false;
8665         }
8666
8667         return true;
8668 }
8669
8670 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8671                                struct bpf_reg_state *known_reg)
8672 {
8673         struct bpf_func_state *state;
8674         struct bpf_reg_state *reg;
8675         int i, j;
8676
8677         for (i = 0; i <= vstate->curframe; i++) {
8678                 state = vstate->frame[i];
8679                 for (j = 0; j < MAX_BPF_REG; j++) {
8680                         reg = &state->regs[j];
8681                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8682                                 *reg = *known_reg;
8683                 }
8684
8685                 bpf_for_each_spilled_reg(j, state, reg) {
8686                         if (!reg)
8687                                 continue;
8688                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8689                                 *reg = *known_reg;
8690                 }
8691         }
8692 }
8693
8694 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8695                              struct bpf_insn *insn, int *insn_idx)
8696 {
8697         struct bpf_verifier_state *this_branch = env->cur_state;
8698         struct bpf_verifier_state *other_branch;
8699         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8700         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8701         u8 opcode = BPF_OP(insn->code);
8702         bool is_jmp32;
8703         int pred = -1;
8704         int err;
8705
8706         /* Only conditional jumps are expected to reach here. */
8707         if (opcode == BPF_JA || opcode > BPF_JSLE) {
8708                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8709                 return -EINVAL;
8710         }
8711
8712         if (BPF_SRC(insn->code) == BPF_X) {
8713                 if (insn->imm != 0) {
8714                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8715                         return -EINVAL;
8716                 }
8717
8718                 /* check src1 operand */
8719                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8720                 if (err)
8721                         return err;
8722
8723                 if (is_pointer_value(env, insn->src_reg)) {
8724                         verbose(env, "R%d pointer comparison prohibited\n",
8725                                 insn->src_reg);
8726                         return -EACCES;
8727                 }
8728                 src_reg = &regs[insn->src_reg];
8729         } else {
8730                 if (insn->src_reg != BPF_REG_0) {
8731                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8732                         return -EINVAL;
8733                 }
8734         }
8735
8736         /* check src2 operand */
8737         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8738         if (err)
8739                 return err;
8740
8741         dst_reg = &regs[insn->dst_reg];
8742         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8743
8744         if (BPF_SRC(insn->code) == BPF_K) {
8745                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8746         } else if (src_reg->type == SCALAR_VALUE &&
8747                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8748                 pred = is_branch_taken(dst_reg,
8749                                        tnum_subreg(src_reg->var_off).value,
8750                                        opcode,
8751                                        is_jmp32);
8752         } else if (src_reg->type == SCALAR_VALUE &&
8753                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8754                 pred = is_branch_taken(dst_reg,
8755                                        src_reg->var_off.value,
8756                                        opcode,
8757                                        is_jmp32);
8758         } else if (reg_is_pkt_pointer_any(dst_reg) &&
8759                    reg_is_pkt_pointer_any(src_reg) &&
8760                    !is_jmp32) {
8761                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8762         }
8763
8764         if (pred >= 0) {
8765                 /* If we get here with a dst_reg pointer type it is because
8766                  * above is_branch_taken() special cased the 0 comparison.
8767                  */
8768                 if (!__is_pointer_value(false, dst_reg))
8769                         err = mark_chain_precision(env, insn->dst_reg);
8770                 if (BPF_SRC(insn->code) == BPF_X && !err &&
8771                     !__is_pointer_value(false, src_reg))
8772                         err = mark_chain_precision(env, insn->src_reg);
8773                 if (err)
8774                         return err;
8775         }
8776
8777         if (pred == 1) {
8778                 /* Only follow the goto, ignore fall-through. If needed, push
8779                  * the fall-through branch for simulation under speculative
8780                  * execution.
8781                  */
8782                 if (!env->bypass_spec_v1 &&
8783                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
8784                                                *insn_idx))
8785                         return -EFAULT;
8786                 *insn_idx += insn->off;
8787                 return 0;
8788         } else if (pred == 0) {
8789                 /* Only follow the fall-through branch, since that's where the
8790                  * program will go. If needed, push the goto branch for
8791                  * simulation under speculative execution.
8792                  */
8793                 if (!env->bypass_spec_v1 &&
8794                     !sanitize_speculative_path(env, insn,
8795                                                *insn_idx + insn->off + 1,
8796                                                *insn_idx))
8797                         return -EFAULT;
8798                 return 0;
8799         }
8800
8801         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8802                                   false);
8803         if (!other_branch)
8804                 return -EFAULT;
8805         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8806
8807         /* detect if we are comparing against a constant value so we can adjust
8808          * our min/max values for our dst register.
8809          * this is only legit if both are scalars (or pointers to the same
8810          * object, I suppose, but we don't support that right now), because
8811          * otherwise the different base pointers mean the offsets aren't
8812          * comparable.
8813          */
8814         if (BPF_SRC(insn->code) == BPF_X) {
8815                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8816
8817                 if (dst_reg->type == SCALAR_VALUE &&
8818                     src_reg->type == SCALAR_VALUE) {
8819                         if (tnum_is_const(src_reg->var_off) ||
8820                             (is_jmp32 &&
8821                              tnum_is_const(tnum_subreg(src_reg->var_off))))
8822                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8823                                                 dst_reg,
8824                                                 src_reg->var_off.value,
8825                                                 tnum_subreg(src_reg->var_off).value,
8826                                                 opcode, is_jmp32);
8827                         else if (tnum_is_const(dst_reg->var_off) ||
8828                                  (is_jmp32 &&
8829                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
8830                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8831                                                     src_reg,
8832                                                     dst_reg->var_off.value,
8833                                                     tnum_subreg(dst_reg->var_off).value,
8834                                                     opcode, is_jmp32);
8835                         else if (!is_jmp32 &&
8836                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
8837                                 /* Comparing for equality, we can combine knowledge */
8838                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8839                                                     &other_branch_regs[insn->dst_reg],
8840                                                     src_reg, dst_reg, opcode);
8841                         if (src_reg->id &&
8842                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8843                                 find_equal_scalars(this_branch, src_reg);
8844                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8845                         }
8846
8847                 }
8848         } else if (dst_reg->type == SCALAR_VALUE) {
8849                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8850                                         dst_reg, insn->imm, (u32)insn->imm,
8851                                         opcode, is_jmp32);
8852         }
8853
8854         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8855             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8856                 find_equal_scalars(this_branch, dst_reg);
8857                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8858         }
8859
8860         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8861          * NOTE: these optimizations below are related with pointer comparison
8862          *       which will never be JMP32.
8863          */
8864         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8865             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8866             reg_type_may_be_null(dst_reg->type)) {
8867                 /* Mark all identical registers in each branch as either
8868                  * safe or unknown depending R == 0 or R != 0 conditional.
8869                  */
8870                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8871                                       opcode == BPF_JNE);
8872                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8873                                       opcode == BPF_JEQ);
8874         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8875                                            this_branch, other_branch) &&
8876                    is_pointer_value(env, insn->dst_reg)) {
8877                 verbose(env, "R%d pointer comparison prohibited\n",
8878                         insn->dst_reg);
8879                 return -EACCES;
8880         }
8881         if (env->log.level & BPF_LOG_LEVEL)
8882                 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8883         return 0;
8884 }
8885
8886 /* verify BPF_LD_IMM64 instruction */
8887 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8888 {
8889         struct bpf_insn_aux_data *aux = cur_aux(env);
8890         struct bpf_reg_state *regs = cur_regs(env);
8891         struct bpf_reg_state *dst_reg;
8892         struct bpf_map *map;
8893         int err;
8894
8895         if (BPF_SIZE(insn->code) != BPF_DW) {
8896                 verbose(env, "invalid BPF_LD_IMM insn\n");
8897                 return -EINVAL;
8898         }
8899         if (insn->off != 0) {
8900                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8901                 return -EINVAL;
8902         }
8903
8904         err = check_reg_arg(env, insn->dst_reg, DST_OP);
8905         if (err)
8906                 return err;
8907
8908         dst_reg = &regs[insn->dst_reg];
8909         if (insn->src_reg == 0) {
8910                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8911
8912                 dst_reg->type = SCALAR_VALUE;
8913                 __mark_reg_known(&regs[insn->dst_reg], imm);
8914                 return 0;
8915         }
8916
8917         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8918                 mark_reg_known_zero(env, regs, insn->dst_reg);
8919
8920                 dst_reg->type = aux->btf_var.reg_type;
8921                 switch (dst_reg->type) {
8922                 case PTR_TO_MEM:
8923                         dst_reg->mem_size = aux->btf_var.mem_size;
8924                         break;
8925                 case PTR_TO_BTF_ID:
8926                 case PTR_TO_PERCPU_BTF_ID:
8927                         dst_reg->btf = aux->btf_var.btf;
8928                         dst_reg->btf_id = aux->btf_var.btf_id;
8929                         break;
8930                 default:
8931                         verbose(env, "bpf verifier is misconfigured\n");
8932                         return -EFAULT;
8933                 }
8934                 return 0;
8935         }
8936
8937         if (insn->src_reg == BPF_PSEUDO_FUNC) {
8938                 struct bpf_prog_aux *aux = env->prog->aux;
8939                 u32 subprogno = insn[1].imm;
8940
8941                 if (!aux->func_info) {
8942                         verbose(env, "missing btf func_info\n");
8943                         return -EINVAL;
8944                 }
8945                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8946                         verbose(env, "callback function not static\n");
8947                         return -EINVAL;
8948                 }
8949
8950                 dst_reg->type = PTR_TO_FUNC;
8951                 dst_reg->subprogno = subprogno;
8952                 return 0;
8953         }
8954
8955         map = env->used_maps[aux->map_index];
8956         mark_reg_known_zero(env, regs, insn->dst_reg);
8957         dst_reg->map_ptr = map;
8958
8959         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8960                 dst_reg->type = PTR_TO_MAP_VALUE;
8961                 dst_reg->off = aux->map_off;
8962                 if (map_value_has_spin_lock(map))
8963                         dst_reg->id = ++env->id_gen;
8964         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8965                 dst_reg->type = CONST_PTR_TO_MAP;
8966         } else {
8967                 verbose(env, "bpf verifier is misconfigured\n");
8968                 return -EINVAL;
8969         }
8970
8971         return 0;
8972 }
8973
8974 static bool may_access_skb(enum bpf_prog_type type)
8975 {
8976         switch (type) {
8977         case BPF_PROG_TYPE_SOCKET_FILTER:
8978         case BPF_PROG_TYPE_SCHED_CLS:
8979         case BPF_PROG_TYPE_SCHED_ACT:
8980                 return true;
8981         default:
8982                 return false;
8983         }
8984 }
8985
8986 /* verify safety of LD_ABS|LD_IND instructions:
8987  * - they can only appear in the programs where ctx == skb
8988  * - since they are wrappers of function calls, they scratch R1-R5 registers,
8989  *   preserve R6-R9, and store return value into R0
8990  *
8991  * Implicit input:
8992  *   ctx == skb == R6 == CTX
8993  *
8994  * Explicit input:
8995  *   SRC == any register
8996  *   IMM == 32-bit immediate
8997  *
8998  * Output:
8999  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9000  */
9001 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9002 {
9003         struct bpf_reg_state *regs = cur_regs(env);
9004         static const int ctx_reg = BPF_REG_6;
9005         u8 mode = BPF_MODE(insn->code);
9006         int i, err;
9007
9008         if (!may_access_skb(resolve_prog_type(env->prog))) {
9009                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9010                 return -EINVAL;
9011         }
9012
9013         if (!env->ops->gen_ld_abs) {
9014                 verbose(env, "bpf verifier is misconfigured\n");
9015                 return -EINVAL;
9016         }
9017
9018         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9019             BPF_SIZE(insn->code) == BPF_DW ||
9020             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9021                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9022                 return -EINVAL;
9023         }
9024
9025         /* check whether implicit source operand (register R6) is readable */
9026         err = check_reg_arg(env, ctx_reg, SRC_OP);
9027         if (err)
9028                 return err;
9029
9030         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9031          * gen_ld_abs() may terminate the program at runtime, leading to
9032          * reference leak.
9033          */
9034         err = check_reference_leak(env);
9035         if (err) {
9036                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9037                 return err;
9038         }
9039
9040         if (env->cur_state->active_spin_lock) {
9041                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9042                 return -EINVAL;
9043         }
9044
9045         if (regs[ctx_reg].type != PTR_TO_CTX) {
9046                 verbose(env,
9047                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9048                 return -EINVAL;
9049         }
9050
9051         if (mode == BPF_IND) {
9052                 /* check explicit source operand */
9053                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9054                 if (err)
9055                         return err;
9056         }
9057
9058         err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9059         if (err < 0)
9060                 return err;
9061
9062         /* reset caller saved regs to unreadable */
9063         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9064                 mark_reg_not_init(env, regs, caller_saved[i]);
9065                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9066         }
9067
9068         /* mark destination R0 register as readable, since it contains
9069          * the value fetched from the packet.
9070          * Already marked as written above.
9071          */
9072         mark_reg_unknown(env, regs, BPF_REG_0);
9073         /* ld_abs load up to 32-bit skb data. */
9074         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9075         return 0;
9076 }
9077
9078 static int check_return_code(struct bpf_verifier_env *env)
9079 {
9080         struct tnum enforce_attach_type_range = tnum_unknown;
9081         const struct bpf_prog *prog = env->prog;
9082         struct bpf_reg_state *reg;
9083         struct tnum range = tnum_range(0, 1);
9084         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9085         int err;
9086         const bool is_subprog = env->cur_state->frame[0]->subprogno;
9087
9088         /* LSM and struct_ops func-ptr's return type could be "void" */
9089         if (!is_subprog &&
9090             (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9091              prog_type == BPF_PROG_TYPE_LSM) &&
9092             !prog->aux->attach_func_proto->type)
9093                 return 0;
9094
9095         /* eBPF calling convetion is such that R0 is used
9096          * to return the value from eBPF program.
9097          * Make sure that it's readable at this time
9098          * of bpf_exit, which means that program wrote
9099          * something into it earlier
9100          */
9101         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9102         if (err)
9103                 return err;
9104
9105         if (is_pointer_value(env, BPF_REG_0)) {
9106                 verbose(env, "R0 leaks addr as return value\n");
9107                 return -EACCES;
9108         }
9109
9110         reg = cur_regs(env) + BPF_REG_0;
9111         if (is_subprog) {
9112                 if (reg->type != SCALAR_VALUE) {
9113                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9114                                 reg_type_str[reg->type]);
9115                         return -EINVAL;
9116                 }
9117                 return 0;
9118         }
9119
9120         switch (prog_type) {
9121         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9122                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9123                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9124                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9125                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9126                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9127                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9128                         range = tnum_range(1, 1);
9129                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9130                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9131                         range = tnum_range(0, 3);
9132                 break;
9133         case BPF_PROG_TYPE_CGROUP_SKB:
9134                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9135                         range = tnum_range(0, 3);
9136                         enforce_attach_type_range = tnum_range(2, 3);
9137                 }
9138                 break;
9139         case BPF_PROG_TYPE_CGROUP_SOCK:
9140         case BPF_PROG_TYPE_SOCK_OPS:
9141         case BPF_PROG_TYPE_CGROUP_DEVICE:
9142         case BPF_PROG_TYPE_CGROUP_SYSCTL:
9143         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9144                 break;
9145         case BPF_PROG_TYPE_RAW_TRACEPOINT:
9146                 if (!env->prog->aux->attach_btf_id)
9147                         return 0;
9148                 range = tnum_const(0);
9149                 break;
9150         case BPF_PROG_TYPE_TRACING:
9151                 switch (env->prog->expected_attach_type) {
9152                 case BPF_TRACE_FENTRY:
9153                 case BPF_TRACE_FEXIT:
9154                         range = tnum_const(0);
9155                         break;
9156                 case BPF_TRACE_RAW_TP:
9157                 case BPF_MODIFY_RETURN:
9158                         return 0;
9159                 case BPF_TRACE_ITER:
9160                         break;
9161                 default:
9162                         return -ENOTSUPP;
9163                 }
9164                 break;
9165         case BPF_PROG_TYPE_SK_LOOKUP:
9166                 range = tnum_range(SK_DROP, SK_PASS);
9167                 break;
9168         case BPF_PROG_TYPE_EXT:
9169                 /* freplace program can return anything as its return value
9170                  * depends on the to-be-replaced kernel func or bpf program.
9171                  */
9172         default:
9173                 return 0;
9174         }
9175
9176         if (reg->type != SCALAR_VALUE) {
9177                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9178                         reg_type_str[reg->type]);
9179                 return -EINVAL;
9180         }
9181
9182         if (!tnum_in(range, reg->var_off)) {
9183                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9184                 return -EINVAL;
9185         }
9186
9187         if (!tnum_is_unknown(enforce_attach_type_range) &&
9188             tnum_in(enforce_attach_type_range, reg->var_off))
9189                 env->prog->enforce_expected_attach_type = 1;
9190         return 0;
9191 }
9192
9193 /* non-recursive DFS pseudo code
9194  * 1  procedure DFS-iterative(G,v):
9195  * 2      label v as discovered
9196  * 3      let S be a stack
9197  * 4      S.push(v)
9198  * 5      while S is not empty
9199  * 6            t <- S.pop()
9200  * 7            if t is what we're looking for:
9201  * 8                return t
9202  * 9            for all edges e in G.adjacentEdges(t) do
9203  * 10               if edge e is already labelled
9204  * 11                   continue with the next edge
9205  * 12               w <- G.adjacentVertex(t,e)
9206  * 13               if vertex w is not discovered and not explored
9207  * 14                   label e as tree-edge
9208  * 15                   label w as discovered
9209  * 16                   S.push(w)
9210  * 17                   continue at 5
9211  * 18               else if vertex w is discovered
9212  * 19                   label e as back-edge
9213  * 20               else
9214  * 21                   // vertex w is explored
9215  * 22                   label e as forward- or cross-edge
9216  * 23           label t as explored
9217  * 24           S.pop()
9218  *
9219  * convention:
9220  * 0x10 - discovered
9221  * 0x11 - discovered and fall-through edge labelled
9222  * 0x12 - discovered and fall-through and branch edges labelled
9223  * 0x20 - explored
9224  */
9225
9226 enum {
9227         DISCOVERED = 0x10,
9228         EXPLORED = 0x20,
9229         FALLTHROUGH = 1,
9230         BRANCH = 2,
9231 };
9232
9233 static u32 state_htab_size(struct bpf_verifier_env *env)
9234 {
9235         return env->prog->len;
9236 }
9237
9238 static struct bpf_verifier_state_list **explored_state(
9239                                         struct bpf_verifier_env *env,
9240                                         int idx)
9241 {
9242         struct bpf_verifier_state *cur = env->cur_state;
9243         struct bpf_func_state *state = cur->frame[cur->curframe];
9244
9245         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9246 }
9247
9248 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9249 {
9250         env->insn_aux_data[idx].prune_point = true;
9251 }
9252
9253 enum {
9254         DONE_EXPLORING = 0,
9255         KEEP_EXPLORING = 1,
9256 };
9257
9258 /* t, w, e - match pseudo-code above:
9259  * t - index of current instruction
9260  * w - next instruction
9261  * e - edge
9262  */
9263 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9264                      bool loop_ok)
9265 {
9266         int *insn_stack = env->cfg.insn_stack;
9267         int *insn_state = env->cfg.insn_state;
9268
9269         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9270                 return DONE_EXPLORING;
9271
9272         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9273                 return DONE_EXPLORING;
9274
9275         if (w < 0 || w >= env->prog->len) {
9276                 verbose_linfo(env, t, "%d: ", t);
9277                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
9278                 return -EINVAL;
9279         }
9280
9281         if (e == BRANCH)
9282                 /* mark branch target for state pruning */
9283                 init_explored_state(env, w);
9284
9285         if (insn_state[w] == 0) {
9286                 /* tree-edge */
9287                 insn_state[t] = DISCOVERED | e;
9288                 insn_state[w] = DISCOVERED;
9289                 if (env->cfg.cur_stack >= env->prog->len)
9290                         return -E2BIG;
9291                 insn_stack[env->cfg.cur_stack++] = w;
9292                 return KEEP_EXPLORING;
9293         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9294                 if (loop_ok && env->bpf_capable)
9295                         return DONE_EXPLORING;
9296                 verbose_linfo(env, t, "%d: ", t);
9297                 verbose_linfo(env, w, "%d: ", w);
9298                 verbose(env, "back-edge from insn %d to %d\n", t, w);
9299                 return -EINVAL;
9300         } else if (insn_state[w] == EXPLORED) {
9301                 /* forward- or cross-edge */
9302                 insn_state[t] = DISCOVERED | e;
9303         } else {
9304                 verbose(env, "insn state internal bug\n");
9305                 return -EFAULT;
9306         }
9307         return DONE_EXPLORING;
9308 }
9309
9310 static int visit_func_call_insn(int t, int insn_cnt,
9311                                 struct bpf_insn *insns,
9312                                 struct bpf_verifier_env *env,
9313                                 bool visit_callee)
9314 {
9315         int ret;
9316
9317         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9318         if (ret)
9319                 return ret;
9320
9321         if (t + 1 < insn_cnt)
9322                 init_explored_state(env, t + 1);
9323         if (visit_callee) {
9324                 init_explored_state(env, t);
9325                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
9326                                 env, false);
9327         }
9328         return ret;
9329 }
9330
9331 /* Visits the instruction at index t and returns one of the following:
9332  *  < 0 - an error occurred
9333  *  DONE_EXPLORING - the instruction was fully explored
9334  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9335  */
9336 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9337 {
9338         struct bpf_insn *insns = env->prog->insnsi;
9339         int ret;
9340
9341         if (bpf_pseudo_func(insns + t))
9342                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9343
9344         /* All non-branch instructions have a single fall-through edge. */
9345         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9346             BPF_CLASS(insns[t].code) != BPF_JMP32)
9347                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9348
9349         switch (BPF_OP(insns[t].code)) {
9350         case BPF_EXIT:
9351                 return DONE_EXPLORING;
9352
9353         case BPF_CALL:
9354                 return visit_func_call_insn(t, insn_cnt, insns, env,
9355                                             insns[t].src_reg == BPF_PSEUDO_CALL);
9356
9357         case BPF_JA:
9358                 if (BPF_SRC(insns[t].code) != BPF_K)
9359                         return -EINVAL;
9360
9361                 /* unconditional jump with single edge */
9362                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9363                                 true);
9364                 if (ret)
9365                         return ret;
9366
9367                 /* unconditional jmp is not a good pruning point,
9368                  * but it's marked, since backtracking needs
9369                  * to record jmp history in is_state_visited().
9370                  */
9371                 init_explored_state(env, t + insns[t].off + 1);
9372                 /* tell verifier to check for equivalent states
9373                  * after every call and jump
9374                  */
9375                 if (t + 1 < insn_cnt)
9376                         init_explored_state(env, t + 1);
9377
9378                 return ret;
9379
9380         default:
9381                 /* conditional jump with two edges */
9382                 init_explored_state(env, t);
9383                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9384                 if (ret)
9385                         return ret;
9386
9387                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9388         }
9389 }
9390
9391 /* non-recursive depth-first-search to detect loops in BPF program
9392  * loop == back-edge in directed graph
9393  */
9394 static int check_cfg(struct bpf_verifier_env *env)
9395 {
9396         int insn_cnt = env->prog->len;
9397         int *insn_stack, *insn_state;
9398         int ret = 0;
9399         int i;
9400
9401         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9402         if (!insn_state)
9403                 return -ENOMEM;
9404
9405         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9406         if (!insn_stack) {
9407                 kvfree(insn_state);
9408                 return -ENOMEM;
9409         }
9410
9411         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9412         insn_stack[0] = 0; /* 0 is the first instruction */
9413         env->cfg.cur_stack = 1;
9414
9415         while (env->cfg.cur_stack > 0) {
9416                 int t = insn_stack[env->cfg.cur_stack - 1];
9417
9418                 ret = visit_insn(t, insn_cnt, env);
9419                 switch (ret) {
9420                 case DONE_EXPLORING:
9421                         insn_state[t] = EXPLORED;
9422                         env->cfg.cur_stack--;
9423                         break;
9424                 case KEEP_EXPLORING:
9425                         break;
9426                 default:
9427                         if (ret > 0) {
9428                                 verbose(env, "visit_insn internal bug\n");
9429                                 ret = -EFAULT;
9430                         }
9431                         goto err_free;
9432                 }
9433         }
9434
9435         if (env->cfg.cur_stack < 0) {
9436                 verbose(env, "pop stack internal bug\n");
9437                 ret = -EFAULT;
9438                 goto err_free;
9439         }
9440
9441         for (i = 0; i < insn_cnt; i++) {
9442                 if (insn_state[i] != EXPLORED) {
9443                         verbose(env, "unreachable insn %d\n", i);
9444                         ret = -EINVAL;
9445                         goto err_free;
9446                 }
9447         }
9448         ret = 0; /* cfg looks good */
9449
9450 err_free:
9451         kvfree(insn_state);
9452         kvfree(insn_stack);
9453         env->cfg.insn_state = env->cfg.insn_stack = NULL;
9454         return ret;
9455 }
9456
9457 static int check_abnormal_return(struct bpf_verifier_env *env)
9458 {
9459         int i;
9460
9461         for (i = 1; i < env->subprog_cnt; i++) {
9462                 if (env->subprog_info[i].has_ld_abs) {
9463                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9464                         return -EINVAL;
9465                 }
9466                 if (env->subprog_info[i].has_tail_call) {
9467                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9468                         return -EINVAL;
9469                 }
9470         }
9471         return 0;
9472 }
9473
9474 /* The minimum supported BTF func info size */
9475 #define MIN_BPF_FUNCINFO_SIZE   8
9476 #define MAX_FUNCINFO_REC_SIZE   252
9477
9478 static int check_btf_func(struct bpf_verifier_env *env,
9479                           const union bpf_attr *attr,
9480                           union bpf_attr __user *uattr)
9481 {
9482         const struct btf_type *type, *func_proto, *ret_type;
9483         u32 i, nfuncs, urec_size, min_size;
9484         u32 krec_size = sizeof(struct bpf_func_info);
9485         struct bpf_func_info *krecord;
9486         struct bpf_func_info_aux *info_aux = NULL;
9487         struct bpf_prog *prog;
9488         const struct btf *btf;
9489         void __user *urecord;
9490         u32 prev_offset = 0;
9491         bool scalar_return;
9492         int ret = -ENOMEM;
9493
9494         nfuncs = attr->func_info_cnt;
9495         if (!nfuncs) {
9496                 if (check_abnormal_return(env))
9497                         return -EINVAL;
9498                 return 0;
9499         }
9500
9501         if (nfuncs != env->subprog_cnt) {
9502                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9503                 return -EINVAL;
9504         }
9505
9506         urec_size = attr->func_info_rec_size;
9507         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9508             urec_size > MAX_FUNCINFO_REC_SIZE ||
9509             urec_size % sizeof(u32)) {
9510                 verbose(env, "invalid func info rec size %u\n", urec_size);
9511                 return -EINVAL;
9512         }
9513
9514         prog = env->prog;
9515         btf = prog->aux->btf;
9516
9517         urecord = u64_to_user_ptr(attr->func_info);
9518         min_size = min_t(u32, krec_size, urec_size);
9519
9520         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9521         if (!krecord)
9522                 return -ENOMEM;
9523         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9524         if (!info_aux)
9525                 goto err_free;
9526
9527         for (i = 0; i < nfuncs; i++) {
9528                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9529                 if (ret) {
9530                         if (ret == -E2BIG) {
9531                                 verbose(env, "nonzero tailing record in func info");
9532                                 /* set the size kernel expects so loader can zero
9533                                  * out the rest of the record.
9534                                  */
9535                                 if (put_user(min_size, &uattr->func_info_rec_size))
9536                                         ret = -EFAULT;
9537                         }
9538                         goto err_free;
9539                 }
9540
9541                 if (copy_from_user(&krecord[i], urecord, min_size)) {
9542                         ret = -EFAULT;
9543                         goto err_free;
9544                 }
9545
9546                 /* check insn_off */
9547                 ret = -EINVAL;
9548                 if (i == 0) {
9549                         if (krecord[i].insn_off) {
9550                                 verbose(env,
9551                                         "nonzero insn_off %u for the first func info record",
9552                                         krecord[i].insn_off);
9553                                 goto err_free;
9554                         }
9555                 } else if (krecord[i].insn_off <= prev_offset) {
9556                         verbose(env,
9557                                 "same or smaller insn offset (%u) than previous func info record (%u)",
9558                                 krecord[i].insn_off, prev_offset);
9559                         goto err_free;
9560                 }
9561
9562                 if (env->subprog_info[i].start != krecord[i].insn_off) {
9563                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9564                         goto err_free;
9565                 }
9566
9567                 /* check type_id */
9568                 type = btf_type_by_id(btf, krecord[i].type_id);
9569                 if (!type || !btf_type_is_func(type)) {
9570                         verbose(env, "invalid type id %d in func info",
9571                                 krecord[i].type_id);
9572                         goto err_free;
9573                 }
9574                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9575
9576                 func_proto = btf_type_by_id(btf, type->type);
9577                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9578                         /* btf_func_check() already verified it during BTF load */
9579                         goto err_free;
9580                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9581                 scalar_return =
9582                         btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9583                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9584                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9585                         goto err_free;
9586                 }
9587                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9588                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9589                         goto err_free;
9590                 }
9591
9592                 prev_offset = krecord[i].insn_off;
9593                 urecord += urec_size;
9594         }
9595
9596         prog->aux->func_info = krecord;
9597         prog->aux->func_info_cnt = nfuncs;
9598         prog->aux->func_info_aux = info_aux;
9599         return 0;
9600
9601 err_free:
9602         kvfree(krecord);
9603         kfree(info_aux);
9604         return ret;
9605 }
9606
9607 static void adjust_btf_func(struct bpf_verifier_env *env)
9608 {
9609         struct bpf_prog_aux *aux = env->prog->aux;
9610         int i;
9611
9612         if (!aux->func_info)
9613                 return;
9614
9615         for (i = 0; i < env->subprog_cnt; i++)
9616                 aux->func_info[i].insn_off = env->subprog_info[i].start;
9617 }
9618
9619 #define MIN_BPF_LINEINFO_SIZE   (offsetof(struct bpf_line_info, line_col) + \
9620                 sizeof(((struct bpf_line_info *)(0))->line_col))
9621 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
9622
9623 static int check_btf_line(struct bpf_verifier_env *env,
9624                           const union bpf_attr *attr,
9625                           union bpf_attr __user *uattr)
9626 {
9627         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9628         struct bpf_subprog_info *sub;
9629         struct bpf_line_info *linfo;
9630         struct bpf_prog *prog;
9631         const struct btf *btf;
9632         void __user *ulinfo;
9633         int err;
9634
9635         nr_linfo = attr->line_info_cnt;
9636         if (!nr_linfo)
9637                 return 0;
9638
9639         rec_size = attr->line_info_rec_size;
9640         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9641             rec_size > MAX_LINEINFO_REC_SIZE ||
9642             rec_size & (sizeof(u32) - 1))
9643                 return -EINVAL;
9644
9645         /* Need to zero it in case the userspace may
9646          * pass in a smaller bpf_line_info object.
9647          */
9648         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9649                          GFP_KERNEL | __GFP_NOWARN);
9650         if (!linfo)
9651                 return -ENOMEM;
9652
9653         prog = env->prog;
9654         btf = prog->aux->btf;
9655
9656         s = 0;
9657         sub = env->subprog_info;
9658         ulinfo = u64_to_user_ptr(attr->line_info);
9659         expected_size = sizeof(struct bpf_line_info);
9660         ncopy = min_t(u32, expected_size, rec_size);
9661         for (i = 0; i < nr_linfo; i++) {
9662                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9663                 if (err) {
9664                         if (err == -E2BIG) {
9665                                 verbose(env, "nonzero tailing record in line_info");
9666                                 if (put_user(expected_size,
9667                                              &uattr->line_info_rec_size))
9668                                         err = -EFAULT;
9669                         }
9670                         goto err_free;
9671                 }
9672
9673                 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9674                         err = -EFAULT;
9675                         goto err_free;
9676                 }
9677
9678                 /*
9679                  * Check insn_off to ensure
9680                  * 1) strictly increasing AND
9681                  * 2) bounded by prog->len
9682                  *
9683                  * The linfo[0].insn_off == 0 check logically falls into
9684                  * the later "missing bpf_line_info for func..." case
9685                  * because the first linfo[0].insn_off must be the
9686                  * first sub also and the first sub must have
9687                  * subprog_info[0].start == 0.
9688                  */
9689                 if ((i && linfo[i].insn_off <= prev_offset) ||
9690                     linfo[i].insn_off >= prog->len) {
9691                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9692                                 i, linfo[i].insn_off, prev_offset,
9693                                 prog->len);
9694                         err = -EINVAL;
9695                         goto err_free;
9696                 }
9697
9698                 if (!prog->insnsi[linfo[i].insn_off].code) {
9699                         verbose(env,
9700                                 "Invalid insn code at line_info[%u].insn_off\n",
9701                                 i);
9702                         err = -EINVAL;
9703                         goto err_free;
9704                 }
9705
9706                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9707                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9708                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9709                         err = -EINVAL;
9710                         goto err_free;
9711                 }
9712
9713                 if (s != env->subprog_cnt) {
9714                         if (linfo[i].insn_off == sub[s].start) {
9715                                 sub[s].linfo_idx = i;
9716                                 s++;
9717                         } else if (sub[s].start < linfo[i].insn_off) {
9718                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
9719                                 err = -EINVAL;
9720                                 goto err_free;
9721                         }
9722                 }
9723
9724                 prev_offset = linfo[i].insn_off;
9725                 ulinfo += rec_size;
9726         }
9727
9728         if (s != env->subprog_cnt) {
9729                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9730                         env->subprog_cnt - s, s);
9731                 err = -EINVAL;
9732                 goto err_free;
9733         }
9734
9735         prog->aux->linfo = linfo;
9736         prog->aux->nr_linfo = nr_linfo;
9737
9738         return 0;
9739
9740 err_free:
9741         kvfree(linfo);
9742         return err;
9743 }
9744
9745 static int check_btf_info(struct bpf_verifier_env *env,
9746                           const union bpf_attr *attr,
9747                           union bpf_attr __user *uattr)
9748 {
9749         struct btf *btf;
9750         int err;
9751
9752         if (!attr->func_info_cnt && !attr->line_info_cnt) {
9753                 if (check_abnormal_return(env))
9754                         return -EINVAL;
9755                 return 0;
9756         }
9757
9758         btf = btf_get_by_fd(attr->prog_btf_fd);
9759         if (IS_ERR(btf))
9760                 return PTR_ERR(btf);
9761         if (btf_is_kernel(btf)) {
9762                 btf_put(btf);
9763                 return -EACCES;
9764         }
9765         env->prog->aux->btf = btf;
9766
9767         err = check_btf_func(env, attr, uattr);
9768         if (err)
9769                 return err;
9770
9771         err = check_btf_line(env, attr, uattr);
9772         if (err)
9773                 return err;
9774
9775         return 0;
9776 }
9777
9778 /* check %cur's range satisfies %old's */
9779 static bool range_within(struct bpf_reg_state *old,
9780                          struct bpf_reg_state *cur)
9781 {
9782         return old->umin_value <= cur->umin_value &&
9783                old->umax_value >= cur->umax_value &&
9784                old->smin_value <= cur->smin_value &&
9785                old->smax_value >= cur->smax_value &&
9786                old->u32_min_value <= cur->u32_min_value &&
9787                old->u32_max_value >= cur->u32_max_value &&
9788                old->s32_min_value <= cur->s32_min_value &&
9789                old->s32_max_value >= cur->s32_max_value;
9790 }
9791
9792 /* If in the old state two registers had the same id, then they need to have
9793  * the same id in the new state as well.  But that id could be different from
9794  * the old state, so we need to track the mapping from old to new ids.
9795  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9796  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9797  * regs with a different old id could still have new id 9, we don't care about
9798  * that.
9799  * So we look through our idmap to see if this old id has been seen before.  If
9800  * so, we require the new id to match; otherwise, we add the id pair to the map.
9801  */
9802 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
9803 {
9804         unsigned int i;
9805
9806         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
9807                 if (!idmap[i].old) {
9808                         /* Reached an empty slot; haven't seen this id before */
9809                         idmap[i].old = old_id;
9810                         idmap[i].cur = cur_id;
9811                         return true;
9812                 }
9813                 if (idmap[i].old == old_id)
9814                         return idmap[i].cur == cur_id;
9815         }
9816         /* We ran out of idmap slots, which should be impossible */
9817         WARN_ON_ONCE(1);
9818         return false;
9819 }
9820
9821 static void clean_func_state(struct bpf_verifier_env *env,
9822                              struct bpf_func_state *st)
9823 {
9824         enum bpf_reg_liveness live;
9825         int i, j;
9826
9827         for (i = 0; i < BPF_REG_FP; i++) {
9828                 live = st->regs[i].live;
9829                 /* liveness must not touch this register anymore */
9830                 st->regs[i].live |= REG_LIVE_DONE;
9831                 if (!(live & REG_LIVE_READ))
9832                         /* since the register is unused, clear its state
9833                          * to make further comparison simpler
9834                          */
9835                         __mark_reg_not_init(env, &st->regs[i]);
9836         }
9837
9838         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9839                 live = st->stack[i].spilled_ptr.live;
9840                 /* liveness must not touch this stack slot anymore */
9841                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9842                 if (!(live & REG_LIVE_READ)) {
9843                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9844                         for (j = 0; j < BPF_REG_SIZE; j++)
9845                                 st->stack[i].slot_type[j] = STACK_INVALID;
9846                 }
9847         }
9848 }
9849
9850 static void clean_verifier_state(struct bpf_verifier_env *env,
9851                                  struct bpf_verifier_state *st)
9852 {
9853         int i;
9854
9855         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9856                 /* all regs in this state in all frames were already marked */
9857                 return;
9858
9859         for (i = 0; i <= st->curframe; i++)
9860                 clean_func_state(env, st->frame[i]);
9861 }
9862
9863 /* the parentage chains form a tree.
9864  * the verifier states are added to state lists at given insn and
9865  * pushed into state stack for future exploration.
9866  * when the verifier reaches bpf_exit insn some of the verifer states
9867  * stored in the state lists have their final liveness state already,
9868  * but a lot of states will get revised from liveness point of view when
9869  * the verifier explores other branches.
9870  * Example:
9871  * 1: r0 = 1
9872  * 2: if r1 == 100 goto pc+1
9873  * 3: r0 = 2
9874  * 4: exit
9875  * when the verifier reaches exit insn the register r0 in the state list of
9876  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9877  * of insn 2 and goes exploring further. At the insn 4 it will walk the
9878  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9879  *
9880  * Since the verifier pushes the branch states as it sees them while exploring
9881  * the program the condition of walking the branch instruction for the second
9882  * time means that all states below this branch were already explored and
9883  * their final liveness markes are already propagated.
9884  * Hence when the verifier completes the search of state list in is_state_visited()
9885  * we can call this clean_live_states() function to mark all liveness states
9886  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9887  * will not be used.
9888  * This function also clears the registers and stack for states that !READ
9889  * to simplify state merging.
9890  *
9891  * Important note here that walking the same branch instruction in the callee
9892  * doesn't meant that the states are DONE. The verifier has to compare
9893  * the callsites
9894  */
9895 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9896                               struct bpf_verifier_state *cur)
9897 {
9898         struct bpf_verifier_state_list *sl;
9899         int i;
9900
9901         sl = *explored_state(env, insn);
9902         while (sl) {
9903                 if (sl->state.branches)
9904                         goto next;
9905                 if (sl->state.insn_idx != insn ||
9906                     sl->state.curframe != cur->curframe)
9907                         goto next;
9908                 for (i = 0; i <= cur->curframe; i++)
9909                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9910                                 goto next;
9911                 clean_verifier_state(env, &sl->state);
9912 next:
9913                 sl = sl->next;
9914         }
9915 }
9916
9917 /* Returns true if (rold safe implies rcur safe) */
9918 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9919                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
9920 {
9921         bool equal;
9922
9923         if (!(rold->live & REG_LIVE_READ))
9924                 /* explored state didn't use this */
9925                 return true;
9926
9927         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9928
9929         if (rold->type == PTR_TO_STACK)
9930                 /* two stack pointers are equal only if they're pointing to
9931                  * the same stack frame, since fp-8 in foo != fp-8 in bar
9932                  */
9933                 return equal && rold->frameno == rcur->frameno;
9934
9935         if (equal)
9936                 return true;
9937
9938         if (rold->type == NOT_INIT)
9939                 /* explored state can't have used this */
9940                 return true;
9941         if (rcur->type == NOT_INIT)
9942                 return false;
9943         switch (rold->type) {
9944         case SCALAR_VALUE:
9945                 if (env->explore_alu_limits)
9946                         return false;
9947                 if (rcur->type == SCALAR_VALUE) {
9948                         if (!rold->precise && !rcur->precise)
9949                                 return true;
9950                         /* new val must satisfy old val knowledge */
9951                         return range_within(rold, rcur) &&
9952                                tnum_in(rold->var_off, rcur->var_off);
9953                 } else {
9954                         /* We're trying to use a pointer in place of a scalar.
9955                          * Even if the scalar was unbounded, this could lead to
9956                          * pointer leaks because scalars are allowed to leak
9957                          * while pointers are not. We could make this safe in
9958                          * special cases if root is calling us, but it's
9959                          * probably not worth the hassle.
9960                          */
9961                         return false;
9962                 }
9963         case PTR_TO_MAP_KEY:
9964         case PTR_TO_MAP_VALUE:
9965                 /* If the new min/max/var_off satisfy the old ones and
9966                  * everything else matches, we are OK.
9967                  * 'id' is not compared, since it's only used for maps with
9968                  * bpf_spin_lock inside map element and in such cases if
9969                  * the rest of the prog is valid for one map element then
9970                  * it's valid for all map elements regardless of the key
9971                  * used in bpf_map_lookup()
9972                  */
9973                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9974                        range_within(rold, rcur) &&
9975                        tnum_in(rold->var_off, rcur->var_off);
9976         case PTR_TO_MAP_VALUE_OR_NULL:
9977                 /* a PTR_TO_MAP_VALUE could be safe to use as a
9978                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9979                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9980                  * checked, doing so could have affected others with the same
9981                  * id, and we can't check for that because we lost the id when
9982                  * we converted to a PTR_TO_MAP_VALUE.
9983                  */
9984                 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9985                         return false;
9986                 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9987                         return false;
9988                 /* Check our ids match any regs they're supposed to */
9989                 return check_ids(rold->id, rcur->id, idmap);
9990         case PTR_TO_PACKET_META:
9991         case PTR_TO_PACKET:
9992                 if (rcur->type != rold->type)
9993                         return false;
9994                 /* We must have at least as much range as the old ptr
9995                  * did, so that any accesses which were safe before are
9996                  * still safe.  This is true even if old range < old off,
9997                  * since someone could have accessed through (ptr - k), or
9998                  * even done ptr -= k in a register, to get a safe access.
9999                  */
10000                 if (rold->range > rcur->range)
10001                         return false;
10002                 /* If the offsets don't match, we can't trust our alignment;
10003                  * nor can we be sure that we won't fall out of range.
10004                  */
10005                 if (rold->off != rcur->off)
10006                         return false;
10007                 /* id relations must be preserved */
10008                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10009                         return false;
10010                 /* new val must satisfy old val knowledge */
10011                 return range_within(rold, rcur) &&
10012                        tnum_in(rold->var_off, rcur->var_off);
10013         case PTR_TO_CTX:
10014         case CONST_PTR_TO_MAP:
10015         case PTR_TO_PACKET_END:
10016         case PTR_TO_FLOW_KEYS:
10017         case PTR_TO_SOCKET:
10018         case PTR_TO_SOCKET_OR_NULL:
10019         case PTR_TO_SOCK_COMMON:
10020         case PTR_TO_SOCK_COMMON_OR_NULL:
10021         case PTR_TO_TCP_SOCK:
10022         case PTR_TO_TCP_SOCK_OR_NULL:
10023         case PTR_TO_XDP_SOCK:
10024                 /* Only valid matches are exact, which memcmp() above
10025                  * would have accepted
10026                  */
10027         default:
10028                 /* Don't know what's going on, just say it's not safe */
10029                 return false;
10030         }
10031
10032         /* Shouldn't get here; if we do, say it's not safe */
10033         WARN_ON_ONCE(1);
10034         return false;
10035 }
10036
10037 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10038                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10039 {
10040         int i, spi;
10041
10042         /* walk slots of the explored stack and ignore any additional
10043          * slots in the current stack, since explored(safe) state
10044          * didn't use them
10045          */
10046         for (i = 0; i < old->allocated_stack; i++) {
10047                 spi = i / BPF_REG_SIZE;
10048
10049                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10050                         i += BPF_REG_SIZE - 1;
10051                         /* explored state didn't use this */
10052                         continue;
10053                 }
10054
10055                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10056                         continue;
10057
10058                 /* explored stack has more populated slots than current stack
10059                  * and these slots were used
10060                  */
10061                 if (i >= cur->allocated_stack)
10062                         return false;
10063
10064                 /* if old state was safe with misc data in the stack
10065                  * it will be safe with zero-initialized stack.
10066                  * The opposite is not true
10067                  */
10068                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10069                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10070                         continue;
10071                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10072                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10073                         /* Ex: old explored (safe) state has STACK_SPILL in
10074                          * this stack slot, but current has STACK_MISC ->
10075                          * this verifier states are not equivalent,
10076                          * return false to continue verification of this path
10077                          */
10078                         return false;
10079                 if (i % BPF_REG_SIZE)
10080                         continue;
10081                 if (old->stack[spi].slot_type[0] != STACK_SPILL)
10082                         continue;
10083                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
10084                              &cur->stack[spi].spilled_ptr, idmap))
10085                         /* when explored and current stack slot are both storing
10086                          * spilled registers, check that stored pointers types
10087                          * are the same as well.
10088                          * Ex: explored safe path could have stored
10089                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10090                          * but current path has stored:
10091                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10092                          * such verifier states are not equivalent.
10093                          * return false to continue verification of this path
10094                          */
10095                         return false;
10096         }
10097         return true;
10098 }
10099
10100 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10101 {
10102         if (old->acquired_refs != cur->acquired_refs)
10103                 return false;
10104         return !memcmp(old->refs, cur->refs,
10105                        sizeof(*old->refs) * old->acquired_refs);
10106 }
10107
10108 /* compare two verifier states
10109  *
10110  * all states stored in state_list are known to be valid, since
10111  * verifier reached 'bpf_exit' instruction through them
10112  *
10113  * this function is called when verifier exploring different branches of
10114  * execution popped from the state stack. If it sees an old state that has
10115  * more strict register state and more strict stack state then this execution
10116  * branch doesn't need to be explored further, since verifier already
10117  * concluded that more strict state leads to valid finish.
10118  *
10119  * Therefore two states are equivalent if register state is more conservative
10120  * and explored stack state is more conservative than the current one.
10121  * Example:
10122  *       explored                   current
10123  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10124  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10125  *
10126  * In other words if current stack state (one being explored) has more
10127  * valid slots than old one that already passed validation, it means
10128  * the verifier can stop exploring and conclude that current state is valid too
10129  *
10130  * Similarly with registers. If explored state has register type as invalid
10131  * whereas register type in current state is meaningful, it means that
10132  * the current state will reach 'bpf_exit' instruction safely
10133  */
10134 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10135                               struct bpf_func_state *cur)
10136 {
10137         int i;
10138
10139         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10140         for (i = 0; i < MAX_BPF_REG; i++)
10141                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
10142                              env->idmap_scratch))
10143                         return false;
10144
10145         if (!stacksafe(env, old, cur, env->idmap_scratch))
10146                 return false;
10147
10148         if (!refsafe(old, cur))
10149                 return false;
10150
10151         return true;
10152 }
10153
10154 static bool states_equal(struct bpf_verifier_env *env,
10155                          struct bpf_verifier_state *old,
10156                          struct bpf_verifier_state *cur)
10157 {
10158         int i;
10159
10160         if (old->curframe != cur->curframe)
10161                 return false;
10162
10163         /* Verification state from speculative execution simulation
10164          * must never prune a non-speculative execution one.
10165          */
10166         if (old->speculative && !cur->speculative)
10167                 return false;
10168
10169         if (old->active_spin_lock != cur->active_spin_lock)
10170                 return false;
10171
10172         /* for states to be equal callsites have to be the same
10173          * and all frame states need to be equivalent
10174          */
10175         for (i = 0; i <= old->curframe; i++) {
10176                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10177                         return false;
10178                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10179                         return false;
10180         }
10181         return true;
10182 }
10183
10184 /* Return 0 if no propagation happened. Return negative error code if error
10185  * happened. Otherwise, return the propagated bit.
10186  */
10187 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10188                                   struct bpf_reg_state *reg,
10189                                   struct bpf_reg_state *parent_reg)
10190 {
10191         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10192         u8 flag = reg->live & REG_LIVE_READ;
10193         int err;
10194
10195         /* When comes here, read flags of PARENT_REG or REG could be any of
10196          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10197          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10198          */
10199         if (parent_flag == REG_LIVE_READ64 ||
10200             /* Or if there is no read flag from REG. */
10201             !flag ||
10202             /* Or if the read flag from REG is the same as PARENT_REG. */
10203             parent_flag == flag)
10204                 return 0;
10205
10206         err = mark_reg_read(env, reg, parent_reg, flag);
10207         if (err)
10208                 return err;
10209
10210         return flag;
10211 }
10212
10213 /* A write screens off any subsequent reads; but write marks come from the
10214  * straight-line code between a state and its parent.  When we arrive at an
10215  * equivalent state (jump target or such) we didn't arrive by the straight-line
10216  * code, so read marks in the state must propagate to the parent regardless
10217  * of the state's write marks. That's what 'parent == state->parent' comparison
10218  * in mark_reg_read() is for.
10219  */
10220 static int propagate_liveness(struct bpf_verifier_env *env,
10221                               const struct bpf_verifier_state *vstate,
10222                               struct bpf_verifier_state *vparent)
10223 {
10224         struct bpf_reg_state *state_reg, *parent_reg;
10225         struct bpf_func_state *state, *parent;
10226         int i, frame, err = 0;
10227
10228         if (vparent->curframe != vstate->curframe) {
10229                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10230                      vparent->curframe, vstate->curframe);
10231                 return -EFAULT;
10232         }
10233         /* Propagate read liveness of registers... */
10234         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10235         for (frame = 0; frame <= vstate->curframe; frame++) {
10236                 parent = vparent->frame[frame];
10237                 state = vstate->frame[frame];
10238                 parent_reg = parent->regs;
10239                 state_reg = state->regs;
10240                 /* We don't need to worry about FP liveness, it's read-only */
10241                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10242                         err = propagate_liveness_reg(env, &state_reg[i],
10243                                                      &parent_reg[i]);
10244                         if (err < 0)
10245                                 return err;
10246                         if (err == REG_LIVE_READ64)
10247                                 mark_insn_zext(env, &parent_reg[i]);
10248                 }
10249
10250                 /* Propagate stack slots. */
10251                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10252                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10253                         parent_reg = &parent->stack[i].spilled_ptr;
10254                         state_reg = &state->stack[i].spilled_ptr;
10255                         err = propagate_liveness_reg(env, state_reg,
10256                                                      parent_reg);
10257                         if (err < 0)
10258                                 return err;
10259                 }
10260         }
10261         return 0;
10262 }
10263
10264 /* find precise scalars in the previous equivalent state and
10265  * propagate them into the current state
10266  */
10267 static int propagate_precision(struct bpf_verifier_env *env,
10268                                const struct bpf_verifier_state *old)
10269 {
10270         struct bpf_reg_state *state_reg;
10271         struct bpf_func_state *state;
10272         int i, err = 0;
10273
10274         state = old->frame[old->curframe];
10275         state_reg = state->regs;
10276         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10277                 if (state_reg->type != SCALAR_VALUE ||
10278                     !state_reg->precise)
10279                         continue;
10280                 if (env->log.level & BPF_LOG_LEVEL2)
10281                         verbose(env, "propagating r%d\n", i);
10282                 err = mark_chain_precision(env, i);
10283                 if (err < 0)
10284                         return err;
10285         }
10286
10287         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10288                 if (state->stack[i].slot_type[0] != STACK_SPILL)
10289                         continue;
10290                 state_reg = &state->stack[i].spilled_ptr;
10291                 if (state_reg->type != SCALAR_VALUE ||
10292                     !state_reg->precise)
10293                         continue;
10294                 if (env->log.level & BPF_LOG_LEVEL2)
10295                         verbose(env, "propagating fp%d\n",
10296                                 (-i - 1) * BPF_REG_SIZE);
10297                 err = mark_chain_precision_stack(env, i);
10298                 if (err < 0)
10299                         return err;
10300         }
10301         return 0;
10302 }
10303
10304 static bool states_maybe_looping(struct bpf_verifier_state *old,
10305                                  struct bpf_verifier_state *cur)
10306 {
10307         struct bpf_func_state *fold, *fcur;
10308         int i, fr = cur->curframe;
10309
10310         if (old->curframe != fr)
10311                 return false;
10312
10313         fold = old->frame[fr];
10314         fcur = cur->frame[fr];
10315         for (i = 0; i < MAX_BPF_REG; i++)
10316                 if (memcmp(&fold->regs[i], &fcur->regs[i],
10317                            offsetof(struct bpf_reg_state, parent)))
10318                         return false;
10319         return true;
10320 }
10321
10322
10323 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10324 {
10325         struct bpf_verifier_state_list *new_sl;
10326         struct bpf_verifier_state_list *sl, **pprev;
10327         struct bpf_verifier_state *cur = env->cur_state, *new;
10328         int i, j, err, states_cnt = 0;
10329         bool add_new_state = env->test_state_freq ? true : false;
10330
10331         cur->last_insn_idx = env->prev_insn_idx;
10332         if (!env->insn_aux_data[insn_idx].prune_point)
10333                 /* this 'insn_idx' instruction wasn't marked, so we will not
10334                  * be doing state search here
10335                  */
10336                 return 0;
10337
10338         /* bpf progs typically have pruning point every 4 instructions
10339          * http://vger.kernel.org/bpfconf2019.html#session-1
10340          * Do not add new state for future pruning if the verifier hasn't seen
10341          * at least 2 jumps and at least 8 instructions.
10342          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10343          * In tests that amounts to up to 50% reduction into total verifier
10344          * memory consumption and 20% verifier time speedup.
10345          */
10346         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10347             env->insn_processed - env->prev_insn_processed >= 8)
10348                 add_new_state = true;
10349
10350         pprev = explored_state(env, insn_idx);
10351         sl = *pprev;
10352
10353         clean_live_states(env, insn_idx, cur);
10354
10355         while (sl) {
10356                 states_cnt++;
10357                 if (sl->state.insn_idx != insn_idx)
10358                         goto next;
10359                 if (sl->state.branches) {
10360                         if (states_maybe_looping(&sl->state, cur) &&
10361                             states_equal(env, &sl->state, cur)) {
10362                                 verbose_linfo(env, insn_idx, "; ");
10363                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10364                                 return -EINVAL;
10365                         }
10366                         /* if the verifier is processing a loop, avoid adding new state
10367                          * too often, since different loop iterations have distinct
10368                          * states and may not help future pruning.
10369                          * This threshold shouldn't be too low to make sure that
10370                          * a loop with large bound will be rejected quickly.
10371                          * The most abusive loop will be:
10372                          * r1 += 1
10373                          * if r1 < 1000000 goto pc-2
10374                          * 1M insn_procssed limit / 100 == 10k peak states.
10375                          * This threshold shouldn't be too high either, since states
10376                          * at the end of the loop are likely to be useful in pruning.
10377                          */
10378                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10379                             env->insn_processed - env->prev_insn_processed < 100)
10380                                 add_new_state = false;
10381                         goto miss;
10382                 }
10383                 if (states_equal(env, &sl->state, cur)) {
10384                         sl->hit_cnt++;
10385                         /* reached equivalent register/stack state,
10386                          * prune the search.
10387                          * Registers read by the continuation are read by us.
10388                          * If we have any write marks in env->cur_state, they
10389                          * will prevent corresponding reads in the continuation
10390                          * from reaching our parent (an explored_state).  Our
10391                          * own state will get the read marks recorded, but
10392                          * they'll be immediately forgotten as we're pruning
10393                          * this state and will pop a new one.
10394                          */
10395                         err = propagate_liveness(env, &sl->state, cur);
10396
10397                         /* if previous state reached the exit with precision and
10398                          * current state is equivalent to it (except precsion marks)
10399                          * the precision needs to be propagated back in
10400                          * the current state.
10401                          */
10402                         err = err ? : push_jmp_history(env, cur);
10403                         err = err ? : propagate_precision(env, &sl->state);
10404                         if (err)
10405                                 return err;
10406                         return 1;
10407                 }
10408 miss:
10409                 /* when new state is not going to be added do not increase miss count.
10410                  * Otherwise several loop iterations will remove the state
10411                  * recorded earlier. The goal of these heuristics is to have
10412                  * states from some iterations of the loop (some in the beginning
10413                  * and some at the end) to help pruning.
10414                  */
10415                 if (add_new_state)
10416                         sl->miss_cnt++;
10417                 /* heuristic to determine whether this state is beneficial
10418                  * to keep checking from state equivalence point of view.
10419                  * Higher numbers increase max_states_per_insn and verification time,
10420                  * but do not meaningfully decrease insn_processed.
10421                  */
10422                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10423                         /* the state is unlikely to be useful. Remove it to
10424                          * speed up verification
10425                          */
10426                         *pprev = sl->next;
10427                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10428                                 u32 br = sl->state.branches;
10429
10430                                 WARN_ONCE(br,
10431                                           "BUG live_done but branches_to_explore %d\n",
10432                                           br);
10433                                 free_verifier_state(&sl->state, false);
10434                                 kfree(sl);
10435                                 env->peak_states--;
10436                         } else {
10437                                 /* cannot free this state, since parentage chain may
10438                                  * walk it later. Add it for free_list instead to
10439                                  * be freed at the end of verification
10440                                  */
10441                                 sl->next = env->free_list;
10442                                 env->free_list = sl;
10443                         }
10444                         sl = *pprev;
10445                         continue;
10446                 }
10447 next:
10448                 pprev = &sl->next;
10449                 sl = *pprev;
10450         }
10451
10452         if (env->max_states_per_insn < states_cnt)
10453                 env->max_states_per_insn = states_cnt;
10454
10455         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10456                 return push_jmp_history(env, cur);
10457
10458         if (!add_new_state)
10459                 return push_jmp_history(env, cur);
10460
10461         /* There were no equivalent states, remember the current one.
10462          * Technically the current state is not proven to be safe yet,
10463          * but it will either reach outer most bpf_exit (which means it's safe)
10464          * or it will be rejected. When there are no loops the verifier won't be
10465          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
10466          * again on the way to bpf_exit.
10467          * When looping the sl->state.branches will be > 0 and this state
10468          * will not be considered for equivalence until branches == 0.
10469          */
10470         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10471         if (!new_sl)
10472                 return -ENOMEM;
10473         env->total_states++;
10474         env->peak_states++;
10475         env->prev_jmps_processed = env->jmps_processed;
10476         env->prev_insn_processed = env->insn_processed;
10477
10478         /* add new state to the head of linked list */
10479         new = &new_sl->state;
10480         err = copy_verifier_state(new, cur);
10481         if (err) {
10482                 free_verifier_state(new, false);
10483                 kfree(new_sl);
10484                 return err;
10485         }
10486         new->insn_idx = insn_idx;
10487         WARN_ONCE(new->branches != 1,
10488                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10489
10490         cur->parent = new;
10491         cur->first_insn_idx = insn_idx;
10492         clear_jmp_history(cur);
10493         new_sl->next = *explored_state(env, insn_idx);
10494         *explored_state(env, insn_idx) = new_sl;
10495         /* connect new state to parentage chain. Current frame needs all
10496          * registers connected. Only r6 - r9 of the callers are alive (pushed
10497          * to the stack implicitly by JITs) so in callers' frames connect just
10498          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10499          * the state of the call instruction (with WRITTEN set), and r0 comes
10500          * from callee with its full parentage chain, anyway.
10501          */
10502         /* clear write marks in current state: the writes we did are not writes
10503          * our child did, so they don't screen off its reads from us.
10504          * (There are no read marks in current state, because reads always mark
10505          * their parent and current state never has children yet.  Only
10506          * explored_states can get read marks.)
10507          */
10508         for (j = 0; j <= cur->curframe; j++) {
10509                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10510                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10511                 for (i = 0; i < BPF_REG_FP; i++)
10512                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10513         }
10514
10515         /* all stack frames are accessible from callee, clear them all */
10516         for (j = 0; j <= cur->curframe; j++) {
10517                 struct bpf_func_state *frame = cur->frame[j];
10518                 struct bpf_func_state *newframe = new->frame[j];
10519
10520                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10521                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10522                         frame->stack[i].spilled_ptr.parent =
10523                                                 &newframe->stack[i].spilled_ptr;
10524                 }
10525         }
10526         return 0;
10527 }
10528
10529 /* Return true if it's OK to have the same insn return a different type. */
10530 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10531 {
10532         switch (type) {
10533         case PTR_TO_CTX:
10534         case PTR_TO_SOCKET:
10535         case PTR_TO_SOCKET_OR_NULL:
10536         case PTR_TO_SOCK_COMMON:
10537         case PTR_TO_SOCK_COMMON_OR_NULL:
10538         case PTR_TO_TCP_SOCK:
10539         case PTR_TO_TCP_SOCK_OR_NULL:
10540         case PTR_TO_XDP_SOCK:
10541         case PTR_TO_BTF_ID:
10542         case PTR_TO_BTF_ID_OR_NULL:
10543                 return false;
10544         default:
10545                 return true;
10546         }
10547 }
10548
10549 /* If an instruction was previously used with particular pointer types, then we
10550  * need to be careful to avoid cases such as the below, where it may be ok
10551  * for one branch accessing the pointer, but not ok for the other branch:
10552  *
10553  * R1 = sock_ptr
10554  * goto X;
10555  * ...
10556  * R1 = some_other_valid_ptr;
10557  * goto X;
10558  * ...
10559  * R2 = *(u32 *)(R1 + 0);
10560  */
10561 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10562 {
10563         return src != prev && (!reg_type_mismatch_ok(src) ||
10564                                !reg_type_mismatch_ok(prev));
10565 }
10566
10567 static int do_check(struct bpf_verifier_env *env)
10568 {
10569         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10570         struct bpf_verifier_state *state = env->cur_state;
10571         struct bpf_insn *insns = env->prog->insnsi;
10572         struct bpf_reg_state *regs;
10573         int insn_cnt = env->prog->len;
10574         bool do_print_state = false;
10575         int prev_insn_idx = -1;
10576
10577         for (;;) {
10578                 struct bpf_insn *insn;
10579                 u8 class;
10580                 int err;
10581
10582                 env->prev_insn_idx = prev_insn_idx;
10583                 if (env->insn_idx >= insn_cnt) {
10584                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
10585                                 env->insn_idx, insn_cnt);
10586                         return -EFAULT;
10587                 }
10588
10589                 insn = &insns[env->insn_idx];
10590                 class = BPF_CLASS(insn->code);
10591
10592                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10593                         verbose(env,
10594                                 "BPF program is too large. Processed %d insn\n",
10595                                 env->insn_processed);
10596                         return -E2BIG;
10597                 }
10598
10599                 err = is_state_visited(env, env->insn_idx);
10600                 if (err < 0)
10601                         return err;
10602                 if (err == 1) {
10603                         /* found equivalent state, can prune the search */
10604                         if (env->log.level & BPF_LOG_LEVEL) {
10605                                 if (do_print_state)
10606                                         verbose(env, "\nfrom %d to %d%s: safe\n",
10607                                                 env->prev_insn_idx, env->insn_idx,
10608                                                 env->cur_state->speculative ?
10609                                                 " (speculative execution)" : "");
10610                                 else
10611                                         verbose(env, "%d: safe\n", env->insn_idx);
10612                         }
10613                         goto process_bpf_exit;
10614                 }
10615
10616                 if (signal_pending(current))
10617                         return -EAGAIN;
10618
10619                 if (need_resched())
10620                         cond_resched();
10621
10622                 if (env->log.level & BPF_LOG_LEVEL2 ||
10623                     (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10624                         if (env->log.level & BPF_LOG_LEVEL2)
10625                                 verbose(env, "%d:", env->insn_idx);
10626                         else
10627                                 verbose(env, "\nfrom %d to %d%s:",
10628                                         env->prev_insn_idx, env->insn_idx,
10629                                         env->cur_state->speculative ?
10630                                         " (speculative execution)" : "");
10631                         print_verifier_state(env, state->frame[state->curframe]);
10632                         do_print_state = false;
10633                 }
10634
10635                 if (env->log.level & BPF_LOG_LEVEL) {
10636                         const struct bpf_insn_cbs cbs = {
10637                                 .cb_call        = disasm_kfunc_name,
10638                                 .cb_print       = verbose,
10639                                 .private_data   = env,
10640                         };
10641
10642                         verbose_linfo(env, env->insn_idx, "; ");
10643                         verbose(env, "%d: ", env->insn_idx);
10644                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10645                 }
10646
10647                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10648                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10649                                                            env->prev_insn_idx);
10650                         if (err)
10651                                 return err;
10652                 }
10653
10654                 regs = cur_regs(env);
10655                 sanitize_mark_insn_seen(env);
10656                 prev_insn_idx = env->insn_idx;
10657
10658                 if (class == BPF_ALU || class == BPF_ALU64) {
10659                         err = check_alu_op(env, insn);
10660                         if (err)
10661                                 return err;
10662
10663                 } else if (class == BPF_LDX) {
10664                         enum bpf_reg_type *prev_src_type, src_reg_type;
10665
10666                         /* check for reserved fields is already done */
10667
10668                         /* check src operand */
10669                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10670                         if (err)
10671                                 return err;
10672
10673                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10674                         if (err)
10675                                 return err;
10676
10677                         src_reg_type = regs[insn->src_reg].type;
10678
10679                         /* check that memory (src_reg + off) is readable,
10680                          * the state of dst_reg will be updated by this func
10681                          */
10682                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
10683                                                insn->off, BPF_SIZE(insn->code),
10684                                                BPF_READ, insn->dst_reg, false);
10685                         if (err)
10686                                 return err;
10687
10688                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10689
10690                         if (*prev_src_type == NOT_INIT) {
10691                                 /* saw a valid insn
10692                                  * dst_reg = *(u32 *)(src_reg + off)
10693                                  * save type to validate intersecting paths
10694                                  */
10695                                 *prev_src_type = src_reg_type;
10696
10697                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10698                                 /* ABuser program is trying to use the same insn
10699                                  * dst_reg = *(u32*) (src_reg + off)
10700                                  * with different pointer types:
10701                                  * src_reg == ctx in one branch and
10702                                  * src_reg == stack|map in some other branch.
10703                                  * Reject it.
10704                                  */
10705                                 verbose(env, "same insn cannot be used with different pointers\n");
10706                                 return -EINVAL;
10707                         }
10708
10709                 } else if (class == BPF_STX) {
10710                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
10711
10712                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10713                                 err = check_atomic(env, env->insn_idx, insn);
10714                                 if (err)
10715                                         return err;
10716                                 env->insn_idx++;
10717                                 continue;
10718                         }
10719
10720                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10721                                 verbose(env, "BPF_STX uses reserved fields\n");
10722                                 return -EINVAL;
10723                         }
10724
10725                         /* check src1 operand */
10726                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10727                         if (err)
10728                                 return err;
10729                         /* check src2 operand */
10730                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10731                         if (err)
10732                                 return err;
10733
10734                         dst_reg_type = regs[insn->dst_reg].type;
10735
10736                         /* check that memory (dst_reg + off) is writeable */
10737                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10738                                                insn->off, BPF_SIZE(insn->code),
10739                                                BPF_WRITE, insn->src_reg, false);
10740                         if (err)
10741                                 return err;
10742
10743                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10744
10745                         if (*prev_dst_type == NOT_INIT) {
10746                                 *prev_dst_type = dst_reg_type;
10747                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10748                                 verbose(env, "same insn cannot be used with different pointers\n");
10749                                 return -EINVAL;
10750                         }
10751
10752                 } else if (class == BPF_ST) {
10753                         if (BPF_MODE(insn->code) != BPF_MEM ||
10754                             insn->src_reg != BPF_REG_0) {
10755                                 verbose(env, "BPF_ST uses reserved fields\n");
10756                                 return -EINVAL;
10757                         }
10758                         /* check src operand */
10759                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10760                         if (err)
10761                                 return err;
10762
10763                         if (is_ctx_reg(env, insn->dst_reg)) {
10764                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10765                                         insn->dst_reg,
10766                                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
10767                                 return -EACCES;
10768                         }
10769
10770                         /* check that memory (dst_reg + off) is writeable */
10771                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10772                                                insn->off, BPF_SIZE(insn->code),
10773                                                BPF_WRITE, -1, false);
10774                         if (err)
10775                                 return err;
10776
10777                 } else if (class == BPF_JMP || class == BPF_JMP32) {
10778                         u8 opcode = BPF_OP(insn->code);
10779
10780                         env->jmps_processed++;
10781                         if (opcode == BPF_CALL) {
10782                                 if (BPF_SRC(insn->code) != BPF_K ||
10783                                     insn->off != 0 ||
10784                                     (insn->src_reg != BPF_REG_0 &&
10785                                      insn->src_reg != BPF_PSEUDO_CALL &&
10786                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
10787                                     insn->dst_reg != BPF_REG_0 ||
10788                                     class == BPF_JMP32) {
10789                                         verbose(env, "BPF_CALL uses reserved fields\n");
10790                                         return -EINVAL;
10791                                 }
10792
10793                                 if (env->cur_state->active_spin_lock &&
10794                                     (insn->src_reg == BPF_PSEUDO_CALL ||
10795                                      insn->imm != BPF_FUNC_spin_unlock)) {
10796                                         verbose(env, "function calls are not allowed while holding a lock\n");
10797                                         return -EINVAL;
10798                                 }
10799                                 if (insn->src_reg == BPF_PSEUDO_CALL)
10800                                         err = check_func_call(env, insn, &env->insn_idx);
10801                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
10802                                         err = check_kfunc_call(env, insn);
10803                                 else
10804                                         err = check_helper_call(env, insn, &env->insn_idx);
10805                                 if (err)
10806                                         return err;
10807                         } else if (opcode == BPF_JA) {
10808                                 if (BPF_SRC(insn->code) != BPF_K ||
10809                                     insn->imm != 0 ||
10810                                     insn->src_reg != BPF_REG_0 ||
10811                                     insn->dst_reg != BPF_REG_0 ||
10812                                     class == BPF_JMP32) {
10813                                         verbose(env, "BPF_JA uses reserved fields\n");
10814                                         return -EINVAL;
10815                                 }
10816
10817                                 env->insn_idx += insn->off + 1;
10818                                 continue;
10819
10820                         } else if (opcode == BPF_EXIT) {
10821                                 if (BPF_SRC(insn->code) != BPF_K ||
10822                                     insn->imm != 0 ||
10823                                     insn->src_reg != BPF_REG_0 ||
10824                                     insn->dst_reg != BPF_REG_0 ||
10825                                     class == BPF_JMP32) {
10826                                         verbose(env, "BPF_EXIT uses reserved fields\n");
10827                                         return -EINVAL;
10828                                 }
10829
10830                                 if (env->cur_state->active_spin_lock) {
10831                                         verbose(env, "bpf_spin_unlock is missing\n");
10832                                         return -EINVAL;
10833                                 }
10834
10835                                 if (state->curframe) {
10836                                         /* exit from nested function */
10837                                         err = prepare_func_exit(env, &env->insn_idx);
10838                                         if (err)
10839                                                 return err;
10840                                         do_print_state = true;
10841                                         continue;
10842                                 }
10843
10844                                 err = check_reference_leak(env);
10845                                 if (err)
10846                                         return err;
10847
10848                                 err = check_return_code(env);
10849                                 if (err)
10850                                         return err;
10851 process_bpf_exit:
10852                                 update_branch_counts(env, env->cur_state);
10853                                 err = pop_stack(env, &prev_insn_idx,
10854                                                 &env->insn_idx, pop_log);
10855                                 if (err < 0) {
10856                                         if (err != -ENOENT)
10857                                                 return err;
10858                                         break;
10859                                 } else {
10860                                         do_print_state = true;
10861                                         continue;
10862                                 }
10863                         } else {
10864                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
10865                                 if (err)
10866                                         return err;
10867                         }
10868                 } else if (class == BPF_LD) {
10869                         u8 mode = BPF_MODE(insn->code);
10870
10871                         if (mode == BPF_ABS || mode == BPF_IND) {
10872                                 err = check_ld_abs(env, insn);
10873                                 if (err)
10874                                         return err;
10875
10876                         } else if (mode == BPF_IMM) {
10877                                 err = check_ld_imm(env, insn);
10878                                 if (err)
10879                                         return err;
10880
10881                                 env->insn_idx++;
10882                                 sanitize_mark_insn_seen(env);
10883                         } else {
10884                                 verbose(env, "invalid BPF_LD mode\n");
10885                                 return -EINVAL;
10886                         }
10887                 } else {
10888                         verbose(env, "unknown insn class %d\n", class);
10889                         return -EINVAL;
10890                 }
10891
10892                 env->insn_idx++;
10893         }
10894
10895         return 0;
10896 }
10897
10898 static int find_btf_percpu_datasec(struct btf *btf)
10899 {
10900         const struct btf_type *t;
10901         const char *tname;
10902         int i, n;
10903
10904         /*
10905          * Both vmlinux and module each have their own ".data..percpu"
10906          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10907          * types to look at only module's own BTF types.
10908          */
10909         n = btf_nr_types(btf);
10910         if (btf_is_module(btf))
10911                 i = btf_nr_types(btf_vmlinux);
10912         else
10913                 i = 1;
10914
10915         for(; i < n; i++) {
10916                 t = btf_type_by_id(btf, i);
10917                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10918                         continue;
10919
10920                 tname = btf_name_by_offset(btf, t->name_off);
10921                 if (!strcmp(tname, ".data..percpu"))
10922                         return i;
10923         }
10924
10925         return -ENOENT;
10926 }
10927
10928 /* replace pseudo btf_id with kernel symbol address */
10929 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10930                                struct bpf_insn *insn,
10931                                struct bpf_insn_aux_data *aux)
10932 {
10933         const struct btf_var_secinfo *vsi;
10934         const struct btf_type *datasec;
10935         struct btf_mod_pair *btf_mod;
10936         const struct btf_type *t;
10937         const char *sym_name;
10938         bool percpu = false;
10939         u32 type, id = insn->imm;
10940         struct btf *btf;
10941         s32 datasec_id;
10942         u64 addr;
10943         int i, btf_fd, err;
10944
10945         btf_fd = insn[1].imm;
10946         if (btf_fd) {
10947                 btf = btf_get_by_fd(btf_fd);
10948                 if (IS_ERR(btf)) {
10949                         verbose(env, "invalid module BTF object FD specified.\n");
10950                         return -EINVAL;
10951                 }
10952         } else {
10953                 if (!btf_vmlinux) {
10954                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10955                         return -EINVAL;
10956                 }
10957                 btf = btf_vmlinux;
10958                 btf_get(btf);
10959         }
10960
10961         t = btf_type_by_id(btf, id);
10962         if (!t) {
10963                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10964                 err = -ENOENT;
10965                 goto err_put;
10966         }
10967
10968         if (!btf_type_is_var(t)) {
10969                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10970                 err = -EINVAL;
10971                 goto err_put;
10972         }
10973
10974         sym_name = btf_name_by_offset(btf, t->name_off);
10975         addr = kallsyms_lookup_name(sym_name);
10976         if (!addr) {
10977                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10978                         sym_name);
10979                 err = -ENOENT;
10980                 goto err_put;
10981         }
10982
10983         datasec_id = find_btf_percpu_datasec(btf);
10984         if (datasec_id > 0) {
10985                 datasec = btf_type_by_id(btf, datasec_id);
10986                 for_each_vsi(i, datasec, vsi) {
10987                         if (vsi->type == id) {
10988                                 percpu = true;
10989                                 break;
10990                         }
10991                 }
10992         }
10993
10994         insn[0].imm = (u32)addr;
10995         insn[1].imm = addr >> 32;
10996
10997         type = t->type;
10998         t = btf_type_skip_modifiers(btf, type, NULL);
10999         if (percpu) {
11000                 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11001                 aux->btf_var.btf = btf;
11002                 aux->btf_var.btf_id = type;
11003         } else if (!btf_type_is_struct(t)) {
11004                 const struct btf_type *ret;
11005                 const char *tname;
11006                 u32 tsize;
11007
11008                 /* resolve the type size of ksym. */
11009                 ret = btf_resolve_size(btf, t, &tsize);
11010                 if (IS_ERR(ret)) {
11011                         tname = btf_name_by_offset(btf, t->name_off);
11012                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11013                                 tname, PTR_ERR(ret));
11014                         err = -EINVAL;
11015                         goto err_put;
11016                 }
11017                 aux->btf_var.reg_type = PTR_TO_MEM;
11018                 aux->btf_var.mem_size = tsize;
11019         } else {
11020                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
11021                 aux->btf_var.btf = btf;
11022                 aux->btf_var.btf_id = type;
11023         }
11024
11025         /* check whether we recorded this BTF (and maybe module) already */
11026         for (i = 0; i < env->used_btf_cnt; i++) {
11027                 if (env->used_btfs[i].btf == btf) {
11028                         btf_put(btf);
11029                         return 0;
11030                 }
11031         }
11032
11033         if (env->used_btf_cnt >= MAX_USED_BTFS) {
11034                 err = -E2BIG;
11035                 goto err_put;
11036         }
11037
11038         btf_mod = &env->used_btfs[env->used_btf_cnt];
11039         btf_mod->btf = btf;
11040         btf_mod->module = NULL;
11041
11042         /* if we reference variables from kernel module, bump its refcount */
11043         if (btf_is_module(btf)) {
11044                 btf_mod->module = btf_try_get_module(btf);
11045                 if (!btf_mod->module) {
11046                         err = -ENXIO;
11047                         goto err_put;
11048                 }
11049         }
11050
11051         env->used_btf_cnt++;
11052
11053         return 0;
11054 err_put:
11055         btf_put(btf);
11056         return err;
11057 }
11058
11059 static int check_map_prealloc(struct bpf_map *map)
11060 {
11061         return (map->map_type != BPF_MAP_TYPE_HASH &&
11062                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11063                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11064                 !(map->map_flags & BPF_F_NO_PREALLOC);
11065 }
11066
11067 static bool is_tracing_prog_type(enum bpf_prog_type type)
11068 {
11069         switch (type) {
11070         case BPF_PROG_TYPE_KPROBE:
11071         case BPF_PROG_TYPE_TRACEPOINT:
11072         case BPF_PROG_TYPE_PERF_EVENT:
11073         case BPF_PROG_TYPE_RAW_TRACEPOINT:
11074                 return true;
11075         default:
11076                 return false;
11077         }
11078 }
11079
11080 static bool is_preallocated_map(struct bpf_map *map)
11081 {
11082         if (!check_map_prealloc(map))
11083                 return false;
11084         if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11085                 return false;
11086         return true;
11087 }
11088
11089 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11090                                         struct bpf_map *map,
11091                                         struct bpf_prog *prog)
11092
11093 {
11094         enum bpf_prog_type prog_type = resolve_prog_type(prog);
11095         /*
11096          * Validate that trace type programs use preallocated hash maps.
11097          *
11098          * For programs attached to PERF events this is mandatory as the
11099          * perf NMI can hit any arbitrary code sequence.
11100          *
11101          * All other trace types using preallocated hash maps are unsafe as
11102          * well because tracepoint or kprobes can be inside locked regions
11103          * of the memory allocator or at a place where a recursion into the
11104          * memory allocator would see inconsistent state.
11105          *
11106          * On RT enabled kernels run-time allocation of all trace type
11107          * programs is strictly prohibited due to lock type constraints. On
11108          * !RT kernels it is allowed for backwards compatibility reasons for
11109          * now, but warnings are emitted so developers are made aware of
11110          * the unsafety and can fix their programs before this is enforced.
11111          */
11112         if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11113                 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11114                         verbose(env, "perf_event programs can only use preallocated hash map\n");
11115                         return -EINVAL;
11116                 }
11117                 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11118                         verbose(env, "trace type programs can only use preallocated hash map\n");
11119                         return -EINVAL;
11120                 }
11121                 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11122                 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11123         }
11124
11125         if (map_value_has_spin_lock(map)) {
11126                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11127                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11128                         return -EINVAL;
11129                 }
11130
11131                 if (is_tracing_prog_type(prog_type)) {
11132                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11133                         return -EINVAL;
11134                 }
11135
11136                 if (prog->aux->sleepable) {
11137                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11138                         return -EINVAL;
11139                 }
11140         }
11141
11142         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11143             !bpf_offload_prog_map_match(prog, map)) {
11144                 verbose(env, "offload device mismatch between prog and map\n");
11145                 return -EINVAL;
11146         }
11147
11148         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11149                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11150                 return -EINVAL;
11151         }
11152
11153         if (prog->aux->sleepable)
11154                 switch (map->map_type) {
11155                 case BPF_MAP_TYPE_HASH:
11156                 case BPF_MAP_TYPE_LRU_HASH:
11157                 case BPF_MAP_TYPE_ARRAY:
11158                 case BPF_MAP_TYPE_PERCPU_HASH:
11159                 case BPF_MAP_TYPE_PERCPU_ARRAY:
11160                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11161                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11162                 case BPF_MAP_TYPE_HASH_OF_MAPS:
11163                         if (!is_preallocated_map(map)) {
11164                                 verbose(env,
11165                                         "Sleepable programs can only use preallocated maps\n");
11166                                 return -EINVAL;
11167                         }
11168                         break;
11169                 case BPF_MAP_TYPE_RINGBUF:
11170                         break;
11171                 default:
11172                         verbose(env,
11173                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
11174                         return -EINVAL;
11175                 }
11176
11177         return 0;
11178 }
11179
11180 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11181 {
11182         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11183                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11184 }
11185
11186 /* find and rewrite pseudo imm in ld_imm64 instructions:
11187  *
11188  * 1. if it accesses map FD, replace it with actual map pointer.
11189  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11190  *
11191  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11192  */
11193 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11194 {
11195         struct bpf_insn *insn = env->prog->insnsi;
11196         int insn_cnt = env->prog->len;
11197         int i, j, err;
11198
11199         err = bpf_prog_calc_tag(env->prog);
11200         if (err)
11201                 return err;
11202
11203         for (i = 0; i < insn_cnt; i++, insn++) {
11204                 if (BPF_CLASS(insn->code) == BPF_LDX &&
11205                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11206                         verbose(env, "BPF_LDX uses reserved fields\n");
11207                         return -EINVAL;
11208                 }
11209
11210                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11211                         struct bpf_insn_aux_data *aux;
11212                         struct bpf_map *map;
11213                         struct fd f;
11214                         u64 addr;
11215
11216                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
11217                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11218                             insn[1].off != 0) {
11219                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
11220                                 return -EINVAL;
11221                         }
11222
11223                         if (insn[0].src_reg == 0)
11224                                 /* valid generic load 64-bit imm */
11225                                 goto next_insn;
11226
11227                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11228                                 aux = &env->insn_aux_data[i];
11229                                 err = check_pseudo_btf_id(env, insn, aux);
11230                                 if (err)
11231                                         return err;
11232                                 goto next_insn;
11233                         }
11234
11235                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11236                                 aux = &env->insn_aux_data[i];
11237                                 aux->ptr_type = PTR_TO_FUNC;
11238                                 goto next_insn;
11239                         }
11240
11241                         /* In final convert_pseudo_ld_imm64() step, this is
11242                          * converted into regular 64-bit imm load insn.
11243                          */
11244                         if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
11245                              insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
11246                             (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
11247                              insn[1].imm != 0)) {
11248                                 verbose(env,
11249                                         "unrecognized bpf_ld_imm64 insn\n");
11250                                 return -EINVAL;
11251                         }
11252
11253                         f = fdget(insn[0].imm);
11254                         map = __bpf_map_get(f);
11255                         if (IS_ERR(map)) {
11256                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
11257                                         insn[0].imm);
11258                                 return PTR_ERR(map);
11259                         }
11260
11261                         err = check_map_prog_compatibility(env, map, env->prog);
11262                         if (err) {
11263                                 fdput(f);
11264                                 return err;
11265                         }
11266
11267                         aux = &env->insn_aux_data[i];
11268                         if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
11269                                 addr = (unsigned long)map;
11270                         } else {
11271                                 u32 off = insn[1].imm;
11272
11273                                 if (off >= BPF_MAX_VAR_OFF) {
11274                                         verbose(env, "direct value offset of %u is not allowed\n", off);
11275                                         fdput(f);
11276                                         return -EINVAL;
11277                                 }
11278
11279                                 if (!map->ops->map_direct_value_addr) {
11280                                         verbose(env, "no direct value access support for this map type\n");
11281                                         fdput(f);
11282                                         return -EINVAL;
11283                                 }
11284
11285                                 err = map->ops->map_direct_value_addr(map, &addr, off);
11286                                 if (err) {
11287                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11288                                                 map->value_size, off);
11289                                         fdput(f);
11290                                         return err;
11291                                 }
11292
11293                                 aux->map_off = off;
11294                                 addr += off;
11295                         }
11296
11297                         insn[0].imm = (u32)addr;
11298                         insn[1].imm = addr >> 32;
11299
11300                         /* check whether we recorded this map already */
11301                         for (j = 0; j < env->used_map_cnt; j++) {
11302                                 if (env->used_maps[j] == map) {
11303                                         aux->map_index = j;
11304                                         fdput(f);
11305                                         goto next_insn;
11306                                 }
11307                         }
11308
11309                         if (env->used_map_cnt >= MAX_USED_MAPS) {
11310                                 fdput(f);
11311                                 return -E2BIG;
11312                         }
11313
11314                         /* hold the map. If the program is rejected by verifier,
11315                          * the map will be released by release_maps() or it
11316                          * will be used by the valid program until it's unloaded
11317                          * and all maps are released in free_used_maps()
11318                          */
11319                         bpf_map_inc(map);
11320
11321                         aux->map_index = env->used_map_cnt;
11322                         env->used_maps[env->used_map_cnt++] = map;
11323
11324                         if (bpf_map_is_cgroup_storage(map) &&
11325                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
11326                                 verbose(env, "only one cgroup storage of each type is allowed\n");
11327                                 fdput(f);
11328                                 return -EBUSY;
11329                         }
11330
11331                         fdput(f);
11332 next_insn:
11333                         insn++;
11334                         i++;
11335                         continue;
11336                 }
11337
11338                 /* Basic sanity check before we invest more work here. */
11339                 if (!bpf_opcode_in_insntable(insn->code)) {
11340                         verbose(env, "unknown opcode %02x\n", insn->code);
11341                         return -EINVAL;
11342                 }
11343         }
11344
11345         /* now all pseudo BPF_LD_IMM64 instructions load valid
11346          * 'struct bpf_map *' into a register instead of user map_fd.
11347          * These pointers will be used later by verifier to validate map access.
11348          */
11349         return 0;
11350 }
11351
11352 /* drop refcnt of maps used by the rejected program */
11353 static void release_maps(struct bpf_verifier_env *env)
11354 {
11355         __bpf_free_used_maps(env->prog->aux, env->used_maps,
11356                              env->used_map_cnt);
11357 }
11358
11359 /* drop refcnt of maps used by the rejected program */
11360 static void release_btfs(struct bpf_verifier_env *env)
11361 {
11362         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11363                              env->used_btf_cnt);
11364 }
11365
11366 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11367 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11368 {
11369         struct bpf_insn *insn = env->prog->insnsi;
11370         int insn_cnt = env->prog->len;
11371         int i;
11372
11373         for (i = 0; i < insn_cnt; i++, insn++) {
11374                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11375                         continue;
11376                 if (insn->src_reg == BPF_PSEUDO_FUNC)
11377                         continue;
11378                 insn->src_reg = 0;
11379         }
11380 }
11381
11382 /* single env->prog->insni[off] instruction was replaced with the range
11383  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11384  * [0, off) and [off, end) to new locations, so the patched range stays zero
11385  */
11386 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
11387                                 struct bpf_prog *new_prog, u32 off, u32 cnt)
11388 {
11389         struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
11390         struct bpf_insn *insn = new_prog->insnsi;
11391         u32 old_seen = old_data[off].seen;
11392         u32 prog_len;
11393         int i;
11394
11395         /* aux info at OFF always needs adjustment, no matter fast path
11396          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11397          * original insn at old prog.
11398          */
11399         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11400
11401         if (cnt == 1)
11402                 return 0;
11403         prog_len = new_prog->len;
11404         new_data = vzalloc(array_size(prog_len,
11405                                       sizeof(struct bpf_insn_aux_data)));
11406         if (!new_data)
11407                 return -ENOMEM;
11408         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11409         memcpy(new_data + off + cnt - 1, old_data + off,
11410                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11411         for (i = off; i < off + cnt - 1; i++) {
11412                 /* Expand insni[off]'s seen count to the patched range. */
11413                 new_data[i].seen = old_seen;
11414                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11415         }
11416         env->insn_aux_data = new_data;
11417         vfree(old_data);
11418         return 0;
11419 }
11420
11421 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11422 {
11423         int i;
11424
11425         if (len == 1)
11426                 return;
11427         /* NOTE: fake 'exit' subprog should be updated as well. */
11428         for (i = 0; i <= env->subprog_cnt; i++) {
11429                 if (env->subprog_info[i].start <= off)
11430                         continue;
11431                 env->subprog_info[i].start += len - 1;
11432         }
11433 }
11434
11435 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
11436 {
11437         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11438         int i, sz = prog->aux->size_poke_tab;
11439         struct bpf_jit_poke_descriptor *desc;
11440
11441         for (i = 0; i < sz; i++) {
11442                 desc = &tab[i];
11443                 if (desc->insn_idx <= off)
11444                         continue;
11445                 desc->insn_idx += len - 1;
11446         }
11447 }
11448
11449 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11450                                             const struct bpf_insn *patch, u32 len)
11451 {
11452         struct bpf_prog *new_prog;
11453
11454         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
11455         if (IS_ERR(new_prog)) {
11456                 if (PTR_ERR(new_prog) == -ERANGE)
11457                         verbose(env,
11458                                 "insn %d cannot be patched due to 16-bit range\n",
11459                                 env->insn_aux_data[off].orig_idx);
11460                 return NULL;
11461         }
11462         if (adjust_insn_aux_data(env, new_prog, off, len))
11463                 return NULL;
11464         adjust_subprog_starts(env, off, len);
11465         adjust_poke_descs(new_prog, off, len);
11466         return new_prog;
11467 }
11468
11469 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11470                                               u32 off, u32 cnt)
11471 {
11472         int i, j;
11473
11474         /* find first prog starting at or after off (first to remove) */
11475         for (i = 0; i < env->subprog_cnt; i++)
11476                 if (env->subprog_info[i].start >= off)
11477                         break;
11478         /* find first prog starting at or after off + cnt (first to stay) */
11479         for (j = i; j < env->subprog_cnt; j++)
11480                 if (env->subprog_info[j].start >= off + cnt)
11481                         break;
11482         /* if j doesn't start exactly at off + cnt, we are just removing
11483          * the front of previous prog
11484          */
11485         if (env->subprog_info[j].start != off + cnt)
11486                 j--;
11487
11488         if (j > i) {
11489                 struct bpf_prog_aux *aux = env->prog->aux;
11490                 int move;
11491
11492                 /* move fake 'exit' subprog as well */
11493                 move = env->subprog_cnt + 1 - j;
11494
11495                 memmove(env->subprog_info + i,
11496                         env->subprog_info + j,
11497                         sizeof(*env->subprog_info) * move);
11498                 env->subprog_cnt -= j - i;
11499
11500                 /* remove func_info */
11501                 if (aux->func_info) {
11502                         move = aux->func_info_cnt - j;
11503
11504                         memmove(aux->func_info + i,
11505                                 aux->func_info + j,
11506                                 sizeof(*aux->func_info) * move);
11507                         aux->func_info_cnt -= j - i;
11508                         /* func_info->insn_off is set after all code rewrites,
11509                          * in adjust_btf_func() - no need to adjust
11510                          */
11511                 }
11512         } else {
11513                 /* convert i from "first prog to remove" to "first to adjust" */
11514                 if (env->subprog_info[i].start == off)
11515                         i++;
11516         }
11517
11518         /* update fake 'exit' subprog as well */
11519         for (; i <= env->subprog_cnt; i++)
11520                 env->subprog_info[i].start -= cnt;
11521
11522         return 0;
11523 }
11524
11525 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11526                                       u32 cnt)
11527 {
11528         struct bpf_prog *prog = env->prog;
11529         u32 i, l_off, l_cnt, nr_linfo;
11530         struct bpf_line_info *linfo;
11531
11532         nr_linfo = prog->aux->nr_linfo;
11533         if (!nr_linfo)
11534                 return 0;
11535
11536         linfo = prog->aux->linfo;
11537
11538         /* find first line info to remove, count lines to be removed */
11539         for (i = 0; i < nr_linfo; i++)
11540                 if (linfo[i].insn_off >= off)
11541                         break;
11542
11543         l_off = i;
11544         l_cnt = 0;
11545         for (; i < nr_linfo; i++)
11546                 if (linfo[i].insn_off < off + cnt)
11547                         l_cnt++;
11548                 else
11549                         break;
11550
11551         /* First live insn doesn't match first live linfo, it needs to "inherit"
11552          * last removed linfo.  prog is already modified, so prog->len == off
11553          * means no live instructions after (tail of the program was removed).
11554          */
11555         if (prog->len != off && l_cnt &&
11556             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11557                 l_cnt--;
11558                 linfo[--i].insn_off = off + cnt;
11559         }
11560
11561         /* remove the line info which refer to the removed instructions */
11562         if (l_cnt) {
11563                 memmove(linfo + l_off, linfo + i,
11564                         sizeof(*linfo) * (nr_linfo - i));
11565
11566                 prog->aux->nr_linfo -= l_cnt;
11567                 nr_linfo = prog->aux->nr_linfo;
11568         }
11569
11570         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11571         for (i = l_off; i < nr_linfo; i++)
11572                 linfo[i].insn_off -= cnt;
11573
11574         /* fix up all subprogs (incl. 'exit') which start >= off */
11575         for (i = 0; i <= env->subprog_cnt; i++)
11576                 if (env->subprog_info[i].linfo_idx > l_off) {
11577                         /* program may have started in the removed region but
11578                          * may not be fully removed
11579                          */
11580                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11581                                 env->subprog_info[i].linfo_idx -= l_cnt;
11582                         else
11583                                 env->subprog_info[i].linfo_idx = l_off;
11584                 }
11585
11586         return 0;
11587 }
11588
11589 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11590 {
11591         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11592         unsigned int orig_prog_len = env->prog->len;
11593         int err;
11594
11595         if (bpf_prog_is_dev_bound(env->prog->aux))
11596                 bpf_prog_offload_remove_insns(env, off, cnt);
11597
11598         err = bpf_remove_insns(env->prog, off, cnt);
11599         if (err)
11600                 return err;
11601
11602         err = adjust_subprog_starts_after_remove(env, off, cnt);
11603         if (err)
11604                 return err;
11605
11606         err = bpf_adj_linfo_after_remove(env, off, cnt);
11607         if (err)
11608                 return err;
11609
11610         memmove(aux_data + off, aux_data + off + cnt,
11611                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11612
11613         return 0;
11614 }
11615
11616 /* The verifier does more data flow analysis than llvm and will not
11617  * explore branches that are dead at run time. Malicious programs can
11618  * have dead code too. Therefore replace all dead at-run-time code
11619  * with 'ja -1'.
11620  *
11621  * Just nops are not optimal, e.g. if they would sit at the end of the
11622  * program and through another bug we would manage to jump there, then
11623  * we'd execute beyond program memory otherwise. Returning exception
11624  * code also wouldn't work since we can have subprogs where the dead
11625  * code could be located.
11626  */
11627 static void sanitize_dead_code(struct bpf_verifier_env *env)
11628 {
11629         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11630         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11631         struct bpf_insn *insn = env->prog->insnsi;
11632         const int insn_cnt = env->prog->len;
11633         int i;
11634
11635         for (i = 0; i < insn_cnt; i++) {
11636                 if (aux_data[i].seen)
11637                         continue;
11638                 memcpy(insn + i, &trap, sizeof(trap));
11639                 aux_data[i].zext_dst = false;
11640         }
11641 }
11642
11643 static bool insn_is_cond_jump(u8 code)
11644 {
11645         u8 op;
11646
11647         if (BPF_CLASS(code) == BPF_JMP32)
11648                 return true;
11649
11650         if (BPF_CLASS(code) != BPF_JMP)
11651                 return false;
11652
11653         op = BPF_OP(code);
11654         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11655 }
11656
11657 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11658 {
11659         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11660         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11661         struct bpf_insn *insn = env->prog->insnsi;
11662         const int insn_cnt = env->prog->len;
11663         int i;
11664
11665         for (i = 0; i < insn_cnt; i++, insn++) {
11666                 if (!insn_is_cond_jump(insn->code))
11667                         continue;
11668
11669                 if (!aux_data[i + 1].seen)
11670                         ja.off = insn->off;
11671                 else if (!aux_data[i + 1 + insn->off].seen)
11672                         ja.off = 0;
11673                 else
11674                         continue;
11675
11676                 if (bpf_prog_is_dev_bound(env->prog->aux))
11677                         bpf_prog_offload_replace_insn(env, i, &ja);
11678
11679                 memcpy(insn, &ja, sizeof(ja));
11680         }
11681 }
11682
11683 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11684 {
11685         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11686         int insn_cnt = env->prog->len;
11687         int i, err;
11688
11689         for (i = 0; i < insn_cnt; i++) {
11690                 int j;
11691
11692                 j = 0;
11693                 while (i + j < insn_cnt && !aux_data[i + j].seen)
11694                         j++;
11695                 if (!j)
11696                         continue;
11697
11698                 err = verifier_remove_insns(env, i, j);
11699                 if (err)
11700                         return err;
11701                 insn_cnt = env->prog->len;
11702         }
11703
11704         return 0;
11705 }
11706
11707 static int opt_remove_nops(struct bpf_verifier_env *env)
11708 {
11709         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11710         struct bpf_insn *insn = env->prog->insnsi;
11711         int insn_cnt = env->prog->len;
11712         int i, err;
11713
11714         for (i = 0; i < insn_cnt; i++) {
11715                 if (memcmp(&insn[i], &ja, sizeof(ja)))
11716                         continue;
11717
11718                 err = verifier_remove_insns(env, i, 1);
11719                 if (err)
11720                         return err;
11721                 insn_cnt--;
11722                 i--;
11723         }
11724
11725         return 0;
11726 }
11727
11728 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11729                                          const union bpf_attr *attr)
11730 {
11731         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11732         struct bpf_insn_aux_data *aux = env->insn_aux_data;
11733         int i, patch_len, delta = 0, len = env->prog->len;
11734         struct bpf_insn *insns = env->prog->insnsi;
11735         struct bpf_prog *new_prog;
11736         bool rnd_hi32;
11737
11738         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11739         zext_patch[1] = BPF_ZEXT_REG(0);
11740         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11741         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11742         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11743         for (i = 0; i < len; i++) {
11744                 int adj_idx = i + delta;
11745                 struct bpf_insn insn;
11746                 int load_reg;
11747
11748                 insn = insns[adj_idx];
11749                 load_reg = insn_def_regno(&insn);
11750                 if (!aux[adj_idx].zext_dst) {
11751                         u8 code, class;
11752                         u32 imm_rnd;
11753
11754                         if (!rnd_hi32)
11755                                 continue;
11756
11757                         code = insn.code;
11758                         class = BPF_CLASS(code);
11759                         if (load_reg == -1)
11760                                 continue;
11761
11762                         /* NOTE: arg "reg" (the fourth one) is only used for
11763                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
11764                          *       here.
11765                          */
11766                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
11767                                 if (class == BPF_LD &&
11768                                     BPF_MODE(code) == BPF_IMM)
11769                                         i++;
11770                                 continue;
11771                         }
11772
11773                         /* ctx load could be transformed into wider load. */
11774                         if (class == BPF_LDX &&
11775                             aux[adj_idx].ptr_type == PTR_TO_CTX)
11776                                 continue;
11777
11778                         imm_rnd = get_random_int();
11779                         rnd_hi32_patch[0] = insn;
11780                         rnd_hi32_patch[1].imm = imm_rnd;
11781                         rnd_hi32_patch[3].dst_reg = load_reg;
11782                         patch = rnd_hi32_patch;
11783                         patch_len = 4;
11784                         goto apply_patch_buffer;
11785                 }
11786
11787                 /* Add in an zero-extend instruction if a) the JIT has requested
11788                  * it or b) it's a CMPXCHG.
11789                  *
11790                  * The latter is because: BPF_CMPXCHG always loads a value into
11791                  * R0, therefore always zero-extends. However some archs'
11792                  * equivalent instruction only does this load when the
11793                  * comparison is successful. This detail of CMPXCHG is
11794                  * orthogonal to the general zero-extension behaviour of the
11795                  * CPU, so it's treated independently of bpf_jit_needs_zext.
11796                  */
11797                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
11798                         continue;
11799
11800                 if (WARN_ON(load_reg == -1)) {
11801                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11802                         return -EFAULT;
11803                 }
11804
11805                 zext_patch[0] = insn;
11806                 zext_patch[1].dst_reg = load_reg;
11807                 zext_patch[1].src_reg = load_reg;
11808                 patch = zext_patch;
11809                 patch_len = 2;
11810 apply_patch_buffer:
11811                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11812                 if (!new_prog)
11813                         return -ENOMEM;
11814                 env->prog = new_prog;
11815                 insns = new_prog->insnsi;
11816                 aux = env->insn_aux_data;
11817                 delta += patch_len - 1;
11818         }
11819
11820         return 0;
11821 }
11822
11823 /* convert load instructions that access fields of a context type into a
11824  * sequence of instructions that access fields of the underlying structure:
11825  *     struct __sk_buff    -> struct sk_buff
11826  *     struct bpf_sock_ops -> struct sock
11827  */
11828 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11829 {
11830         const struct bpf_verifier_ops *ops = env->ops;
11831         int i, cnt, size, ctx_field_size, delta = 0;
11832         const int insn_cnt = env->prog->len;
11833         struct bpf_insn insn_buf[16], *insn;
11834         u32 target_size, size_default, off;
11835         struct bpf_prog *new_prog;
11836         enum bpf_access_type type;
11837         bool is_narrower_load;
11838
11839         if (ops->gen_prologue || env->seen_direct_write) {
11840                 if (!ops->gen_prologue) {
11841                         verbose(env, "bpf verifier is misconfigured\n");
11842                         return -EINVAL;
11843                 }
11844                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11845                                         env->prog);
11846                 if (cnt >= ARRAY_SIZE(insn_buf)) {
11847                         verbose(env, "bpf verifier is misconfigured\n");
11848                         return -EINVAL;
11849                 } else if (cnt) {
11850                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11851                         if (!new_prog)
11852                                 return -ENOMEM;
11853
11854                         env->prog = new_prog;
11855                         delta += cnt - 1;
11856                 }
11857         }
11858
11859         if (bpf_prog_is_dev_bound(env->prog->aux))
11860                 return 0;
11861
11862         insn = env->prog->insnsi + delta;
11863
11864         for (i = 0; i < insn_cnt; i++, insn++) {
11865                 bpf_convert_ctx_access_t convert_ctx_access;
11866                 bool ctx_access;
11867
11868                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11869                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11870                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11871                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
11872                         type = BPF_READ;
11873                         ctx_access = true;
11874                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11875                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11876                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11877                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
11878                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
11879                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
11880                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
11881                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
11882                         type = BPF_WRITE;
11883                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
11884                 } else {
11885                         continue;
11886                 }
11887
11888                 if (type == BPF_WRITE &&
11889                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
11890                         struct bpf_insn patch[] = {
11891                                 *insn,
11892                                 BPF_ST_NOSPEC(),
11893                         };
11894
11895                         cnt = ARRAY_SIZE(patch);
11896                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11897                         if (!new_prog)
11898                                 return -ENOMEM;
11899
11900                         delta    += cnt - 1;
11901                         env->prog = new_prog;
11902                         insn      = new_prog->insnsi + i + delta;
11903                         continue;
11904                 }
11905
11906                 if (!ctx_access)
11907                         continue;
11908
11909                 switch (env->insn_aux_data[i + delta].ptr_type) {
11910                 case PTR_TO_CTX:
11911                         if (!ops->convert_ctx_access)
11912                                 continue;
11913                         convert_ctx_access = ops->convert_ctx_access;
11914                         break;
11915                 case PTR_TO_SOCKET:
11916                 case PTR_TO_SOCK_COMMON:
11917                         convert_ctx_access = bpf_sock_convert_ctx_access;
11918                         break;
11919                 case PTR_TO_TCP_SOCK:
11920                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11921                         break;
11922                 case PTR_TO_XDP_SOCK:
11923                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11924                         break;
11925                 case PTR_TO_BTF_ID:
11926                         if (type == BPF_READ) {
11927                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
11928                                         BPF_SIZE((insn)->code);
11929                                 env->prog->aux->num_exentries++;
11930                         } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11931                                 verbose(env, "Writes through BTF pointers are not allowed\n");
11932                                 return -EINVAL;
11933                         }
11934                         continue;
11935                 default:
11936                         continue;
11937                 }
11938
11939                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11940                 size = BPF_LDST_BYTES(insn);
11941
11942                 /* If the read access is a narrower load of the field,
11943                  * convert to a 4/8-byte load, to minimum program type specific
11944                  * convert_ctx_access changes. If conversion is successful,
11945                  * we will apply proper mask to the result.
11946                  */
11947                 is_narrower_load = size < ctx_field_size;
11948                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11949                 off = insn->off;
11950                 if (is_narrower_load) {
11951                         u8 size_code;
11952
11953                         if (type == BPF_WRITE) {
11954                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11955                                 return -EINVAL;
11956                         }
11957
11958                         size_code = BPF_H;
11959                         if (ctx_field_size == 4)
11960                                 size_code = BPF_W;
11961                         else if (ctx_field_size == 8)
11962                                 size_code = BPF_DW;
11963
11964                         insn->off = off & ~(size_default - 1);
11965                         insn->code = BPF_LDX | BPF_MEM | size_code;
11966                 }
11967
11968                 target_size = 0;
11969                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11970                                          &target_size);
11971                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11972                     (ctx_field_size && !target_size)) {
11973                         verbose(env, "bpf verifier is misconfigured\n");
11974                         return -EINVAL;
11975                 }
11976
11977                 if (is_narrower_load && size < target_size) {
11978                         u8 shift = bpf_ctx_narrow_access_offset(
11979                                 off, size, size_default) * 8;
11980                         if (ctx_field_size <= 4) {
11981                                 if (shift)
11982                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11983                                                                         insn->dst_reg,
11984                                                                         shift);
11985                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11986                                                                 (1 << size * 8) - 1);
11987                         } else {
11988                                 if (shift)
11989                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11990                                                                         insn->dst_reg,
11991                                                                         shift);
11992                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
11993                                                                 (1ULL << size * 8) - 1);
11994                         }
11995                 }
11996
11997                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11998                 if (!new_prog)
11999                         return -ENOMEM;
12000
12001                 delta += cnt - 1;
12002
12003                 /* keep walking new program and skip insns we just inserted */
12004                 env->prog = new_prog;
12005                 insn      = new_prog->insnsi + i + delta;
12006         }
12007
12008         return 0;
12009 }
12010
12011 static int jit_subprogs(struct bpf_verifier_env *env)
12012 {
12013         struct bpf_prog *prog = env->prog, **func, *tmp;
12014         int i, j, subprog_start, subprog_end = 0, len, subprog;
12015         struct bpf_map *map_ptr;
12016         struct bpf_insn *insn;
12017         void *old_bpf_func;
12018         int err, num_exentries;
12019
12020         if (env->subprog_cnt <= 1)
12021                 return 0;
12022
12023         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12024                 if (bpf_pseudo_func(insn)) {
12025                         env->insn_aux_data[i].call_imm = insn->imm;
12026                         /* subprog is encoded in insn[1].imm */
12027                         continue;
12028                 }
12029
12030                 if (!bpf_pseudo_call(insn))
12031                         continue;
12032                 /* Upon error here we cannot fall back to interpreter but
12033                  * need a hard reject of the program. Thus -EFAULT is
12034                  * propagated in any case.
12035                  */
12036                 subprog = find_subprog(env, i + insn->imm + 1);
12037                 if (subprog < 0) {
12038                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12039                                   i + insn->imm + 1);
12040                         return -EFAULT;
12041                 }
12042                 /* temporarily remember subprog id inside insn instead of
12043                  * aux_data, since next loop will split up all insns into funcs
12044                  */
12045                 insn->off = subprog;
12046                 /* remember original imm in case JIT fails and fallback
12047                  * to interpreter will be needed
12048                  */
12049                 env->insn_aux_data[i].call_imm = insn->imm;
12050                 /* point imm to __bpf_call_base+1 from JITs point of view */
12051                 insn->imm = 1;
12052         }
12053
12054         err = bpf_prog_alloc_jited_linfo(prog);
12055         if (err)
12056                 goto out_undo_insn;
12057
12058         err = -ENOMEM;
12059         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12060         if (!func)
12061                 goto out_undo_insn;
12062
12063         for (i = 0; i < env->subprog_cnt; i++) {
12064                 subprog_start = subprog_end;
12065                 subprog_end = env->subprog_info[i + 1].start;
12066
12067                 len = subprog_end - subprog_start;
12068                 /* BPF_PROG_RUN doesn't call subprogs directly,
12069                  * hence main prog stats include the runtime of subprogs.
12070                  * subprogs don't have IDs and not reachable via prog_get_next_id
12071                  * func[i]->stats will never be accessed and stays NULL
12072                  */
12073                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12074                 if (!func[i])
12075                         goto out_free;
12076                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12077                        len * sizeof(struct bpf_insn));
12078                 func[i]->type = prog->type;
12079                 func[i]->len = len;
12080                 if (bpf_prog_calc_tag(func[i]))
12081                         goto out_free;
12082                 func[i]->is_func = 1;
12083                 func[i]->aux->func_idx = i;
12084                 /* Below members will be freed only at prog->aux */
12085                 func[i]->aux->btf = prog->aux->btf;
12086                 func[i]->aux->func_info = prog->aux->func_info;
12087                 func[i]->aux->poke_tab = prog->aux->poke_tab;
12088                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12089
12090                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
12091                         struct bpf_jit_poke_descriptor *poke;
12092
12093                         poke = &prog->aux->poke_tab[j];
12094                         if (poke->insn_idx < subprog_end &&
12095                             poke->insn_idx >= subprog_start)
12096                                 poke->aux = func[i]->aux;
12097                 }
12098
12099                 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12100                  * Long term would need debug info to populate names
12101                  */
12102                 func[i]->aux->name[0] = 'F';
12103                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12104                 func[i]->jit_requested = 1;
12105                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12106                 func[i]->aux->linfo = prog->aux->linfo;
12107                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12108                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12109                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12110                 num_exentries = 0;
12111                 insn = func[i]->insnsi;
12112                 for (j = 0; j < func[i]->len; j++, insn++) {
12113                         if (BPF_CLASS(insn->code) == BPF_LDX &&
12114                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
12115                                 num_exentries++;
12116                 }
12117                 func[i]->aux->num_exentries = num_exentries;
12118                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12119                 func[i] = bpf_int_jit_compile(func[i]);
12120                 if (!func[i]->jited) {
12121                         err = -ENOTSUPP;
12122                         goto out_free;
12123                 }
12124                 cond_resched();
12125         }
12126
12127         /* at this point all bpf functions were successfully JITed
12128          * now populate all bpf_calls with correct addresses and
12129          * run last pass of JIT
12130          */
12131         for (i = 0; i < env->subprog_cnt; i++) {
12132                 insn = func[i]->insnsi;
12133                 for (j = 0; j < func[i]->len; j++, insn++) {
12134                         if (bpf_pseudo_func(insn)) {
12135                                 subprog = insn[1].imm;
12136                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12137                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12138                                 continue;
12139                         }
12140                         if (!bpf_pseudo_call(insn))
12141                                 continue;
12142                         subprog = insn->off;
12143                         insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12144                                     __bpf_call_base;
12145                 }
12146
12147                 /* we use the aux data to keep a list of the start addresses
12148                  * of the JITed images for each function in the program
12149                  *
12150                  * for some architectures, such as powerpc64, the imm field
12151                  * might not be large enough to hold the offset of the start
12152                  * address of the callee's JITed image from __bpf_call_base
12153                  *
12154                  * in such cases, we can lookup the start address of a callee
12155                  * by using its subprog id, available from the off field of
12156                  * the call instruction, as an index for this list
12157                  */
12158                 func[i]->aux->func = func;
12159                 func[i]->aux->func_cnt = env->subprog_cnt;
12160         }
12161         for (i = 0; i < env->subprog_cnt; i++) {
12162                 old_bpf_func = func[i]->bpf_func;
12163                 tmp = bpf_int_jit_compile(func[i]);
12164                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12165                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12166                         err = -ENOTSUPP;
12167                         goto out_free;
12168                 }
12169                 cond_resched();
12170         }
12171
12172         /* finally lock prog and jit images for all functions and
12173          * populate kallsysm
12174          */
12175         for (i = 0; i < env->subprog_cnt; i++) {
12176                 bpf_prog_lock_ro(func[i]);
12177                 bpf_prog_kallsyms_add(func[i]);
12178         }
12179
12180         /* Last step: make now unused interpreter insns from main
12181          * prog consistent for later dump requests, so they can
12182          * later look the same as if they were interpreted only.
12183          */
12184         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12185                 if (bpf_pseudo_func(insn)) {
12186                         insn[0].imm = env->insn_aux_data[i].call_imm;
12187                         insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12188                         continue;
12189                 }
12190                 if (!bpf_pseudo_call(insn))
12191                         continue;
12192                 insn->off = env->insn_aux_data[i].call_imm;
12193                 subprog = find_subprog(env, i + insn->off + 1);
12194                 insn->imm = subprog;
12195         }
12196
12197         prog->jited = 1;
12198         prog->bpf_func = func[0]->bpf_func;
12199         prog->aux->func = func;
12200         prog->aux->func_cnt = env->subprog_cnt;
12201         bpf_prog_jit_attempt_done(prog);
12202         return 0;
12203 out_free:
12204         /* We failed JIT'ing, so at this point we need to unregister poke
12205          * descriptors from subprogs, so that kernel is not attempting to
12206          * patch it anymore as we're freeing the subprog JIT memory.
12207          */
12208         for (i = 0; i < prog->aux->size_poke_tab; i++) {
12209                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12210                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12211         }
12212         /* At this point we're guaranteed that poke descriptors are not
12213          * live anymore. We can just unlink its descriptor table as it's
12214          * released with the main prog.
12215          */
12216         for (i = 0; i < env->subprog_cnt; i++) {
12217                 if (!func[i])
12218                         continue;
12219                 func[i]->aux->poke_tab = NULL;
12220                 bpf_jit_free(func[i]);
12221         }
12222         kfree(func);
12223 out_undo_insn:
12224         /* cleanup main prog to be interpreted */
12225         prog->jit_requested = 0;
12226         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12227                 if (!bpf_pseudo_call(insn))
12228                         continue;
12229                 insn->off = 0;
12230                 insn->imm = env->insn_aux_data[i].call_imm;
12231         }
12232         bpf_prog_jit_attempt_done(prog);
12233         return err;
12234 }
12235
12236 static int fixup_call_args(struct bpf_verifier_env *env)
12237 {
12238 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12239         struct bpf_prog *prog = env->prog;
12240         struct bpf_insn *insn = prog->insnsi;
12241         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12242         int i, depth;
12243 #endif
12244         int err = 0;
12245
12246         if (env->prog->jit_requested &&
12247             !bpf_prog_is_dev_bound(env->prog->aux)) {
12248                 err = jit_subprogs(env);
12249                 if (err == 0)
12250                         return 0;
12251                 if (err == -EFAULT)
12252                         return err;
12253         }
12254 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12255         if (has_kfunc_call) {
12256                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12257                 return -EINVAL;
12258         }
12259         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12260                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12261                  * have to be rejected, since interpreter doesn't support them yet.
12262                  */
12263                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12264                 return -EINVAL;
12265         }
12266         for (i = 0; i < prog->len; i++, insn++) {
12267                 if (bpf_pseudo_func(insn)) {
12268                         /* When JIT fails the progs with callback calls
12269                          * have to be rejected, since interpreter doesn't support them yet.
12270                          */
12271                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
12272                         return -EINVAL;
12273                 }
12274
12275                 if (!bpf_pseudo_call(insn))
12276                         continue;
12277                 depth = get_callee_stack_depth(env, insn, i);
12278                 if (depth < 0)
12279                         return depth;
12280                 bpf_patch_call_args(insn, depth);
12281         }
12282         err = 0;
12283 #endif
12284         return err;
12285 }
12286
12287 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12288                             struct bpf_insn *insn)
12289 {
12290         const struct bpf_kfunc_desc *desc;
12291
12292         /* insn->imm has the btf func_id. Replace it with
12293          * an address (relative to __bpf_base_call).
12294          */
12295         desc = find_kfunc_desc(env->prog, insn->imm);
12296         if (!desc) {
12297                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12298                         insn->imm);
12299                 return -EFAULT;
12300         }
12301
12302         insn->imm = desc->imm;
12303
12304         return 0;
12305 }
12306
12307 /* Do various post-verification rewrites in a single program pass.
12308  * These rewrites simplify JIT and interpreter implementations.
12309  */
12310 static int do_misc_fixups(struct bpf_verifier_env *env)
12311 {
12312         struct bpf_prog *prog = env->prog;
12313         bool expect_blinding = bpf_jit_blinding_enabled(prog);
12314         struct bpf_insn *insn = prog->insnsi;
12315         const struct bpf_func_proto *fn;
12316         const int insn_cnt = prog->len;
12317         const struct bpf_map_ops *ops;
12318         struct bpf_insn_aux_data *aux;
12319         struct bpf_insn insn_buf[16];
12320         struct bpf_prog *new_prog;
12321         struct bpf_map *map_ptr;
12322         int i, ret, cnt, delta = 0;
12323
12324         for (i = 0; i < insn_cnt; i++, insn++) {
12325                 /* Make divide-by-zero exceptions impossible. */
12326                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12327                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12328                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12329                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12330                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12331                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12332                         struct bpf_insn *patchlet;
12333                         struct bpf_insn chk_and_div[] = {
12334                                 /* [R,W]x div 0 -> 0 */
12335                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12336                                              BPF_JNE | BPF_K, insn->src_reg,
12337                                              0, 2, 0),
12338                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12339                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12340                                 *insn,
12341                         };
12342                         struct bpf_insn chk_and_mod[] = {
12343                                 /* [R,W]x mod 0 -> [R,W]x */
12344                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12345                                              BPF_JEQ | BPF_K, insn->src_reg,
12346                                              0, 1 + (is64 ? 0 : 1), 0),
12347                                 *insn,
12348                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12349                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12350                         };
12351
12352                         patchlet = isdiv ? chk_and_div : chk_and_mod;
12353                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12354                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12355
12356                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12357                         if (!new_prog)
12358                                 return -ENOMEM;
12359
12360                         delta    += cnt - 1;
12361                         env->prog = prog = new_prog;
12362                         insn      = new_prog->insnsi + i + delta;
12363                         continue;
12364                 }
12365
12366                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12367                 if (BPF_CLASS(insn->code) == BPF_LD &&
12368                     (BPF_MODE(insn->code) == BPF_ABS ||
12369                      BPF_MODE(insn->code) == BPF_IND)) {
12370                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
12371                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12372                                 verbose(env, "bpf verifier is misconfigured\n");
12373                                 return -EINVAL;
12374                         }
12375
12376                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12377                         if (!new_prog)
12378                                 return -ENOMEM;
12379
12380                         delta    += cnt - 1;
12381                         env->prog = prog = new_prog;
12382                         insn      = new_prog->insnsi + i + delta;
12383                         continue;
12384                 }
12385
12386                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
12387                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12388                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12389                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12390                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12391                         struct bpf_insn *patch = &insn_buf[0];
12392                         bool issrc, isneg, isimm;
12393                         u32 off_reg;
12394
12395                         aux = &env->insn_aux_data[i + delta];
12396                         if (!aux->alu_state ||
12397                             aux->alu_state == BPF_ALU_NON_POINTER)
12398                                 continue;
12399
12400                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12401                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12402                                 BPF_ALU_SANITIZE_SRC;
12403                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12404
12405                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
12406                         if (isimm) {
12407                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12408                         } else {
12409                                 if (isneg)
12410                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12411                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12412                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12413                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12414                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12415                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12416                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12417                         }
12418                         if (!issrc)
12419                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12420                         insn->src_reg = BPF_REG_AX;
12421                         if (isneg)
12422                                 insn->code = insn->code == code_add ?
12423                                              code_sub : code_add;
12424                         *patch++ = *insn;
12425                         if (issrc && isneg && !isimm)
12426                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12427                         cnt = patch - insn_buf;
12428
12429                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12430                         if (!new_prog)
12431                                 return -ENOMEM;
12432
12433                         delta    += cnt - 1;
12434                         env->prog = prog = new_prog;
12435                         insn      = new_prog->insnsi + i + delta;
12436                         continue;
12437                 }
12438
12439                 if (insn->code != (BPF_JMP | BPF_CALL))
12440                         continue;
12441                 if (insn->src_reg == BPF_PSEUDO_CALL)
12442                         continue;
12443                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12444                         ret = fixup_kfunc_call(env, insn);
12445                         if (ret)
12446                                 return ret;
12447                         continue;
12448                 }
12449
12450                 if (insn->imm == BPF_FUNC_get_route_realm)
12451                         prog->dst_needed = 1;
12452                 if (insn->imm == BPF_FUNC_get_prandom_u32)
12453                         bpf_user_rnd_init_once();
12454                 if (insn->imm == BPF_FUNC_override_return)
12455                         prog->kprobe_override = 1;
12456                 if (insn->imm == BPF_FUNC_tail_call) {
12457                         /* If we tail call into other programs, we
12458                          * cannot make any assumptions since they can
12459                          * be replaced dynamically during runtime in
12460                          * the program array.
12461                          */
12462                         prog->cb_access = 1;
12463                         if (!allow_tail_call_in_subprogs(env))
12464                                 prog->aux->stack_depth = MAX_BPF_STACK;
12465                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
12466
12467                         /* mark bpf_tail_call as different opcode to avoid
12468                          * conditional branch in the interpeter for every normal
12469                          * call and to prevent accidental JITing by JIT compiler
12470                          * that doesn't support bpf_tail_call yet
12471                          */
12472                         insn->imm = 0;
12473                         insn->code = BPF_JMP | BPF_TAIL_CALL;
12474
12475                         aux = &env->insn_aux_data[i + delta];
12476                         if (env->bpf_capable && !expect_blinding &&
12477                             prog->jit_requested &&
12478                             !bpf_map_key_poisoned(aux) &&
12479                             !bpf_map_ptr_poisoned(aux) &&
12480                             !bpf_map_ptr_unpriv(aux)) {
12481                                 struct bpf_jit_poke_descriptor desc = {
12482                                         .reason = BPF_POKE_REASON_TAIL_CALL,
12483                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12484                                         .tail_call.key = bpf_map_key_immediate(aux),
12485                                         .insn_idx = i + delta,
12486                                 };
12487
12488                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12489                                 if (ret < 0) {
12490                                         verbose(env, "adding tail call poke descriptor failed\n");
12491                                         return ret;
12492                                 }
12493
12494                                 insn->imm = ret + 1;
12495                                 continue;
12496                         }
12497
12498                         if (!bpf_map_ptr_unpriv(aux))
12499                                 continue;
12500
12501                         /* instead of changing every JIT dealing with tail_call
12502                          * emit two extra insns:
12503                          * if (index >= max_entries) goto out;
12504                          * index &= array->index_mask;
12505                          * to avoid out-of-bounds cpu speculation
12506                          */
12507                         if (bpf_map_ptr_poisoned(aux)) {
12508                                 verbose(env, "tail_call abusing map_ptr\n");
12509                                 return -EINVAL;
12510                         }
12511
12512                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12513                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12514                                                   map_ptr->max_entries, 2);
12515                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12516                                                     container_of(map_ptr,
12517                                                                  struct bpf_array,
12518                                                                  map)->index_mask);
12519                         insn_buf[2] = *insn;
12520                         cnt = 3;
12521                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12522                         if (!new_prog)
12523                                 return -ENOMEM;
12524
12525                         delta    += cnt - 1;
12526                         env->prog = prog = new_prog;
12527                         insn      = new_prog->insnsi + i + delta;
12528                         continue;
12529                 }
12530
12531                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
12532                  * and other inlining handlers are currently limited to 64 bit
12533                  * only.
12534                  */
12535                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12536                     (insn->imm == BPF_FUNC_map_lookup_elem ||
12537                      insn->imm == BPF_FUNC_map_update_elem ||
12538                      insn->imm == BPF_FUNC_map_delete_elem ||
12539                      insn->imm == BPF_FUNC_map_push_elem   ||
12540                      insn->imm == BPF_FUNC_map_pop_elem    ||
12541                      insn->imm == BPF_FUNC_map_peek_elem   ||
12542                      insn->imm == BPF_FUNC_redirect_map)) {
12543                         aux = &env->insn_aux_data[i + delta];
12544                         if (bpf_map_ptr_poisoned(aux))
12545                                 goto patch_call_imm;
12546
12547                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12548                         ops = map_ptr->ops;
12549                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
12550                             ops->map_gen_lookup) {
12551                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
12552                                 if (cnt == -EOPNOTSUPP)
12553                                         goto patch_map_ops_generic;
12554                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12555                                         verbose(env, "bpf verifier is misconfigured\n");
12556                                         return -EINVAL;
12557                                 }
12558
12559                                 new_prog = bpf_patch_insn_data(env, i + delta,
12560                                                                insn_buf, cnt);
12561                                 if (!new_prog)
12562                                         return -ENOMEM;
12563
12564                                 delta    += cnt - 1;
12565                                 env->prog = prog = new_prog;
12566                                 insn      = new_prog->insnsi + i + delta;
12567                                 continue;
12568                         }
12569
12570                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12571                                      (void *(*)(struct bpf_map *map, void *key))NULL));
12572                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12573                                      (int (*)(struct bpf_map *map, void *key))NULL));
12574                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12575                                      (int (*)(struct bpf_map *map, void *key, void *value,
12576                                               u64 flags))NULL));
12577                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12578                                      (int (*)(struct bpf_map *map, void *value,
12579                                               u64 flags))NULL));
12580                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12581                                      (int (*)(struct bpf_map *map, void *value))NULL));
12582                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12583                                      (int (*)(struct bpf_map *map, void *value))NULL));
12584                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
12585                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12586
12587 patch_map_ops_generic:
12588                         switch (insn->imm) {
12589                         case BPF_FUNC_map_lookup_elem:
12590                                 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12591                                             __bpf_call_base;
12592                                 continue;
12593                         case BPF_FUNC_map_update_elem:
12594                                 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12595                                             __bpf_call_base;
12596                                 continue;
12597                         case BPF_FUNC_map_delete_elem:
12598                                 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12599                                             __bpf_call_base;
12600                                 continue;
12601                         case BPF_FUNC_map_push_elem:
12602                                 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12603                                             __bpf_call_base;
12604                                 continue;
12605                         case BPF_FUNC_map_pop_elem:
12606                                 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12607                                             __bpf_call_base;
12608                                 continue;
12609                         case BPF_FUNC_map_peek_elem:
12610                                 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12611                                             __bpf_call_base;
12612                                 continue;
12613                         case BPF_FUNC_redirect_map:
12614                                 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12615                                             __bpf_call_base;
12616                                 continue;
12617                         }
12618
12619                         goto patch_call_imm;
12620                 }
12621
12622                 /* Implement bpf_jiffies64 inline. */
12623                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12624                     insn->imm == BPF_FUNC_jiffies64) {
12625                         struct bpf_insn ld_jiffies_addr[2] = {
12626                                 BPF_LD_IMM64(BPF_REG_0,
12627                                              (unsigned long)&jiffies),
12628                         };
12629
12630                         insn_buf[0] = ld_jiffies_addr[0];
12631                         insn_buf[1] = ld_jiffies_addr[1];
12632                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12633                                                   BPF_REG_0, 0);
12634                         cnt = 3;
12635
12636                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12637                                                        cnt);
12638                         if (!new_prog)
12639                                 return -ENOMEM;
12640
12641                         delta    += cnt - 1;
12642                         env->prog = prog = new_prog;
12643                         insn      = new_prog->insnsi + i + delta;
12644                         continue;
12645                 }
12646
12647 patch_call_imm:
12648                 fn = env->ops->get_func_proto(insn->imm, env->prog);
12649                 /* all functions that have prototype and verifier allowed
12650                  * programs to call them, must be real in-kernel functions
12651                  */
12652                 if (!fn->func) {
12653                         verbose(env,
12654                                 "kernel subsystem misconfigured func %s#%d\n",
12655                                 func_id_name(insn->imm), insn->imm);
12656                         return -EFAULT;
12657                 }
12658                 insn->imm = fn->func - __bpf_call_base;
12659         }
12660
12661         /* Since poke tab is now finalized, publish aux to tracker. */
12662         for (i = 0; i < prog->aux->size_poke_tab; i++) {
12663                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12664                 if (!map_ptr->ops->map_poke_track ||
12665                     !map_ptr->ops->map_poke_untrack ||
12666                     !map_ptr->ops->map_poke_run) {
12667                         verbose(env, "bpf verifier is misconfigured\n");
12668                         return -EINVAL;
12669                 }
12670
12671                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12672                 if (ret < 0) {
12673                         verbose(env, "tracking tail call prog failed\n");
12674                         return ret;
12675                 }
12676         }
12677
12678         sort_kfunc_descs_by_imm(env->prog);
12679
12680         return 0;
12681 }
12682
12683 static void free_states(struct bpf_verifier_env *env)
12684 {
12685         struct bpf_verifier_state_list *sl, *sln;
12686         int i;
12687
12688         sl = env->free_list;
12689         while (sl) {
12690                 sln = sl->next;
12691                 free_verifier_state(&sl->state, false);
12692                 kfree(sl);
12693                 sl = sln;
12694         }
12695         env->free_list = NULL;
12696
12697         if (!env->explored_states)
12698                 return;
12699
12700         for (i = 0; i < state_htab_size(env); i++) {
12701                 sl = env->explored_states[i];
12702
12703                 while (sl) {
12704                         sln = sl->next;
12705                         free_verifier_state(&sl->state, false);
12706                         kfree(sl);
12707                         sl = sln;
12708                 }
12709                 env->explored_states[i] = NULL;
12710         }
12711 }
12712
12713 static int do_check_common(struct bpf_verifier_env *env, int subprog)
12714 {
12715         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12716         struct bpf_verifier_state *state;
12717         struct bpf_reg_state *regs;
12718         int ret, i;
12719
12720         env->prev_linfo = NULL;
12721         env->pass_cnt++;
12722
12723         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12724         if (!state)
12725                 return -ENOMEM;
12726         state->curframe = 0;
12727         state->speculative = false;
12728         state->branches = 1;
12729         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12730         if (!state->frame[0]) {
12731                 kfree(state);
12732                 return -ENOMEM;
12733         }
12734         env->cur_state = state;
12735         init_func_state(env, state->frame[0],
12736                         BPF_MAIN_FUNC /* callsite */,
12737                         0 /* frameno */,
12738                         subprog);
12739
12740         regs = state->frame[state->curframe]->regs;
12741         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12742                 ret = btf_prepare_func_args(env, subprog, regs);
12743                 if (ret)
12744                         goto out;
12745                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12746                         if (regs[i].type == PTR_TO_CTX)
12747                                 mark_reg_known_zero(env, regs, i);
12748                         else if (regs[i].type == SCALAR_VALUE)
12749                                 mark_reg_unknown(env, regs, i);
12750                         else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12751                                 const u32 mem_size = regs[i].mem_size;
12752
12753                                 mark_reg_known_zero(env, regs, i);
12754                                 regs[i].mem_size = mem_size;
12755                                 regs[i].id = ++env->id_gen;
12756                         }
12757                 }
12758         } else {
12759                 /* 1st arg to a function */
12760                 regs[BPF_REG_1].type = PTR_TO_CTX;
12761                 mark_reg_known_zero(env, regs, BPF_REG_1);
12762                 ret = btf_check_subprog_arg_match(env, subprog, regs);
12763                 if (ret == -EFAULT)
12764                         /* unlikely verifier bug. abort.
12765                          * ret == 0 and ret < 0 are sadly acceptable for
12766                          * main() function due to backward compatibility.
12767                          * Like socket filter program may be written as:
12768                          * int bpf_prog(struct pt_regs *ctx)
12769                          * and never dereference that ctx in the program.
12770                          * 'struct pt_regs' is a type mismatch for socket
12771                          * filter that should be using 'struct __sk_buff'.
12772                          */
12773                         goto out;
12774         }
12775
12776         ret = do_check(env);
12777 out:
12778         /* check for NULL is necessary, since cur_state can be freed inside
12779          * do_check() under memory pressure.
12780          */
12781         if (env->cur_state) {
12782                 free_verifier_state(env->cur_state, true);
12783                 env->cur_state = NULL;
12784         }
12785         while (!pop_stack(env, NULL, NULL, false));
12786         if (!ret && pop_log)
12787                 bpf_vlog_reset(&env->log, 0);
12788         free_states(env);
12789         return ret;
12790 }
12791
12792 /* Verify all global functions in a BPF program one by one based on their BTF.
12793  * All global functions must pass verification. Otherwise the whole program is rejected.
12794  * Consider:
12795  * int bar(int);
12796  * int foo(int f)
12797  * {
12798  *    return bar(f);
12799  * }
12800  * int bar(int b)
12801  * {
12802  *    ...
12803  * }
12804  * foo() will be verified first for R1=any_scalar_value. During verification it
12805  * will be assumed that bar() already verified successfully and call to bar()
12806  * from foo() will be checked for type match only. Later bar() will be verified
12807  * independently to check that it's safe for R1=any_scalar_value.
12808  */
12809 static int do_check_subprogs(struct bpf_verifier_env *env)
12810 {
12811         struct bpf_prog_aux *aux = env->prog->aux;
12812         int i, ret;
12813
12814         if (!aux->func_info)
12815                 return 0;
12816
12817         for (i = 1; i < env->subprog_cnt; i++) {
12818                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12819                         continue;
12820                 env->insn_idx = env->subprog_info[i].start;
12821                 WARN_ON_ONCE(env->insn_idx == 0);
12822                 ret = do_check_common(env, i);
12823                 if (ret) {
12824                         return ret;
12825                 } else if (env->log.level & BPF_LOG_LEVEL) {
12826                         verbose(env,
12827                                 "Func#%d is safe for any args that match its prototype\n",
12828                                 i);
12829                 }
12830         }
12831         return 0;
12832 }
12833
12834 static int do_check_main(struct bpf_verifier_env *env)
12835 {
12836         int ret;
12837
12838         env->insn_idx = 0;
12839         ret = do_check_common(env, 0);
12840         if (!ret)
12841                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12842         return ret;
12843 }
12844
12845
12846 static void print_verification_stats(struct bpf_verifier_env *env)
12847 {
12848         int i;
12849
12850         if (env->log.level & BPF_LOG_STATS) {
12851                 verbose(env, "verification time %lld usec\n",
12852                         div_u64(env->verification_time, 1000));
12853                 verbose(env, "stack depth ");
12854                 for (i = 0; i < env->subprog_cnt; i++) {
12855                         u32 depth = env->subprog_info[i].stack_depth;
12856
12857                         verbose(env, "%d", depth);
12858                         if (i + 1 < env->subprog_cnt)
12859                                 verbose(env, "+");
12860                 }
12861                 verbose(env, "\n");
12862         }
12863         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12864                 "total_states %d peak_states %d mark_read %d\n",
12865                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12866                 env->max_states_per_insn, env->total_states,
12867                 env->peak_states, env->longest_mark_read_walk);
12868 }
12869
12870 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12871 {
12872         const struct btf_type *t, *func_proto;
12873         const struct bpf_struct_ops *st_ops;
12874         const struct btf_member *member;
12875         struct bpf_prog *prog = env->prog;
12876         u32 btf_id, member_idx;
12877         const char *mname;
12878
12879         if (!prog->gpl_compatible) {
12880                 verbose(env, "struct ops programs must have a GPL compatible license\n");
12881                 return -EINVAL;
12882         }
12883
12884         btf_id = prog->aux->attach_btf_id;
12885         st_ops = bpf_struct_ops_find(btf_id);
12886         if (!st_ops) {
12887                 verbose(env, "attach_btf_id %u is not a supported struct\n",
12888                         btf_id);
12889                 return -ENOTSUPP;
12890         }
12891
12892         t = st_ops->type;
12893         member_idx = prog->expected_attach_type;
12894         if (member_idx >= btf_type_vlen(t)) {
12895                 verbose(env, "attach to invalid member idx %u of struct %s\n",
12896                         member_idx, st_ops->name);
12897                 return -EINVAL;
12898         }
12899
12900         member = &btf_type_member(t)[member_idx];
12901         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12902         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12903                                                NULL);
12904         if (!func_proto) {
12905                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12906                         mname, member_idx, st_ops->name);
12907                 return -EINVAL;
12908         }
12909
12910         if (st_ops->check_member) {
12911                 int err = st_ops->check_member(t, member);
12912
12913                 if (err) {
12914                         verbose(env, "attach to unsupported member %s of struct %s\n",
12915                                 mname, st_ops->name);
12916                         return err;
12917                 }
12918         }
12919
12920         prog->aux->attach_func_proto = func_proto;
12921         prog->aux->attach_func_name = mname;
12922         env->ops = st_ops->verifier_ops;
12923
12924         return 0;
12925 }
12926 #define SECURITY_PREFIX "security_"
12927
12928 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12929 {
12930         if (within_error_injection_list(addr) ||
12931             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12932                 return 0;
12933
12934         return -EINVAL;
12935 }
12936
12937 /* list of non-sleepable functions that are otherwise on
12938  * ALLOW_ERROR_INJECTION list
12939  */
12940 BTF_SET_START(btf_non_sleepable_error_inject)
12941 /* Three functions below can be called from sleepable and non-sleepable context.
12942  * Assume non-sleepable from bpf safety point of view.
12943  */
12944 BTF_ID(func, __add_to_page_cache_locked)
12945 BTF_ID(func, should_fail_alloc_page)
12946 BTF_ID(func, should_failslab)
12947 BTF_SET_END(btf_non_sleepable_error_inject)
12948
12949 static int check_non_sleepable_error_inject(u32 btf_id)
12950 {
12951         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12952 }
12953
12954 int bpf_check_attach_target(struct bpf_verifier_log *log,
12955                             const struct bpf_prog *prog,
12956                             const struct bpf_prog *tgt_prog,
12957                             u32 btf_id,
12958                             struct bpf_attach_target_info *tgt_info)
12959 {
12960         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12961         const char prefix[] = "btf_trace_";
12962         int ret = 0, subprog = -1, i;
12963         const struct btf_type *t;
12964         bool conservative = true;
12965         const char *tname;
12966         struct btf *btf;
12967         long addr = 0;
12968
12969         if (!btf_id) {
12970                 bpf_log(log, "Tracing programs must provide btf_id\n");
12971                 return -EINVAL;
12972         }
12973         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
12974         if (!btf) {
12975                 bpf_log(log,
12976                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12977                 return -EINVAL;
12978         }
12979         t = btf_type_by_id(btf, btf_id);
12980         if (!t) {
12981                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12982                 return -EINVAL;
12983         }
12984         tname = btf_name_by_offset(btf, t->name_off);
12985         if (!tname) {
12986                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12987                 return -EINVAL;
12988         }
12989         if (tgt_prog) {
12990                 struct bpf_prog_aux *aux = tgt_prog->aux;
12991
12992                 for (i = 0; i < aux->func_info_cnt; i++)
12993                         if (aux->func_info[i].type_id == btf_id) {
12994                                 subprog = i;
12995                                 break;
12996                         }
12997                 if (subprog == -1) {
12998                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
12999                         return -EINVAL;
13000                 }
13001                 conservative = aux->func_info_aux[subprog].unreliable;
13002                 if (prog_extension) {
13003                         if (conservative) {
13004                                 bpf_log(log,
13005                                         "Cannot replace static functions\n");
13006                                 return -EINVAL;
13007                         }
13008                         if (!prog->jit_requested) {
13009                                 bpf_log(log,
13010                                         "Extension programs should be JITed\n");
13011                                 return -EINVAL;
13012                         }
13013                 }
13014                 if (!tgt_prog->jited) {
13015                         bpf_log(log, "Can attach to only JITed progs\n");
13016                         return -EINVAL;
13017                 }
13018                 if (tgt_prog->type == prog->type) {
13019                         /* Cannot fentry/fexit another fentry/fexit program.
13020                          * Cannot attach program extension to another extension.
13021                          * It's ok to attach fentry/fexit to extension program.
13022                          */
13023                         bpf_log(log, "Cannot recursively attach\n");
13024                         return -EINVAL;
13025                 }
13026                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13027                     prog_extension &&
13028                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13029                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13030                         /* Program extensions can extend all program types
13031                          * except fentry/fexit. The reason is the following.
13032                          * The fentry/fexit programs are used for performance
13033                          * analysis, stats and can be attached to any program
13034                          * type except themselves. When extension program is
13035                          * replacing XDP function it is necessary to allow
13036                          * performance analysis of all functions. Both original
13037                          * XDP program and its program extension. Hence
13038                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13039                          * allowed. If extending of fentry/fexit was allowed it
13040                          * would be possible to create long call chain
13041                          * fentry->extension->fentry->extension beyond
13042                          * reasonable stack size. Hence extending fentry is not
13043                          * allowed.
13044                          */
13045                         bpf_log(log, "Cannot extend fentry/fexit\n");
13046                         return -EINVAL;
13047                 }
13048         } else {
13049                 if (prog_extension) {
13050                         bpf_log(log, "Cannot replace kernel functions\n");
13051                         return -EINVAL;
13052                 }
13053         }
13054
13055         switch (prog->expected_attach_type) {
13056         case BPF_TRACE_RAW_TP:
13057                 if (tgt_prog) {
13058                         bpf_log(log,
13059                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13060                         return -EINVAL;
13061                 }
13062                 if (!btf_type_is_typedef(t)) {
13063                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
13064                                 btf_id);
13065                         return -EINVAL;
13066                 }
13067                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13068                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13069                                 btf_id, tname);
13070                         return -EINVAL;
13071                 }
13072                 tname += sizeof(prefix) - 1;
13073                 t = btf_type_by_id(btf, t->type);
13074                 if (!btf_type_is_ptr(t))
13075                         /* should never happen in valid vmlinux build */
13076                         return -EINVAL;
13077                 t = btf_type_by_id(btf, t->type);
13078                 if (!btf_type_is_func_proto(t))
13079                         /* should never happen in valid vmlinux build */
13080                         return -EINVAL;
13081
13082                 break;
13083         case BPF_TRACE_ITER:
13084                 if (!btf_type_is_func(t)) {
13085                         bpf_log(log, "attach_btf_id %u is not a function\n",
13086                                 btf_id);
13087                         return -EINVAL;
13088                 }
13089                 t = btf_type_by_id(btf, t->type);
13090                 if (!btf_type_is_func_proto(t))
13091                         return -EINVAL;
13092                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13093                 if (ret)
13094                         return ret;
13095                 break;
13096         default:
13097                 if (!prog_extension)
13098                         return -EINVAL;
13099                 fallthrough;
13100         case BPF_MODIFY_RETURN:
13101         case BPF_LSM_MAC:
13102         case BPF_TRACE_FENTRY:
13103         case BPF_TRACE_FEXIT:
13104                 if (!btf_type_is_func(t)) {
13105                         bpf_log(log, "attach_btf_id %u is not a function\n",
13106                                 btf_id);
13107                         return -EINVAL;
13108                 }
13109                 if (prog_extension &&
13110                     btf_check_type_match(log, prog, btf, t))
13111                         return -EINVAL;
13112                 t = btf_type_by_id(btf, t->type);
13113                 if (!btf_type_is_func_proto(t))
13114                         return -EINVAL;
13115
13116                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13117                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13118                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13119                         return -EINVAL;
13120
13121                 if (tgt_prog && conservative)
13122                         t = NULL;
13123
13124                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13125                 if (ret < 0)
13126                         return ret;
13127
13128                 if (tgt_prog) {
13129                         if (subprog == 0)
13130                                 addr = (long) tgt_prog->bpf_func;
13131                         else
13132                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13133                 } else {
13134                         addr = kallsyms_lookup_name(tname);
13135                         if (!addr) {
13136                                 bpf_log(log,
13137                                         "The address of function %s cannot be found\n",
13138                                         tname);
13139                                 return -ENOENT;
13140                         }
13141                 }
13142
13143                 if (prog->aux->sleepable) {
13144                         ret = -EINVAL;
13145                         switch (prog->type) {
13146                         case BPF_PROG_TYPE_TRACING:
13147                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13148                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13149                                  */
13150                                 if (!check_non_sleepable_error_inject(btf_id) &&
13151                                     within_error_injection_list(addr))
13152                                         ret = 0;
13153                                 break;
13154                         case BPF_PROG_TYPE_LSM:
13155                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13156                                  * Only some of them are sleepable.
13157                                  */
13158                                 if (bpf_lsm_is_sleepable_hook(btf_id))
13159                                         ret = 0;
13160                                 break;
13161                         default:
13162                                 break;
13163                         }
13164                         if (ret) {
13165                                 bpf_log(log, "%s is not sleepable\n", tname);
13166                                 return ret;
13167                         }
13168                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13169                         if (tgt_prog) {
13170                                 bpf_log(log, "can't modify return codes of BPF programs\n");
13171                                 return -EINVAL;
13172                         }
13173                         ret = check_attach_modify_return(addr, tname);
13174                         if (ret) {
13175                                 bpf_log(log, "%s() is not modifiable\n", tname);
13176                                 return ret;
13177                         }
13178                 }
13179
13180                 break;
13181         }
13182         tgt_info->tgt_addr = addr;
13183         tgt_info->tgt_name = tname;
13184         tgt_info->tgt_type = t;
13185         return 0;
13186 }
13187
13188 BTF_SET_START(btf_id_deny)
13189 BTF_ID_UNUSED
13190 #ifdef CONFIG_SMP
13191 BTF_ID(func, migrate_disable)
13192 BTF_ID(func, migrate_enable)
13193 #endif
13194 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13195 BTF_ID(func, rcu_read_unlock_strict)
13196 #endif
13197 BTF_SET_END(btf_id_deny)
13198
13199 static int check_attach_btf_id(struct bpf_verifier_env *env)
13200 {
13201         struct bpf_prog *prog = env->prog;
13202         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13203         struct bpf_attach_target_info tgt_info = {};
13204         u32 btf_id = prog->aux->attach_btf_id;
13205         struct bpf_trampoline *tr;
13206         int ret;
13207         u64 key;
13208
13209         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13210             prog->type != BPF_PROG_TYPE_LSM) {
13211                 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13212                 return -EINVAL;
13213         }
13214
13215         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13216                 return check_struct_ops_btf_id(env);
13217
13218         if (prog->type != BPF_PROG_TYPE_TRACING &&
13219             prog->type != BPF_PROG_TYPE_LSM &&
13220             prog->type != BPF_PROG_TYPE_EXT)
13221                 return 0;
13222
13223         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13224         if (ret)
13225                 return ret;
13226
13227         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13228                 /* to make freplace equivalent to their targets, they need to
13229                  * inherit env->ops and expected_attach_type for the rest of the
13230                  * verification
13231                  */
13232                 env->ops = bpf_verifier_ops[tgt_prog->type];
13233                 prog->expected_attach_type = tgt_prog->expected_attach_type;
13234         }
13235
13236         /* store info about the attachment target that will be used later */
13237         prog->aux->attach_func_proto = tgt_info.tgt_type;
13238         prog->aux->attach_func_name = tgt_info.tgt_name;
13239
13240         if (tgt_prog) {
13241                 prog->aux->saved_dst_prog_type = tgt_prog->type;
13242                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13243         }
13244
13245         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13246                 prog->aux->attach_btf_trace = true;
13247                 return 0;
13248         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13249                 if (!bpf_iter_prog_supported(prog))
13250                         return -EINVAL;
13251                 return 0;
13252         }
13253
13254         if (prog->type == BPF_PROG_TYPE_LSM) {
13255                 ret = bpf_lsm_verify_prog(&env->log, prog);
13256                 if (ret < 0)
13257                         return ret;
13258         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
13259                    btf_id_set_contains(&btf_id_deny, btf_id)) {
13260                 return -EINVAL;
13261         }
13262
13263         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13264         tr = bpf_trampoline_get(key, &tgt_info);
13265         if (!tr)
13266                 return -ENOMEM;
13267
13268         prog->aux->dst_trampoline = tr;
13269         return 0;
13270 }
13271
13272 struct btf *bpf_get_btf_vmlinux(void)
13273 {
13274         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13275                 mutex_lock(&bpf_verifier_lock);
13276                 if (!btf_vmlinux)
13277                         btf_vmlinux = btf_parse_vmlinux();
13278                 mutex_unlock(&bpf_verifier_lock);
13279         }
13280         return btf_vmlinux;
13281 }
13282
13283 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
13284               union bpf_attr __user *uattr)
13285 {
13286         u64 start_time = ktime_get_ns();
13287         struct bpf_verifier_env *env;
13288         struct bpf_verifier_log *log;
13289         int i, len, ret = -EINVAL;
13290         bool is_priv;
13291
13292         /* no program is valid */
13293         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13294                 return -EINVAL;
13295
13296         /* 'struct bpf_verifier_env' can be global, but since it's not small,
13297          * allocate/free it every time bpf_check() is called
13298          */
13299         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13300         if (!env)
13301                 return -ENOMEM;
13302         log = &env->log;
13303
13304         len = (*prog)->len;
13305         env->insn_aux_data =
13306                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13307         ret = -ENOMEM;
13308         if (!env->insn_aux_data)
13309                 goto err_free_env;
13310         for (i = 0; i < len; i++)
13311                 env->insn_aux_data[i].orig_idx = i;
13312         env->prog = *prog;
13313         env->ops = bpf_verifier_ops[env->prog->type];
13314         is_priv = bpf_capable();
13315
13316         bpf_get_btf_vmlinux();
13317
13318         /* grab the mutex to protect few globals used by verifier */
13319         if (!is_priv)
13320                 mutex_lock(&bpf_verifier_lock);
13321
13322         if (attr->log_level || attr->log_buf || attr->log_size) {
13323                 /* user requested verbose verifier output
13324                  * and supplied buffer to store the verification trace
13325                  */
13326                 log->level = attr->log_level;
13327                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13328                 log->len_total = attr->log_size;
13329
13330                 ret = -EINVAL;
13331                 /* log attributes have to be sane */
13332                 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
13333                     !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
13334                         goto err_unlock;
13335         }
13336
13337         if (IS_ERR(btf_vmlinux)) {
13338                 /* Either gcc or pahole or kernel are broken. */
13339                 verbose(env, "in-kernel BTF is malformed\n");
13340                 ret = PTR_ERR(btf_vmlinux);
13341                 goto skip_full_check;
13342         }
13343
13344         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13345         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13346                 env->strict_alignment = true;
13347         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13348                 env->strict_alignment = false;
13349
13350         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13351         env->allow_uninit_stack = bpf_allow_uninit_stack();
13352         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13353         env->bypass_spec_v1 = bpf_bypass_spec_v1();
13354         env->bypass_spec_v4 = bpf_bypass_spec_v4();
13355         env->bpf_capable = bpf_capable();
13356
13357         if (is_priv)
13358                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13359
13360         env->explored_states = kvcalloc(state_htab_size(env),
13361                                        sizeof(struct bpf_verifier_state_list *),
13362                                        GFP_USER);
13363         ret = -ENOMEM;
13364         if (!env->explored_states)
13365                 goto skip_full_check;
13366
13367         ret = add_subprog_and_kfunc(env);
13368         if (ret < 0)
13369                 goto skip_full_check;
13370
13371         ret = check_subprogs(env);
13372         if (ret < 0)
13373                 goto skip_full_check;
13374
13375         ret = check_btf_info(env, attr, uattr);
13376         if (ret < 0)
13377                 goto skip_full_check;
13378
13379         ret = check_attach_btf_id(env);
13380         if (ret)
13381                 goto skip_full_check;
13382
13383         ret = resolve_pseudo_ldimm64(env);
13384         if (ret < 0)
13385                 goto skip_full_check;
13386
13387         if (bpf_prog_is_dev_bound(env->prog->aux)) {
13388                 ret = bpf_prog_offload_verifier_prep(env->prog);
13389                 if (ret)
13390                         goto skip_full_check;
13391         }
13392
13393         ret = check_cfg(env);
13394         if (ret < 0)
13395                 goto skip_full_check;
13396
13397         ret = do_check_subprogs(env);
13398         ret = ret ?: do_check_main(env);
13399
13400         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13401                 ret = bpf_prog_offload_finalize(env);
13402
13403 skip_full_check:
13404         kvfree(env->explored_states);
13405
13406         if (ret == 0)
13407                 ret = check_max_stack_depth(env);
13408
13409         /* instruction rewrites happen after this point */
13410         if (is_priv) {
13411                 if (ret == 0)
13412                         opt_hard_wire_dead_code_branches(env);
13413                 if (ret == 0)
13414                         ret = opt_remove_dead_code(env);
13415                 if (ret == 0)
13416                         ret = opt_remove_nops(env);
13417         } else {
13418                 if (ret == 0)
13419                         sanitize_dead_code(env);
13420         }
13421
13422         if (ret == 0)
13423                 /* program is valid, convert *(u32*)(ctx + off) accesses */
13424                 ret = convert_ctx_accesses(env);
13425
13426         if (ret == 0)
13427                 ret = do_misc_fixups(env);
13428
13429         /* do 32-bit optimization after insn patching has done so those patched
13430          * insns could be handled correctly.
13431          */
13432         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13433                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13434                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13435                                                                      : false;
13436         }
13437
13438         if (ret == 0)
13439                 ret = fixup_call_args(env);
13440
13441         env->verification_time = ktime_get_ns() - start_time;
13442         print_verification_stats(env);
13443
13444         if (log->level && bpf_verifier_log_full(log))
13445                 ret = -ENOSPC;
13446         if (log->level && !log->ubuf) {
13447                 ret = -EFAULT;
13448                 goto err_release_maps;
13449         }
13450
13451         if (ret)
13452                 goto err_release_maps;
13453
13454         if (env->used_map_cnt) {
13455                 /* if program passed verifier, update used_maps in bpf_prog_info */
13456                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13457                                                           sizeof(env->used_maps[0]),
13458                                                           GFP_KERNEL);
13459
13460                 if (!env->prog->aux->used_maps) {
13461                         ret = -ENOMEM;
13462                         goto err_release_maps;
13463                 }
13464
13465                 memcpy(env->prog->aux->used_maps, env->used_maps,
13466                        sizeof(env->used_maps[0]) * env->used_map_cnt);
13467                 env->prog->aux->used_map_cnt = env->used_map_cnt;
13468         }
13469         if (env->used_btf_cnt) {
13470                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13471                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13472                                                           sizeof(env->used_btfs[0]),
13473                                                           GFP_KERNEL);
13474                 if (!env->prog->aux->used_btfs) {
13475                         ret = -ENOMEM;
13476                         goto err_release_maps;
13477                 }
13478
13479                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13480                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13481                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13482         }
13483         if (env->used_map_cnt || env->used_btf_cnt) {
13484                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13485                  * bpf_ld_imm64 instructions
13486                  */
13487                 convert_pseudo_ld_imm64(env);
13488         }
13489
13490         adjust_btf_func(env);
13491
13492 err_release_maps:
13493         if (!env->prog->aux->used_maps)
13494                 /* if we didn't copy map pointers into bpf_prog_info, release
13495                  * them now. Otherwise free_used_maps() will release them.
13496                  */
13497                 release_maps(env);
13498         if (!env->prog->aux->used_btfs)
13499                 release_btfs(env);
13500
13501         /* extension progs temporarily inherit the attach_type of their targets
13502            for verification purposes, so set it back to zero before returning
13503          */
13504         if (env->prog->type == BPF_PROG_TYPE_EXT)
13505                 env->prog->expected_attach_type = 0;
13506
13507         *prog = env->prog;
13508 err_unlock:
13509         if (!is_priv)
13510                 mutex_unlock(&bpf_verifier_lock);
13511         vfree(env->insn_aux_data);
13512 err_free_env:
13513         kfree(env);
13514         return ret;
13515 }