bpf: Add get_func_[arg|ret|arg_cnt] helpers
[platform/kernel/linux-starfive.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 paths 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 either 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 struct bpf_call_arg_meta {
244         struct bpf_map *map_ptr;
245         bool raw_mode;
246         bool pkt_access;
247         int regno;
248         int access_size;
249         int mem_size;
250         u64 msize_max_value;
251         int ref_obj_id;
252         int map_uid;
253         int func_id;
254         struct btf *btf;
255         u32 btf_id;
256         struct btf *ret_btf;
257         u32 ret_btf_id;
258         u32 subprogno;
259 };
260
261 struct btf *btf_vmlinux;
262
263 static DEFINE_MUTEX(bpf_verifier_lock);
264
265 static const struct bpf_line_info *
266 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
267 {
268         const struct bpf_line_info *linfo;
269         const struct bpf_prog *prog;
270         u32 i, nr_linfo;
271
272         prog = env->prog;
273         nr_linfo = prog->aux->nr_linfo;
274
275         if (!nr_linfo || insn_off >= prog->len)
276                 return NULL;
277
278         linfo = prog->aux->linfo;
279         for (i = 1; i < nr_linfo; i++)
280                 if (insn_off < linfo[i].insn_off)
281                         break;
282
283         return &linfo[i - 1];
284 }
285
286 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
287                        va_list args)
288 {
289         unsigned int n;
290
291         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
292
293         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
294                   "verifier log line truncated - local buffer too short\n");
295
296         if (log->level == BPF_LOG_KERNEL) {
297                 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
298
299                 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
300                 return;
301         }
302
303         n = min(log->len_total - log->len_used - 1, n);
304         log->kbuf[n] = '\0';
305         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
306                 log->len_used += n;
307         else
308                 log->ubuf = NULL;
309 }
310
311 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
312 {
313         char zero = 0;
314
315         if (!bpf_verifier_log_needed(log))
316                 return;
317
318         log->len_used = new_pos;
319         if (put_user(zero, log->ubuf + new_pos))
320                 log->ubuf = NULL;
321 }
322
323 /* log_level controls verbosity level of eBPF verifier.
324  * bpf_verifier_log_write() is used to dump the verification trace to the log,
325  * so the user can figure out what's wrong with the program
326  */
327 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
328                                            const char *fmt, ...)
329 {
330         va_list args;
331
332         if (!bpf_verifier_log_needed(&env->log))
333                 return;
334
335         va_start(args, fmt);
336         bpf_verifier_vlog(&env->log, fmt, args);
337         va_end(args);
338 }
339 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
340
341 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
342 {
343         struct bpf_verifier_env *env = private_data;
344         va_list args;
345
346         if (!bpf_verifier_log_needed(&env->log))
347                 return;
348
349         va_start(args, fmt);
350         bpf_verifier_vlog(&env->log, fmt, args);
351         va_end(args);
352 }
353
354 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
355                             const char *fmt, ...)
356 {
357         va_list args;
358
359         if (!bpf_verifier_log_needed(log))
360                 return;
361
362         va_start(args, fmt);
363         bpf_verifier_vlog(log, fmt, args);
364         va_end(args);
365 }
366
367 static const char *ltrim(const char *s)
368 {
369         while (isspace(*s))
370                 s++;
371
372         return s;
373 }
374
375 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
376                                          u32 insn_off,
377                                          const char *prefix_fmt, ...)
378 {
379         const struct bpf_line_info *linfo;
380
381         if (!bpf_verifier_log_needed(&env->log))
382                 return;
383
384         linfo = find_linfo(env, insn_off);
385         if (!linfo || linfo == env->prev_linfo)
386                 return;
387
388         if (prefix_fmt) {
389                 va_list args;
390
391                 va_start(args, prefix_fmt);
392                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
393                 va_end(args);
394         }
395
396         verbose(env, "%s\n",
397                 ltrim(btf_name_by_offset(env->prog->aux->btf,
398                                          linfo->line_off)));
399
400         env->prev_linfo = linfo;
401 }
402
403 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
404                                    struct bpf_reg_state *reg,
405                                    struct tnum *range, const char *ctx,
406                                    const char *reg_name)
407 {
408         char tn_buf[48];
409
410         verbose(env, "At %s the register %s ", ctx, reg_name);
411         if (!tnum_is_unknown(reg->var_off)) {
412                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
413                 verbose(env, "has value %s", tn_buf);
414         } else {
415                 verbose(env, "has unknown scalar value");
416         }
417         tnum_strn(tn_buf, sizeof(tn_buf), *range);
418         verbose(env, " should have been in %s\n", tn_buf);
419 }
420
421 static bool type_is_pkt_pointer(enum bpf_reg_type type)
422 {
423         return type == PTR_TO_PACKET ||
424                type == PTR_TO_PACKET_META;
425 }
426
427 static bool type_is_sk_pointer(enum bpf_reg_type type)
428 {
429         return type == PTR_TO_SOCKET ||
430                 type == PTR_TO_SOCK_COMMON ||
431                 type == PTR_TO_TCP_SOCK ||
432                 type == PTR_TO_XDP_SOCK;
433 }
434
435 static bool reg_type_not_null(enum bpf_reg_type type)
436 {
437         return type == PTR_TO_SOCKET ||
438                 type == PTR_TO_TCP_SOCK ||
439                 type == PTR_TO_MAP_VALUE ||
440                 type == PTR_TO_MAP_KEY ||
441                 type == PTR_TO_SOCK_COMMON;
442 }
443
444 static bool reg_type_may_be_null(enum bpf_reg_type type)
445 {
446         return type == PTR_TO_MAP_VALUE_OR_NULL ||
447                type == PTR_TO_SOCKET_OR_NULL ||
448                type == PTR_TO_SOCK_COMMON_OR_NULL ||
449                type == PTR_TO_TCP_SOCK_OR_NULL ||
450                type == PTR_TO_BTF_ID_OR_NULL ||
451                type == PTR_TO_MEM_OR_NULL ||
452                type == PTR_TO_RDONLY_BUF_OR_NULL ||
453                type == PTR_TO_RDWR_BUF_OR_NULL;
454 }
455
456 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
457 {
458         return reg->type == PTR_TO_MAP_VALUE &&
459                 map_value_has_spin_lock(reg->map_ptr);
460 }
461
462 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
463 {
464         return type == PTR_TO_SOCKET ||
465                 type == PTR_TO_SOCKET_OR_NULL ||
466                 type == PTR_TO_TCP_SOCK ||
467                 type == PTR_TO_TCP_SOCK_OR_NULL ||
468                 type == PTR_TO_MEM ||
469                 type == PTR_TO_MEM_OR_NULL;
470 }
471
472 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
473 {
474         return type == ARG_PTR_TO_SOCK_COMMON;
475 }
476
477 static bool arg_type_may_be_null(enum bpf_arg_type type)
478 {
479         return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
480                type == ARG_PTR_TO_MEM_OR_NULL ||
481                type == ARG_PTR_TO_CTX_OR_NULL ||
482                type == ARG_PTR_TO_SOCKET_OR_NULL ||
483                type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
484                type == ARG_PTR_TO_STACK_OR_NULL;
485 }
486
487 /* Determine whether the function releases some resources allocated by another
488  * function call. The first reference type argument will be assumed to be
489  * released by release_reference().
490  */
491 static bool is_release_function(enum bpf_func_id func_id)
492 {
493         return func_id == BPF_FUNC_sk_release ||
494                func_id == BPF_FUNC_ringbuf_submit ||
495                func_id == BPF_FUNC_ringbuf_discard;
496 }
497
498 static bool may_be_acquire_function(enum bpf_func_id func_id)
499 {
500         return func_id == BPF_FUNC_sk_lookup_tcp ||
501                 func_id == BPF_FUNC_sk_lookup_udp ||
502                 func_id == BPF_FUNC_skc_lookup_tcp ||
503                 func_id == BPF_FUNC_map_lookup_elem ||
504                 func_id == BPF_FUNC_ringbuf_reserve;
505 }
506
507 static bool is_acquire_function(enum bpf_func_id func_id,
508                                 const struct bpf_map *map)
509 {
510         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
511
512         if (func_id == BPF_FUNC_sk_lookup_tcp ||
513             func_id == BPF_FUNC_sk_lookup_udp ||
514             func_id == BPF_FUNC_skc_lookup_tcp ||
515             func_id == BPF_FUNC_ringbuf_reserve)
516                 return true;
517
518         if (func_id == BPF_FUNC_map_lookup_elem &&
519             (map_type == BPF_MAP_TYPE_SOCKMAP ||
520              map_type == BPF_MAP_TYPE_SOCKHASH))
521                 return true;
522
523         return false;
524 }
525
526 static bool is_ptr_cast_function(enum bpf_func_id func_id)
527 {
528         return func_id == BPF_FUNC_tcp_sock ||
529                 func_id == BPF_FUNC_sk_fullsock ||
530                 func_id == BPF_FUNC_skc_to_tcp_sock ||
531                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
532                 func_id == BPF_FUNC_skc_to_udp6_sock ||
533                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
534                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
535 }
536
537 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
538 {
539         return BPF_CLASS(insn->code) == BPF_STX &&
540                BPF_MODE(insn->code) == BPF_ATOMIC &&
541                insn->imm == BPF_CMPXCHG;
542 }
543
544 /* string representation of 'enum bpf_reg_type' */
545 static const char * const reg_type_str[] = {
546         [NOT_INIT]              = "?",
547         [SCALAR_VALUE]          = "inv",
548         [PTR_TO_CTX]            = "ctx",
549         [CONST_PTR_TO_MAP]      = "map_ptr",
550         [PTR_TO_MAP_VALUE]      = "map_value",
551         [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
552         [PTR_TO_STACK]          = "fp",
553         [PTR_TO_PACKET]         = "pkt",
554         [PTR_TO_PACKET_META]    = "pkt_meta",
555         [PTR_TO_PACKET_END]     = "pkt_end",
556         [PTR_TO_FLOW_KEYS]      = "flow_keys",
557         [PTR_TO_SOCKET]         = "sock",
558         [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
559         [PTR_TO_SOCK_COMMON]    = "sock_common",
560         [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
561         [PTR_TO_TCP_SOCK]       = "tcp_sock",
562         [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
563         [PTR_TO_TP_BUFFER]      = "tp_buffer",
564         [PTR_TO_XDP_SOCK]       = "xdp_sock",
565         [PTR_TO_BTF_ID]         = "ptr_",
566         [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
567         [PTR_TO_PERCPU_BTF_ID]  = "percpu_ptr_",
568         [PTR_TO_MEM]            = "mem",
569         [PTR_TO_MEM_OR_NULL]    = "mem_or_null",
570         [PTR_TO_RDONLY_BUF]     = "rdonly_buf",
571         [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
572         [PTR_TO_RDWR_BUF]       = "rdwr_buf",
573         [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
574         [PTR_TO_FUNC]           = "func",
575         [PTR_TO_MAP_KEY]        = "map_key",
576 };
577
578 static char slot_type_char[] = {
579         [STACK_INVALID] = '?',
580         [STACK_SPILL]   = 'r',
581         [STACK_MISC]    = 'm',
582         [STACK_ZERO]    = '0',
583 };
584
585 static void print_liveness(struct bpf_verifier_env *env,
586                            enum bpf_reg_liveness live)
587 {
588         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
589             verbose(env, "_");
590         if (live & REG_LIVE_READ)
591                 verbose(env, "r");
592         if (live & REG_LIVE_WRITTEN)
593                 verbose(env, "w");
594         if (live & REG_LIVE_DONE)
595                 verbose(env, "D");
596 }
597
598 static struct bpf_func_state *func(struct bpf_verifier_env *env,
599                                    const struct bpf_reg_state *reg)
600 {
601         struct bpf_verifier_state *cur = env->cur_state;
602
603         return cur->frame[reg->frameno];
604 }
605
606 static const char *kernel_type_name(const struct btf* btf, u32 id)
607 {
608         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
609 }
610
611 /* The reg state of a pointer or a bounded scalar was saved when
612  * it was spilled to the stack.
613  */
614 static bool is_spilled_reg(const struct bpf_stack_state *stack)
615 {
616         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
617 }
618
619 static void scrub_spilled_slot(u8 *stype)
620 {
621         if (*stype != STACK_INVALID)
622                 *stype = STACK_MISC;
623 }
624
625 static void print_verifier_state(struct bpf_verifier_env *env,
626                                  const struct bpf_func_state *state)
627 {
628         const struct bpf_reg_state *reg;
629         enum bpf_reg_type t;
630         int i;
631
632         if (state->frameno)
633                 verbose(env, " frame%d:", state->frameno);
634         for (i = 0; i < MAX_BPF_REG; i++) {
635                 reg = &state->regs[i];
636                 t = reg->type;
637                 if (t == NOT_INIT)
638                         continue;
639                 verbose(env, " R%d", i);
640                 print_liveness(env, reg->live);
641                 verbose(env, "=%s", reg_type_str[t]);
642                 if (t == SCALAR_VALUE && reg->precise)
643                         verbose(env, "P");
644                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
645                     tnum_is_const(reg->var_off)) {
646                         /* reg->off should be 0 for SCALAR_VALUE */
647                         verbose(env, "%lld", reg->var_off.value + reg->off);
648                 } else {
649                         if (t == PTR_TO_BTF_ID ||
650                             t == PTR_TO_BTF_ID_OR_NULL ||
651                             t == PTR_TO_PERCPU_BTF_ID)
652                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
653                         verbose(env, "(id=%d", reg->id);
654                         if (reg_type_may_be_refcounted_or_null(t))
655                                 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
656                         if (t != SCALAR_VALUE)
657                                 verbose(env, ",off=%d", reg->off);
658                         if (type_is_pkt_pointer(t))
659                                 verbose(env, ",r=%d", reg->range);
660                         else if (t == CONST_PTR_TO_MAP ||
661                                  t == PTR_TO_MAP_KEY ||
662                                  t == PTR_TO_MAP_VALUE ||
663                                  t == PTR_TO_MAP_VALUE_OR_NULL)
664                                 verbose(env, ",ks=%d,vs=%d",
665                                         reg->map_ptr->key_size,
666                                         reg->map_ptr->value_size);
667                         if (tnum_is_const(reg->var_off)) {
668                                 /* Typically an immediate SCALAR_VALUE, but
669                                  * could be a pointer whose offset is too big
670                                  * for reg->off
671                                  */
672                                 verbose(env, ",imm=%llx", reg->var_off.value);
673                         } else {
674                                 if (reg->smin_value != reg->umin_value &&
675                                     reg->smin_value != S64_MIN)
676                                         verbose(env, ",smin_value=%lld",
677                                                 (long long)reg->smin_value);
678                                 if (reg->smax_value != reg->umax_value &&
679                                     reg->smax_value != S64_MAX)
680                                         verbose(env, ",smax_value=%lld",
681                                                 (long long)reg->smax_value);
682                                 if (reg->umin_value != 0)
683                                         verbose(env, ",umin_value=%llu",
684                                                 (unsigned long long)reg->umin_value);
685                                 if (reg->umax_value != U64_MAX)
686                                         verbose(env, ",umax_value=%llu",
687                                                 (unsigned long long)reg->umax_value);
688                                 if (!tnum_is_unknown(reg->var_off)) {
689                                         char tn_buf[48];
690
691                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
692                                         verbose(env, ",var_off=%s", tn_buf);
693                                 }
694                                 if (reg->s32_min_value != reg->smin_value &&
695                                     reg->s32_min_value != S32_MIN)
696                                         verbose(env, ",s32_min_value=%d",
697                                                 (int)(reg->s32_min_value));
698                                 if (reg->s32_max_value != reg->smax_value &&
699                                     reg->s32_max_value != S32_MAX)
700                                         verbose(env, ",s32_max_value=%d",
701                                                 (int)(reg->s32_max_value));
702                                 if (reg->u32_min_value != reg->umin_value &&
703                                     reg->u32_min_value != U32_MIN)
704                                         verbose(env, ",u32_min_value=%d",
705                                                 (int)(reg->u32_min_value));
706                                 if (reg->u32_max_value != reg->umax_value &&
707                                     reg->u32_max_value != U32_MAX)
708                                         verbose(env, ",u32_max_value=%d",
709                                                 (int)(reg->u32_max_value));
710                         }
711                         verbose(env, ")");
712                 }
713         }
714         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
715                 char types_buf[BPF_REG_SIZE + 1];
716                 bool valid = false;
717                 int j;
718
719                 for (j = 0; j < BPF_REG_SIZE; j++) {
720                         if (state->stack[i].slot_type[j] != STACK_INVALID)
721                                 valid = true;
722                         types_buf[j] = slot_type_char[
723                                         state->stack[i].slot_type[j]];
724                 }
725                 types_buf[BPF_REG_SIZE] = 0;
726                 if (!valid)
727                         continue;
728                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
729                 print_liveness(env, state->stack[i].spilled_ptr.live);
730                 if (is_spilled_reg(&state->stack[i])) {
731                         reg = &state->stack[i].spilled_ptr;
732                         t = reg->type;
733                         verbose(env, "=%s", reg_type_str[t]);
734                         if (t == SCALAR_VALUE && reg->precise)
735                                 verbose(env, "P");
736                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
737                                 verbose(env, "%lld", reg->var_off.value + reg->off);
738                 } else {
739                         verbose(env, "=%s", types_buf);
740                 }
741         }
742         if (state->acquired_refs && state->refs[0].id) {
743                 verbose(env, " refs=%d", state->refs[0].id);
744                 for (i = 1; i < state->acquired_refs; i++)
745                         if (state->refs[i].id)
746                                 verbose(env, ",%d", state->refs[i].id);
747         }
748         if (state->in_callback_fn)
749                 verbose(env, " cb");
750         if (state->in_async_callback_fn)
751                 verbose(env, " async_cb");
752         verbose(env, "\n");
753 }
754
755 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
756  * small to hold src. This is different from krealloc since we don't want to preserve
757  * the contents of dst.
758  *
759  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
760  * not be allocated.
761  */
762 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
763 {
764         size_t bytes;
765
766         if (ZERO_OR_NULL_PTR(src))
767                 goto out;
768
769         if (unlikely(check_mul_overflow(n, size, &bytes)))
770                 return NULL;
771
772         if (ksize(dst) < bytes) {
773                 kfree(dst);
774                 dst = kmalloc_track_caller(bytes, flags);
775                 if (!dst)
776                         return NULL;
777         }
778
779         memcpy(dst, src, bytes);
780 out:
781         return dst ? dst : ZERO_SIZE_PTR;
782 }
783
784 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
785  * small to hold new_n items. new items are zeroed out if the array grows.
786  *
787  * Contrary to krealloc_array, does not free arr if new_n is zero.
788  */
789 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
790 {
791         if (!new_n || old_n == new_n)
792                 goto out;
793
794         arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
795         if (!arr)
796                 return NULL;
797
798         if (new_n > old_n)
799                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
800
801 out:
802         return arr ? arr : ZERO_SIZE_PTR;
803 }
804
805 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
806 {
807         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
808                                sizeof(struct bpf_reference_state), GFP_KERNEL);
809         if (!dst->refs)
810                 return -ENOMEM;
811
812         dst->acquired_refs = src->acquired_refs;
813         return 0;
814 }
815
816 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
817 {
818         size_t n = src->allocated_stack / BPF_REG_SIZE;
819
820         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
821                                 GFP_KERNEL);
822         if (!dst->stack)
823                 return -ENOMEM;
824
825         dst->allocated_stack = src->allocated_stack;
826         return 0;
827 }
828
829 static int resize_reference_state(struct bpf_func_state *state, size_t n)
830 {
831         state->refs = realloc_array(state->refs, state->acquired_refs, n,
832                                     sizeof(struct bpf_reference_state));
833         if (!state->refs)
834                 return -ENOMEM;
835
836         state->acquired_refs = n;
837         return 0;
838 }
839
840 static int grow_stack_state(struct bpf_func_state *state, int size)
841 {
842         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
843
844         if (old_n >= n)
845                 return 0;
846
847         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
848         if (!state->stack)
849                 return -ENOMEM;
850
851         state->allocated_stack = size;
852         return 0;
853 }
854
855 /* Acquire a pointer id from the env and update the state->refs to include
856  * this new pointer reference.
857  * On success, returns a valid pointer id to associate with the register
858  * On failure, returns a negative errno.
859  */
860 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
861 {
862         struct bpf_func_state *state = cur_func(env);
863         int new_ofs = state->acquired_refs;
864         int id, err;
865
866         err = resize_reference_state(state, state->acquired_refs + 1);
867         if (err)
868                 return err;
869         id = ++env->id_gen;
870         state->refs[new_ofs].id = id;
871         state->refs[new_ofs].insn_idx = insn_idx;
872
873         return id;
874 }
875
876 /* release function corresponding to acquire_reference_state(). Idempotent. */
877 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
878 {
879         int i, last_idx;
880
881         last_idx = state->acquired_refs - 1;
882         for (i = 0; i < state->acquired_refs; i++) {
883                 if (state->refs[i].id == ptr_id) {
884                         if (last_idx && i != last_idx)
885                                 memcpy(&state->refs[i], &state->refs[last_idx],
886                                        sizeof(*state->refs));
887                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
888                         state->acquired_refs--;
889                         return 0;
890                 }
891         }
892         return -EINVAL;
893 }
894
895 static void free_func_state(struct bpf_func_state *state)
896 {
897         if (!state)
898                 return;
899         kfree(state->refs);
900         kfree(state->stack);
901         kfree(state);
902 }
903
904 static void clear_jmp_history(struct bpf_verifier_state *state)
905 {
906         kfree(state->jmp_history);
907         state->jmp_history = NULL;
908         state->jmp_history_cnt = 0;
909 }
910
911 static void free_verifier_state(struct bpf_verifier_state *state,
912                                 bool free_self)
913 {
914         int i;
915
916         for (i = 0; i <= state->curframe; i++) {
917                 free_func_state(state->frame[i]);
918                 state->frame[i] = NULL;
919         }
920         clear_jmp_history(state);
921         if (free_self)
922                 kfree(state);
923 }
924
925 /* copy verifier state from src to dst growing dst stack space
926  * when necessary to accommodate larger src stack
927  */
928 static int copy_func_state(struct bpf_func_state *dst,
929                            const struct bpf_func_state *src)
930 {
931         int err;
932
933         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
934         err = copy_reference_state(dst, src);
935         if (err)
936                 return err;
937         return copy_stack_state(dst, src);
938 }
939
940 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
941                                const struct bpf_verifier_state *src)
942 {
943         struct bpf_func_state *dst;
944         int i, err;
945
946         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
947                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
948                                             GFP_USER);
949         if (!dst_state->jmp_history)
950                 return -ENOMEM;
951         dst_state->jmp_history_cnt = src->jmp_history_cnt;
952
953         /* if dst has more stack frames then src frame, free them */
954         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
955                 free_func_state(dst_state->frame[i]);
956                 dst_state->frame[i] = NULL;
957         }
958         dst_state->speculative = src->speculative;
959         dst_state->curframe = src->curframe;
960         dst_state->active_spin_lock = src->active_spin_lock;
961         dst_state->branches = src->branches;
962         dst_state->parent = src->parent;
963         dst_state->first_insn_idx = src->first_insn_idx;
964         dst_state->last_insn_idx = src->last_insn_idx;
965         for (i = 0; i <= src->curframe; i++) {
966                 dst = dst_state->frame[i];
967                 if (!dst) {
968                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
969                         if (!dst)
970                                 return -ENOMEM;
971                         dst_state->frame[i] = dst;
972                 }
973                 err = copy_func_state(dst, src->frame[i]);
974                 if (err)
975                         return err;
976         }
977         return 0;
978 }
979
980 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
981 {
982         while (st) {
983                 u32 br = --st->branches;
984
985                 /* WARN_ON(br > 1) technically makes sense here,
986                  * but see comment in push_stack(), hence:
987                  */
988                 WARN_ONCE((int)br < 0,
989                           "BUG update_branch_counts:branches_to_explore=%d\n",
990                           br);
991                 if (br)
992                         break;
993                 st = st->parent;
994         }
995 }
996
997 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
998                      int *insn_idx, bool pop_log)
999 {
1000         struct bpf_verifier_state *cur = env->cur_state;
1001         struct bpf_verifier_stack_elem *elem, *head = env->head;
1002         int err;
1003
1004         if (env->head == NULL)
1005                 return -ENOENT;
1006
1007         if (cur) {
1008                 err = copy_verifier_state(cur, &head->st);
1009                 if (err)
1010                         return err;
1011         }
1012         if (pop_log)
1013                 bpf_vlog_reset(&env->log, head->log_pos);
1014         if (insn_idx)
1015                 *insn_idx = head->insn_idx;
1016         if (prev_insn_idx)
1017                 *prev_insn_idx = head->prev_insn_idx;
1018         elem = head->next;
1019         free_verifier_state(&head->st, false);
1020         kfree(head);
1021         env->head = elem;
1022         env->stack_size--;
1023         return 0;
1024 }
1025
1026 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1027                                              int insn_idx, int prev_insn_idx,
1028                                              bool speculative)
1029 {
1030         struct bpf_verifier_state *cur = env->cur_state;
1031         struct bpf_verifier_stack_elem *elem;
1032         int err;
1033
1034         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1035         if (!elem)
1036                 goto err;
1037
1038         elem->insn_idx = insn_idx;
1039         elem->prev_insn_idx = prev_insn_idx;
1040         elem->next = env->head;
1041         elem->log_pos = env->log.len_used;
1042         env->head = elem;
1043         env->stack_size++;
1044         err = copy_verifier_state(&elem->st, cur);
1045         if (err)
1046                 goto err;
1047         elem->st.speculative |= speculative;
1048         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1049                 verbose(env, "The sequence of %d jumps is too complex.\n",
1050                         env->stack_size);
1051                 goto err;
1052         }
1053         if (elem->st.parent) {
1054                 ++elem->st.parent->branches;
1055                 /* WARN_ON(branches > 2) technically makes sense here,
1056                  * but
1057                  * 1. speculative states will bump 'branches' for non-branch
1058                  * instructions
1059                  * 2. is_state_visited() heuristics may decide not to create
1060                  * a new state for a sequence of branches and all such current
1061                  * and cloned states will be pointing to a single parent state
1062                  * which might have large 'branches' count.
1063                  */
1064         }
1065         return &elem->st;
1066 err:
1067         free_verifier_state(env->cur_state, true);
1068         env->cur_state = NULL;
1069         /* pop all elements and return */
1070         while (!pop_stack(env, NULL, NULL, false));
1071         return NULL;
1072 }
1073
1074 #define CALLER_SAVED_REGS 6
1075 static const int caller_saved[CALLER_SAVED_REGS] = {
1076         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1077 };
1078
1079 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1080                                 struct bpf_reg_state *reg);
1081
1082 /* This helper doesn't clear reg->id */
1083 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1084 {
1085         reg->var_off = tnum_const(imm);
1086         reg->smin_value = (s64)imm;
1087         reg->smax_value = (s64)imm;
1088         reg->umin_value = imm;
1089         reg->umax_value = imm;
1090
1091         reg->s32_min_value = (s32)imm;
1092         reg->s32_max_value = (s32)imm;
1093         reg->u32_min_value = (u32)imm;
1094         reg->u32_max_value = (u32)imm;
1095 }
1096
1097 /* Mark the unknown part of a register (variable offset or scalar value) as
1098  * known to have the value @imm.
1099  */
1100 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1101 {
1102         /* Clear id, off, and union(map_ptr, range) */
1103         memset(((u8 *)reg) + sizeof(reg->type), 0,
1104                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1105         ___mark_reg_known(reg, imm);
1106 }
1107
1108 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1109 {
1110         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1111         reg->s32_min_value = (s32)imm;
1112         reg->s32_max_value = (s32)imm;
1113         reg->u32_min_value = (u32)imm;
1114         reg->u32_max_value = (u32)imm;
1115 }
1116
1117 /* Mark the 'variable offset' part of a register as zero.  This should be
1118  * used only on registers holding a pointer type.
1119  */
1120 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1121 {
1122         __mark_reg_known(reg, 0);
1123 }
1124
1125 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1126 {
1127         __mark_reg_known(reg, 0);
1128         reg->type = SCALAR_VALUE;
1129 }
1130
1131 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1132                                 struct bpf_reg_state *regs, u32 regno)
1133 {
1134         if (WARN_ON(regno >= MAX_BPF_REG)) {
1135                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1136                 /* Something bad happened, let's kill all regs */
1137                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1138                         __mark_reg_not_init(env, regs + regno);
1139                 return;
1140         }
1141         __mark_reg_known_zero(regs + regno);
1142 }
1143
1144 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1145 {
1146         switch (reg->type) {
1147         case PTR_TO_MAP_VALUE_OR_NULL: {
1148                 const struct bpf_map *map = reg->map_ptr;
1149
1150                 if (map->inner_map_meta) {
1151                         reg->type = CONST_PTR_TO_MAP;
1152                         reg->map_ptr = map->inner_map_meta;
1153                         /* transfer reg's id which is unique for every map_lookup_elem
1154                          * as UID of the inner map.
1155                          */
1156                         if (map_value_has_timer(map->inner_map_meta))
1157                                 reg->map_uid = reg->id;
1158                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1159                         reg->type = PTR_TO_XDP_SOCK;
1160                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1161                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1162                         reg->type = PTR_TO_SOCKET;
1163                 } else {
1164                         reg->type = PTR_TO_MAP_VALUE;
1165                 }
1166                 break;
1167         }
1168         case PTR_TO_SOCKET_OR_NULL:
1169                 reg->type = PTR_TO_SOCKET;
1170                 break;
1171         case PTR_TO_SOCK_COMMON_OR_NULL:
1172                 reg->type = PTR_TO_SOCK_COMMON;
1173                 break;
1174         case PTR_TO_TCP_SOCK_OR_NULL:
1175                 reg->type = PTR_TO_TCP_SOCK;
1176                 break;
1177         case PTR_TO_BTF_ID_OR_NULL:
1178                 reg->type = PTR_TO_BTF_ID;
1179                 break;
1180         case PTR_TO_MEM_OR_NULL:
1181                 reg->type = PTR_TO_MEM;
1182                 break;
1183         case PTR_TO_RDONLY_BUF_OR_NULL:
1184                 reg->type = PTR_TO_RDONLY_BUF;
1185                 break;
1186         case PTR_TO_RDWR_BUF_OR_NULL:
1187                 reg->type = PTR_TO_RDWR_BUF;
1188                 break;
1189         default:
1190                 WARN_ONCE(1, "unknown nullable register type");
1191         }
1192 }
1193
1194 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1195 {
1196         return type_is_pkt_pointer(reg->type);
1197 }
1198
1199 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1200 {
1201         return reg_is_pkt_pointer(reg) ||
1202                reg->type == PTR_TO_PACKET_END;
1203 }
1204
1205 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1206 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1207                                     enum bpf_reg_type which)
1208 {
1209         /* The register can already have a range from prior markings.
1210          * This is fine as long as it hasn't been advanced from its
1211          * origin.
1212          */
1213         return reg->type == which &&
1214                reg->id == 0 &&
1215                reg->off == 0 &&
1216                tnum_equals_const(reg->var_off, 0);
1217 }
1218
1219 /* Reset the min/max bounds of a register */
1220 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1221 {
1222         reg->smin_value = S64_MIN;
1223         reg->smax_value = S64_MAX;
1224         reg->umin_value = 0;
1225         reg->umax_value = U64_MAX;
1226
1227         reg->s32_min_value = S32_MIN;
1228         reg->s32_max_value = S32_MAX;
1229         reg->u32_min_value = 0;
1230         reg->u32_max_value = U32_MAX;
1231 }
1232
1233 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1234 {
1235         reg->smin_value = S64_MIN;
1236         reg->smax_value = S64_MAX;
1237         reg->umin_value = 0;
1238         reg->umax_value = U64_MAX;
1239 }
1240
1241 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1242 {
1243         reg->s32_min_value = S32_MIN;
1244         reg->s32_max_value = S32_MAX;
1245         reg->u32_min_value = 0;
1246         reg->u32_max_value = U32_MAX;
1247 }
1248
1249 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1250 {
1251         struct tnum var32_off = tnum_subreg(reg->var_off);
1252
1253         /* min signed is max(sign bit) | min(other bits) */
1254         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1255                         var32_off.value | (var32_off.mask & S32_MIN));
1256         /* max signed is min(sign bit) | max(other bits) */
1257         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1258                         var32_off.value | (var32_off.mask & S32_MAX));
1259         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1260         reg->u32_max_value = min(reg->u32_max_value,
1261                                  (u32)(var32_off.value | var32_off.mask));
1262 }
1263
1264 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1265 {
1266         /* min signed is max(sign bit) | min(other bits) */
1267         reg->smin_value = max_t(s64, reg->smin_value,
1268                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1269         /* max signed is min(sign bit) | max(other bits) */
1270         reg->smax_value = min_t(s64, reg->smax_value,
1271                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1272         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1273         reg->umax_value = min(reg->umax_value,
1274                               reg->var_off.value | reg->var_off.mask);
1275 }
1276
1277 static void __update_reg_bounds(struct bpf_reg_state *reg)
1278 {
1279         __update_reg32_bounds(reg);
1280         __update_reg64_bounds(reg);
1281 }
1282
1283 /* Uses signed min/max values to inform unsigned, and vice-versa */
1284 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1285 {
1286         /* Learn sign from signed bounds.
1287          * If we cannot cross the sign boundary, then signed and unsigned bounds
1288          * are the same, so combine.  This works even in the negative case, e.g.
1289          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1290          */
1291         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1292                 reg->s32_min_value = reg->u32_min_value =
1293                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1294                 reg->s32_max_value = reg->u32_max_value =
1295                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1296                 return;
1297         }
1298         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1299          * boundary, so we must be careful.
1300          */
1301         if ((s32)reg->u32_max_value >= 0) {
1302                 /* Positive.  We can't learn anything from the smin, but smax
1303                  * is positive, hence safe.
1304                  */
1305                 reg->s32_min_value = reg->u32_min_value;
1306                 reg->s32_max_value = reg->u32_max_value =
1307                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1308         } else if ((s32)reg->u32_min_value < 0) {
1309                 /* Negative.  We can't learn anything from the smax, but smin
1310                  * is negative, hence safe.
1311                  */
1312                 reg->s32_min_value = reg->u32_min_value =
1313                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1314                 reg->s32_max_value = reg->u32_max_value;
1315         }
1316 }
1317
1318 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1319 {
1320         /* Learn sign from signed bounds.
1321          * If we cannot cross the sign boundary, then signed and unsigned bounds
1322          * are the same, so combine.  This works even in the negative case, e.g.
1323          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1324          */
1325         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1326                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1327                                                           reg->umin_value);
1328                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1329                                                           reg->umax_value);
1330                 return;
1331         }
1332         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1333          * boundary, so we must be careful.
1334          */
1335         if ((s64)reg->umax_value >= 0) {
1336                 /* Positive.  We can't learn anything from the smin, but smax
1337                  * is positive, hence safe.
1338                  */
1339                 reg->smin_value = reg->umin_value;
1340                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1341                                                           reg->umax_value);
1342         } else if ((s64)reg->umin_value < 0) {
1343                 /* Negative.  We can't learn anything from the smax, but smin
1344                  * is negative, hence safe.
1345                  */
1346                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1347                                                           reg->umin_value);
1348                 reg->smax_value = reg->umax_value;
1349         }
1350 }
1351
1352 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1353 {
1354         __reg32_deduce_bounds(reg);
1355         __reg64_deduce_bounds(reg);
1356 }
1357
1358 /* Attempts to improve var_off based on unsigned min/max information */
1359 static void __reg_bound_offset(struct bpf_reg_state *reg)
1360 {
1361         struct tnum var64_off = tnum_intersect(reg->var_off,
1362                                                tnum_range(reg->umin_value,
1363                                                           reg->umax_value));
1364         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1365                                                 tnum_range(reg->u32_min_value,
1366                                                            reg->u32_max_value));
1367
1368         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1369 }
1370
1371 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1372 {
1373         reg->umin_value = reg->u32_min_value;
1374         reg->umax_value = reg->u32_max_value;
1375         /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1376          * but must be positive otherwise set to worse case bounds
1377          * and refine later from tnum.
1378          */
1379         if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1380                 reg->smax_value = reg->s32_max_value;
1381         else
1382                 reg->smax_value = U32_MAX;
1383         if (reg->s32_min_value >= 0)
1384                 reg->smin_value = reg->s32_min_value;
1385         else
1386                 reg->smin_value = 0;
1387 }
1388
1389 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1390 {
1391         /* special case when 64-bit register has upper 32-bit register
1392          * zeroed. Typically happens after zext or <<32, >>32 sequence
1393          * allowing us to use 32-bit bounds directly,
1394          */
1395         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1396                 __reg_assign_32_into_64(reg);
1397         } else {
1398                 /* Otherwise the best we can do is push lower 32bit known and
1399                  * unknown bits into register (var_off set from jmp logic)
1400                  * then learn as much as possible from the 64-bit tnum
1401                  * known and unknown bits. The previous smin/smax bounds are
1402                  * invalid here because of jmp32 compare so mark them unknown
1403                  * so they do not impact tnum bounds calculation.
1404                  */
1405                 __mark_reg64_unbounded(reg);
1406                 __update_reg_bounds(reg);
1407         }
1408
1409         /* Intersecting with the old var_off might have improved our bounds
1410          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1411          * then new var_off is (0; 0x7f...fc) which improves our umax.
1412          */
1413         __reg_deduce_bounds(reg);
1414         __reg_bound_offset(reg);
1415         __update_reg_bounds(reg);
1416 }
1417
1418 static bool __reg64_bound_s32(s64 a)
1419 {
1420         return a >= S32_MIN && a <= S32_MAX;
1421 }
1422
1423 static bool __reg64_bound_u32(u64 a)
1424 {
1425         return a >= U32_MIN && a <= U32_MAX;
1426 }
1427
1428 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1429 {
1430         __mark_reg32_unbounded(reg);
1431
1432         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1433                 reg->s32_min_value = (s32)reg->smin_value;
1434                 reg->s32_max_value = (s32)reg->smax_value;
1435         }
1436         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1437                 reg->u32_min_value = (u32)reg->umin_value;
1438                 reg->u32_max_value = (u32)reg->umax_value;
1439         }
1440
1441         /* Intersecting with the old var_off might have improved our bounds
1442          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1443          * then new var_off is (0; 0x7f...fc) which improves our umax.
1444          */
1445         __reg_deduce_bounds(reg);
1446         __reg_bound_offset(reg);
1447         __update_reg_bounds(reg);
1448 }
1449
1450 /* Mark a register as having a completely unknown (scalar) value. */
1451 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1452                                struct bpf_reg_state *reg)
1453 {
1454         /*
1455          * Clear type, id, off, and union(map_ptr, range) and
1456          * padding between 'type' and union
1457          */
1458         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1459         reg->type = SCALAR_VALUE;
1460         reg->var_off = tnum_unknown;
1461         reg->frameno = 0;
1462         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1463         __mark_reg_unbounded(reg);
1464 }
1465
1466 static void mark_reg_unknown(struct bpf_verifier_env *env,
1467                              struct bpf_reg_state *regs, u32 regno)
1468 {
1469         if (WARN_ON(regno >= MAX_BPF_REG)) {
1470                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1471                 /* Something bad happened, let's kill all regs except FP */
1472                 for (regno = 0; regno < BPF_REG_FP; regno++)
1473                         __mark_reg_not_init(env, regs + regno);
1474                 return;
1475         }
1476         __mark_reg_unknown(env, regs + regno);
1477 }
1478
1479 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1480                                 struct bpf_reg_state *reg)
1481 {
1482         __mark_reg_unknown(env, reg);
1483         reg->type = NOT_INIT;
1484 }
1485
1486 static void mark_reg_not_init(struct bpf_verifier_env *env,
1487                               struct bpf_reg_state *regs, u32 regno)
1488 {
1489         if (WARN_ON(regno >= MAX_BPF_REG)) {
1490                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1491                 /* Something bad happened, let's kill all regs except FP */
1492                 for (regno = 0; regno < BPF_REG_FP; regno++)
1493                         __mark_reg_not_init(env, regs + regno);
1494                 return;
1495         }
1496         __mark_reg_not_init(env, regs + regno);
1497 }
1498
1499 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1500                             struct bpf_reg_state *regs, u32 regno,
1501                             enum bpf_reg_type reg_type,
1502                             struct btf *btf, u32 btf_id)
1503 {
1504         if (reg_type == SCALAR_VALUE) {
1505                 mark_reg_unknown(env, regs, regno);
1506                 return;
1507         }
1508         mark_reg_known_zero(env, regs, regno);
1509         regs[regno].type = PTR_TO_BTF_ID;
1510         regs[regno].btf = btf;
1511         regs[regno].btf_id = btf_id;
1512 }
1513
1514 #define DEF_NOT_SUBREG  (0)
1515 static void init_reg_state(struct bpf_verifier_env *env,
1516                            struct bpf_func_state *state)
1517 {
1518         struct bpf_reg_state *regs = state->regs;
1519         int i;
1520
1521         for (i = 0; i < MAX_BPF_REG; i++) {
1522                 mark_reg_not_init(env, regs, i);
1523                 regs[i].live = REG_LIVE_NONE;
1524                 regs[i].parent = NULL;
1525                 regs[i].subreg_def = DEF_NOT_SUBREG;
1526         }
1527
1528         /* frame pointer */
1529         regs[BPF_REG_FP].type = PTR_TO_STACK;
1530         mark_reg_known_zero(env, regs, BPF_REG_FP);
1531         regs[BPF_REG_FP].frameno = state->frameno;
1532 }
1533
1534 #define BPF_MAIN_FUNC (-1)
1535 static void init_func_state(struct bpf_verifier_env *env,
1536                             struct bpf_func_state *state,
1537                             int callsite, int frameno, int subprogno)
1538 {
1539         state->callsite = callsite;
1540         state->frameno = frameno;
1541         state->subprogno = subprogno;
1542         init_reg_state(env, state);
1543 }
1544
1545 /* Similar to push_stack(), but for async callbacks */
1546 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1547                                                 int insn_idx, int prev_insn_idx,
1548                                                 int subprog)
1549 {
1550         struct bpf_verifier_stack_elem *elem;
1551         struct bpf_func_state *frame;
1552
1553         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1554         if (!elem)
1555                 goto err;
1556
1557         elem->insn_idx = insn_idx;
1558         elem->prev_insn_idx = prev_insn_idx;
1559         elem->next = env->head;
1560         elem->log_pos = env->log.len_used;
1561         env->head = elem;
1562         env->stack_size++;
1563         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1564                 verbose(env,
1565                         "The sequence of %d jumps is too complex for async cb.\n",
1566                         env->stack_size);
1567                 goto err;
1568         }
1569         /* Unlike push_stack() do not copy_verifier_state().
1570          * The caller state doesn't matter.
1571          * This is async callback. It starts in a fresh stack.
1572          * Initialize it similar to do_check_common().
1573          */
1574         elem->st.branches = 1;
1575         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1576         if (!frame)
1577                 goto err;
1578         init_func_state(env, frame,
1579                         BPF_MAIN_FUNC /* callsite */,
1580                         0 /* frameno within this callchain */,
1581                         subprog /* subprog number within this prog */);
1582         elem->st.frame[0] = frame;
1583         return &elem->st;
1584 err:
1585         free_verifier_state(env->cur_state, true);
1586         env->cur_state = NULL;
1587         /* pop all elements and return */
1588         while (!pop_stack(env, NULL, NULL, false));
1589         return NULL;
1590 }
1591
1592
1593 enum reg_arg_type {
1594         SRC_OP,         /* register is used as source operand */
1595         DST_OP,         /* register is used as destination operand */
1596         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1597 };
1598
1599 static int cmp_subprogs(const void *a, const void *b)
1600 {
1601         return ((struct bpf_subprog_info *)a)->start -
1602                ((struct bpf_subprog_info *)b)->start;
1603 }
1604
1605 static int find_subprog(struct bpf_verifier_env *env, int off)
1606 {
1607         struct bpf_subprog_info *p;
1608
1609         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1610                     sizeof(env->subprog_info[0]), cmp_subprogs);
1611         if (!p)
1612                 return -ENOENT;
1613         return p - env->subprog_info;
1614
1615 }
1616
1617 static int add_subprog(struct bpf_verifier_env *env, int off)
1618 {
1619         int insn_cnt = env->prog->len;
1620         int ret;
1621
1622         if (off >= insn_cnt || off < 0) {
1623                 verbose(env, "call to invalid destination\n");
1624                 return -EINVAL;
1625         }
1626         ret = find_subprog(env, off);
1627         if (ret >= 0)
1628                 return ret;
1629         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1630                 verbose(env, "too many subprograms\n");
1631                 return -E2BIG;
1632         }
1633         /* determine subprog starts. The end is one before the next starts */
1634         env->subprog_info[env->subprog_cnt++].start = off;
1635         sort(env->subprog_info, env->subprog_cnt,
1636              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1637         return env->subprog_cnt - 1;
1638 }
1639
1640 #define MAX_KFUNC_DESCS 256
1641 #define MAX_KFUNC_BTFS  256
1642
1643 struct bpf_kfunc_desc {
1644         struct btf_func_model func_model;
1645         u32 func_id;
1646         s32 imm;
1647         u16 offset;
1648 };
1649
1650 struct bpf_kfunc_btf {
1651         struct btf *btf;
1652         struct module *module;
1653         u16 offset;
1654 };
1655
1656 struct bpf_kfunc_desc_tab {
1657         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1658         u32 nr_descs;
1659 };
1660
1661 struct bpf_kfunc_btf_tab {
1662         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1663         u32 nr_descs;
1664 };
1665
1666 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1667 {
1668         const struct bpf_kfunc_desc *d0 = a;
1669         const struct bpf_kfunc_desc *d1 = b;
1670
1671         /* func_id is not greater than BTF_MAX_TYPE */
1672         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1673 }
1674
1675 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1676 {
1677         const struct bpf_kfunc_btf *d0 = a;
1678         const struct bpf_kfunc_btf *d1 = b;
1679
1680         return d0->offset - d1->offset;
1681 }
1682
1683 static const struct bpf_kfunc_desc *
1684 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1685 {
1686         struct bpf_kfunc_desc desc = {
1687                 .func_id = func_id,
1688                 .offset = offset,
1689         };
1690         struct bpf_kfunc_desc_tab *tab;
1691
1692         tab = prog->aux->kfunc_tab;
1693         return bsearch(&desc, tab->descs, tab->nr_descs,
1694                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1695 }
1696
1697 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1698                                          s16 offset, struct module **btf_modp)
1699 {
1700         struct bpf_kfunc_btf kf_btf = { .offset = offset };
1701         struct bpf_kfunc_btf_tab *tab;
1702         struct bpf_kfunc_btf *b;
1703         struct module *mod;
1704         struct btf *btf;
1705         int btf_fd;
1706
1707         tab = env->prog->aux->kfunc_btf_tab;
1708         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1709                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1710         if (!b) {
1711                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1712                         verbose(env, "too many different module BTFs\n");
1713                         return ERR_PTR(-E2BIG);
1714                 }
1715
1716                 if (bpfptr_is_null(env->fd_array)) {
1717                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1718                         return ERR_PTR(-EPROTO);
1719                 }
1720
1721                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1722                                             offset * sizeof(btf_fd),
1723                                             sizeof(btf_fd)))
1724                         return ERR_PTR(-EFAULT);
1725
1726                 btf = btf_get_by_fd(btf_fd);
1727                 if (IS_ERR(btf)) {
1728                         verbose(env, "invalid module BTF fd specified\n");
1729                         return btf;
1730                 }
1731
1732                 if (!btf_is_module(btf)) {
1733                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
1734                         btf_put(btf);
1735                         return ERR_PTR(-EINVAL);
1736                 }
1737
1738                 mod = btf_try_get_module(btf);
1739                 if (!mod) {
1740                         btf_put(btf);
1741                         return ERR_PTR(-ENXIO);
1742                 }
1743
1744                 b = &tab->descs[tab->nr_descs++];
1745                 b->btf = btf;
1746                 b->module = mod;
1747                 b->offset = offset;
1748
1749                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1750                      kfunc_btf_cmp_by_off, NULL);
1751         }
1752         if (btf_modp)
1753                 *btf_modp = b->module;
1754         return b->btf;
1755 }
1756
1757 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1758 {
1759         if (!tab)
1760                 return;
1761
1762         while (tab->nr_descs--) {
1763                 module_put(tab->descs[tab->nr_descs].module);
1764                 btf_put(tab->descs[tab->nr_descs].btf);
1765         }
1766         kfree(tab);
1767 }
1768
1769 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env,
1770                                        u32 func_id, s16 offset,
1771                                        struct module **btf_modp)
1772 {
1773         if (offset) {
1774                 if (offset < 0) {
1775                         /* In the future, this can be allowed to increase limit
1776                          * of fd index into fd_array, interpreted as u16.
1777                          */
1778                         verbose(env, "negative offset disallowed for kernel module function call\n");
1779                         return ERR_PTR(-EINVAL);
1780                 }
1781
1782                 return __find_kfunc_desc_btf(env, offset, btf_modp);
1783         }
1784         return btf_vmlinux ?: ERR_PTR(-ENOENT);
1785 }
1786
1787 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
1788 {
1789         const struct btf_type *func, *func_proto;
1790         struct bpf_kfunc_btf_tab *btf_tab;
1791         struct bpf_kfunc_desc_tab *tab;
1792         struct bpf_prog_aux *prog_aux;
1793         struct bpf_kfunc_desc *desc;
1794         const char *func_name;
1795         struct btf *desc_btf;
1796         unsigned long addr;
1797         int err;
1798
1799         prog_aux = env->prog->aux;
1800         tab = prog_aux->kfunc_tab;
1801         btf_tab = prog_aux->kfunc_btf_tab;
1802         if (!tab) {
1803                 if (!btf_vmlinux) {
1804                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1805                         return -ENOTSUPP;
1806                 }
1807
1808                 if (!env->prog->jit_requested) {
1809                         verbose(env, "JIT is required for calling kernel function\n");
1810                         return -ENOTSUPP;
1811                 }
1812
1813                 if (!bpf_jit_supports_kfunc_call()) {
1814                         verbose(env, "JIT does not support calling kernel function\n");
1815                         return -ENOTSUPP;
1816                 }
1817
1818                 if (!env->prog->gpl_compatible) {
1819                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1820                         return -EINVAL;
1821                 }
1822
1823                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1824                 if (!tab)
1825                         return -ENOMEM;
1826                 prog_aux->kfunc_tab = tab;
1827         }
1828
1829         /* func_id == 0 is always invalid, but instead of returning an error, be
1830          * conservative and wait until the code elimination pass before returning
1831          * error, so that invalid calls that get pruned out can be in BPF programs
1832          * loaded from userspace.  It is also required that offset be untouched
1833          * for such calls.
1834          */
1835         if (!func_id && !offset)
1836                 return 0;
1837
1838         if (!btf_tab && offset) {
1839                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
1840                 if (!btf_tab)
1841                         return -ENOMEM;
1842                 prog_aux->kfunc_btf_tab = btf_tab;
1843         }
1844
1845         desc_btf = find_kfunc_desc_btf(env, func_id, offset, NULL);
1846         if (IS_ERR(desc_btf)) {
1847                 verbose(env, "failed to find BTF for kernel function\n");
1848                 return PTR_ERR(desc_btf);
1849         }
1850
1851         if (find_kfunc_desc(env->prog, func_id, offset))
1852                 return 0;
1853
1854         if (tab->nr_descs == MAX_KFUNC_DESCS) {
1855                 verbose(env, "too many different kernel function calls\n");
1856                 return -E2BIG;
1857         }
1858
1859         func = btf_type_by_id(desc_btf, func_id);
1860         if (!func || !btf_type_is_func(func)) {
1861                 verbose(env, "kernel btf_id %u is not a function\n",
1862                         func_id);
1863                 return -EINVAL;
1864         }
1865         func_proto = btf_type_by_id(desc_btf, func->type);
1866         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1867                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1868                         func_id);
1869                 return -EINVAL;
1870         }
1871
1872         func_name = btf_name_by_offset(desc_btf, func->name_off);
1873         addr = kallsyms_lookup_name(func_name);
1874         if (!addr) {
1875                 verbose(env, "cannot find address for kernel function %s\n",
1876                         func_name);
1877                 return -EINVAL;
1878         }
1879
1880         desc = &tab->descs[tab->nr_descs++];
1881         desc->func_id = func_id;
1882         desc->imm = BPF_CALL_IMM(addr);
1883         desc->offset = offset;
1884         err = btf_distill_func_proto(&env->log, desc_btf,
1885                                      func_proto, func_name,
1886                                      &desc->func_model);
1887         if (!err)
1888                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1889                      kfunc_desc_cmp_by_id_off, NULL);
1890         return err;
1891 }
1892
1893 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1894 {
1895         const struct bpf_kfunc_desc *d0 = a;
1896         const struct bpf_kfunc_desc *d1 = b;
1897
1898         if (d0->imm > d1->imm)
1899                 return 1;
1900         else if (d0->imm < d1->imm)
1901                 return -1;
1902         return 0;
1903 }
1904
1905 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1906 {
1907         struct bpf_kfunc_desc_tab *tab;
1908
1909         tab = prog->aux->kfunc_tab;
1910         if (!tab)
1911                 return;
1912
1913         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1914              kfunc_desc_cmp_by_imm, NULL);
1915 }
1916
1917 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1918 {
1919         return !!prog->aux->kfunc_tab;
1920 }
1921
1922 const struct btf_func_model *
1923 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1924                          const struct bpf_insn *insn)
1925 {
1926         const struct bpf_kfunc_desc desc = {
1927                 .imm = insn->imm,
1928         };
1929         const struct bpf_kfunc_desc *res;
1930         struct bpf_kfunc_desc_tab *tab;
1931
1932         tab = prog->aux->kfunc_tab;
1933         res = bsearch(&desc, tab->descs, tab->nr_descs,
1934                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1935
1936         return res ? &res->func_model : NULL;
1937 }
1938
1939 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1940 {
1941         struct bpf_subprog_info *subprog = env->subprog_info;
1942         struct bpf_insn *insn = env->prog->insnsi;
1943         int i, ret, insn_cnt = env->prog->len;
1944
1945         /* Add entry function. */
1946         ret = add_subprog(env, 0);
1947         if (ret)
1948                 return ret;
1949
1950         for (i = 0; i < insn_cnt; i++, insn++) {
1951                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1952                     !bpf_pseudo_kfunc_call(insn))
1953                         continue;
1954
1955                 if (!env->bpf_capable) {
1956                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1957                         return -EPERM;
1958                 }
1959
1960                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
1961                         ret = add_subprog(env, i + insn->imm + 1);
1962                 else
1963                         ret = add_kfunc_call(env, insn->imm, insn->off);
1964
1965                 if (ret < 0)
1966                         return ret;
1967         }
1968
1969         /* Add a fake 'exit' subprog which could simplify subprog iteration
1970          * logic. 'subprog_cnt' should not be increased.
1971          */
1972         subprog[env->subprog_cnt].start = insn_cnt;
1973
1974         if (env->log.level & BPF_LOG_LEVEL2)
1975                 for (i = 0; i < env->subprog_cnt; i++)
1976                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
1977
1978         return 0;
1979 }
1980
1981 static int check_subprogs(struct bpf_verifier_env *env)
1982 {
1983         int i, subprog_start, subprog_end, off, cur_subprog = 0;
1984         struct bpf_subprog_info *subprog = env->subprog_info;
1985         struct bpf_insn *insn = env->prog->insnsi;
1986         int insn_cnt = env->prog->len;
1987
1988         /* now check that all jumps are within the same subprog */
1989         subprog_start = subprog[cur_subprog].start;
1990         subprog_end = subprog[cur_subprog + 1].start;
1991         for (i = 0; i < insn_cnt; i++) {
1992                 u8 code = insn[i].code;
1993
1994                 if (code == (BPF_JMP | BPF_CALL) &&
1995                     insn[i].imm == BPF_FUNC_tail_call &&
1996                     insn[i].src_reg != BPF_PSEUDO_CALL)
1997                         subprog[cur_subprog].has_tail_call = true;
1998                 if (BPF_CLASS(code) == BPF_LD &&
1999                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2000                         subprog[cur_subprog].has_ld_abs = true;
2001                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2002                         goto next;
2003                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2004                         goto next;
2005                 off = i + insn[i].off + 1;
2006                 if (off < subprog_start || off >= subprog_end) {
2007                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2008                         return -EINVAL;
2009                 }
2010 next:
2011                 if (i == subprog_end - 1) {
2012                         /* to avoid fall-through from one subprog into another
2013                          * the last insn of the subprog should be either exit
2014                          * or unconditional jump back
2015                          */
2016                         if (code != (BPF_JMP | BPF_EXIT) &&
2017                             code != (BPF_JMP | BPF_JA)) {
2018                                 verbose(env, "last insn is not an exit or jmp\n");
2019                                 return -EINVAL;
2020                         }
2021                         subprog_start = subprog_end;
2022                         cur_subprog++;
2023                         if (cur_subprog < env->subprog_cnt)
2024                                 subprog_end = subprog[cur_subprog + 1].start;
2025                 }
2026         }
2027         return 0;
2028 }
2029
2030 /* Parentage chain of this register (or stack slot) should take care of all
2031  * issues like callee-saved registers, stack slot allocation time, etc.
2032  */
2033 static int mark_reg_read(struct bpf_verifier_env *env,
2034                          const struct bpf_reg_state *state,
2035                          struct bpf_reg_state *parent, u8 flag)
2036 {
2037         bool writes = parent == state->parent; /* Observe write marks */
2038         int cnt = 0;
2039
2040         while (parent) {
2041                 /* if read wasn't screened by an earlier write ... */
2042                 if (writes && state->live & REG_LIVE_WRITTEN)
2043                         break;
2044                 if (parent->live & REG_LIVE_DONE) {
2045                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2046                                 reg_type_str[parent->type],
2047                                 parent->var_off.value, parent->off);
2048                         return -EFAULT;
2049                 }
2050                 /* The first condition is more likely to be true than the
2051                  * second, checked it first.
2052                  */
2053                 if ((parent->live & REG_LIVE_READ) == flag ||
2054                     parent->live & REG_LIVE_READ64)
2055                         /* The parentage chain never changes and
2056                          * this parent was already marked as LIVE_READ.
2057                          * There is no need to keep walking the chain again and
2058                          * keep re-marking all parents as LIVE_READ.
2059                          * This case happens when the same register is read
2060                          * multiple times without writes into it in-between.
2061                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2062                          * then no need to set the weak REG_LIVE_READ32.
2063                          */
2064                         break;
2065                 /* ... then we depend on parent's value */
2066                 parent->live |= flag;
2067                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2068                 if (flag == REG_LIVE_READ64)
2069                         parent->live &= ~REG_LIVE_READ32;
2070                 state = parent;
2071                 parent = state->parent;
2072                 writes = true;
2073                 cnt++;
2074         }
2075
2076         if (env->longest_mark_read_walk < cnt)
2077                 env->longest_mark_read_walk = cnt;
2078         return 0;
2079 }
2080
2081 /* This function is supposed to be used by the following 32-bit optimization
2082  * code only. It returns TRUE if the source or destination register operates
2083  * on 64-bit, otherwise return FALSE.
2084  */
2085 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2086                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2087 {
2088         u8 code, class, op;
2089
2090         code = insn->code;
2091         class = BPF_CLASS(code);
2092         op = BPF_OP(code);
2093         if (class == BPF_JMP) {
2094                 /* BPF_EXIT for "main" will reach here. Return TRUE
2095                  * conservatively.
2096                  */
2097                 if (op == BPF_EXIT)
2098                         return true;
2099                 if (op == BPF_CALL) {
2100                         /* BPF to BPF call will reach here because of marking
2101                          * caller saved clobber with DST_OP_NO_MARK for which we
2102                          * don't care the register def because they are anyway
2103                          * marked as NOT_INIT already.
2104                          */
2105                         if (insn->src_reg == BPF_PSEUDO_CALL)
2106                                 return false;
2107                         /* Helper call will reach here because of arg type
2108                          * check, conservatively return TRUE.
2109                          */
2110                         if (t == SRC_OP)
2111                                 return true;
2112
2113                         return false;
2114                 }
2115         }
2116
2117         if (class == BPF_ALU64 || class == BPF_JMP ||
2118             /* BPF_END always use BPF_ALU class. */
2119             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2120                 return true;
2121
2122         if (class == BPF_ALU || class == BPF_JMP32)
2123                 return false;
2124
2125         if (class == BPF_LDX) {
2126                 if (t != SRC_OP)
2127                         return BPF_SIZE(code) == BPF_DW;
2128                 /* LDX source must be ptr. */
2129                 return true;
2130         }
2131
2132         if (class == BPF_STX) {
2133                 /* BPF_STX (including atomic variants) has multiple source
2134                  * operands, one of which is a ptr. Check whether the caller is
2135                  * asking about it.
2136                  */
2137                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2138                         return true;
2139                 return BPF_SIZE(code) == BPF_DW;
2140         }
2141
2142         if (class == BPF_LD) {
2143                 u8 mode = BPF_MODE(code);
2144
2145                 /* LD_IMM64 */
2146                 if (mode == BPF_IMM)
2147                         return true;
2148
2149                 /* Both LD_IND and LD_ABS return 32-bit data. */
2150                 if (t != SRC_OP)
2151                         return  false;
2152
2153                 /* Implicit ctx ptr. */
2154                 if (regno == BPF_REG_6)
2155                         return true;
2156
2157                 /* Explicit source could be any width. */
2158                 return true;
2159         }
2160
2161         if (class == BPF_ST)
2162                 /* The only source register for BPF_ST is a ptr. */
2163                 return true;
2164
2165         /* Conservatively return true at default. */
2166         return true;
2167 }
2168
2169 /* Return the regno defined by the insn, or -1. */
2170 static int insn_def_regno(const struct bpf_insn *insn)
2171 {
2172         switch (BPF_CLASS(insn->code)) {
2173         case BPF_JMP:
2174         case BPF_JMP32:
2175         case BPF_ST:
2176                 return -1;
2177         case BPF_STX:
2178                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2179                     (insn->imm & BPF_FETCH)) {
2180                         if (insn->imm == BPF_CMPXCHG)
2181                                 return BPF_REG_0;
2182                         else
2183                                 return insn->src_reg;
2184                 } else {
2185                         return -1;
2186                 }
2187         default:
2188                 return insn->dst_reg;
2189         }
2190 }
2191
2192 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2193 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2194 {
2195         int dst_reg = insn_def_regno(insn);
2196
2197         if (dst_reg == -1)
2198                 return false;
2199
2200         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2201 }
2202
2203 static void mark_insn_zext(struct bpf_verifier_env *env,
2204                            struct bpf_reg_state *reg)
2205 {
2206         s32 def_idx = reg->subreg_def;
2207
2208         if (def_idx == DEF_NOT_SUBREG)
2209                 return;
2210
2211         env->insn_aux_data[def_idx - 1].zext_dst = true;
2212         /* The dst will be zero extended, so won't be sub-register anymore. */
2213         reg->subreg_def = DEF_NOT_SUBREG;
2214 }
2215
2216 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2217                          enum reg_arg_type t)
2218 {
2219         struct bpf_verifier_state *vstate = env->cur_state;
2220         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2221         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2222         struct bpf_reg_state *reg, *regs = state->regs;
2223         bool rw64;
2224
2225         if (regno >= MAX_BPF_REG) {
2226                 verbose(env, "R%d is invalid\n", regno);
2227                 return -EINVAL;
2228         }
2229
2230         reg = &regs[regno];
2231         rw64 = is_reg64(env, insn, regno, reg, t);
2232         if (t == SRC_OP) {
2233                 /* check whether register used as source operand can be read */
2234                 if (reg->type == NOT_INIT) {
2235                         verbose(env, "R%d !read_ok\n", regno);
2236                         return -EACCES;
2237                 }
2238                 /* We don't need to worry about FP liveness because it's read-only */
2239                 if (regno == BPF_REG_FP)
2240                         return 0;
2241
2242                 if (rw64)
2243                         mark_insn_zext(env, reg);
2244
2245                 return mark_reg_read(env, reg, reg->parent,
2246                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2247         } else {
2248                 /* check whether register used as dest operand can be written to */
2249                 if (regno == BPF_REG_FP) {
2250                         verbose(env, "frame pointer is read only\n");
2251                         return -EACCES;
2252                 }
2253                 reg->live |= REG_LIVE_WRITTEN;
2254                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2255                 if (t == DST_OP)
2256                         mark_reg_unknown(env, regs, regno);
2257         }
2258         return 0;
2259 }
2260
2261 /* for any branch, call, exit record the history of jmps in the given state */
2262 static int push_jmp_history(struct bpf_verifier_env *env,
2263                             struct bpf_verifier_state *cur)
2264 {
2265         u32 cnt = cur->jmp_history_cnt;
2266         struct bpf_idx_pair *p;
2267
2268         cnt++;
2269         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2270         if (!p)
2271                 return -ENOMEM;
2272         p[cnt - 1].idx = env->insn_idx;
2273         p[cnt - 1].prev_idx = env->prev_insn_idx;
2274         cur->jmp_history = p;
2275         cur->jmp_history_cnt = cnt;
2276         return 0;
2277 }
2278
2279 /* Backtrack one insn at a time. If idx is not at the top of recorded
2280  * history then previous instruction came from straight line execution.
2281  */
2282 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2283                              u32 *history)
2284 {
2285         u32 cnt = *history;
2286
2287         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2288                 i = st->jmp_history[cnt - 1].prev_idx;
2289                 (*history)--;
2290         } else {
2291                 i--;
2292         }
2293         return i;
2294 }
2295
2296 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2297 {
2298         const struct btf_type *func;
2299         struct btf *desc_btf;
2300
2301         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2302                 return NULL;
2303
2304         desc_btf = find_kfunc_desc_btf(data, insn->imm, insn->off, NULL);
2305         if (IS_ERR(desc_btf))
2306                 return "<error>";
2307
2308         func = btf_type_by_id(desc_btf, insn->imm);
2309         return btf_name_by_offset(desc_btf, func->name_off);
2310 }
2311
2312 /* For given verifier state backtrack_insn() is called from the last insn to
2313  * the first insn. Its purpose is to compute a bitmask of registers and
2314  * stack slots that needs precision in the parent verifier state.
2315  */
2316 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2317                           u32 *reg_mask, u64 *stack_mask)
2318 {
2319         const struct bpf_insn_cbs cbs = {
2320                 .cb_call        = disasm_kfunc_name,
2321                 .cb_print       = verbose,
2322                 .private_data   = env,
2323         };
2324         struct bpf_insn *insn = env->prog->insnsi + idx;
2325         u8 class = BPF_CLASS(insn->code);
2326         u8 opcode = BPF_OP(insn->code);
2327         u8 mode = BPF_MODE(insn->code);
2328         u32 dreg = 1u << insn->dst_reg;
2329         u32 sreg = 1u << insn->src_reg;
2330         u32 spi;
2331
2332         if (insn->code == 0)
2333                 return 0;
2334         if (env->log.level & BPF_LOG_LEVEL) {
2335                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2336                 verbose(env, "%d: ", idx);
2337                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2338         }
2339
2340         if (class == BPF_ALU || class == BPF_ALU64) {
2341                 if (!(*reg_mask & dreg))
2342                         return 0;
2343                 if (opcode == BPF_MOV) {
2344                         if (BPF_SRC(insn->code) == BPF_X) {
2345                                 /* dreg = sreg
2346                                  * dreg needs precision after this insn
2347                                  * sreg needs precision before this insn
2348                                  */
2349                                 *reg_mask &= ~dreg;
2350                                 *reg_mask |= sreg;
2351                         } else {
2352                                 /* dreg = K
2353                                  * dreg needs precision after this insn.
2354                                  * Corresponding register is already marked
2355                                  * as precise=true in this verifier state.
2356                                  * No further markings in parent are necessary
2357                                  */
2358                                 *reg_mask &= ~dreg;
2359                         }
2360                 } else {
2361                         if (BPF_SRC(insn->code) == BPF_X) {
2362                                 /* dreg += sreg
2363                                  * both dreg and sreg need precision
2364                                  * before this insn
2365                                  */
2366                                 *reg_mask |= sreg;
2367                         } /* else dreg += K
2368                            * dreg still needs precision before this insn
2369                            */
2370                 }
2371         } else if (class == BPF_LDX) {
2372                 if (!(*reg_mask & dreg))
2373                         return 0;
2374                 *reg_mask &= ~dreg;
2375
2376                 /* scalars can only be spilled into stack w/o losing precision.
2377                  * Load from any other memory can be zero extended.
2378                  * The desire to keep that precision is already indicated
2379                  * by 'precise' mark in corresponding register of this state.
2380                  * No further tracking necessary.
2381                  */
2382                 if (insn->src_reg != BPF_REG_FP)
2383                         return 0;
2384                 if (BPF_SIZE(insn->code) != BPF_DW)
2385                         return 0;
2386
2387                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2388                  * that [fp - off] slot contains scalar that needs to be
2389                  * tracked with precision
2390                  */
2391                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2392                 if (spi >= 64) {
2393                         verbose(env, "BUG spi %d\n", spi);
2394                         WARN_ONCE(1, "verifier backtracking bug");
2395                         return -EFAULT;
2396                 }
2397                 *stack_mask |= 1ull << spi;
2398         } else if (class == BPF_STX || class == BPF_ST) {
2399                 if (*reg_mask & dreg)
2400                         /* stx & st shouldn't be using _scalar_ dst_reg
2401                          * to access memory. It means backtracking
2402                          * encountered a case of pointer subtraction.
2403                          */
2404                         return -ENOTSUPP;
2405                 /* scalars can only be spilled into stack */
2406                 if (insn->dst_reg != BPF_REG_FP)
2407                         return 0;
2408                 if (BPF_SIZE(insn->code) != BPF_DW)
2409                         return 0;
2410                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2411                 if (spi >= 64) {
2412                         verbose(env, "BUG spi %d\n", spi);
2413                         WARN_ONCE(1, "verifier backtracking bug");
2414                         return -EFAULT;
2415                 }
2416                 if (!(*stack_mask & (1ull << spi)))
2417                         return 0;
2418                 *stack_mask &= ~(1ull << spi);
2419                 if (class == BPF_STX)
2420                         *reg_mask |= sreg;
2421         } else if (class == BPF_JMP || class == BPF_JMP32) {
2422                 if (opcode == BPF_CALL) {
2423                         if (insn->src_reg == BPF_PSEUDO_CALL)
2424                                 return -ENOTSUPP;
2425                         /* regular helper call sets R0 */
2426                         *reg_mask &= ~1;
2427                         if (*reg_mask & 0x3f) {
2428                                 /* if backtracing was looking for registers R1-R5
2429                                  * they should have been found already.
2430                                  */
2431                                 verbose(env, "BUG regs %x\n", *reg_mask);
2432                                 WARN_ONCE(1, "verifier backtracking bug");
2433                                 return -EFAULT;
2434                         }
2435                 } else if (opcode == BPF_EXIT) {
2436                         return -ENOTSUPP;
2437                 }
2438         } else if (class == BPF_LD) {
2439                 if (!(*reg_mask & dreg))
2440                         return 0;
2441                 *reg_mask &= ~dreg;
2442                 /* It's ld_imm64 or ld_abs or ld_ind.
2443                  * For ld_imm64 no further tracking of precision
2444                  * into parent is necessary
2445                  */
2446                 if (mode == BPF_IND || mode == BPF_ABS)
2447                         /* to be analyzed */
2448                         return -ENOTSUPP;
2449         }
2450         return 0;
2451 }
2452
2453 /* the scalar precision tracking algorithm:
2454  * . at the start all registers have precise=false.
2455  * . scalar ranges are tracked as normal through alu and jmp insns.
2456  * . once precise value of the scalar register is used in:
2457  *   .  ptr + scalar alu
2458  *   . if (scalar cond K|scalar)
2459  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2460  *   backtrack through the verifier states and mark all registers and
2461  *   stack slots with spilled constants that these scalar regisers
2462  *   should be precise.
2463  * . during state pruning two registers (or spilled stack slots)
2464  *   are equivalent if both are not precise.
2465  *
2466  * Note the verifier cannot simply walk register parentage chain,
2467  * since many different registers and stack slots could have been
2468  * used to compute single precise scalar.
2469  *
2470  * The approach of starting with precise=true for all registers and then
2471  * backtrack to mark a register as not precise when the verifier detects
2472  * that program doesn't care about specific value (e.g., when helper
2473  * takes register as ARG_ANYTHING parameter) is not safe.
2474  *
2475  * It's ok to walk single parentage chain of the verifier states.
2476  * It's possible that this backtracking will go all the way till 1st insn.
2477  * All other branches will be explored for needing precision later.
2478  *
2479  * The backtracking needs to deal with cases like:
2480  *   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)
2481  * r9 -= r8
2482  * r5 = r9
2483  * if r5 > 0x79f goto pc+7
2484  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2485  * r5 += 1
2486  * ...
2487  * call bpf_perf_event_output#25
2488  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2489  *
2490  * and this case:
2491  * r6 = 1
2492  * call foo // uses callee's r6 inside to compute r0
2493  * r0 += r6
2494  * if r0 == 0 goto
2495  *
2496  * to track above reg_mask/stack_mask needs to be independent for each frame.
2497  *
2498  * Also if parent's curframe > frame where backtracking started,
2499  * the verifier need to mark registers in both frames, otherwise callees
2500  * may incorrectly prune callers. This is similar to
2501  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2502  *
2503  * For now backtracking falls back into conservative marking.
2504  */
2505 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2506                                      struct bpf_verifier_state *st)
2507 {
2508         struct bpf_func_state *func;
2509         struct bpf_reg_state *reg;
2510         int i, j;
2511
2512         /* big hammer: mark all scalars precise in this path.
2513          * pop_stack may still get !precise scalars.
2514          */
2515         for (; st; st = st->parent)
2516                 for (i = 0; i <= st->curframe; i++) {
2517                         func = st->frame[i];
2518                         for (j = 0; j < BPF_REG_FP; j++) {
2519                                 reg = &func->regs[j];
2520                                 if (reg->type != SCALAR_VALUE)
2521                                         continue;
2522                                 reg->precise = true;
2523                         }
2524                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2525                                 if (!is_spilled_reg(&func->stack[j]))
2526                                         continue;
2527                                 reg = &func->stack[j].spilled_ptr;
2528                                 if (reg->type != SCALAR_VALUE)
2529                                         continue;
2530                                 reg->precise = true;
2531                         }
2532                 }
2533 }
2534
2535 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2536                                   int spi)
2537 {
2538         struct bpf_verifier_state *st = env->cur_state;
2539         int first_idx = st->first_insn_idx;
2540         int last_idx = env->insn_idx;
2541         struct bpf_func_state *func;
2542         struct bpf_reg_state *reg;
2543         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2544         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2545         bool skip_first = true;
2546         bool new_marks = false;
2547         int i, err;
2548
2549         if (!env->bpf_capable)
2550                 return 0;
2551
2552         func = st->frame[st->curframe];
2553         if (regno >= 0) {
2554                 reg = &func->regs[regno];
2555                 if (reg->type != SCALAR_VALUE) {
2556                         WARN_ONCE(1, "backtracing misuse");
2557                         return -EFAULT;
2558                 }
2559                 if (!reg->precise)
2560                         new_marks = true;
2561                 else
2562                         reg_mask = 0;
2563                 reg->precise = true;
2564         }
2565
2566         while (spi >= 0) {
2567                 if (!is_spilled_reg(&func->stack[spi])) {
2568                         stack_mask = 0;
2569                         break;
2570                 }
2571                 reg = &func->stack[spi].spilled_ptr;
2572                 if (reg->type != SCALAR_VALUE) {
2573                         stack_mask = 0;
2574                         break;
2575                 }
2576                 if (!reg->precise)
2577                         new_marks = true;
2578                 else
2579                         stack_mask = 0;
2580                 reg->precise = true;
2581                 break;
2582         }
2583
2584         if (!new_marks)
2585                 return 0;
2586         if (!reg_mask && !stack_mask)
2587                 return 0;
2588         for (;;) {
2589                 DECLARE_BITMAP(mask, 64);
2590                 u32 history = st->jmp_history_cnt;
2591
2592                 if (env->log.level & BPF_LOG_LEVEL)
2593                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2594                 for (i = last_idx;;) {
2595                         if (skip_first) {
2596                                 err = 0;
2597                                 skip_first = false;
2598                         } else {
2599                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2600                         }
2601                         if (err == -ENOTSUPP) {
2602                                 mark_all_scalars_precise(env, st);
2603                                 return 0;
2604                         } else if (err) {
2605                                 return err;
2606                         }
2607                         if (!reg_mask && !stack_mask)
2608                                 /* Found assignment(s) into tracked register in this state.
2609                                  * Since this state is already marked, just return.
2610                                  * Nothing to be tracked further in the parent state.
2611                                  */
2612                                 return 0;
2613                         if (i == first_idx)
2614                                 break;
2615                         i = get_prev_insn_idx(st, i, &history);
2616                         if (i >= env->prog->len) {
2617                                 /* This can happen if backtracking reached insn 0
2618                                  * and there are still reg_mask or stack_mask
2619                                  * to backtrack.
2620                                  * It means the backtracking missed the spot where
2621                                  * particular register was initialized with a constant.
2622                                  */
2623                                 verbose(env, "BUG backtracking idx %d\n", i);
2624                                 WARN_ONCE(1, "verifier backtracking bug");
2625                                 return -EFAULT;
2626                         }
2627                 }
2628                 st = st->parent;
2629                 if (!st)
2630                         break;
2631
2632                 new_marks = false;
2633                 func = st->frame[st->curframe];
2634                 bitmap_from_u64(mask, reg_mask);
2635                 for_each_set_bit(i, mask, 32) {
2636                         reg = &func->regs[i];
2637                         if (reg->type != SCALAR_VALUE) {
2638                                 reg_mask &= ~(1u << i);
2639                                 continue;
2640                         }
2641                         if (!reg->precise)
2642                                 new_marks = true;
2643                         reg->precise = true;
2644                 }
2645
2646                 bitmap_from_u64(mask, stack_mask);
2647                 for_each_set_bit(i, mask, 64) {
2648                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2649                                 /* the sequence of instructions:
2650                                  * 2: (bf) r3 = r10
2651                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2652                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2653                                  * doesn't contain jmps. It's backtracked
2654                                  * as a single block.
2655                                  * During backtracking insn 3 is not recognized as
2656                                  * stack access, so at the end of backtracking
2657                                  * stack slot fp-8 is still marked in stack_mask.
2658                                  * However the parent state may not have accessed
2659                                  * fp-8 and it's "unallocated" stack space.
2660                                  * In such case fallback to conservative.
2661                                  */
2662                                 mark_all_scalars_precise(env, st);
2663                                 return 0;
2664                         }
2665
2666                         if (!is_spilled_reg(&func->stack[i])) {
2667                                 stack_mask &= ~(1ull << i);
2668                                 continue;
2669                         }
2670                         reg = &func->stack[i].spilled_ptr;
2671                         if (reg->type != SCALAR_VALUE) {
2672                                 stack_mask &= ~(1ull << i);
2673                                 continue;
2674                         }
2675                         if (!reg->precise)
2676                                 new_marks = true;
2677                         reg->precise = true;
2678                 }
2679                 if (env->log.level & BPF_LOG_LEVEL) {
2680                         print_verifier_state(env, func);
2681                         verbose(env, "parent %s regs=%x stack=%llx marks\n",
2682                                 new_marks ? "didn't have" : "already had",
2683                                 reg_mask, stack_mask);
2684                 }
2685
2686                 if (!reg_mask && !stack_mask)
2687                         break;
2688                 if (!new_marks)
2689                         break;
2690
2691                 last_idx = st->last_insn_idx;
2692                 first_idx = st->first_insn_idx;
2693         }
2694         return 0;
2695 }
2696
2697 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2698 {
2699         return __mark_chain_precision(env, regno, -1);
2700 }
2701
2702 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2703 {
2704         return __mark_chain_precision(env, -1, spi);
2705 }
2706
2707 static bool is_spillable_regtype(enum bpf_reg_type type)
2708 {
2709         switch (type) {
2710         case PTR_TO_MAP_VALUE:
2711         case PTR_TO_MAP_VALUE_OR_NULL:
2712         case PTR_TO_STACK:
2713         case PTR_TO_CTX:
2714         case PTR_TO_PACKET:
2715         case PTR_TO_PACKET_META:
2716         case PTR_TO_PACKET_END:
2717         case PTR_TO_FLOW_KEYS:
2718         case CONST_PTR_TO_MAP:
2719         case PTR_TO_SOCKET:
2720         case PTR_TO_SOCKET_OR_NULL:
2721         case PTR_TO_SOCK_COMMON:
2722         case PTR_TO_SOCK_COMMON_OR_NULL:
2723         case PTR_TO_TCP_SOCK:
2724         case PTR_TO_TCP_SOCK_OR_NULL:
2725         case PTR_TO_XDP_SOCK:
2726         case PTR_TO_BTF_ID:
2727         case PTR_TO_BTF_ID_OR_NULL:
2728         case PTR_TO_RDONLY_BUF:
2729         case PTR_TO_RDONLY_BUF_OR_NULL:
2730         case PTR_TO_RDWR_BUF:
2731         case PTR_TO_RDWR_BUF_OR_NULL:
2732         case PTR_TO_PERCPU_BTF_ID:
2733         case PTR_TO_MEM:
2734         case PTR_TO_MEM_OR_NULL:
2735         case PTR_TO_FUNC:
2736         case PTR_TO_MAP_KEY:
2737                 return true;
2738         default:
2739                 return false;
2740         }
2741 }
2742
2743 /* Does this register contain a constant zero? */
2744 static bool register_is_null(struct bpf_reg_state *reg)
2745 {
2746         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2747 }
2748
2749 static bool register_is_const(struct bpf_reg_state *reg)
2750 {
2751         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2752 }
2753
2754 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2755 {
2756         return tnum_is_unknown(reg->var_off) &&
2757                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2758                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2759                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2760                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2761 }
2762
2763 static bool register_is_bounded(struct bpf_reg_state *reg)
2764 {
2765         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2766 }
2767
2768 static bool __is_pointer_value(bool allow_ptr_leaks,
2769                                const struct bpf_reg_state *reg)
2770 {
2771         if (allow_ptr_leaks)
2772                 return false;
2773
2774         return reg->type != SCALAR_VALUE;
2775 }
2776
2777 static void save_register_state(struct bpf_func_state *state,
2778                                 int spi, struct bpf_reg_state *reg,
2779                                 int size)
2780 {
2781         int i;
2782
2783         state->stack[spi].spilled_ptr = *reg;
2784         if (size == BPF_REG_SIZE)
2785                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2786
2787         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2788                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2789
2790         /* size < 8 bytes spill */
2791         for (; i; i--)
2792                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2793 }
2794
2795 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2796  * stack boundary and alignment are checked in check_mem_access()
2797  */
2798 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2799                                        /* stack frame we're writing to */
2800                                        struct bpf_func_state *state,
2801                                        int off, int size, int value_regno,
2802                                        int insn_idx)
2803 {
2804         struct bpf_func_state *cur; /* state of the current function */
2805         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2806         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2807         struct bpf_reg_state *reg = NULL;
2808
2809         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2810         if (err)
2811                 return err;
2812         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2813          * so it's aligned access and [off, off + size) are within stack limits
2814          */
2815         if (!env->allow_ptr_leaks &&
2816             state->stack[spi].slot_type[0] == STACK_SPILL &&
2817             size != BPF_REG_SIZE) {
2818                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2819                 return -EACCES;
2820         }
2821
2822         cur = env->cur_state->frame[env->cur_state->curframe];
2823         if (value_regno >= 0)
2824                 reg = &cur->regs[value_regno];
2825         if (!env->bypass_spec_v4) {
2826                 bool sanitize = reg && is_spillable_regtype(reg->type);
2827
2828                 for (i = 0; i < size; i++) {
2829                         if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2830                                 sanitize = true;
2831                                 break;
2832                         }
2833                 }
2834
2835                 if (sanitize)
2836                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2837         }
2838
2839         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2840             !register_is_null(reg) && env->bpf_capable) {
2841                 if (dst_reg != BPF_REG_FP) {
2842                         /* The backtracking logic can only recognize explicit
2843                          * stack slot address like [fp - 8]. Other spill of
2844                          * scalar via different register has to be conservative.
2845                          * Backtrack from here and mark all registers as precise
2846                          * that contributed into 'reg' being a constant.
2847                          */
2848                         err = mark_chain_precision(env, value_regno);
2849                         if (err)
2850                                 return err;
2851                 }
2852                 save_register_state(state, spi, reg, size);
2853         } else if (reg && is_spillable_regtype(reg->type)) {
2854                 /* register containing pointer is being spilled into stack */
2855                 if (size != BPF_REG_SIZE) {
2856                         verbose_linfo(env, insn_idx, "; ");
2857                         verbose(env, "invalid size of register spill\n");
2858                         return -EACCES;
2859                 }
2860                 if (state != cur && reg->type == PTR_TO_STACK) {
2861                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2862                         return -EINVAL;
2863                 }
2864                 save_register_state(state, spi, reg, size);
2865         } else {
2866                 u8 type = STACK_MISC;
2867
2868                 /* regular write of data into stack destroys any spilled ptr */
2869                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2870                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2871                 if (is_spilled_reg(&state->stack[spi]))
2872                         for (i = 0; i < BPF_REG_SIZE; i++)
2873                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2874
2875                 /* only mark the slot as written if all 8 bytes were written
2876                  * otherwise read propagation may incorrectly stop too soon
2877                  * when stack slots are partially written.
2878                  * This heuristic means that read propagation will be
2879                  * conservative, since it will add reg_live_read marks
2880                  * to stack slots all the way to first state when programs
2881                  * writes+reads less than 8 bytes
2882                  */
2883                 if (size == BPF_REG_SIZE)
2884                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2885
2886                 /* when we zero initialize stack slots mark them as such */
2887                 if (reg && register_is_null(reg)) {
2888                         /* backtracking doesn't work for STACK_ZERO yet. */
2889                         err = mark_chain_precision(env, value_regno);
2890                         if (err)
2891                                 return err;
2892                         type = STACK_ZERO;
2893                 }
2894
2895                 /* Mark slots affected by this stack write. */
2896                 for (i = 0; i < size; i++)
2897                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2898                                 type;
2899         }
2900         return 0;
2901 }
2902
2903 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2904  * known to contain a variable offset.
2905  * This function checks whether the write is permitted and conservatively
2906  * tracks the effects of the write, considering that each stack slot in the
2907  * dynamic range is potentially written to.
2908  *
2909  * 'off' includes 'regno->off'.
2910  * 'value_regno' can be -1, meaning that an unknown value is being written to
2911  * the stack.
2912  *
2913  * Spilled pointers in range are not marked as written because we don't know
2914  * what's going to be actually written. This means that read propagation for
2915  * future reads cannot be terminated by this write.
2916  *
2917  * For privileged programs, uninitialized stack slots are considered
2918  * initialized by this write (even though we don't know exactly what offsets
2919  * are going to be written to). The idea is that we don't want the verifier to
2920  * reject future reads that access slots written to through variable offsets.
2921  */
2922 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2923                                      /* func where register points to */
2924                                      struct bpf_func_state *state,
2925                                      int ptr_regno, int off, int size,
2926                                      int value_regno, int insn_idx)
2927 {
2928         struct bpf_func_state *cur; /* state of the current function */
2929         int min_off, max_off;
2930         int i, err;
2931         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2932         bool writing_zero = false;
2933         /* set if the fact that we're writing a zero is used to let any
2934          * stack slots remain STACK_ZERO
2935          */
2936         bool zero_used = false;
2937
2938         cur = env->cur_state->frame[env->cur_state->curframe];
2939         ptr_reg = &cur->regs[ptr_regno];
2940         min_off = ptr_reg->smin_value + off;
2941         max_off = ptr_reg->smax_value + off + size;
2942         if (value_regno >= 0)
2943                 value_reg = &cur->regs[value_regno];
2944         if (value_reg && register_is_null(value_reg))
2945                 writing_zero = true;
2946
2947         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2948         if (err)
2949                 return err;
2950
2951
2952         /* Variable offset writes destroy any spilled pointers in range. */
2953         for (i = min_off; i < max_off; i++) {
2954                 u8 new_type, *stype;
2955                 int slot, spi;
2956
2957                 slot = -i - 1;
2958                 spi = slot / BPF_REG_SIZE;
2959                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2960
2961                 if (!env->allow_ptr_leaks
2962                                 && *stype != NOT_INIT
2963                                 && *stype != SCALAR_VALUE) {
2964                         /* Reject the write if there's are spilled pointers in
2965                          * range. If we didn't reject here, the ptr status
2966                          * would be erased below (even though not all slots are
2967                          * actually overwritten), possibly opening the door to
2968                          * leaks.
2969                          */
2970                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2971                                 insn_idx, i);
2972                         return -EINVAL;
2973                 }
2974
2975                 /* Erase all spilled pointers. */
2976                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2977
2978                 /* Update the slot type. */
2979                 new_type = STACK_MISC;
2980                 if (writing_zero && *stype == STACK_ZERO) {
2981                         new_type = STACK_ZERO;
2982                         zero_used = true;
2983                 }
2984                 /* If the slot is STACK_INVALID, we check whether it's OK to
2985                  * pretend that it will be initialized by this write. The slot
2986                  * might not actually be written to, and so if we mark it as
2987                  * initialized future reads might leak uninitialized memory.
2988                  * For privileged programs, we will accept such reads to slots
2989                  * that may or may not be written because, if we're reject
2990                  * them, the error would be too confusing.
2991                  */
2992                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2993                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2994                                         insn_idx, i);
2995                         return -EINVAL;
2996                 }
2997                 *stype = new_type;
2998         }
2999         if (zero_used) {
3000                 /* backtracking doesn't work for STACK_ZERO yet. */
3001                 err = mark_chain_precision(env, value_regno);
3002                 if (err)
3003                         return err;
3004         }
3005         return 0;
3006 }
3007
3008 /* When register 'dst_regno' is assigned some values from stack[min_off,
3009  * max_off), we set the register's type according to the types of the
3010  * respective stack slots. If all the stack values are known to be zeros, then
3011  * so is the destination reg. Otherwise, the register is considered to be
3012  * SCALAR. This function does not deal with register filling; the caller must
3013  * ensure that all spilled registers in the stack range have been marked as
3014  * read.
3015  */
3016 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3017                                 /* func where src register points to */
3018                                 struct bpf_func_state *ptr_state,
3019                                 int min_off, int max_off, int dst_regno)
3020 {
3021         struct bpf_verifier_state *vstate = env->cur_state;
3022         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3023         int i, slot, spi;
3024         u8 *stype;
3025         int zeros = 0;
3026
3027         for (i = min_off; i < max_off; i++) {
3028                 slot = -i - 1;
3029                 spi = slot / BPF_REG_SIZE;
3030                 stype = ptr_state->stack[spi].slot_type;
3031                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3032                         break;
3033                 zeros++;
3034         }
3035         if (zeros == max_off - min_off) {
3036                 /* any access_size read into register is zero extended,
3037                  * so the whole register == const_zero
3038                  */
3039                 __mark_reg_const_zero(&state->regs[dst_regno]);
3040                 /* backtracking doesn't support STACK_ZERO yet,
3041                  * so mark it precise here, so that later
3042                  * backtracking can stop here.
3043                  * Backtracking may not need this if this register
3044                  * doesn't participate in pointer adjustment.
3045                  * Forward propagation of precise flag is not
3046                  * necessary either. This mark is only to stop
3047                  * backtracking. Any register that contributed
3048                  * to const 0 was marked precise before spill.
3049                  */
3050                 state->regs[dst_regno].precise = true;
3051         } else {
3052                 /* have read misc data from the stack */
3053                 mark_reg_unknown(env, state->regs, dst_regno);
3054         }
3055         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3056 }
3057
3058 /* Read the stack at 'off' and put the results into the register indicated by
3059  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3060  * spilled reg.
3061  *
3062  * 'dst_regno' can be -1, meaning that the read value is not going to a
3063  * register.
3064  *
3065  * The access is assumed to be within the current stack bounds.
3066  */
3067 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3068                                       /* func where src register points to */
3069                                       struct bpf_func_state *reg_state,
3070                                       int off, int size, int dst_regno)
3071 {
3072         struct bpf_verifier_state *vstate = env->cur_state;
3073         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3074         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3075         struct bpf_reg_state *reg;
3076         u8 *stype, type;
3077
3078         stype = reg_state->stack[spi].slot_type;
3079         reg = &reg_state->stack[spi].spilled_ptr;
3080
3081         if (is_spilled_reg(&reg_state->stack[spi])) {
3082                 u8 spill_size = 1;
3083
3084                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3085                         spill_size++;
3086
3087                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3088                         if (reg->type != SCALAR_VALUE) {
3089                                 verbose_linfo(env, env->insn_idx, "; ");
3090                                 verbose(env, "invalid size of register fill\n");
3091                                 return -EACCES;
3092                         }
3093
3094                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3095                         if (dst_regno < 0)
3096                                 return 0;
3097
3098                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
3099                                 /* The earlier check_reg_arg() has decided the
3100                                  * subreg_def for this insn.  Save it first.
3101                                  */
3102                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
3103
3104                                 state->regs[dst_regno] = *reg;
3105                                 state->regs[dst_regno].subreg_def = subreg_def;
3106                         } else {
3107                                 for (i = 0; i < size; i++) {
3108                                         type = stype[(slot - i) % BPF_REG_SIZE];
3109                                         if (type == STACK_SPILL)
3110                                                 continue;
3111                                         if (type == STACK_MISC)
3112                                                 continue;
3113                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3114                                                 off, i, size);
3115                                         return -EACCES;
3116                                 }
3117                                 mark_reg_unknown(env, state->regs, dst_regno);
3118                         }
3119                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3120                         return 0;
3121                 }
3122
3123                 if (dst_regno >= 0) {
3124                         /* restore register state from stack */
3125                         state->regs[dst_regno] = *reg;
3126                         /* mark reg as written since spilled pointer state likely
3127                          * has its liveness marks cleared by is_state_visited()
3128                          * which resets stack/reg liveness for state transitions
3129                          */
3130                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3131                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3132                         /* If dst_regno==-1, the caller is asking us whether
3133                          * it is acceptable to use this value as a SCALAR_VALUE
3134                          * (e.g. for XADD).
3135                          * We must not allow unprivileged callers to do that
3136                          * with spilled pointers.
3137                          */
3138                         verbose(env, "leaking pointer from stack off %d\n",
3139                                 off);
3140                         return -EACCES;
3141                 }
3142                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3143         } else {
3144                 for (i = 0; i < size; i++) {
3145                         type = stype[(slot - i) % BPF_REG_SIZE];
3146                         if (type == STACK_MISC)
3147                                 continue;
3148                         if (type == STACK_ZERO)
3149                                 continue;
3150                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3151                                 off, i, size);
3152                         return -EACCES;
3153                 }
3154                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3155                 if (dst_regno >= 0)
3156                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3157         }
3158         return 0;
3159 }
3160
3161 enum stack_access_src {
3162         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3163         ACCESS_HELPER = 2,  /* the access is performed by a helper */
3164 };
3165
3166 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3167                                          int regno, int off, int access_size,
3168                                          bool zero_size_allowed,
3169                                          enum stack_access_src type,
3170                                          struct bpf_call_arg_meta *meta);
3171
3172 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3173 {
3174         return cur_regs(env) + regno;
3175 }
3176
3177 /* Read the stack at 'ptr_regno + off' and put the result into the register
3178  * 'dst_regno'.
3179  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3180  * but not its variable offset.
3181  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3182  *
3183  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3184  * filling registers (i.e. reads of spilled register cannot be detected when
3185  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3186  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3187  * offset; for a fixed offset check_stack_read_fixed_off should be used
3188  * instead.
3189  */
3190 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3191                                     int ptr_regno, int off, int size, int dst_regno)
3192 {
3193         /* The state of the source register. */
3194         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3195         struct bpf_func_state *ptr_state = func(env, reg);
3196         int err;
3197         int min_off, max_off;
3198
3199         /* Note that we pass a NULL meta, so raw access will not be permitted.
3200          */
3201         err = check_stack_range_initialized(env, ptr_regno, off, size,
3202                                             false, ACCESS_DIRECT, NULL);
3203         if (err)
3204                 return err;
3205
3206         min_off = reg->smin_value + off;
3207         max_off = reg->smax_value + off;
3208         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3209         return 0;
3210 }
3211
3212 /* check_stack_read dispatches to check_stack_read_fixed_off or
3213  * check_stack_read_var_off.
3214  *
3215  * The caller must ensure that the offset falls within the allocated stack
3216  * bounds.
3217  *
3218  * 'dst_regno' is a register which will receive the value from the stack. It
3219  * can be -1, meaning that the read value is not going to a register.
3220  */
3221 static int check_stack_read(struct bpf_verifier_env *env,
3222                             int ptr_regno, int off, int size,
3223                             int dst_regno)
3224 {
3225         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3226         struct bpf_func_state *state = func(env, reg);
3227         int err;
3228         /* Some accesses are only permitted with a static offset. */
3229         bool var_off = !tnum_is_const(reg->var_off);
3230
3231         /* The offset is required to be static when reads don't go to a
3232          * register, in order to not leak pointers (see
3233          * check_stack_read_fixed_off).
3234          */
3235         if (dst_regno < 0 && var_off) {
3236                 char tn_buf[48];
3237
3238                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3239                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3240                         tn_buf, off, size);
3241                 return -EACCES;
3242         }
3243         /* Variable offset is prohibited for unprivileged mode for simplicity
3244          * since it requires corresponding support in Spectre masking for stack
3245          * ALU. See also retrieve_ptr_limit().
3246          */
3247         if (!env->bypass_spec_v1 && var_off) {
3248                 char tn_buf[48];
3249
3250                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3251                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3252                                 ptr_regno, tn_buf);
3253                 return -EACCES;
3254         }
3255
3256         if (!var_off) {
3257                 off += reg->var_off.value;
3258                 err = check_stack_read_fixed_off(env, state, off, size,
3259                                                  dst_regno);
3260         } else {
3261                 /* Variable offset stack reads need more conservative handling
3262                  * than fixed offset ones. Note that dst_regno >= 0 on this
3263                  * branch.
3264                  */
3265                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3266                                                dst_regno);
3267         }
3268         return err;
3269 }
3270
3271
3272 /* check_stack_write dispatches to check_stack_write_fixed_off or
3273  * check_stack_write_var_off.
3274  *
3275  * 'ptr_regno' is the register used as a pointer into the stack.
3276  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3277  * 'value_regno' is the register whose value we're writing to the stack. It can
3278  * be -1, meaning that we're not writing from a register.
3279  *
3280  * The caller must ensure that the offset falls within the maximum stack size.
3281  */
3282 static int check_stack_write(struct bpf_verifier_env *env,
3283                              int ptr_regno, int off, int size,
3284                              int value_regno, int insn_idx)
3285 {
3286         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3287         struct bpf_func_state *state = func(env, reg);
3288         int err;
3289
3290         if (tnum_is_const(reg->var_off)) {
3291                 off += reg->var_off.value;
3292                 err = check_stack_write_fixed_off(env, state, off, size,
3293                                                   value_regno, insn_idx);
3294         } else {
3295                 /* Variable offset stack reads need more conservative handling
3296                  * than fixed offset ones.
3297                  */
3298                 err = check_stack_write_var_off(env, state,
3299                                                 ptr_regno, off, size,
3300                                                 value_regno, insn_idx);
3301         }
3302         return err;
3303 }
3304
3305 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3306                                  int off, int size, enum bpf_access_type type)
3307 {
3308         struct bpf_reg_state *regs = cur_regs(env);
3309         struct bpf_map *map = regs[regno].map_ptr;
3310         u32 cap = bpf_map_flags_to_cap(map);
3311
3312         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3313                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3314                         map->value_size, off, size);
3315                 return -EACCES;
3316         }
3317
3318         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3319                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3320                         map->value_size, off, size);
3321                 return -EACCES;
3322         }
3323
3324         return 0;
3325 }
3326
3327 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3328 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3329                               int off, int size, u32 mem_size,
3330                               bool zero_size_allowed)
3331 {
3332         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3333         struct bpf_reg_state *reg;
3334
3335         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3336                 return 0;
3337
3338         reg = &cur_regs(env)[regno];
3339         switch (reg->type) {
3340         case PTR_TO_MAP_KEY:
3341                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3342                         mem_size, off, size);
3343                 break;
3344         case PTR_TO_MAP_VALUE:
3345                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3346                         mem_size, off, size);
3347                 break;
3348         case PTR_TO_PACKET:
3349         case PTR_TO_PACKET_META:
3350         case PTR_TO_PACKET_END:
3351                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3352                         off, size, regno, reg->id, off, mem_size);
3353                 break;
3354         case PTR_TO_MEM:
3355         default:
3356                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3357                         mem_size, off, size);
3358         }
3359
3360         return -EACCES;
3361 }
3362
3363 /* check read/write into a memory region with possible variable offset */
3364 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3365                                    int off, int size, u32 mem_size,
3366                                    bool zero_size_allowed)
3367 {
3368         struct bpf_verifier_state *vstate = env->cur_state;
3369         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3370         struct bpf_reg_state *reg = &state->regs[regno];
3371         int err;
3372
3373         /* We may have adjusted the register pointing to memory region, so we
3374          * need to try adding each of min_value and max_value to off
3375          * to make sure our theoretical access will be safe.
3376          */
3377         if (env->log.level & BPF_LOG_LEVEL)
3378                 print_verifier_state(env, state);
3379
3380         /* The minimum value is only important with signed
3381          * comparisons where we can't assume the floor of a
3382          * value is 0.  If we are using signed variables for our
3383          * index'es we need to make sure that whatever we use
3384          * will have a set floor within our range.
3385          */
3386         if (reg->smin_value < 0 &&
3387             (reg->smin_value == S64_MIN ||
3388              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3389               reg->smin_value + off < 0)) {
3390                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3391                         regno);
3392                 return -EACCES;
3393         }
3394         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3395                                  mem_size, zero_size_allowed);
3396         if (err) {
3397                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3398                         regno);
3399                 return err;
3400         }
3401
3402         /* If we haven't set a max value then we need to bail since we can't be
3403          * sure we won't do bad things.
3404          * If reg->umax_value + off could overflow, treat that as unbounded too.
3405          */
3406         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3407                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3408                         regno);
3409                 return -EACCES;
3410         }
3411         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3412                                  mem_size, zero_size_allowed);
3413         if (err) {
3414                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3415                         regno);
3416                 return err;
3417         }
3418
3419         return 0;
3420 }
3421
3422 /* check read/write into a map element with possible variable offset */
3423 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3424                             int off, int size, bool zero_size_allowed)
3425 {
3426         struct bpf_verifier_state *vstate = env->cur_state;
3427         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3428         struct bpf_reg_state *reg = &state->regs[regno];
3429         struct bpf_map *map = reg->map_ptr;
3430         int err;
3431
3432         err = check_mem_region_access(env, regno, off, size, map->value_size,
3433                                       zero_size_allowed);
3434         if (err)
3435                 return err;
3436
3437         if (map_value_has_spin_lock(map)) {
3438                 u32 lock = map->spin_lock_off;
3439
3440                 /* if any part of struct bpf_spin_lock can be touched by
3441                  * load/store reject this program.
3442                  * To check that [x1, x2) overlaps with [y1, y2)
3443                  * it is sufficient to check x1 < y2 && y1 < x2.
3444                  */
3445                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3446                      lock < reg->umax_value + off + size) {
3447                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3448                         return -EACCES;
3449                 }
3450         }
3451         if (map_value_has_timer(map)) {
3452                 u32 t = map->timer_off;
3453
3454                 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3455                      t < reg->umax_value + off + size) {
3456                         verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3457                         return -EACCES;
3458                 }
3459         }
3460         return err;
3461 }
3462
3463 #define MAX_PACKET_OFF 0xffff
3464
3465 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3466 {
3467         return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3468 }
3469
3470 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3471                                        const struct bpf_call_arg_meta *meta,
3472                                        enum bpf_access_type t)
3473 {
3474         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3475
3476         switch (prog_type) {
3477         /* Program types only with direct read access go here! */
3478         case BPF_PROG_TYPE_LWT_IN:
3479         case BPF_PROG_TYPE_LWT_OUT:
3480         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3481         case BPF_PROG_TYPE_SK_REUSEPORT:
3482         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3483         case BPF_PROG_TYPE_CGROUP_SKB:
3484                 if (t == BPF_WRITE)
3485                         return false;
3486                 fallthrough;
3487
3488         /* Program types with direct read + write access go here! */
3489         case BPF_PROG_TYPE_SCHED_CLS:
3490         case BPF_PROG_TYPE_SCHED_ACT:
3491         case BPF_PROG_TYPE_XDP:
3492         case BPF_PROG_TYPE_LWT_XMIT:
3493         case BPF_PROG_TYPE_SK_SKB:
3494         case BPF_PROG_TYPE_SK_MSG:
3495                 if (meta)
3496                         return meta->pkt_access;
3497
3498                 env->seen_direct_write = true;
3499                 return true;
3500
3501         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3502                 if (t == BPF_WRITE)
3503                         env->seen_direct_write = true;
3504
3505                 return true;
3506
3507         default:
3508                 return false;
3509         }
3510 }
3511
3512 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3513                                int size, bool zero_size_allowed)
3514 {
3515         struct bpf_reg_state *regs = cur_regs(env);
3516         struct bpf_reg_state *reg = &regs[regno];
3517         int err;
3518
3519         /* We may have added a variable offset to the packet pointer; but any
3520          * reg->range we have comes after that.  We are only checking the fixed
3521          * offset.
3522          */
3523
3524         /* We don't allow negative numbers, because we aren't tracking enough
3525          * detail to prove they're safe.
3526          */
3527         if (reg->smin_value < 0) {
3528                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3529                         regno);
3530                 return -EACCES;
3531         }
3532
3533         err = reg->range < 0 ? -EINVAL :
3534               __check_mem_access(env, regno, off, size, reg->range,
3535                                  zero_size_allowed);
3536         if (err) {
3537                 verbose(env, "R%d offset is outside of the packet\n", regno);
3538                 return err;
3539         }
3540
3541         /* __check_mem_access has made sure "off + size - 1" is within u16.
3542          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3543          * otherwise find_good_pkt_pointers would have refused to set range info
3544          * that __check_mem_access would have rejected this pkt access.
3545          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3546          */
3547         env->prog->aux->max_pkt_offset =
3548                 max_t(u32, env->prog->aux->max_pkt_offset,
3549                       off + reg->umax_value + size - 1);
3550
3551         return err;
3552 }
3553
3554 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3555 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3556                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
3557                             struct btf **btf, u32 *btf_id)
3558 {
3559         struct bpf_insn_access_aux info = {
3560                 .reg_type = *reg_type,
3561                 .log = &env->log,
3562         };
3563
3564         if (env->ops->is_valid_access &&
3565             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3566                 /* A non zero info.ctx_field_size indicates that this field is a
3567                  * candidate for later verifier transformation to load the whole
3568                  * field and then apply a mask when accessed with a narrower
3569                  * access than actual ctx access size. A zero info.ctx_field_size
3570                  * will only allow for whole field access and rejects any other
3571                  * type of narrower access.
3572                  */
3573                 *reg_type = info.reg_type;
3574
3575                 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3576                         *btf = info.btf;
3577                         *btf_id = info.btf_id;
3578                 } else {
3579                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3580                 }
3581                 /* remember the offset of last byte accessed in ctx */
3582                 if (env->prog->aux->max_ctx_offset < off + size)
3583                         env->prog->aux->max_ctx_offset = off + size;
3584                 return 0;
3585         }
3586
3587         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3588         return -EACCES;
3589 }
3590
3591 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3592                                   int size)
3593 {
3594         if (size < 0 || off < 0 ||
3595             (u64)off + size > sizeof(struct bpf_flow_keys)) {
3596                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3597                         off, size);
3598                 return -EACCES;
3599         }
3600         return 0;
3601 }
3602
3603 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3604                              u32 regno, int off, int size,
3605                              enum bpf_access_type t)
3606 {
3607         struct bpf_reg_state *regs = cur_regs(env);
3608         struct bpf_reg_state *reg = &regs[regno];
3609         struct bpf_insn_access_aux info = {};
3610         bool valid;
3611
3612         if (reg->smin_value < 0) {
3613                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3614                         regno);
3615                 return -EACCES;
3616         }
3617
3618         switch (reg->type) {
3619         case PTR_TO_SOCK_COMMON:
3620                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3621                 break;
3622         case PTR_TO_SOCKET:
3623                 valid = bpf_sock_is_valid_access(off, size, t, &info);
3624                 break;
3625         case PTR_TO_TCP_SOCK:
3626                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3627                 break;
3628         case PTR_TO_XDP_SOCK:
3629                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3630                 break;
3631         default:
3632                 valid = false;
3633         }
3634
3635
3636         if (valid) {
3637                 env->insn_aux_data[insn_idx].ctx_field_size =
3638                         info.ctx_field_size;
3639                 return 0;
3640         }
3641
3642         verbose(env, "R%d invalid %s access off=%d size=%d\n",
3643                 regno, reg_type_str[reg->type], off, size);
3644
3645         return -EACCES;
3646 }
3647
3648 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3649 {
3650         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3651 }
3652
3653 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3654 {
3655         const struct bpf_reg_state *reg = reg_state(env, regno);
3656
3657         return reg->type == PTR_TO_CTX;
3658 }
3659
3660 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3661 {
3662         const struct bpf_reg_state *reg = reg_state(env, regno);
3663
3664         return type_is_sk_pointer(reg->type);
3665 }
3666
3667 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3668 {
3669         const struct bpf_reg_state *reg = reg_state(env, regno);
3670
3671         return type_is_pkt_pointer(reg->type);
3672 }
3673
3674 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3675 {
3676         const struct bpf_reg_state *reg = reg_state(env, regno);
3677
3678         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3679         return reg->type == PTR_TO_FLOW_KEYS;
3680 }
3681
3682 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3683                                    const struct bpf_reg_state *reg,
3684                                    int off, int size, bool strict)
3685 {
3686         struct tnum reg_off;
3687         int ip_align;
3688
3689         /* Byte size accesses are always allowed. */
3690         if (!strict || size == 1)
3691                 return 0;
3692
3693         /* For platforms that do not have a Kconfig enabling
3694          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3695          * NET_IP_ALIGN is universally set to '2'.  And on platforms
3696          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3697          * to this code only in strict mode where we want to emulate
3698          * the NET_IP_ALIGN==2 checking.  Therefore use an
3699          * unconditional IP align value of '2'.
3700          */
3701         ip_align = 2;
3702
3703         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3704         if (!tnum_is_aligned(reg_off, size)) {
3705                 char tn_buf[48];
3706
3707                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3708                 verbose(env,
3709                         "misaligned packet access off %d+%s+%d+%d size %d\n",
3710                         ip_align, tn_buf, reg->off, off, size);
3711                 return -EACCES;
3712         }
3713
3714         return 0;
3715 }
3716
3717 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3718                                        const struct bpf_reg_state *reg,
3719                                        const char *pointer_desc,
3720                                        int off, int size, bool strict)
3721 {
3722         struct tnum reg_off;
3723
3724         /* Byte size accesses are always allowed. */
3725         if (!strict || size == 1)
3726                 return 0;
3727
3728         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3729         if (!tnum_is_aligned(reg_off, size)) {
3730                 char tn_buf[48];
3731
3732                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3733                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3734                         pointer_desc, tn_buf, reg->off, off, size);
3735                 return -EACCES;
3736         }
3737
3738         return 0;
3739 }
3740
3741 static int check_ptr_alignment(struct bpf_verifier_env *env,
3742                                const struct bpf_reg_state *reg, int off,
3743                                int size, bool strict_alignment_once)
3744 {
3745         bool strict = env->strict_alignment || strict_alignment_once;
3746         const char *pointer_desc = "";
3747
3748         switch (reg->type) {
3749         case PTR_TO_PACKET:
3750         case PTR_TO_PACKET_META:
3751                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3752                  * right in front, treat it the very same way.
3753                  */
3754                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3755         case PTR_TO_FLOW_KEYS:
3756                 pointer_desc = "flow keys ";
3757                 break;
3758         case PTR_TO_MAP_KEY:
3759                 pointer_desc = "key ";
3760                 break;
3761         case PTR_TO_MAP_VALUE:
3762                 pointer_desc = "value ";
3763                 break;
3764         case PTR_TO_CTX:
3765                 pointer_desc = "context ";
3766                 break;
3767         case PTR_TO_STACK:
3768                 pointer_desc = "stack ";
3769                 /* The stack spill tracking logic in check_stack_write_fixed_off()
3770                  * and check_stack_read_fixed_off() relies on stack accesses being
3771                  * aligned.
3772                  */
3773                 strict = true;
3774                 break;
3775         case PTR_TO_SOCKET:
3776                 pointer_desc = "sock ";
3777                 break;
3778         case PTR_TO_SOCK_COMMON:
3779                 pointer_desc = "sock_common ";
3780                 break;
3781         case PTR_TO_TCP_SOCK:
3782                 pointer_desc = "tcp_sock ";
3783                 break;
3784         case PTR_TO_XDP_SOCK:
3785                 pointer_desc = "xdp_sock ";
3786                 break;
3787         default:
3788                 break;
3789         }
3790         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3791                                            strict);
3792 }
3793
3794 static int update_stack_depth(struct bpf_verifier_env *env,
3795                               const struct bpf_func_state *func,
3796                               int off)
3797 {
3798         u16 stack = env->subprog_info[func->subprogno].stack_depth;
3799
3800         if (stack >= -off)
3801                 return 0;
3802
3803         /* update known max for given subprogram */
3804         env->subprog_info[func->subprogno].stack_depth = -off;
3805         return 0;
3806 }
3807
3808 /* starting from main bpf function walk all instructions of the function
3809  * and recursively walk all callees that given function can call.
3810  * Ignore jump and exit insns.
3811  * Since recursion is prevented by check_cfg() this algorithm
3812  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3813  */
3814 static int check_max_stack_depth(struct bpf_verifier_env *env)
3815 {
3816         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3817         struct bpf_subprog_info *subprog = env->subprog_info;
3818         struct bpf_insn *insn = env->prog->insnsi;
3819         bool tail_call_reachable = false;
3820         int ret_insn[MAX_CALL_FRAMES];
3821         int ret_prog[MAX_CALL_FRAMES];
3822         int j;
3823
3824 process_func:
3825         /* protect against potential stack overflow that might happen when
3826          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3827          * depth for such case down to 256 so that the worst case scenario
3828          * would result in 8k stack size (32 which is tailcall limit * 256 =
3829          * 8k).
3830          *
3831          * To get the idea what might happen, see an example:
3832          * func1 -> sub rsp, 128
3833          *  subfunc1 -> sub rsp, 256
3834          *  tailcall1 -> add rsp, 256
3835          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3836          *   subfunc2 -> sub rsp, 64
3837          *   subfunc22 -> sub rsp, 128
3838          *   tailcall2 -> add rsp, 128
3839          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3840          *
3841          * tailcall will unwind the current stack frame but it will not get rid
3842          * of caller's stack as shown on the example above.
3843          */
3844         if (idx && subprog[idx].has_tail_call && depth >= 256) {
3845                 verbose(env,
3846                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3847                         depth);
3848                 return -EACCES;
3849         }
3850         /* round up to 32-bytes, since this is granularity
3851          * of interpreter stack size
3852          */
3853         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3854         if (depth > MAX_BPF_STACK) {
3855                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3856                         frame + 1, depth);
3857                 return -EACCES;
3858         }
3859 continue_func:
3860         subprog_end = subprog[idx + 1].start;
3861         for (; i < subprog_end; i++) {
3862                 int next_insn;
3863
3864                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3865                         continue;
3866                 /* remember insn and function to return to */
3867                 ret_insn[frame] = i + 1;
3868                 ret_prog[frame] = idx;
3869
3870                 /* find the callee */
3871                 next_insn = i + insn[i].imm + 1;
3872                 idx = find_subprog(env, next_insn);
3873                 if (idx < 0) {
3874                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3875                                   next_insn);
3876                         return -EFAULT;
3877                 }
3878                 if (subprog[idx].is_async_cb) {
3879                         if (subprog[idx].has_tail_call) {
3880                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3881                                 return -EFAULT;
3882                         }
3883                          /* async callbacks don't increase bpf prog stack size */
3884                         continue;
3885                 }
3886                 i = next_insn;
3887
3888                 if (subprog[idx].has_tail_call)
3889                         tail_call_reachable = true;
3890
3891                 frame++;
3892                 if (frame >= MAX_CALL_FRAMES) {
3893                         verbose(env, "the call stack of %d frames is too deep !\n",
3894                                 frame);
3895                         return -E2BIG;
3896                 }
3897                 goto process_func;
3898         }
3899         /* if tail call got detected across bpf2bpf calls then mark each of the
3900          * currently present subprog frames as tail call reachable subprogs;
3901          * this info will be utilized by JIT so that we will be preserving the
3902          * tail call counter throughout bpf2bpf calls combined with tailcalls
3903          */
3904         if (tail_call_reachable)
3905                 for (j = 0; j < frame; j++)
3906                         subprog[ret_prog[j]].tail_call_reachable = true;
3907         if (subprog[0].tail_call_reachable)
3908                 env->prog->aux->tail_call_reachable = true;
3909
3910         /* end of for() loop means the last insn of the 'subprog'
3911          * was reached. Doesn't matter whether it was JA or EXIT
3912          */
3913         if (frame == 0)
3914                 return 0;
3915         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3916         frame--;
3917         i = ret_insn[frame];
3918         idx = ret_prog[frame];
3919         goto continue_func;
3920 }
3921
3922 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3923 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3924                                   const struct bpf_insn *insn, int idx)
3925 {
3926         int start = idx + insn->imm + 1, subprog;
3927
3928         subprog = find_subprog(env, start);
3929         if (subprog < 0) {
3930                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3931                           start);
3932                 return -EFAULT;
3933         }
3934         return env->subprog_info[subprog].stack_depth;
3935 }
3936 #endif
3937
3938 int check_ctx_reg(struct bpf_verifier_env *env,
3939                   const struct bpf_reg_state *reg, int regno)
3940 {
3941         /* Access to ctx or passing it to a helper is only allowed in
3942          * its original, unmodified form.
3943          */
3944
3945         if (reg->off) {
3946                 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3947                         regno, reg->off);
3948                 return -EACCES;
3949         }
3950
3951         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3952                 char tn_buf[48];
3953
3954                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3955                 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3956                 return -EACCES;
3957         }
3958
3959         return 0;
3960 }
3961
3962 static int __check_buffer_access(struct bpf_verifier_env *env,
3963                                  const char *buf_info,
3964                                  const struct bpf_reg_state *reg,
3965                                  int regno, int off, int size)
3966 {
3967         if (off < 0) {
3968                 verbose(env,
3969                         "R%d invalid %s buffer access: off=%d, size=%d\n",
3970                         regno, buf_info, off, size);
3971                 return -EACCES;
3972         }
3973         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3974                 char tn_buf[48];
3975
3976                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3977                 verbose(env,
3978                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3979                         regno, off, tn_buf);
3980                 return -EACCES;
3981         }
3982
3983         return 0;
3984 }
3985
3986 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3987                                   const struct bpf_reg_state *reg,
3988                                   int regno, int off, int size)
3989 {
3990         int err;
3991
3992         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3993         if (err)
3994                 return err;
3995
3996         if (off + size > env->prog->aux->max_tp_access)
3997                 env->prog->aux->max_tp_access = off + size;
3998
3999         return 0;
4000 }
4001
4002 static int check_buffer_access(struct bpf_verifier_env *env,
4003                                const struct bpf_reg_state *reg,
4004                                int regno, int off, int size,
4005                                bool zero_size_allowed,
4006                                const char *buf_info,
4007                                u32 *max_access)
4008 {
4009         int err;
4010
4011         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4012         if (err)
4013                 return err;
4014
4015         if (off + size > *max_access)
4016                 *max_access = off + size;
4017
4018         return 0;
4019 }
4020
4021 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4022 static void zext_32_to_64(struct bpf_reg_state *reg)
4023 {
4024         reg->var_off = tnum_subreg(reg->var_off);
4025         __reg_assign_32_into_64(reg);
4026 }
4027
4028 /* truncate register to smaller size (in bytes)
4029  * must be called with size < BPF_REG_SIZE
4030  */
4031 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4032 {
4033         u64 mask;
4034
4035         /* clear high bits in bit representation */
4036         reg->var_off = tnum_cast(reg->var_off, size);
4037
4038         /* fix arithmetic bounds */
4039         mask = ((u64)1 << (size * 8)) - 1;
4040         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4041                 reg->umin_value &= mask;
4042                 reg->umax_value &= mask;
4043         } else {
4044                 reg->umin_value = 0;
4045                 reg->umax_value = mask;
4046         }
4047         reg->smin_value = reg->umin_value;
4048         reg->smax_value = reg->umax_value;
4049
4050         /* If size is smaller than 32bit register the 32bit register
4051          * values are also truncated so we push 64-bit bounds into
4052          * 32-bit bounds. Above were truncated < 32-bits already.
4053          */
4054         if (size >= 4)
4055                 return;
4056         __reg_combine_64_into_32(reg);
4057 }
4058
4059 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4060 {
4061         /* A map is considered read-only if the following condition are true:
4062          *
4063          * 1) BPF program side cannot change any of the map content. The
4064          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4065          *    and was set at map creation time.
4066          * 2) The map value(s) have been initialized from user space by a
4067          *    loader and then "frozen", such that no new map update/delete
4068          *    operations from syscall side are possible for the rest of
4069          *    the map's lifetime from that point onwards.
4070          * 3) Any parallel/pending map update/delete operations from syscall
4071          *    side have been completed. Only after that point, it's safe to
4072          *    assume that map value(s) are immutable.
4073          */
4074         return (map->map_flags & BPF_F_RDONLY_PROG) &&
4075                READ_ONCE(map->frozen) &&
4076                !bpf_map_write_active(map);
4077 }
4078
4079 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4080 {
4081         void *ptr;
4082         u64 addr;
4083         int err;
4084
4085         err = map->ops->map_direct_value_addr(map, &addr, off);
4086         if (err)
4087                 return err;
4088         ptr = (void *)(long)addr + off;
4089
4090         switch (size) {
4091         case sizeof(u8):
4092                 *val = (u64)*(u8 *)ptr;
4093                 break;
4094         case sizeof(u16):
4095                 *val = (u64)*(u16 *)ptr;
4096                 break;
4097         case sizeof(u32):
4098                 *val = (u64)*(u32 *)ptr;
4099                 break;
4100         case sizeof(u64):
4101                 *val = *(u64 *)ptr;
4102                 break;
4103         default:
4104                 return -EINVAL;
4105         }
4106         return 0;
4107 }
4108
4109 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4110                                    struct bpf_reg_state *regs,
4111                                    int regno, int off, int size,
4112                                    enum bpf_access_type atype,
4113                                    int value_regno)
4114 {
4115         struct bpf_reg_state *reg = regs + regno;
4116         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4117         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4118         u32 btf_id;
4119         int ret;
4120
4121         if (off < 0) {
4122                 verbose(env,
4123                         "R%d is ptr_%s invalid negative access: off=%d\n",
4124                         regno, tname, off);
4125                 return -EACCES;
4126         }
4127         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4128                 char tn_buf[48];
4129
4130                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4131                 verbose(env,
4132                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4133                         regno, tname, off, tn_buf);
4134                 return -EACCES;
4135         }
4136
4137         if (env->ops->btf_struct_access) {
4138                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4139                                                   off, size, atype, &btf_id);
4140         } else {
4141                 if (atype != BPF_READ) {
4142                         verbose(env, "only read is supported\n");
4143                         return -EACCES;
4144                 }
4145
4146                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4147                                         atype, &btf_id);
4148         }
4149
4150         if (ret < 0)
4151                 return ret;
4152
4153         if (atype == BPF_READ && value_regno >= 0)
4154                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
4155
4156         return 0;
4157 }
4158
4159 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4160                                    struct bpf_reg_state *regs,
4161                                    int regno, int off, int size,
4162                                    enum bpf_access_type atype,
4163                                    int value_regno)
4164 {
4165         struct bpf_reg_state *reg = regs + regno;
4166         struct bpf_map *map = reg->map_ptr;
4167         const struct btf_type *t;
4168         const char *tname;
4169         u32 btf_id;
4170         int ret;
4171
4172         if (!btf_vmlinux) {
4173                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4174                 return -ENOTSUPP;
4175         }
4176
4177         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4178                 verbose(env, "map_ptr access not supported for map type %d\n",
4179                         map->map_type);
4180                 return -ENOTSUPP;
4181         }
4182
4183         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4184         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4185
4186         if (!env->allow_ptr_to_map_access) {
4187                 verbose(env,
4188                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4189                         tname);
4190                 return -EPERM;
4191         }
4192
4193         if (off < 0) {
4194                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4195                         regno, tname, off);
4196                 return -EACCES;
4197         }
4198
4199         if (atype != BPF_READ) {
4200                 verbose(env, "only read from %s is supported\n", tname);
4201                 return -EACCES;
4202         }
4203
4204         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
4205         if (ret < 0)
4206                 return ret;
4207
4208         if (value_regno >= 0)
4209                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
4210
4211         return 0;
4212 }
4213
4214 /* Check that the stack access at the given offset is within bounds. The
4215  * maximum valid offset is -1.
4216  *
4217  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4218  * -state->allocated_stack for reads.
4219  */
4220 static int check_stack_slot_within_bounds(int off,
4221                                           struct bpf_func_state *state,
4222                                           enum bpf_access_type t)
4223 {
4224         int min_valid_off;
4225
4226         if (t == BPF_WRITE)
4227                 min_valid_off = -MAX_BPF_STACK;
4228         else
4229                 min_valid_off = -state->allocated_stack;
4230
4231         if (off < min_valid_off || off > -1)
4232                 return -EACCES;
4233         return 0;
4234 }
4235
4236 /* Check that the stack access at 'regno + off' falls within the maximum stack
4237  * bounds.
4238  *
4239  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4240  */
4241 static int check_stack_access_within_bounds(
4242                 struct bpf_verifier_env *env,
4243                 int regno, int off, int access_size,
4244                 enum stack_access_src src, enum bpf_access_type type)
4245 {
4246         struct bpf_reg_state *regs = cur_regs(env);
4247         struct bpf_reg_state *reg = regs + regno;
4248         struct bpf_func_state *state = func(env, reg);
4249         int min_off, max_off;
4250         int err;
4251         char *err_extra;
4252
4253         if (src == ACCESS_HELPER)
4254                 /* We don't know if helpers are reading or writing (or both). */
4255                 err_extra = " indirect access to";
4256         else if (type == BPF_READ)
4257                 err_extra = " read from";
4258         else
4259                 err_extra = " write to";
4260
4261         if (tnum_is_const(reg->var_off)) {
4262                 min_off = reg->var_off.value + off;
4263                 if (access_size > 0)
4264                         max_off = min_off + access_size - 1;
4265                 else
4266                         max_off = min_off;
4267         } else {
4268                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4269                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4270                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4271                                 err_extra, regno);
4272                         return -EACCES;
4273                 }
4274                 min_off = reg->smin_value + off;
4275                 if (access_size > 0)
4276                         max_off = reg->smax_value + off + access_size - 1;
4277                 else
4278                         max_off = min_off;
4279         }
4280
4281         err = check_stack_slot_within_bounds(min_off, state, type);
4282         if (!err)
4283                 err = check_stack_slot_within_bounds(max_off, state, type);
4284
4285         if (err) {
4286                 if (tnum_is_const(reg->var_off)) {
4287                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4288                                 err_extra, regno, off, access_size);
4289                 } else {
4290                         char tn_buf[48];
4291
4292                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4293                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4294                                 err_extra, regno, tn_buf, access_size);
4295                 }
4296         }
4297         return err;
4298 }
4299
4300 /* check whether memory at (regno + off) is accessible for t = (read | write)
4301  * if t==write, value_regno is a register which value is stored into memory
4302  * if t==read, value_regno is a register which will receive the value from memory
4303  * if t==write && value_regno==-1, some unknown value is stored into memory
4304  * if t==read && value_regno==-1, don't care what we read from memory
4305  */
4306 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4307                             int off, int bpf_size, enum bpf_access_type t,
4308                             int value_regno, bool strict_alignment_once)
4309 {
4310         struct bpf_reg_state *regs = cur_regs(env);
4311         struct bpf_reg_state *reg = regs + regno;
4312         struct bpf_func_state *state;
4313         int size, err = 0;
4314
4315         size = bpf_size_to_bytes(bpf_size);
4316         if (size < 0)
4317                 return size;
4318
4319         /* alignment checks will add in reg->off themselves */
4320         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4321         if (err)
4322                 return err;
4323
4324         /* for access checks, reg->off is just part of off */
4325         off += reg->off;
4326
4327         if (reg->type == PTR_TO_MAP_KEY) {
4328                 if (t == BPF_WRITE) {
4329                         verbose(env, "write to change key R%d not allowed\n", regno);
4330                         return -EACCES;
4331                 }
4332
4333                 err = check_mem_region_access(env, regno, off, size,
4334                                               reg->map_ptr->key_size, false);
4335                 if (err)
4336                         return err;
4337                 if (value_regno >= 0)
4338                         mark_reg_unknown(env, regs, value_regno);
4339         } else if (reg->type == PTR_TO_MAP_VALUE) {
4340                 if (t == BPF_WRITE && value_regno >= 0 &&
4341                     is_pointer_value(env, value_regno)) {
4342                         verbose(env, "R%d leaks addr into map\n", value_regno);
4343                         return -EACCES;
4344                 }
4345                 err = check_map_access_type(env, regno, off, size, t);
4346                 if (err)
4347                         return err;
4348                 err = check_map_access(env, regno, off, size, false);
4349                 if (!err && t == BPF_READ && value_regno >= 0) {
4350                         struct bpf_map *map = reg->map_ptr;
4351
4352                         /* if map is read-only, track its contents as scalars */
4353                         if (tnum_is_const(reg->var_off) &&
4354                             bpf_map_is_rdonly(map) &&
4355                             map->ops->map_direct_value_addr) {
4356                                 int map_off = off + reg->var_off.value;
4357                                 u64 val = 0;
4358
4359                                 err = bpf_map_direct_read(map, map_off, size,
4360                                                           &val);
4361                                 if (err)
4362                                         return err;
4363
4364                                 regs[value_regno].type = SCALAR_VALUE;
4365                                 __mark_reg_known(&regs[value_regno], val);
4366                         } else {
4367                                 mark_reg_unknown(env, regs, value_regno);
4368                         }
4369                 }
4370         } else if (reg->type == PTR_TO_MEM) {
4371                 if (t == BPF_WRITE && value_regno >= 0 &&
4372                     is_pointer_value(env, value_regno)) {
4373                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4374                         return -EACCES;
4375                 }
4376                 err = check_mem_region_access(env, regno, off, size,
4377                                               reg->mem_size, false);
4378                 if (!err && t == BPF_READ && value_regno >= 0)
4379                         mark_reg_unknown(env, regs, value_regno);
4380         } else if (reg->type == PTR_TO_CTX) {
4381                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4382                 struct btf *btf = NULL;
4383                 u32 btf_id = 0;
4384
4385                 if (t == BPF_WRITE && value_regno >= 0 &&
4386                     is_pointer_value(env, value_regno)) {
4387                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4388                         return -EACCES;
4389                 }
4390
4391                 err = check_ctx_reg(env, reg, regno);
4392                 if (err < 0)
4393                         return err;
4394
4395                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4396                 if (err)
4397                         verbose_linfo(env, insn_idx, "; ");
4398                 if (!err && t == BPF_READ && value_regno >= 0) {
4399                         /* ctx access returns either a scalar, or a
4400                          * PTR_TO_PACKET[_META,_END]. In the latter
4401                          * case, we know the offset is zero.
4402                          */
4403                         if (reg_type == SCALAR_VALUE) {
4404                                 mark_reg_unknown(env, regs, value_regno);
4405                         } else {
4406                                 mark_reg_known_zero(env, regs,
4407                                                     value_regno);
4408                                 if (reg_type_may_be_null(reg_type))
4409                                         regs[value_regno].id = ++env->id_gen;
4410                                 /* A load of ctx field could have different
4411                                  * actual load size with the one encoded in the
4412                                  * insn. When the dst is PTR, it is for sure not
4413                                  * a sub-register.
4414                                  */
4415                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4416                                 if (reg_type == PTR_TO_BTF_ID ||
4417                                     reg_type == PTR_TO_BTF_ID_OR_NULL) {
4418                                         regs[value_regno].btf = btf;
4419                                         regs[value_regno].btf_id = btf_id;
4420                                 }
4421                         }
4422                         regs[value_regno].type = reg_type;
4423                 }
4424
4425         } else if (reg->type == PTR_TO_STACK) {
4426                 /* Basic bounds checks. */
4427                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4428                 if (err)
4429                         return err;
4430
4431                 state = func(env, reg);
4432                 err = update_stack_depth(env, state, off);
4433                 if (err)
4434                         return err;
4435
4436                 if (t == BPF_READ)
4437                         err = check_stack_read(env, regno, off, size,
4438                                                value_regno);
4439                 else
4440                         err = check_stack_write(env, regno, off, size,
4441                                                 value_regno, insn_idx);
4442         } else if (reg_is_pkt_pointer(reg)) {
4443                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4444                         verbose(env, "cannot write into packet\n");
4445                         return -EACCES;
4446                 }
4447                 if (t == BPF_WRITE && value_regno >= 0 &&
4448                     is_pointer_value(env, value_regno)) {
4449                         verbose(env, "R%d leaks addr into packet\n",
4450                                 value_regno);
4451                         return -EACCES;
4452                 }
4453                 err = check_packet_access(env, regno, off, size, false);
4454                 if (!err && t == BPF_READ && value_regno >= 0)
4455                         mark_reg_unknown(env, regs, value_regno);
4456         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4457                 if (t == BPF_WRITE && value_regno >= 0 &&
4458                     is_pointer_value(env, value_regno)) {
4459                         verbose(env, "R%d leaks addr into flow keys\n",
4460                                 value_regno);
4461                         return -EACCES;
4462                 }
4463
4464                 err = check_flow_keys_access(env, off, size);
4465                 if (!err && t == BPF_READ && value_regno >= 0)
4466                         mark_reg_unknown(env, regs, value_regno);
4467         } else if (type_is_sk_pointer(reg->type)) {
4468                 if (t == BPF_WRITE) {
4469                         verbose(env, "R%d cannot write into %s\n",
4470                                 regno, reg_type_str[reg->type]);
4471                         return -EACCES;
4472                 }
4473                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4474                 if (!err && value_regno >= 0)
4475                         mark_reg_unknown(env, regs, value_regno);
4476         } else if (reg->type == PTR_TO_TP_BUFFER) {
4477                 err = check_tp_buffer_access(env, reg, regno, off, size);
4478                 if (!err && t == BPF_READ && value_regno >= 0)
4479                         mark_reg_unknown(env, regs, value_regno);
4480         } else if (reg->type == PTR_TO_BTF_ID) {
4481                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4482                                               value_regno);
4483         } else if (reg->type == CONST_PTR_TO_MAP) {
4484                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4485                                               value_regno);
4486         } else if (reg->type == PTR_TO_RDONLY_BUF) {
4487                 if (t == BPF_WRITE) {
4488                         verbose(env, "R%d cannot write into %s\n",
4489                                 regno, reg_type_str[reg->type]);
4490                         return -EACCES;
4491                 }
4492                 err = check_buffer_access(env, reg, regno, off, size, false,
4493                                           "rdonly",
4494                                           &env->prog->aux->max_rdonly_access);
4495                 if (!err && value_regno >= 0)
4496                         mark_reg_unknown(env, regs, value_regno);
4497         } else if (reg->type == PTR_TO_RDWR_BUF) {
4498                 err = check_buffer_access(env, reg, regno, off, size, false,
4499                                           "rdwr",
4500                                           &env->prog->aux->max_rdwr_access);
4501                 if (!err && t == BPF_READ && value_regno >= 0)
4502                         mark_reg_unknown(env, regs, value_regno);
4503         } else {
4504                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4505                         reg_type_str[reg->type]);
4506                 return -EACCES;
4507         }
4508
4509         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4510             regs[value_regno].type == SCALAR_VALUE) {
4511                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4512                 coerce_reg_to_size(&regs[value_regno], size);
4513         }
4514         return err;
4515 }
4516
4517 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4518 {
4519         int load_reg;
4520         int err;
4521
4522         switch (insn->imm) {
4523         case BPF_ADD:
4524         case BPF_ADD | BPF_FETCH:
4525         case BPF_AND:
4526         case BPF_AND | BPF_FETCH:
4527         case BPF_OR:
4528         case BPF_OR | BPF_FETCH:
4529         case BPF_XOR:
4530         case BPF_XOR | BPF_FETCH:
4531         case BPF_XCHG:
4532         case BPF_CMPXCHG:
4533                 break;
4534         default:
4535                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4536                 return -EINVAL;
4537         }
4538
4539         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4540                 verbose(env, "invalid atomic operand size\n");
4541                 return -EINVAL;
4542         }
4543
4544         /* check src1 operand */
4545         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4546         if (err)
4547                 return err;
4548
4549         /* check src2 operand */
4550         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4551         if (err)
4552                 return err;
4553
4554         if (insn->imm == BPF_CMPXCHG) {
4555                 /* Check comparison of R0 with memory location */
4556                 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4557                 if (err)
4558                         return err;
4559         }
4560
4561         if (is_pointer_value(env, insn->src_reg)) {
4562                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4563                 return -EACCES;
4564         }
4565
4566         if (is_ctx_reg(env, insn->dst_reg) ||
4567             is_pkt_reg(env, insn->dst_reg) ||
4568             is_flow_key_reg(env, insn->dst_reg) ||
4569             is_sk_reg(env, insn->dst_reg)) {
4570                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4571                         insn->dst_reg,
4572                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
4573                 return -EACCES;
4574         }
4575
4576         if (insn->imm & BPF_FETCH) {
4577                 if (insn->imm == BPF_CMPXCHG)
4578                         load_reg = BPF_REG_0;
4579                 else
4580                         load_reg = insn->src_reg;
4581
4582                 /* check and record load of old value */
4583                 err = check_reg_arg(env, load_reg, DST_OP);
4584                 if (err)
4585                         return err;
4586         } else {
4587                 /* This instruction accesses a memory location but doesn't
4588                  * actually load it into a register.
4589                  */
4590                 load_reg = -1;
4591         }
4592
4593         /* check whether we can read the memory */
4594         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4595                                BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4596         if (err)
4597                 return err;
4598
4599         /* check whether we can write into the same memory */
4600         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4601                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4602         if (err)
4603                 return err;
4604
4605         return 0;
4606 }
4607
4608 /* When register 'regno' is used to read the stack (either directly or through
4609  * a helper function) make sure that it's within stack boundary and, depending
4610  * on the access type, that all elements of the stack are initialized.
4611  *
4612  * 'off' includes 'regno->off', but not its dynamic part (if any).
4613  *
4614  * All registers that have been spilled on the stack in the slots within the
4615  * read offsets are marked as read.
4616  */
4617 static int check_stack_range_initialized(
4618                 struct bpf_verifier_env *env, int regno, int off,
4619                 int access_size, bool zero_size_allowed,
4620                 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4621 {
4622         struct bpf_reg_state *reg = reg_state(env, regno);
4623         struct bpf_func_state *state = func(env, reg);
4624         int err, min_off, max_off, i, j, slot, spi;
4625         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4626         enum bpf_access_type bounds_check_type;
4627         /* Some accesses can write anything into the stack, others are
4628          * read-only.
4629          */
4630         bool clobber = false;
4631
4632         if (access_size == 0 && !zero_size_allowed) {
4633                 verbose(env, "invalid zero-sized read\n");
4634                 return -EACCES;
4635         }
4636
4637         if (type == ACCESS_HELPER) {
4638                 /* The bounds checks for writes are more permissive than for
4639                  * reads. However, if raw_mode is not set, we'll do extra
4640                  * checks below.
4641                  */
4642                 bounds_check_type = BPF_WRITE;
4643                 clobber = true;
4644         } else {
4645                 bounds_check_type = BPF_READ;
4646         }
4647         err = check_stack_access_within_bounds(env, regno, off, access_size,
4648                                                type, bounds_check_type);
4649         if (err)
4650                 return err;
4651
4652
4653         if (tnum_is_const(reg->var_off)) {
4654                 min_off = max_off = reg->var_off.value + off;
4655         } else {
4656                 /* Variable offset is prohibited for unprivileged mode for
4657                  * simplicity since it requires corresponding support in
4658                  * Spectre masking for stack ALU.
4659                  * See also retrieve_ptr_limit().
4660                  */
4661                 if (!env->bypass_spec_v1) {
4662                         char tn_buf[48];
4663
4664                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4665                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4666                                 regno, err_extra, tn_buf);
4667                         return -EACCES;
4668                 }
4669                 /* Only initialized buffer on stack is allowed to be accessed
4670                  * with variable offset. With uninitialized buffer it's hard to
4671                  * guarantee that whole memory is marked as initialized on
4672                  * helper return since specific bounds are unknown what may
4673                  * cause uninitialized stack leaking.
4674                  */
4675                 if (meta && meta->raw_mode)
4676                         meta = NULL;
4677
4678                 min_off = reg->smin_value + off;
4679                 max_off = reg->smax_value + off;
4680         }
4681
4682         if (meta && meta->raw_mode) {
4683                 meta->access_size = access_size;
4684                 meta->regno = regno;
4685                 return 0;
4686         }
4687
4688         for (i = min_off; i < max_off + access_size; i++) {
4689                 u8 *stype;
4690
4691                 slot = -i - 1;
4692                 spi = slot / BPF_REG_SIZE;
4693                 if (state->allocated_stack <= slot)
4694                         goto err;
4695                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4696                 if (*stype == STACK_MISC)
4697                         goto mark;
4698                 if (*stype == STACK_ZERO) {
4699                         if (clobber) {
4700                                 /* helper can write anything into the stack */
4701                                 *stype = STACK_MISC;
4702                         }
4703                         goto mark;
4704                 }
4705
4706                 if (is_spilled_reg(&state->stack[spi]) &&
4707                     state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4708                         goto mark;
4709
4710                 if (is_spilled_reg(&state->stack[spi]) &&
4711                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4712                      env->allow_ptr_leaks)) {
4713                         if (clobber) {
4714                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4715                                 for (j = 0; j < BPF_REG_SIZE; j++)
4716                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4717                         }
4718                         goto mark;
4719                 }
4720
4721 err:
4722                 if (tnum_is_const(reg->var_off)) {
4723                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4724                                 err_extra, regno, min_off, i - min_off, access_size);
4725                 } else {
4726                         char tn_buf[48];
4727
4728                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4729                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4730                                 err_extra, regno, tn_buf, i - min_off, access_size);
4731                 }
4732                 return -EACCES;
4733 mark:
4734                 /* reading any byte out of 8-byte 'spill_slot' will cause
4735                  * the whole slot to be marked as 'read'
4736                  */
4737                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4738                               state->stack[spi].spilled_ptr.parent,
4739                               REG_LIVE_READ64);
4740         }
4741         return update_stack_depth(env, state, min_off);
4742 }
4743
4744 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4745                                    int access_size, bool zero_size_allowed,
4746                                    struct bpf_call_arg_meta *meta)
4747 {
4748         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4749
4750         switch (reg->type) {
4751         case PTR_TO_PACKET:
4752         case PTR_TO_PACKET_META:
4753                 return check_packet_access(env, regno, reg->off, access_size,
4754                                            zero_size_allowed);
4755         case PTR_TO_MAP_KEY:
4756                 return check_mem_region_access(env, regno, reg->off, access_size,
4757                                                reg->map_ptr->key_size, false);
4758         case PTR_TO_MAP_VALUE:
4759                 if (check_map_access_type(env, regno, reg->off, access_size,
4760                                           meta && meta->raw_mode ? BPF_WRITE :
4761                                           BPF_READ))
4762                         return -EACCES;
4763                 return check_map_access(env, regno, reg->off, access_size,
4764                                         zero_size_allowed);
4765         case PTR_TO_MEM:
4766                 return check_mem_region_access(env, regno, reg->off,
4767                                                access_size, reg->mem_size,
4768                                                zero_size_allowed);
4769         case PTR_TO_RDONLY_BUF:
4770                 if (meta && meta->raw_mode)
4771                         return -EACCES;
4772                 return check_buffer_access(env, reg, regno, reg->off,
4773                                            access_size, zero_size_allowed,
4774                                            "rdonly",
4775                                            &env->prog->aux->max_rdonly_access);
4776         case PTR_TO_RDWR_BUF:
4777                 return check_buffer_access(env, reg, regno, reg->off,
4778                                            access_size, zero_size_allowed,
4779                                            "rdwr",
4780                                            &env->prog->aux->max_rdwr_access);
4781         case PTR_TO_STACK:
4782                 return check_stack_range_initialized(
4783                                 env,
4784                                 regno, reg->off, access_size,
4785                                 zero_size_allowed, ACCESS_HELPER, meta);
4786         default: /* scalar_value or invalid ptr */
4787                 /* Allow zero-byte read from NULL, regardless of pointer type */
4788                 if (zero_size_allowed && access_size == 0 &&
4789                     register_is_null(reg))
4790                         return 0;
4791
4792                 verbose(env, "R%d type=%s expected=%s\n", regno,
4793                         reg_type_str[reg->type],
4794                         reg_type_str[PTR_TO_STACK]);
4795                 return -EACCES;
4796         }
4797 }
4798
4799 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4800                    u32 regno, u32 mem_size)
4801 {
4802         if (register_is_null(reg))
4803                 return 0;
4804
4805         if (reg_type_may_be_null(reg->type)) {
4806                 /* Assuming that the register contains a value check if the memory
4807                  * access is safe. Temporarily save and restore the register's state as
4808                  * the conversion shouldn't be visible to a caller.
4809                  */
4810                 const struct bpf_reg_state saved_reg = *reg;
4811                 int rv;
4812
4813                 mark_ptr_not_null_reg(reg);
4814                 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4815                 *reg = saved_reg;
4816                 return rv;
4817         }
4818
4819         return check_helper_mem_access(env, regno, mem_size, true, NULL);
4820 }
4821
4822 /* Implementation details:
4823  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4824  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4825  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4826  * value_or_null->value transition, since the verifier only cares about
4827  * the range of access to valid map value pointer and doesn't care about actual
4828  * address of the map element.
4829  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4830  * reg->id > 0 after value_or_null->value transition. By doing so
4831  * two bpf_map_lookups will be considered two different pointers that
4832  * point to different bpf_spin_locks.
4833  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4834  * dead-locks.
4835  * Since only one bpf_spin_lock is allowed the checks are simpler than
4836  * reg_is_refcounted() logic. The verifier needs to remember only
4837  * one spin_lock instead of array of acquired_refs.
4838  * cur_state->active_spin_lock remembers which map value element got locked
4839  * and clears it after bpf_spin_unlock.
4840  */
4841 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4842                              bool is_lock)
4843 {
4844         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4845         struct bpf_verifier_state *cur = env->cur_state;
4846         bool is_const = tnum_is_const(reg->var_off);
4847         struct bpf_map *map = reg->map_ptr;
4848         u64 val = reg->var_off.value;
4849
4850         if (!is_const) {
4851                 verbose(env,
4852                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4853                         regno);
4854                 return -EINVAL;
4855         }
4856         if (!map->btf) {
4857                 verbose(env,
4858                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4859                         map->name);
4860                 return -EINVAL;
4861         }
4862         if (!map_value_has_spin_lock(map)) {
4863                 if (map->spin_lock_off == -E2BIG)
4864                         verbose(env,
4865                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4866                                 map->name);
4867                 else if (map->spin_lock_off == -ENOENT)
4868                         verbose(env,
4869                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4870                                 map->name);
4871                 else
4872                         verbose(env,
4873                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4874                                 map->name);
4875                 return -EINVAL;
4876         }
4877         if (map->spin_lock_off != val + reg->off) {
4878                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4879                         val + reg->off);
4880                 return -EINVAL;
4881         }
4882         if (is_lock) {
4883                 if (cur->active_spin_lock) {
4884                         verbose(env,
4885                                 "Locking two bpf_spin_locks are not allowed\n");
4886                         return -EINVAL;
4887                 }
4888                 cur->active_spin_lock = reg->id;
4889         } else {
4890                 if (!cur->active_spin_lock) {
4891                         verbose(env, "bpf_spin_unlock without taking a lock\n");
4892                         return -EINVAL;
4893                 }
4894                 if (cur->active_spin_lock != reg->id) {
4895                         verbose(env, "bpf_spin_unlock of different lock\n");
4896                         return -EINVAL;
4897                 }
4898                 cur->active_spin_lock = 0;
4899         }
4900         return 0;
4901 }
4902
4903 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4904                               struct bpf_call_arg_meta *meta)
4905 {
4906         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4907         bool is_const = tnum_is_const(reg->var_off);
4908         struct bpf_map *map = reg->map_ptr;
4909         u64 val = reg->var_off.value;
4910
4911         if (!is_const) {
4912                 verbose(env,
4913                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
4914                         regno);
4915                 return -EINVAL;
4916         }
4917         if (!map->btf) {
4918                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
4919                         map->name);
4920                 return -EINVAL;
4921         }
4922         if (!map_value_has_timer(map)) {
4923                 if (map->timer_off == -E2BIG)
4924                         verbose(env,
4925                                 "map '%s' has more than one 'struct bpf_timer'\n",
4926                                 map->name);
4927                 else if (map->timer_off == -ENOENT)
4928                         verbose(env,
4929                                 "map '%s' doesn't have 'struct bpf_timer'\n",
4930                                 map->name);
4931                 else
4932                         verbose(env,
4933                                 "map '%s' is not a struct type or bpf_timer is mangled\n",
4934                                 map->name);
4935                 return -EINVAL;
4936         }
4937         if (map->timer_off != val + reg->off) {
4938                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
4939                         val + reg->off, map->timer_off);
4940                 return -EINVAL;
4941         }
4942         if (meta->map_ptr) {
4943                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
4944                 return -EFAULT;
4945         }
4946         meta->map_uid = reg->map_uid;
4947         meta->map_ptr = map;
4948         return 0;
4949 }
4950
4951 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4952 {
4953         return type == ARG_PTR_TO_MEM ||
4954                type == ARG_PTR_TO_MEM_OR_NULL ||
4955                type == ARG_PTR_TO_UNINIT_MEM;
4956 }
4957
4958 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4959 {
4960         return type == ARG_CONST_SIZE ||
4961                type == ARG_CONST_SIZE_OR_ZERO;
4962 }
4963
4964 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4965 {
4966         return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4967 }
4968
4969 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4970 {
4971         return type == ARG_PTR_TO_INT ||
4972                type == ARG_PTR_TO_LONG;
4973 }
4974
4975 static int int_ptr_type_to_size(enum bpf_arg_type type)
4976 {
4977         if (type == ARG_PTR_TO_INT)
4978                 return sizeof(u32);
4979         else if (type == ARG_PTR_TO_LONG)
4980                 return sizeof(u64);
4981
4982         return -EINVAL;
4983 }
4984
4985 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4986                                  const struct bpf_call_arg_meta *meta,
4987                                  enum bpf_arg_type *arg_type)
4988 {
4989         if (!meta->map_ptr) {
4990                 /* kernel subsystem misconfigured verifier */
4991                 verbose(env, "invalid map_ptr to access map->type\n");
4992                 return -EACCES;
4993         }
4994
4995         switch (meta->map_ptr->map_type) {
4996         case BPF_MAP_TYPE_SOCKMAP:
4997         case BPF_MAP_TYPE_SOCKHASH:
4998                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4999                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5000                 } else {
5001                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
5002                         return -EINVAL;
5003                 }
5004                 break;
5005         case BPF_MAP_TYPE_BLOOM_FILTER:
5006                 if (meta->func_id == BPF_FUNC_map_peek_elem)
5007                         *arg_type = ARG_PTR_TO_MAP_VALUE;
5008                 break;
5009         default:
5010                 break;
5011         }
5012         return 0;
5013 }
5014
5015 struct bpf_reg_types {
5016         const enum bpf_reg_type types[10];
5017         u32 *btf_id;
5018 };
5019
5020 static const struct bpf_reg_types map_key_value_types = {
5021         .types = {
5022                 PTR_TO_STACK,
5023                 PTR_TO_PACKET,
5024                 PTR_TO_PACKET_META,
5025                 PTR_TO_MAP_KEY,
5026                 PTR_TO_MAP_VALUE,
5027         },
5028 };
5029
5030 static const struct bpf_reg_types sock_types = {
5031         .types = {
5032                 PTR_TO_SOCK_COMMON,
5033                 PTR_TO_SOCKET,
5034                 PTR_TO_TCP_SOCK,
5035                 PTR_TO_XDP_SOCK,
5036         },
5037 };
5038
5039 #ifdef CONFIG_NET
5040 static const struct bpf_reg_types btf_id_sock_common_types = {
5041         .types = {
5042                 PTR_TO_SOCK_COMMON,
5043                 PTR_TO_SOCKET,
5044                 PTR_TO_TCP_SOCK,
5045                 PTR_TO_XDP_SOCK,
5046                 PTR_TO_BTF_ID,
5047         },
5048         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5049 };
5050 #endif
5051
5052 static const struct bpf_reg_types mem_types = {
5053         .types = {
5054                 PTR_TO_STACK,
5055                 PTR_TO_PACKET,
5056                 PTR_TO_PACKET_META,
5057                 PTR_TO_MAP_KEY,
5058                 PTR_TO_MAP_VALUE,
5059                 PTR_TO_MEM,
5060                 PTR_TO_RDONLY_BUF,
5061                 PTR_TO_RDWR_BUF,
5062         },
5063 };
5064
5065 static const struct bpf_reg_types int_ptr_types = {
5066         .types = {
5067                 PTR_TO_STACK,
5068                 PTR_TO_PACKET,
5069                 PTR_TO_PACKET_META,
5070                 PTR_TO_MAP_KEY,
5071                 PTR_TO_MAP_VALUE,
5072         },
5073 };
5074
5075 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5076 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5077 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5078 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
5079 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5080 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5081 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5082 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
5083 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5084 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5085 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5086 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5087
5088 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5089         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
5090         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
5091         [ARG_PTR_TO_UNINIT_MAP_VALUE]   = &map_key_value_types,
5092         [ARG_PTR_TO_MAP_VALUE_OR_NULL]  = &map_key_value_types,
5093         [ARG_CONST_SIZE]                = &scalar_types,
5094         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
5095         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
5096         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
5097         [ARG_PTR_TO_CTX]                = &context_types,
5098         [ARG_PTR_TO_CTX_OR_NULL]        = &context_types,
5099         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
5100 #ifdef CONFIG_NET
5101         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5102 #endif
5103         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
5104         [ARG_PTR_TO_SOCKET_OR_NULL]     = &fullsock_types,
5105         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
5106         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
5107         [ARG_PTR_TO_MEM]                = &mem_types,
5108         [ARG_PTR_TO_MEM_OR_NULL]        = &mem_types,
5109         [ARG_PTR_TO_UNINIT_MEM]         = &mem_types,
5110         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
5111         [ARG_PTR_TO_ALLOC_MEM_OR_NULL]  = &alloc_mem_types,
5112         [ARG_PTR_TO_INT]                = &int_ptr_types,
5113         [ARG_PTR_TO_LONG]               = &int_ptr_types,
5114         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
5115         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
5116         [ARG_PTR_TO_STACK_OR_NULL]      = &stack_ptr_types,
5117         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
5118         [ARG_PTR_TO_TIMER]              = &timer_types,
5119 };
5120
5121 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5122                           enum bpf_arg_type arg_type,
5123                           const u32 *arg_btf_id)
5124 {
5125         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5126         enum bpf_reg_type expected, type = reg->type;
5127         const struct bpf_reg_types *compatible;
5128         int i, j;
5129
5130         compatible = compatible_reg_types[arg_type];
5131         if (!compatible) {
5132                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5133                 return -EFAULT;
5134         }
5135
5136         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5137                 expected = compatible->types[i];
5138                 if (expected == NOT_INIT)
5139                         break;
5140
5141                 if (type == expected)
5142                         goto found;
5143         }
5144
5145         verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
5146         for (j = 0; j + 1 < i; j++)
5147                 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
5148         verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
5149         return -EACCES;
5150
5151 found:
5152         if (type == PTR_TO_BTF_ID) {
5153                 if (!arg_btf_id) {
5154                         if (!compatible->btf_id) {
5155                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5156                                 return -EFAULT;
5157                         }
5158                         arg_btf_id = compatible->btf_id;
5159                 }
5160
5161                 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5162                                           btf_vmlinux, *arg_btf_id)) {
5163                         verbose(env, "R%d is of type %s but %s is expected\n",
5164                                 regno, kernel_type_name(reg->btf, reg->btf_id),
5165                                 kernel_type_name(btf_vmlinux, *arg_btf_id));
5166                         return -EACCES;
5167                 }
5168
5169                 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5170                         verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
5171                                 regno);
5172                         return -EACCES;
5173                 }
5174         }
5175
5176         return 0;
5177 }
5178
5179 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5180                           struct bpf_call_arg_meta *meta,
5181                           const struct bpf_func_proto *fn)
5182 {
5183         u32 regno = BPF_REG_1 + arg;
5184         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5185         enum bpf_arg_type arg_type = fn->arg_type[arg];
5186         enum bpf_reg_type type = reg->type;
5187         int err = 0;
5188
5189         if (arg_type == ARG_DONTCARE)
5190                 return 0;
5191
5192         err = check_reg_arg(env, regno, SRC_OP);
5193         if (err)
5194                 return err;
5195
5196         if (arg_type == ARG_ANYTHING) {
5197                 if (is_pointer_value(env, regno)) {
5198                         verbose(env, "R%d leaks addr into helper function\n",
5199                                 regno);
5200                         return -EACCES;
5201                 }
5202                 return 0;
5203         }
5204
5205         if (type_is_pkt_pointer(type) &&
5206             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5207                 verbose(env, "helper access to the packet is not allowed\n");
5208                 return -EACCES;
5209         }
5210
5211         if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5212             arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
5213             arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
5214                 err = resolve_map_arg_type(env, meta, &arg_type);
5215                 if (err)
5216                         return err;
5217         }
5218
5219         if (register_is_null(reg) && arg_type_may_be_null(arg_type))
5220                 /* A NULL register has a SCALAR_VALUE type, so skip
5221                  * type checking.
5222                  */
5223                 goto skip_type_check;
5224
5225         err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5226         if (err)
5227                 return err;
5228
5229         if (type == PTR_TO_CTX) {
5230                 err = check_ctx_reg(env, reg, regno);
5231                 if (err < 0)
5232                         return err;
5233         }
5234
5235 skip_type_check:
5236         if (reg->ref_obj_id) {
5237                 if (meta->ref_obj_id) {
5238                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5239                                 regno, reg->ref_obj_id,
5240                                 meta->ref_obj_id);
5241                         return -EFAULT;
5242                 }
5243                 meta->ref_obj_id = reg->ref_obj_id;
5244         }
5245
5246         if (arg_type == ARG_CONST_MAP_PTR) {
5247                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5248                 if (meta->map_ptr) {
5249                         /* Use map_uid (which is unique id of inner map) to reject:
5250                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5251                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5252                          * if (inner_map1 && inner_map2) {
5253                          *     timer = bpf_map_lookup_elem(inner_map1);
5254                          *     if (timer)
5255                          *         // mismatch would have been allowed
5256                          *         bpf_timer_init(timer, inner_map2);
5257                          * }
5258                          *
5259                          * Comparing map_ptr is enough to distinguish normal and outer maps.
5260                          */
5261                         if (meta->map_ptr != reg->map_ptr ||
5262                             meta->map_uid != reg->map_uid) {
5263                                 verbose(env,
5264                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5265                                         meta->map_uid, reg->map_uid);
5266                                 return -EINVAL;
5267                         }
5268                 }
5269                 meta->map_ptr = reg->map_ptr;
5270                 meta->map_uid = reg->map_uid;
5271         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5272                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
5273                  * check that [key, key + map->key_size) are within
5274                  * stack limits and initialized
5275                  */
5276                 if (!meta->map_ptr) {
5277                         /* in function declaration map_ptr must come before
5278                          * map_key, so that it's verified and known before
5279                          * we have to check map_key here. Otherwise it means
5280                          * that kernel subsystem misconfigured verifier
5281                          */
5282                         verbose(env, "invalid map_ptr to access map->key\n");
5283                         return -EACCES;
5284                 }
5285                 err = check_helper_mem_access(env, regno,
5286                                               meta->map_ptr->key_size, false,
5287                                               NULL);
5288         } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5289                    (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
5290                     !register_is_null(reg)) ||
5291                    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5292                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
5293                  * check [value, value + map->value_size) validity
5294                  */
5295                 if (!meta->map_ptr) {
5296                         /* kernel subsystem misconfigured verifier */
5297                         verbose(env, "invalid map_ptr to access map->value\n");
5298                         return -EACCES;
5299                 }
5300                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5301                 err = check_helper_mem_access(env, regno,
5302                                               meta->map_ptr->value_size, false,
5303                                               meta);
5304         } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5305                 if (!reg->btf_id) {
5306                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5307                         return -EACCES;
5308                 }
5309                 meta->ret_btf = reg->btf;
5310                 meta->ret_btf_id = reg->btf_id;
5311         } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5312                 if (meta->func_id == BPF_FUNC_spin_lock) {
5313                         if (process_spin_lock(env, regno, true))
5314                                 return -EACCES;
5315                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
5316                         if (process_spin_lock(env, regno, false))
5317                                 return -EACCES;
5318                 } else {
5319                         verbose(env, "verifier internal error\n");
5320                         return -EFAULT;
5321                 }
5322         } else if (arg_type == ARG_PTR_TO_TIMER) {
5323                 if (process_timer_func(env, regno, meta))
5324                         return -EACCES;
5325         } else if (arg_type == ARG_PTR_TO_FUNC) {
5326                 meta->subprogno = reg->subprogno;
5327         } else if (arg_type_is_mem_ptr(arg_type)) {
5328                 /* The access to this pointer is only checked when we hit the
5329                  * next is_mem_size argument below.
5330                  */
5331                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5332         } else if (arg_type_is_mem_size(arg_type)) {
5333                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5334
5335                 /* This is used to refine r0 return value bounds for helpers
5336                  * that enforce this value as an upper bound on return values.
5337                  * See do_refine_retval_range() for helpers that can refine
5338                  * the return value. C type of helper is u32 so we pull register
5339                  * bound from umax_value however, if negative verifier errors
5340                  * out. Only upper bounds can be learned because retval is an
5341                  * int type and negative retvals are allowed.
5342                  */
5343                 meta->msize_max_value = reg->umax_value;
5344
5345                 /* The register is SCALAR_VALUE; the access check
5346                  * happens using its boundaries.
5347                  */
5348                 if (!tnum_is_const(reg->var_off))
5349                         /* For unprivileged variable accesses, disable raw
5350                          * mode so that the program is required to
5351                          * initialize all the memory that the helper could
5352                          * just partially fill up.
5353                          */
5354                         meta = NULL;
5355
5356                 if (reg->smin_value < 0) {
5357                         verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5358                                 regno);
5359                         return -EACCES;
5360                 }
5361
5362                 if (reg->umin_value == 0) {
5363                         err = check_helper_mem_access(env, regno - 1, 0,
5364                                                       zero_size_allowed,
5365                                                       meta);
5366                         if (err)
5367                                 return err;
5368                 }
5369
5370                 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5371                         verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5372                                 regno);
5373                         return -EACCES;
5374                 }
5375                 err = check_helper_mem_access(env, regno - 1,
5376                                               reg->umax_value,
5377                                               zero_size_allowed, meta);
5378                 if (!err)
5379                         err = mark_chain_precision(env, regno);
5380         } else if (arg_type_is_alloc_size(arg_type)) {
5381                 if (!tnum_is_const(reg->var_off)) {
5382                         verbose(env, "R%d is not a known constant'\n",
5383                                 regno);
5384                         return -EACCES;
5385                 }
5386                 meta->mem_size = reg->var_off.value;
5387         } else if (arg_type_is_int_ptr(arg_type)) {
5388                 int size = int_ptr_type_to_size(arg_type);
5389
5390                 err = check_helper_mem_access(env, regno, size, false, meta);
5391                 if (err)
5392                         return err;
5393                 err = check_ptr_alignment(env, reg, 0, size, true);
5394         } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5395                 struct bpf_map *map = reg->map_ptr;
5396                 int map_off;
5397                 u64 map_addr;
5398                 char *str_ptr;
5399
5400                 if (!bpf_map_is_rdonly(map)) {
5401                         verbose(env, "R%d does not point to a readonly map'\n", regno);
5402                         return -EACCES;
5403                 }
5404
5405                 if (!tnum_is_const(reg->var_off)) {
5406                         verbose(env, "R%d is not a constant address'\n", regno);
5407                         return -EACCES;
5408                 }
5409
5410                 if (!map->ops->map_direct_value_addr) {
5411                         verbose(env, "no direct value access support for this map type\n");
5412                         return -EACCES;
5413                 }
5414
5415                 err = check_map_access(env, regno, reg->off,
5416                                        map->value_size - reg->off, false);
5417                 if (err)
5418                         return err;
5419
5420                 map_off = reg->off + reg->var_off.value;
5421                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5422                 if (err) {
5423                         verbose(env, "direct value access on string failed\n");
5424                         return err;
5425                 }
5426
5427                 str_ptr = (char *)(long)(map_addr);
5428                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5429                         verbose(env, "string is not zero-terminated\n");
5430                         return -EINVAL;
5431                 }
5432         }
5433
5434         return err;
5435 }
5436
5437 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5438 {
5439         enum bpf_attach_type eatype = env->prog->expected_attach_type;
5440         enum bpf_prog_type type = resolve_prog_type(env->prog);
5441
5442         if (func_id != BPF_FUNC_map_update_elem)
5443                 return false;
5444
5445         /* It's not possible to get access to a locked struct sock in these
5446          * contexts, so updating is safe.
5447          */
5448         switch (type) {
5449         case BPF_PROG_TYPE_TRACING:
5450                 if (eatype == BPF_TRACE_ITER)
5451                         return true;
5452                 break;
5453         case BPF_PROG_TYPE_SOCKET_FILTER:
5454         case BPF_PROG_TYPE_SCHED_CLS:
5455         case BPF_PROG_TYPE_SCHED_ACT:
5456         case BPF_PROG_TYPE_XDP:
5457         case BPF_PROG_TYPE_SK_REUSEPORT:
5458         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5459         case BPF_PROG_TYPE_SK_LOOKUP:
5460                 return true;
5461         default:
5462                 break;
5463         }
5464
5465         verbose(env, "cannot update sockmap in this context\n");
5466         return false;
5467 }
5468
5469 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5470 {
5471         return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5472 }
5473
5474 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5475                                         struct bpf_map *map, int func_id)
5476 {
5477         if (!map)
5478                 return 0;
5479
5480         /* We need a two way check, first is from map perspective ... */
5481         switch (map->map_type) {
5482         case BPF_MAP_TYPE_PROG_ARRAY:
5483                 if (func_id != BPF_FUNC_tail_call)
5484                         goto error;
5485                 break;
5486         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5487                 if (func_id != BPF_FUNC_perf_event_read &&
5488                     func_id != BPF_FUNC_perf_event_output &&
5489                     func_id != BPF_FUNC_skb_output &&
5490                     func_id != BPF_FUNC_perf_event_read_value &&
5491                     func_id != BPF_FUNC_xdp_output)
5492                         goto error;
5493                 break;
5494         case BPF_MAP_TYPE_RINGBUF:
5495                 if (func_id != BPF_FUNC_ringbuf_output &&
5496                     func_id != BPF_FUNC_ringbuf_reserve &&
5497                     func_id != BPF_FUNC_ringbuf_query)
5498                         goto error;
5499                 break;
5500         case BPF_MAP_TYPE_STACK_TRACE:
5501                 if (func_id != BPF_FUNC_get_stackid)
5502                         goto error;
5503                 break;
5504         case BPF_MAP_TYPE_CGROUP_ARRAY:
5505                 if (func_id != BPF_FUNC_skb_under_cgroup &&
5506                     func_id != BPF_FUNC_current_task_under_cgroup)
5507                         goto error;
5508                 break;
5509         case BPF_MAP_TYPE_CGROUP_STORAGE:
5510         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5511                 if (func_id != BPF_FUNC_get_local_storage)
5512                         goto error;
5513                 break;
5514         case BPF_MAP_TYPE_DEVMAP:
5515         case BPF_MAP_TYPE_DEVMAP_HASH:
5516                 if (func_id != BPF_FUNC_redirect_map &&
5517                     func_id != BPF_FUNC_map_lookup_elem)
5518                         goto error;
5519                 break;
5520         /* Restrict bpf side of cpumap and xskmap, open when use-cases
5521          * appear.
5522          */
5523         case BPF_MAP_TYPE_CPUMAP:
5524                 if (func_id != BPF_FUNC_redirect_map)
5525                         goto error;
5526                 break;
5527         case BPF_MAP_TYPE_XSKMAP:
5528                 if (func_id != BPF_FUNC_redirect_map &&
5529                     func_id != BPF_FUNC_map_lookup_elem)
5530                         goto error;
5531                 break;
5532         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5533         case BPF_MAP_TYPE_HASH_OF_MAPS:
5534                 if (func_id != BPF_FUNC_map_lookup_elem)
5535                         goto error;
5536                 break;
5537         case BPF_MAP_TYPE_SOCKMAP:
5538                 if (func_id != BPF_FUNC_sk_redirect_map &&
5539                     func_id != BPF_FUNC_sock_map_update &&
5540                     func_id != BPF_FUNC_map_delete_elem &&
5541                     func_id != BPF_FUNC_msg_redirect_map &&
5542                     func_id != BPF_FUNC_sk_select_reuseport &&
5543                     func_id != BPF_FUNC_map_lookup_elem &&
5544                     !may_update_sockmap(env, func_id))
5545                         goto error;
5546                 break;
5547         case BPF_MAP_TYPE_SOCKHASH:
5548                 if (func_id != BPF_FUNC_sk_redirect_hash &&
5549                     func_id != BPF_FUNC_sock_hash_update &&
5550                     func_id != BPF_FUNC_map_delete_elem &&
5551                     func_id != BPF_FUNC_msg_redirect_hash &&
5552                     func_id != BPF_FUNC_sk_select_reuseport &&
5553                     func_id != BPF_FUNC_map_lookup_elem &&
5554                     !may_update_sockmap(env, func_id))
5555                         goto error;
5556                 break;
5557         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5558                 if (func_id != BPF_FUNC_sk_select_reuseport)
5559                         goto error;
5560                 break;
5561         case BPF_MAP_TYPE_QUEUE:
5562         case BPF_MAP_TYPE_STACK:
5563                 if (func_id != BPF_FUNC_map_peek_elem &&
5564                     func_id != BPF_FUNC_map_pop_elem &&
5565                     func_id != BPF_FUNC_map_push_elem)
5566                         goto error;
5567                 break;
5568         case BPF_MAP_TYPE_SK_STORAGE:
5569                 if (func_id != BPF_FUNC_sk_storage_get &&
5570                     func_id != BPF_FUNC_sk_storage_delete)
5571                         goto error;
5572                 break;
5573         case BPF_MAP_TYPE_INODE_STORAGE:
5574                 if (func_id != BPF_FUNC_inode_storage_get &&
5575                     func_id != BPF_FUNC_inode_storage_delete)
5576                         goto error;
5577                 break;
5578         case BPF_MAP_TYPE_TASK_STORAGE:
5579                 if (func_id != BPF_FUNC_task_storage_get &&
5580                     func_id != BPF_FUNC_task_storage_delete)
5581                         goto error;
5582                 break;
5583         case BPF_MAP_TYPE_BLOOM_FILTER:
5584                 if (func_id != BPF_FUNC_map_peek_elem &&
5585                     func_id != BPF_FUNC_map_push_elem)
5586                         goto error;
5587                 break;
5588         default:
5589                 break;
5590         }
5591
5592         /* ... and second from the function itself. */
5593         switch (func_id) {
5594         case BPF_FUNC_tail_call:
5595                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5596                         goto error;
5597                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5598                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5599                         return -EINVAL;
5600                 }
5601                 break;
5602         case BPF_FUNC_perf_event_read:
5603         case BPF_FUNC_perf_event_output:
5604         case BPF_FUNC_perf_event_read_value:
5605         case BPF_FUNC_skb_output:
5606         case BPF_FUNC_xdp_output:
5607                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5608                         goto error;
5609                 break;
5610         case BPF_FUNC_ringbuf_output:
5611         case BPF_FUNC_ringbuf_reserve:
5612         case BPF_FUNC_ringbuf_query:
5613                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5614                         goto error;
5615                 break;
5616         case BPF_FUNC_get_stackid:
5617                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5618                         goto error;
5619                 break;
5620         case BPF_FUNC_current_task_under_cgroup:
5621         case BPF_FUNC_skb_under_cgroup:
5622                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5623                         goto error;
5624                 break;
5625         case BPF_FUNC_redirect_map:
5626                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5627                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5628                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
5629                     map->map_type != BPF_MAP_TYPE_XSKMAP)
5630                         goto error;
5631                 break;
5632         case BPF_FUNC_sk_redirect_map:
5633         case BPF_FUNC_msg_redirect_map:
5634         case BPF_FUNC_sock_map_update:
5635                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5636                         goto error;
5637                 break;
5638         case BPF_FUNC_sk_redirect_hash:
5639         case BPF_FUNC_msg_redirect_hash:
5640         case BPF_FUNC_sock_hash_update:
5641                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5642                         goto error;
5643                 break;
5644         case BPF_FUNC_get_local_storage:
5645                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5646                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5647                         goto error;
5648                 break;
5649         case BPF_FUNC_sk_select_reuseport:
5650                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5651                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5652                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
5653                         goto error;
5654                 break;
5655         case BPF_FUNC_map_pop_elem:
5656                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5657                     map->map_type != BPF_MAP_TYPE_STACK)
5658                         goto error;
5659                 break;
5660         case BPF_FUNC_map_peek_elem:
5661         case BPF_FUNC_map_push_elem:
5662                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5663                     map->map_type != BPF_MAP_TYPE_STACK &&
5664                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
5665                         goto error;
5666                 break;
5667         case BPF_FUNC_sk_storage_get:
5668         case BPF_FUNC_sk_storage_delete:
5669                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5670                         goto error;
5671                 break;
5672         case BPF_FUNC_inode_storage_get:
5673         case BPF_FUNC_inode_storage_delete:
5674                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5675                         goto error;
5676                 break;
5677         case BPF_FUNC_task_storage_get:
5678         case BPF_FUNC_task_storage_delete:
5679                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5680                         goto error;
5681                 break;
5682         default:
5683                 break;
5684         }
5685
5686         return 0;
5687 error:
5688         verbose(env, "cannot pass map_type %d into func %s#%d\n",
5689                 map->map_type, func_id_name(func_id), func_id);
5690         return -EINVAL;
5691 }
5692
5693 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5694 {
5695         int count = 0;
5696
5697         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5698                 count++;
5699         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5700                 count++;
5701         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5702                 count++;
5703         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5704                 count++;
5705         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5706                 count++;
5707
5708         /* We only support one arg being in raw mode at the moment,
5709          * which is sufficient for the helper functions we have
5710          * right now.
5711          */
5712         return count <= 1;
5713 }
5714
5715 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5716                                     enum bpf_arg_type arg_next)
5717 {
5718         return (arg_type_is_mem_ptr(arg_curr) &&
5719                 !arg_type_is_mem_size(arg_next)) ||
5720                (!arg_type_is_mem_ptr(arg_curr) &&
5721                 arg_type_is_mem_size(arg_next));
5722 }
5723
5724 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5725 {
5726         /* bpf_xxx(..., buf, len) call will access 'len'
5727          * bytes from memory 'buf'. Both arg types need
5728          * to be paired, so make sure there's no buggy
5729          * helper function specification.
5730          */
5731         if (arg_type_is_mem_size(fn->arg1_type) ||
5732             arg_type_is_mem_ptr(fn->arg5_type)  ||
5733             check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5734             check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5735             check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5736             check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5737                 return false;
5738
5739         return true;
5740 }
5741
5742 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5743 {
5744         int count = 0;
5745
5746         if (arg_type_may_be_refcounted(fn->arg1_type))
5747                 count++;
5748         if (arg_type_may_be_refcounted(fn->arg2_type))
5749                 count++;
5750         if (arg_type_may_be_refcounted(fn->arg3_type))
5751                 count++;
5752         if (arg_type_may_be_refcounted(fn->arg4_type))
5753                 count++;
5754         if (arg_type_may_be_refcounted(fn->arg5_type))
5755                 count++;
5756
5757         /* A reference acquiring function cannot acquire
5758          * another refcounted ptr.
5759          */
5760         if (may_be_acquire_function(func_id) && count)
5761                 return false;
5762
5763         /* We only support one arg being unreferenced at the moment,
5764          * which is sufficient for the helper functions we have right now.
5765          */
5766         return count <= 1;
5767 }
5768
5769 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5770 {
5771         int i;
5772
5773         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5774                 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5775                         return false;
5776
5777                 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5778                         return false;
5779         }
5780
5781         return true;
5782 }
5783
5784 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5785 {
5786         return check_raw_mode_ok(fn) &&
5787                check_arg_pair_ok(fn) &&
5788                check_btf_id_ok(fn) &&
5789                check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5790 }
5791
5792 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5793  * are now invalid, so turn them into unknown SCALAR_VALUE.
5794  */
5795 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5796                                      struct bpf_func_state *state)
5797 {
5798         struct bpf_reg_state *regs = state->regs, *reg;
5799         int i;
5800
5801         for (i = 0; i < MAX_BPF_REG; i++)
5802                 if (reg_is_pkt_pointer_any(&regs[i]))
5803                         mark_reg_unknown(env, regs, i);
5804
5805         bpf_for_each_spilled_reg(i, state, reg) {
5806                 if (!reg)
5807                         continue;
5808                 if (reg_is_pkt_pointer_any(reg))
5809                         __mark_reg_unknown(env, reg);
5810         }
5811 }
5812
5813 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5814 {
5815         struct bpf_verifier_state *vstate = env->cur_state;
5816         int i;
5817
5818         for (i = 0; i <= vstate->curframe; i++)
5819                 __clear_all_pkt_pointers(env, vstate->frame[i]);
5820 }
5821
5822 enum {
5823         AT_PKT_END = -1,
5824         BEYOND_PKT_END = -2,
5825 };
5826
5827 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5828 {
5829         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5830         struct bpf_reg_state *reg = &state->regs[regn];
5831
5832         if (reg->type != PTR_TO_PACKET)
5833                 /* PTR_TO_PACKET_META is not supported yet */
5834                 return;
5835
5836         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5837          * How far beyond pkt_end it goes is unknown.
5838          * if (!range_open) it's the case of pkt >= pkt_end
5839          * if (range_open) it's the case of pkt > pkt_end
5840          * hence this pointer is at least 1 byte bigger than pkt_end
5841          */
5842         if (range_open)
5843                 reg->range = BEYOND_PKT_END;
5844         else
5845                 reg->range = AT_PKT_END;
5846 }
5847
5848 static void release_reg_references(struct bpf_verifier_env *env,
5849                                    struct bpf_func_state *state,
5850                                    int ref_obj_id)
5851 {
5852         struct bpf_reg_state *regs = state->regs, *reg;
5853         int i;
5854
5855         for (i = 0; i < MAX_BPF_REG; i++)
5856                 if (regs[i].ref_obj_id == ref_obj_id)
5857                         mark_reg_unknown(env, regs, i);
5858
5859         bpf_for_each_spilled_reg(i, state, reg) {
5860                 if (!reg)
5861                         continue;
5862                 if (reg->ref_obj_id == ref_obj_id)
5863                         __mark_reg_unknown(env, reg);
5864         }
5865 }
5866
5867 /* The pointer with the specified id has released its reference to kernel
5868  * resources. Identify all copies of the same pointer and clear the reference.
5869  */
5870 static int release_reference(struct bpf_verifier_env *env,
5871                              int ref_obj_id)
5872 {
5873         struct bpf_verifier_state *vstate = env->cur_state;
5874         int err;
5875         int i;
5876
5877         err = release_reference_state(cur_func(env), ref_obj_id);
5878         if (err)
5879                 return err;
5880
5881         for (i = 0; i <= vstate->curframe; i++)
5882                 release_reg_references(env, vstate->frame[i], ref_obj_id);
5883
5884         return 0;
5885 }
5886
5887 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5888                                     struct bpf_reg_state *regs)
5889 {
5890         int i;
5891
5892         /* after the call registers r0 - r5 were scratched */
5893         for (i = 0; i < CALLER_SAVED_REGS; i++) {
5894                 mark_reg_not_init(env, regs, caller_saved[i]);
5895                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5896         }
5897 }
5898
5899 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5900                                    struct bpf_func_state *caller,
5901                                    struct bpf_func_state *callee,
5902                                    int insn_idx);
5903
5904 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5905                              int *insn_idx, int subprog,
5906                              set_callee_state_fn set_callee_state_cb)
5907 {
5908         struct bpf_verifier_state *state = env->cur_state;
5909         struct bpf_func_info_aux *func_info_aux;
5910         struct bpf_func_state *caller, *callee;
5911         int err;
5912         bool is_global = false;
5913
5914         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5915                 verbose(env, "the call stack of %d frames is too deep\n",
5916                         state->curframe + 2);
5917                 return -E2BIG;
5918         }
5919
5920         caller = state->frame[state->curframe];
5921         if (state->frame[state->curframe + 1]) {
5922                 verbose(env, "verifier bug. Frame %d already allocated\n",
5923                         state->curframe + 1);
5924                 return -EFAULT;
5925         }
5926
5927         func_info_aux = env->prog->aux->func_info_aux;
5928         if (func_info_aux)
5929                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5930         err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5931         if (err == -EFAULT)
5932                 return err;
5933         if (is_global) {
5934                 if (err) {
5935                         verbose(env, "Caller passes invalid args into func#%d\n",
5936                                 subprog);
5937                         return err;
5938                 } else {
5939                         if (env->log.level & BPF_LOG_LEVEL)
5940                                 verbose(env,
5941                                         "Func#%d is global and valid. Skipping.\n",
5942                                         subprog);
5943                         clear_caller_saved_regs(env, caller->regs);
5944
5945                         /* All global functions return a 64-bit SCALAR_VALUE */
5946                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
5947                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5948
5949                         /* continue with next insn after call */
5950                         return 0;
5951                 }
5952         }
5953
5954         if (insn->code == (BPF_JMP | BPF_CALL) &&
5955             insn->imm == BPF_FUNC_timer_set_callback) {
5956                 struct bpf_verifier_state *async_cb;
5957
5958                 /* there is no real recursion here. timer callbacks are async */
5959                 env->subprog_info[subprog].is_async_cb = true;
5960                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
5961                                          *insn_idx, subprog);
5962                 if (!async_cb)
5963                         return -EFAULT;
5964                 callee = async_cb->frame[0];
5965                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
5966
5967                 /* Convert bpf_timer_set_callback() args into timer callback args */
5968                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5969                 if (err)
5970                         return err;
5971
5972                 clear_caller_saved_regs(env, caller->regs);
5973                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5974                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5975                 /* continue with next insn after call */
5976                 return 0;
5977         }
5978
5979         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5980         if (!callee)
5981                 return -ENOMEM;
5982         state->frame[state->curframe + 1] = callee;
5983
5984         /* callee cannot access r0, r6 - r9 for reading and has to write
5985          * into its own stack before reading from it.
5986          * callee can read/write into caller's stack
5987          */
5988         init_func_state(env, callee,
5989                         /* remember the callsite, it will be used by bpf_exit */
5990                         *insn_idx /* callsite */,
5991                         state->curframe + 1 /* frameno within this callchain */,
5992                         subprog /* subprog number within this prog */);
5993
5994         /* Transfer references to the callee */
5995         err = copy_reference_state(callee, caller);
5996         if (err)
5997                 return err;
5998
5999         err = set_callee_state_cb(env, caller, callee, *insn_idx);
6000         if (err)
6001                 return err;
6002
6003         clear_caller_saved_regs(env, caller->regs);
6004
6005         /* only increment it after check_reg_arg() finished */
6006         state->curframe++;
6007
6008         /* and go analyze first insn of the callee */
6009         *insn_idx = env->subprog_info[subprog].start - 1;
6010
6011         if (env->log.level & BPF_LOG_LEVEL) {
6012                 verbose(env, "caller:\n");
6013                 print_verifier_state(env, caller);
6014                 verbose(env, "callee:\n");
6015                 print_verifier_state(env, callee);
6016         }
6017         return 0;
6018 }
6019
6020 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6021                                    struct bpf_func_state *caller,
6022                                    struct bpf_func_state *callee)
6023 {
6024         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6025          *      void *callback_ctx, u64 flags);
6026          * callback_fn(struct bpf_map *map, void *key, void *value,
6027          *      void *callback_ctx);
6028          */
6029         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6030
6031         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6032         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6033         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6034
6035         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6036         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6037         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6038
6039         /* pointer to stack or null */
6040         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6041
6042         /* unused */
6043         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6044         return 0;
6045 }
6046
6047 static int set_callee_state(struct bpf_verifier_env *env,
6048                             struct bpf_func_state *caller,
6049                             struct bpf_func_state *callee, int insn_idx)
6050 {
6051         int i;
6052
6053         /* copy r1 - r5 args that callee can access.  The copy includes parent
6054          * pointers, which connects us up to the liveness chain
6055          */
6056         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6057                 callee->regs[i] = caller->regs[i];
6058         return 0;
6059 }
6060
6061 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6062                            int *insn_idx)
6063 {
6064         int subprog, target_insn;
6065
6066         target_insn = *insn_idx + insn->imm + 1;
6067         subprog = find_subprog(env, target_insn);
6068         if (subprog < 0) {
6069                 verbose(env, "verifier bug. No program starts at insn %d\n",
6070                         target_insn);
6071                 return -EFAULT;
6072         }
6073
6074         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6075 }
6076
6077 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6078                                        struct bpf_func_state *caller,
6079                                        struct bpf_func_state *callee,
6080                                        int insn_idx)
6081 {
6082         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6083         struct bpf_map *map;
6084         int err;
6085
6086         if (bpf_map_ptr_poisoned(insn_aux)) {
6087                 verbose(env, "tail_call abusing map_ptr\n");
6088                 return -EINVAL;
6089         }
6090
6091         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6092         if (!map->ops->map_set_for_each_callback_args ||
6093             !map->ops->map_for_each_callback) {
6094                 verbose(env, "callback function not allowed for map\n");
6095                 return -ENOTSUPP;
6096         }
6097
6098         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6099         if (err)
6100                 return err;
6101
6102         callee->in_callback_fn = true;
6103         return 0;
6104 }
6105
6106 static int set_loop_callback_state(struct bpf_verifier_env *env,
6107                                    struct bpf_func_state *caller,
6108                                    struct bpf_func_state *callee,
6109                                    int insn_idx)
6110 {
6111         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6112          *          u64 flags);
6113          * callback_fn(u32 index, void *callback_ctx);
6114          */
6115         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6116         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6117
6118         /* unused */
6119         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6120         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6121         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6122
6123         callee->in_callback_fn = true;
6124         return 0;
6125 }
6126
6127 static int set_timer_callback_state(struct bpf_verifier_env *env,
6128                                     struct bpf_func_state *caller,
6129                                     struct bpf_func_state *callee,
6130                                     int insn_idx)
6131 {
6132         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6133
6134         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6135          * callback_fn(struct bpf_map *map, void *key, void *value);
6136          */
6137         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6138         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6139         callee->regs[BPF_REG_1].map_ptr = map_ptr;
6140
6141         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6142         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6143         callee->regs[BPF_REG_2].map_ptr = map_ptr;
6144
6145         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6146         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6147         callee->regs[BPF_REG_3].map_ptr = map_ptr;
6148
6149         /* unused */
6150         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6151         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6152         callee->in_async_callback_fn = true;
6153         return 0;
6154 }
6155
6156 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6157                                        struct bpf_func_state *caller,
6158                                        struct bpf_func_state *callee,
6159                                        int insn_idx)
6160 {
6161         /* bpf_find_vma(struct task_struct *task, u64 addr,
6162          *               void *callback_fn, void *callback_ctx, u64 flags)
6163          * (callback_fn)(struct task_struct *task,
6164          *               struct vm_area_struct *vma, void *callback_ctx);
6165          */
6166         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6167
6168         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6169         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6170         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6171         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6172
6173         /* pointer to stack or null */
6174         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6175
6176         /* unused */
6177         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6178         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6179         callee->in_callback_fn = true;
6180         return 0;
6181 }
6182
6183 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6184 {
6185         struct bpf_verifier_state *state = env->cur_state;
6186         struct bpf_func_state *caller, *callee;
6187         struct bpf_reg_state *r0;
6188         int err;
6189
6190         callee = state->frame[state->curframe];
6191         r0 = &callee->regs[BPF_REG_0];
6192         if (r0->type == PTR_TO_STACK) {
6193                 /* technically it's ok to return caller's stack pointer
6194                  * (or caller's caller's pointer) back to the caller,
6195                  * since these pointers are valid. Only current stack
6196                  * pointer will be invalid as soon as function exits,
6197                  * but let's be conservative
6198                  */
6199                 verbose(env, "cannot return stack pointer to the caller\n");
6200                 return -EINVAL;
6201         }
6202
6203         state->curframe--;
6204         caller = state->frame[state->curframe];
6205         if (callee->in_callback_fn) {
6206                 /* enforce R0 return value range [0, 1]. */
6207                 struct tnum range = tnum_range(0, 1);
6208
6209                 if (r0->type != SCALAR_VALUE) {
6210                         verbose(env, "R0 not a scalar value\n");
6211                         return -EACCES;
6212                 }
6213                 if (!tnum_in(range, r0->var_off)) {
6214                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6215                         return -EINVAL;
6216                 }
6217         } else {
6218                 /* return to the caller whatever r0 had in the callee */
6219                 caller->regs[BPF_REG_0] = *r0;
6220         }
6221
6222         /* Transfer references to the caller */
6223         err = copy_reference_state(caller, callee);
6224         if (err)
6225                 return err;
6226
6227         *insn_idx = callee->callsite + 1;
6228         if (env->log.level & BPF_LOG_LEVEL) {
6229                 verbose(env, "returning from callee:\n");
6230                 print_verifier_state(env, callee);
6231                 verbose(env, "to caller at %d:\n", *insn_idx);
6232                 print_verifier_state(env, caller);
6233         }
6234         /* clear everything in the callee */
6235         free_func_state(callee);
6236         state->frame[state->curframe + 1] = NULL;
6237         return 0;
6238 }
6239
6240 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6241                                    int func_id,
6242                                    struct bpf_call_arg_meta *meta)
6243 {
6244         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6245
6246         if (ret_type != RET_INTEGER ||
6247             (func_id != BPF_FUNC_get_stack &&
6248              func_id != BPF_FUNC_get_task_stack &&
6249              func_id != BPF_FUNC_probe_read_str &&
6250              func_id != BPF_FUNC_probe_read_kernel_str &&
6251              func_id != BPF_FUNC_probe_read_user_str))
6252                 return;
6253
6254         ret_reg->smax_value = meta->msize_max_value;
6255         ret_reg->s32_max_value = meta->msize_max_value;
6256         ret_reg->smin_value = -MAX_ERRNO;
6257         ret_reg->s32_min_value = -MAX_ERRNO;
6258         __reg_deduce_bounds(ret_reg);
6259         __reg_bound_offset(ret_reg);
6260         __update_reg_bounds(ret_reg);
6261 }
6262
6263 static int
6264 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6265                 int func_id, int insn_idx)
6266 {
6267         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6268         struct bpf_map *map = meta->map_ptr;
6269
6270         if (func_id != BPF_FUNC_tail_call &&
6271             func_id != BPF_FUNC_map_lookup_elem &&
6272             func_id != BPF_FUNC_map_update_elem &&
6273             func_id != BPF_FUNC_map_delete_elem &&
6274             func_id != BPF_FUNC_map_push_elem &&
6275             func_id != BPF_FUNC_map_pop_elem &&
6276             func_id != BPF_FUNC_map_peek_elem &&
6277             func_id != BPF_FUNC_for_each_map_elem &&
6278             func_id != BPF_FUNC_redirect_map)
6279                 return 0;
6280
6281         if (map == NULL) {
6282                 verbose(env, "kernel subsystem misconfigured verifier\n");
6283                 return -EINVAL;
6284         }
6285
6286         /* In case of read-only, some additional restrictions
6287          * need to be applied in order to prevent altering the
6288          * state of the map from program side.
6289          */
6290         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6291             (func_id == BPF_FUNC_map_delete_elem ||
6292              func_id == BPF_FUNC_map_update_elem ||
6293              func_id == BPF_FUNC_map_push_elem ||
6294              func_id == BPF_FUNC_map_pop_elem)) {
6295                 verbose(env, "write into map forbidden\n");
6296                 return -EACCES;
6297         }
6298
6299         if (!BPF_MAP_PTR(aux->map_ptr_state))
6300                 bpf_map_ptr_store(aux, meta->map_ptr,
6301                                   !meta->map_ptr->bypass_spec_v1);
6302         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6303                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6304                                   !meta->map_ptr->bypass_spec_v1);
6305         return 0;
6306 }
6307
6308 static int
6309 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6310                 int func_id, int insn_idx)
6311 {
6312         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6313         struct bpf_reg_state *regs = cur_regs(env), *reg;
6314         struct bpf_map *map = meta->map_ptr;
6315         struct tnum range;
6316         u64 val;
6317         int err;
6318
6319         if (func_id != BPF_FUNC_tail_call)
6320                 return 0;
6321         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6322                 verbose(env, "kernel subsystem misconfigured verifier\n");
6323                 return -EINVAL;
6324         }
6325
6326         range = tnum_range(0, map->max_entries - 1);
6327         reg = &regs[BPF_REG_3];
6328
6329         if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6330                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6331                 return 0;
6332         }
6333
6334         err = mark_chain_precision(env, BPF_REG_3);
6335         if (err)
6336                 return err;
6337
6338         val = reg->var_off.value;
6339         if (bpf_map_key_unseen(aux))
6340                 bpf_map_key_store(aux, val);
6341         else if (!bpf_map_key_poisoned(aux) &&
6342                   bpf_map_key_immediate(aux) != val)
6343                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6344         return 0;
6345 }
6346
6347 static int check_reference_leak(struct bpf_verifier_env *env)
6348 {
6349         struct bpf_func_state *state = cur_func(env);
6350         int i;
6351
6352         for (i = 0; i < state->acquired_refs; i++) {
6353                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6354                         state->refs[i].id, state->refs[i].insn_idx);
6355         }
6356         return state->acquired_refs ? -EINVAL : 0;
6357 }
6358
6359 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6360                                    struct bpf_reg_state *regs)
6361 {
6362         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6363         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6364         struct bpf_map *fmt_map = fmt_reg->map_ptr;
6365         int err, fmt_map_off, num_args;
6366         u64 fmt_addr;
6367         char *fmt;
6368
6369         /* data must be an array of u64 */
6370         if (data_len_reg->var_off.value % 8)
6371                 return -EINVAL;
6372         num_args = data_len_reg->var_off.value / 8;
6373
6374         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6375          * and map_direct_value_addr is set.
6376          */
6377         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6378         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6379                                                   fmt_map_off);
6380         if (err) {
6381                 verbose(env, "verifier bug\n");
6382                 return -EFAULT;
6383         }
6384         fmt = (char *)(long)fmt_addr + fmt_map_off;
6385
6386         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6387          * can focus on validating the format specifiers.
6388          */
6389         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6390         if (err < 0)
6391                 verbose(env, "Invalid format string\n");
6392
6393         return err;
6394 }
6395
6396 static int check_get_func_ip(struct bpf_verifier_env *env)
6397 {
6398         enum bpf_prog_type type = resolve_prog_type(env->prog);
6399         int func_id = BPF_FUNC_get_func_ip;
6400
6401         if (type == BPF_PROG_TYPE_TRACING) {
6402                 if (!bpf_prog_has_trampoline(env->prog)) {
6403                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6404                                 func_id_name(func_id), func_id);
6405                         return -ENOTSUPP;
6406                 }
6407                 return 0;
6408         } else if (type == BPF_PROG_TYPE_KPROBE) {
6409                 return 0;
6410         }
6411
6412         verbose(env, "func %s#%d not supported for program type %d\n",
6413                 func_id_name(func_id), func_id, type);
6414         return -ENOTSUPP;
6415 }
6416
6417 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6418                              int *insn_idx_p)
6419 {
6420         const struct bpf_func_proto *fn = NULL;
6421         struct bpf_reg_state *regs;
6422         struct bpf_call_arg_meta meta;
6423         int insn_idx = *insn_idx_p;
6424         bool changes_data;
6425         int i, err, func_id;
6426
6427         /* find function prototype */
6428         func_id = insn->imm;
6429         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6430                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6431                         func_id);
6432                 return -EINVAL;
6433         }
6434
6435         if (env->ops->get_func_proto)
6436                 fn = env->ops->get_func_proto(func_id, env->prog);
6437         if (!fn) {
6438                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6439                         func_id);
6440                 return -EINVAL;
6441         }
6442
6443         /* eBPF programs must be GPL compatible to use GPL-ed functions */
6444         if (!env->prog->gpl_compatible && fn->gpl_only) {
6445                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6446                 return -EINVAL;
6447         }
6448
6449         if (fn->allowed && !fn->allowed(env->prog)) {
6450                 verbose(env, "helper call is not allowed in probe\n");
6451                 return -EINVAL;
6452         }
6453
6454         /* With LD_ABS/IND some JITs save/restore skb from r1. */
6455         changes_data = bpf_helper_changes_pkt_data(fn->func);
6456         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6457                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6458                         func_id_name(func_id), func_id);
6459                 return -EINVAL;
6460         }
6461
6462         memset(&meta, 0, sizeof(meta));
6463         meta.pkt_access = fn->pkt_access;
6464
6465         err = check_func_proto(fn, func_id);
6466         if (err) {
6467                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6468                         func_id_name(func_id), func_id);
6469                 return err;
6470         }
6471
6472         meta.func_id = func_id;
6473         /* check args */
6474         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6475                 err = check_func_arg(env, i, &meta, fn);
6476                 if (err)
6477                         return err;
6478         }
6479
6480         err = record_func_map(env, &meta, func_id, insn_idx);
6481         if (err)
6482                 return err;
6483
6484         err = record_func_key(env, &meta, func_id, insn_idx);
6485         if (err)
6486                 return err;
6487
6488         /* Mark slots with STACK_MISC in case of raw mode, stack offset
6489          * is inferred from register state.
6490          */
6491         for (i = 0; i < meta.access_size; i++) {
6492                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6493                                        BPF_WRITE, -1, false);
6494                 if (err)
6495                         return err;
6496         }
6497
6498         if (is_release_function(func_id)) {
6499                 err = release_reference(env, meta.ref_obj_id);
6500                 if (err) {
6501                         verbose(env, "func %s#%d reference has not been acquired before\n",
6502                                 func_id_name(func_id), func_id);
6503                         return err;
6504                 }
6505         }
6506
6507         regs = cur_regs(env);
6508
6509         switch (func_id) {
6510         case BPF_FUNC_tail_call:
6511                 err = check_reference_leak(env);
6512                 if (err) {
6513                         verbose(env, "tail_call would lead to reference leak\n");
6514                         return err;
6515                 }
6516                 break;
6517         case BPF_FUNC_get_local_storage:
6518                 /* check that flags argument in get_local_storage(map, flags) is 0,
6519                  * this is required because get_local_storage() can't return an error.
6520                  */
6521                 if (!register_is_null(&regs[BPF_REG_2])) {
6522                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6523                         return -EINVAL;
6524                 }
6525                 break;
6526         case BPF_FUNC_for_each_map_elem:
6527                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6528                                         set_map_elem_callback_state);
6529                 break;
6530         case BPF_FUNC_timer_set_callback:
6531                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6532                                         set_timer_callback_state);
6533                 break;
6534         case BPF_FUNC_find_vma:
6535                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6536                                         set_find_vma_callback_state);
6537                 break;
6538         case BPF_FUNC_snprintf:
6539                 err = check_bpf_snprintf_call(env, regs);
6540                 break;
6541         case BPF_FUNC_loop:
6542                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6543                                         set_loop_callback_state);
6544                 break;
6545         }
6546
6547         if (err)
6548                 return err;
6549
6550         /* reset caller saved regs */
6551         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6552                 mark_reg_not_init(env, regs, caller_saved[i]);
6553                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6554         }
6555
6556         /* helper call returns 64-bit value. */
6557         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6558
6559         /* update return register (already marked as written above) */
6560         if (fn->ret_type == RET_INTEGER) {
6561                 /* sets type to SCALAR_VALUE */
6562                 mark_reg_unknown(env, regs, BPF_REG_0);
6563         } else if (fn->ret_type == RET_VOID) {
6564                 regs[BPF_REG_0].type = NOT_INIT;
6565         } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6566                    fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6567                 /* There is no offset yet applied, variable or fixed */
6568                 mark_reg_known_zero(env, regs, BPF_REG_0);
6569                 /* remember map_ptr, so that check_map_access()
6570                  * can check 'value_size' boundary of memory access
6571                  * to map element returned from bpf_map_lookup_elem()
6572                  */
6573                 if (meta.map_ptr == NULL) {
6574                         verbose(env,
6575                                 "kernel subsystem misconfigured verifier\n");
6576                         return -EINVAL;
6577                 }
6578                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
6579                 regs[BPF_REG_0].map_uid = meta.map_uid;
6580                 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6581                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
6582                         if (map_value_has_spin_lock(meta.map_ptr))
6583                                 regs[BPF_REG_0].id = ++env->id_gen;
6584                 } else {
6585                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
6586                 }
6587         } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6588                 mark_reg_known_zero(env, regs, BPF_REG_0);
6589                 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
6590         } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6591                 mark_reg_known_zero(env, regs, BPF_REG_0);
6592                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
6593         } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6594                 mark_reg_known_zero(env, regs, BPF_REG_0);
6595                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
6596         } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6597                 mark_reg_known_zero(env, regs, BPF_REG_0);
6598                 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
6599                 regs[BPF_REG_0].mem_size = meta.mem_size;
6600         } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6601                    fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
6602                 const struct btf_type *t;
6603
6604                 mark_reg_known_zero(env, regs, BPF_REG_0);
6605                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6606                 if (!btf_type_is_struct(t)) {
6607                         u32 tsize;
6608                         const struct btf_type *ret;
6609                         const char *tname;
6610
6611                         /* resolve the type size of ksym. */
6612                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6613                         if (IS_ERR(ret)) {
6614                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6615                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6616                                         tname, PTR_ERR(ret));
6617                                 return -EINVAL;
6618                         }
6619                         regs[BPF_REG_0].type =
6620                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6621                                 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
6622                         regs[BPF_REG_0].mem_size = tsize;
6623                 } else {
6624                         regs[BPF_REG_0].type =
6625                                 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6626                                 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
6627                         regs[BPF_REG_0].btf = meta.ret_btf;
6628                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6629                 }
6630         } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6631                    fn->ret_type == RET_PTR_TO_BTF_ID) {
6632                 int ret_btf_id;
6633
6634                 mark_reg_known_zero(env, regs, BPF_REG_0);
6635                 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6636                                                      PTR_TO_BTF_ID :
6637                                                      PTR_TO_BTF_ID_OR_NULL;
6638                 ret_btf_id = *fn->ret_btf_id;
6639                 if (ret_btf_id == 0) {
6640                         verbose(env, "invalid return type %d of func %s#%d\n",
6641                                 fn->ret_type, func_id_name(func_id), func_id);
6642                         return -EINVAL;
6643                 }
6644                 /* current BPF helper definitions are only coming from
6645                  * built-in code with type IDs from  vmlinux BTF
6646                  */
6647                 regs[BPF_REG_0].btf = btf_vmlinux;
6648                 regs[BPF_REG_0].btf_id = ret_btf_id;
6649         } else {
6650                 verbose(env, "unknown return type %d of func %s#%d\n",
6651                         fn->ret_type, func_id_name(func_id), func_id);
6652                 return -EINVAL;
6653         }
6654
6655         if (reg_type_may_be_null(regs[BPF_REG_0].type))
6656                 regs[BPF_REG_0].id = ++env->id_gen;
6657
6658         if (is_ptr_cast_function(func_id)) {
6659                 /* For release_reference() */
6660                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6661         } else if (is_acquire_function(func_id, meta.map_ptr)) {
6662                 int id = acquire_reference_state(env, insn_idx);
6663
6664                 if (id < 0)
6665                         return id;
6666                 /* For mark_ptr_or_null_reg() */
6667                 regs[BPF_REG_0].id = id;
6668                 /* For release_reference() */
6669                 regs[BPF_REG_0].ref_obj_id = id;
6670         }
6671
6672         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6673
6674         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6675         if (err)
6676                 return err;
6677
6678         if ((func_id == BPF_FUNC_get_stack ||
6679              func_id == BPF_FUNC_get_task_stack) &&
6680             !env->prog->has_callchain_buf) {
6681                 const char *err_str;
6682
6683 #ifdef CONFIG_PERF_EVENTS
6684                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6685                 err_str = "cannot get callchain buffer for func %s#%d\n";
6686 #else
6687                 err = -ENOTSUPP;
6688                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6689 #endif
6690                 if (err) {
6691                         verbose(env, err_str, func_id_name(func_id), func_id);
6692                         return err;
6693                 }
6694
6695                 env->prog->has_callchain_buf = true;
6696         }
6697
6698         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6699                 env->prog->call_get_stack = true;
6700
6701         if (func_id == BPF_FUNC_get_func_ip) {
6702                 if (check_get_func_ip(env))
6703                         return -ENOTSUPP;
6704                 env->prog->call_get_func_ip = true;
6705         }
6706
6707         if (changes_data)
6708                 clear_all_pkt_pointers(env);
6709         return 0;
6710 }
6711
6712 /* mark_btf_func_reg_size() is used when the reg size is determined by
6713  * the BTF func_proto's return value size and argument.
6714  */
6715 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6716                                    size_t reg_size)
6717 {
6718         struct bpf_reg_state *reg = &cur_regs(env)[regno];
6719
6720         if (regno == BPF_REG_0) {
6721                 /* Function return value */
6722                 reg->live |= REG_LIVE_WRITTEN;
6723                 reg->subreg_def = reg_size == sizeof(u64) ?
6724                         DEF_NOT_SUBREG : env->insn_idx + 1;
6725         } else {
6726                 /* Function argument */
6727                 if (reg_size == sizeof(u64)) {
6728                         mark_insn_zext(env, reg);
6729                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6730                 } else {
6731                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6732                 }
6733         }
6734 }
6735
6736 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6737 {
6738         const struct btf_type *t, *func, *func_proto, *ptr_type;
6739         struct bpf_reg_state *regs = cur_regs(env);
6740         const char *func_name, *ptr_type_name;
6741         u32 i, nargs, func_id, ptr_type_id;
6742         struct module *btf_mod = NULL;
6743         const struct btf_param *args;
6744         struct btf *desc_btf;
6745         int err;
6746
6747         /* skip for now, but return error when we find this in fixup_kfunc_call */
6748         if (!insn->imm)
6749                 return 0;
6750
6751         desc_btf = find_kfunc_desc_btf(env, insn->imm, insn->off, &btf_mod);
6752         if (IS_ERR(desc_btf))
6753                 return PTR_ERR(desc_btf);
6754
6755         func_id = insn->imm;
6756         func = btf_type_by_id(desc_btf, func_id);
6757         func_name = btf_name_by_offset(desc_btf, func->name_off);
6758         func_proto = btf_type_by_id(desc_btf, func->type);
6759
6760         if (!env->ops->check_kfunc_call ||
6761             !env->ops->check_kfunc_call(func_id, btf_mod)) {
6762                 verbose(env, "calling kernel function %s is not allowed\n",
6763                         func_name);
6764                 return -EACCES;
6765         }
6766
6767         /* Check the arguments */
6768         err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs);
6769         if (err)
6770                 return err;
6771
6772         for (i = 0; i < CALLER_SAVED_REGS; i++)
6773                 mark_reg_not_init(env, regs, caller_saved[i]);
6774
6775         /* Check return type */
6776         t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
6777         if (btf_type_is_scalar(t)) {
6778                 mark_reg_unknown(env, regs, BPF_REG_0);
6779                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6780         } else if (btf_type_is_ptr(t)) {
6781                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
6782                                                    &ptr_type_id);
6783                 if (!btf_type_is_struct(ptr_type)) {
6784                         ptr_type_name = btf_name_by_offset(desc_btf,
6785                                                            ptr_type->name_off);
6786                         verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6787                                 func_name, btf_type_str(ptr_type),
6788                                 ptr_type_name);
6789                         return -EINVAL;
6790                 }
6791                 mark_reg_known_zero(env, regs, BPF_REG_0);
6792                 regs[BPF_REG_0].btf = desc_btf;
6793                 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6794                 regs[BPF_REG_0].btf_id = ptr_type_id;
6795                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6796         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6797
6798         nargs = btf_type_vlen(func_proto);
6799         args = (const struct btf_param *)(func_proto + 1);
6800         for (i = 0; i < nargs; i++) {
6801                 u32 regno = i + 1;
6802
6803                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
6804                 if (btf_type_is_ptr(t))
6805                         mark_btf_func_reg_size(env, regno, sizeof(void *));
6806                 else
6807                         /* scalar. ensured by btf_check_kfunc_arg_match() */
6808                         mark_btf_func_reg_size(env, regno, t->size);
6809         }
6810
6811         return 0;
6812 }
6813
6814 static bool signed_add_overflows(s64 a, s64 b)
6815 {
6816         /* Do the add in u64, where overflow is well-defined */
6817         s64 res = (s64)((u64)a + (u64)b);
6818
6819         if (b < 0)
6820                 return res > a;
6821         return res < a;
6822 }
6823
6824 static bool signed_add32_overflows(s32 a, s32 b)
6825 {
6826         /* Do the add in u32, where overflow is well-defined */
6827         s32 res = (s32)((u32)a + (u32)b);
6828
6829         if (b < 0)
6830                 return res > a;
6831         return res < a;
6832 }
6833
6834 static bool signed_sub_overflows(s64 a, s64 b)
6835 {
6836         /* Do the sub in u64, where overflow is well-defined */
6837         s64 res = (s64)((u64)a - (u64)b);
6838
6839         if (b < 0)
6840                 return res < a;
6841         return res > a;
6842 }
6843
6844 static bool signed_sub32_overflows(s32 a, s32 b)
6845 {
6846         /* Do the sub in u32, where overflow is well-defined */
6847         s32 res = (s32)((u32)a - (u32)b);
6848
6849         if (b < 0)
6850                 return res < a;
6851         return res > a;
6852 }
6853
6854 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6855                                   const struct bpf_reg_state *reg,
6856                                   enum bpf_reg_type type)
6857 {
6858         bool known = tnum_is_const(reg->var_off);
6859         s64 val = reg->var_off.value;
6860         s64 smin = reg->smin_value;
6861
6862         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6863                 verbose(env, "math between %s pointer and %lld is not allowed\n",
6864                         reg_type_str[type], val);
6865                 return false;
6866         }
6867
6868         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6869                 verbose(env, "%s pointer offset %d is not allowed\n",
6870                         reg_type_str[type], reg->off);
6871                 return false;
6872         }
6873
6874         if (smin == S64_MIN) {
6875                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6876                         reg_type_str[type]);
6877                 return false;
6878         }
6879
6880         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6881                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6882                         smin, reg_type_str[type]);
6883                 return false;
6884         }
6885
6886         return true;
6887 }
6888
6889 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6890 {
6891         return &env->insn_aux_data[env->insn_idx];
6892 }
6893
6894 enum {
6895         REASON_BOUNDS   = -1,
6896         REASON_TYPE     = -2,
6897         REASON_PATHS    = -3,
6898         REASON_LIMIT    = -4,
6899         REASON_STACK    = -5,
6900 };
6901
6902 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6903                               u32 *alu_limit, bool mask_to_left)
6904 {
6905         u32 max = 0, ptr_limit = 0;
6906
6907         switch (ptr_reg->type) {
6908         case PTR_TO_STACK:
6909                 /* Offset 0 is out-of-bounds, but acceptable start for the
6910                  * left direction, see BPF_REG_FP. Also, unknown scalar
6911                  * offset where we would need to deal with min/max bounds is
6912                  * currently prohibited for unprivileged.
6913                  */
6914                 max = MAX_BPF_STACK + mask_to_left;
6915                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6916                 break;
6917         case PTR_TO_MAP_VALUE:
6918                 max = ptr_reg->map_ptr->value_size;
6919                 ptr_limit = (mask_to_left ?
6920                              ptr_reg->smin_value :
6921                              ptr_reg->umax_value) + ptr_reg->off;
6922                 break;
6923         default:
6924                 return REASON_TYPE;
6925         }
6926
6927         if (ptr_limit >= max)
6928                 return REASON_LIMIT;
6929         *alu_limit = ptr_limit;
6930         return 0;
6931 }
6932
6933 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6934                                     const struct bpf_insn *insn)
6935 {
6936         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6937 }
6938
6939 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6940                                        u32 alu_state, u32 alu_limit)
6941 {
6942         /* If we arrived here from different branches with different
6943          * state or limits to sanitize, then this won't work.
6944          */
6945         if (aux->alu_state &&
6946             (aux->alu_state != alu_state ||
6947              aux->alu_limit != alu_limit))
6948                 return REASON_PATHS;
6949
6950         /* Corresponding fixup done in do_misc_fixups(). */
6951         aux->alu_state = alu_state;
6952         aux->alu_limit = alu_limit;
6953         return 0;
6954 }
6955
6956 static int sanitize_val_alu(struct bpf_verifier_env *env,
6957                             struct bpf_insn *insn)
6958 {
6959         struct bpf_insn_aux_data *aux = cur_aux(env);
6960
6961         if (can_skip_alu_sanitation(env, insn))
6962                 return 0;
6963
6964         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6965 }
6966
6967 static bool sanitize_needed(u8 opcode)
6968 {
6969         return opcode == BPF_ADD || opcode == BPF_SUB;
6970 }
6971
6972 struct bpf_sanitize_info {
6973         struct bpf_insn_aux_data aux;
6974         bool mask_to_left;
6975 };
6976
6977 static struct bpf_verifier_state *
6978 sanitize_speculative_path(struct bpf_verifier_env *env,
6979                           const struct bpf_insn *insn,
6980                           u32 next_idx, u32 curr_idx)
6981 {
6982         struct bpf_verifier_state *branch;
6983         struct bpf_reg_state *regs;
6984
6985         branch = push_stack(env, next_idx, curr_idx, true);
6986         if (branch && insn) {
6987                 regs = branch->frame[branch->curframe]->regs;
6988                 if (BPF_SRC(insn->code) == BPF_K) {
6989                         mark_reg_unknown(env, regs, insn->dst_reg);
6990                 } else if (BPF_SRC(insn->code) == BPF_X) {
6991                         mark_reg_unknown(env, regs, insn->dst_reg);
6992                         mark_reg_unknown(env, regs, insn->src_reg);
6993                 }
6994         }
6995         return branch;
6996 }
6997
6998 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6999                             struct bpf_insn *insn,
7000                             const struct bpf_reg_state *ptr_reg,
7001                             const struct bpf_reg_state *off_reg,
7002                             struct bpf_reg_state *dst_reg,
7003                             struct bpf_sanitize_info *info,
7004                             const bool commit_window)
7005 {
7006         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7007         struct bpf_verifier_state *vstate = env->cur_state;
7008         bool off_is_imm = tnum_is_const(off_reg->var_off);
7009         bool off_is_neg = off_reg->smin_value < 0;
7010         bool ptr_is_dst_reg = ptr_reg == dst_reg;
7011         u8 opcode = BPF_OP(insn->code);
7012         u32 alu_state, alu_limit;
7013         struct bpf_reg_state tmp;
7014         bool ret;
7015         int err;
7016
7017         if (can_skip_alu_sanitation(env, insn))
7018                 return 0;
7019
7020         /* We already marked aux for masking from non-speculative
7021          * paths, thus we got here in the first place. We only care
7022          * to explore bad access from here.
7023          */
7024         if (vstate->speculative)
7025                 goto do_sim;
7026
7027         if (!commit_window) {
7028                 if (!tnum_is_const(off_reg->var_off) &&
7029                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7030                         return REASON_BOUNDS;
7031
7032                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
7033                                      (opcode == BPF_SUB && !off_is_neg);
7034         }
7035
7036         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
7037         if (err < 0)
7038                 return err;
7039
7040         if (commit_window) {
7041                 /* In commit phase we narrow the masking window based on
7042                  * the observed pointer move after the simulated operation.
7043                  */
7044                 alu_state = info->aux.alu_state;
7045                 alu_limit = abs(info->aux.alu_limit - alu_limit);
7046         } else {
7047                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
7048                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7049                 alu_state |= ptr_is_dst_reg ?
7050                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
7051
7052                 /* Limit pruning on unknown scalars to enable deep search for
7053                  * potential masking differences from other program paths.
7054                  */
7055                 if (!off_is_imm)
7056                         env->explore_alu_limits = true;
7057         }
7058
7059         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7060         if (err < 0)
7061                 return err;
7062 do_sim:
7063         /* If we're in commit phase, we're done here given we already
7064          * pushed the truncated dst_reg into the speculative verification
7065          * stack.
7066          *
7067          * Also, when register is a known constant, we rewrite register-based
7068          * operation to immediate-based, and thus do not need masking (and as
7069          * a consequence, do not need to simulate the zero-truncation either).
7070          */
7071         if (commit_window || off_is_imm)
7072                 return 0;
7073
7074         /* Simulate and find potential out-of-bounds access under
7075          * speculative execution from truncation as a result of
7076          * masking when off was not within expected range. If off
7077          * sits in dst, then we temporarily need to move ptr there
7078          * to simulate dst (== 0) +/-= ptr. Needed, for example,
7079          * for cases where we use K-based arithmetic in one direction
7080          * and truncated reg-based in the other in order to explore
7081          * bad access.
7082          */
7083         if (!ptr_is_dst_reg) {
7084                 tmp = *dst_reg;
7085                 *dst_reg = *ptr_reg;
7086         }
7087         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7088                                         env->insn_idx);
7089         if (!ptr_is_dst_reg && ret)
7090                 *dst_reg = tmp;
7091         return !ret ? REASON_STACK : 0;
7092 }
7093
7094 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7095 {
7096         struct bpf_verifier_state *vstate = env->cur_state;
7097
7098         /* If we simulate paths under speculation, we don't update the
7099          * insn as 'seen' such that when we verify unreachable paths in
7100          * the non-speculative domain, sanitize_dead_code() can still
7101          * rewrite/sanitize them.
7102          */
7103         if (!vstate->speculative)
7104                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7105 }
7106
7107 static int sanitize_err(struct bpf_verifier_env *env,
7108                         const struct bpf_insn *insn, int reason,
7109                         const struct bpf_reg_state *off_reg,
7110                         const struct bpf_reg_state *dst_reg)
7111 {
7112         static const char *err = "pointer arithmetic with it prohibited for !root";
7113         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7114         u32 dst = insn->dst_reg, src = insn->src_reg;
7115
7116         switch (reason) {
7117         case REASON_BOUNDS:
7118                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7119                         off_reg == dst_reg ? dst : src, err);
7120                 break;
7121         case REASON_TYPE:
7122                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7123                         off_reg == dst_reg ? src : dst, err);
7124                 break;
7125         case REASON_PATHS:
7126                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7127                         dst, op, err);
7128                 break;
7129         case REASON_LIMIT:
7130                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7131                         dst, op, err);
7132                 break;
7133         case REASON_STACK:
7134                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7135                         dst, err);
7136                 break;
7137         default:
7138                 verbose(env, "verifier internal error: unknown reason (%d)\n",
7139                         reason);
7140                 break;
7141         }
7142
7143         return -EACCES;
7144 }
7145
7146 /* check that stack access falls within stack limits and that 'reg' doesn't
7147  * have a variable offset.
7148  *
7149  * Variable offset is prohibited for unprivileged mode for simplicity since it
7150  * requires corresponding support in Spectre masking for stack ALU.  See also
7151  * retrieve_ptr_limit().
7152  *
7153  *
7154  * 'off' includes 'reg->off'.
7155  */
7156 static int check_stack_access_for_ptr_arithmetic(
7157                                 struct bpf_verifier_env *env,
7158                                 int regno,
7159                                 const struct bpf_reg_state *reg,
7160                                 int off)
7161 {
7162         if (!tnum_is_const(reg->var_off)) {
7163                 char tn_buf[48];
7164
7165                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7166                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
7167                         regno, tn_buf, off);
7168                 return -EACCES;
7169         }
7170
7171         if (off >= 0 || off < -MAX_BPF_STACK) {
7172                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
7173                         "prohibited for !root; off=%d\n", regno, off);
7174                 return -EACCES;
7175         }
7176
7177         return 0;
7178 }
7179
7180 static int sanitize_check_bounds(struct bpf_verifier_env *env,
7181                                  const struct bpf_insn *insn,
7182                                  const struct bpf_reg_state *dst_reg)
7183 {
7184         u32 dst = insn->dst_reg;
7185
7186         /* For unprivileged we require that resulting offset must be in bounds
7187          * in order to be able to sanitize access later on.
7188          */
7189         if (env->bypass_spec_v1)
7190                 return 0;
7191
7192         switch (dst_reg->type) {
7193         case PTR_TO_STACK:
7194                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
7195                                         dst_reg->off + dst_reg->var_off.value))
7196                         return -EACCES;
7197                 break;
7198         case PTR_TO_MAP_VALUE:
7199                 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
7200                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
7201                                 "prohibited for !root\n", dst);
7202                         return -EACCES;
7203                 }
7204                 break;
7205         default:
7206                 break;
7207         }
7208
7209         return 0;
7210 }
7211
7212 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
7213  * Caller should also handle BPF_MOV case separately.
7214  * If we return -EACCES, caller may want to try again treating pointer as a
7215  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
7216  */
7217 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
7218                                    struct bpf_insn *insn,
7219                                    const struct bpf_reg_state *ptr_reg,
7220                                    const struct bpf_reg_state *off_reg)
7221 {
7222         struct bpf_verifier_state *vstate = env->cur_state;
7223         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7224         struct bpf_reg_state *regs = state->regs, *dst_reg;
7225         bool known = tnum_is_const(off_reg->var_off);
7226         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7227             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7228         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7229             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7230         struct bpf_sanitize_info info = {};
7231         u8 opcode = BPF_OP(insn->code);
7232         u32 dst = insn->dst_reg;
7233         int ret;
7234
7235         dst_reg = &regs[dst];
7236
7237         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7238             smin_val > smax_val || umin_val > umax_val) {
7239                 /* Taint dst register if offset had invalid bounds derived from
7240                  * e.g. dead branches.
7241                  */
7242                 __mark_reg_unknown(env, dst_reg);
7243                 return 0;
7244         }
7245
7246         if (BPF_CLASS(insn->code) != BPF_ALU64) {
7247                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
7248                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7249                         __mark_reg_unknown(env, dst_reg);
7250                         return 0;
7251                 }
7252
7253                 verbose(env,
7254                         "R%d 32-bit pointer arithmetic prohibited\n",
7255                         dst);
7256                 return -EACCES;
7257         }
7258
7259         switch (ptr_reg->type) {
7260         case PTR_TO_MAP_VALUE_OR_NULL:
7261                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7262                         dst, reg_type_str[ptr_reg->type]);
7263                 return -EACCES;
7264         case CONST_PTR_TO_MAP:
7265                 /* smin_val represents the known value */
7266                 if (known && smin_val == 0 && opcode == BPF_ADD)
7267                         break;
7268                 fallthrough;
7269         case PTR_TO_PACKET_END:
7270         case PTR_TO_SOCKET:
7271         case PTR_TO_SOCKET_OR_NULL:
7272         case PTR_TO_SOCK_COMMON:
7273         case PTR_TO_SOCK_COMMON_OR_NULL:
7274         case PTR_TO_TCP_SOCK:
7275         case PTR_TO_TCP_SOCK_OR_NULL:
7276         case PTR_TO_XDP_SOCK:
7277                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7278                         dst, reg_type_str[ptr_reg->type]);
7279                 return -EACCES;
7280         default:
7281                 break;
7282         }
7283
7284         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7285          * The id may be overwritten later if we create a new variable offset.
7286          */
7287         dst_reg->type = ptr_reg->type;
7288         dst_reg->id = ptr_reg->id;
7289
7290         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7291             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7292                 return -EINVAL;
7293
7294         /* pointer types do not carry 32-bit bounds at the moment. */
7295         __mark_reg32_unbounded(dst_reg);
7296
7297         if (sanitize_needed(opcode)) {
7298                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7299                                        &info, false);
7300                 if (ret < 0)
7301                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
7302         }
7303
7304         switch (opcode) {
7305         case BPF_ADD:
7306                 /* We can take a fixed offset as long as it doesn't overflow
7307                  * the s32 'off' field
7308                  */
7309                 if (known && (ptr_reg->off + smin_val ==
7310                               (s64)(s32)(ptr_reg->off + smin_val))) {
7311                         /* pointer += K.  Accumulate it into fixed offset */
7312                         dst_reg->smin_value = smin_ptr;
7313                         dst_reg->smax_value = smax_ptr;
7314                         dst_reg->umin_value = umin_ptr;
7315                         dst_reg->umax_value = umax_ptr;
7316                         dst_reg->var_off = ptr_reg->var_off;
7317                         dst_reg->off = ptr_reg->off + smin_val;
7318                         dst_reg->raw = ptr_reg->raw;
7319                         break;
7320                 }
7321                 /* A new variable offset is created.  Note that off_reg->off
7322                  * == 0, since it's a scalar.
7323                  * dst_reg gets the pointer type and since some positive
7324                  * integer value was added to the pointer, give it a new 'id'
7325                  * if it's a PTR_TO_PACKET.
7326                  * this creates a new 'base' pointer, off_reg (variable) gets
7327                  * added into the variable offset, and we copy the fixed offset
7328                  * from ptr_reg.
7329                  */
7330                 if (signed_add_overflows(smin_ptr, smin_val) ||
7331                     signed_add_overflows(smax_ptr, smax_val)) {
7332                         dst_reg->smin_value = S64_MIN;
7333                         dst_reg->smax_value = S64_MAX;
7334                 } else {
7335                         dst_reg->smin_value = smin_ptr + smin_val;
7336                         dst_reg->smax_value = smax_ptr + smax_val;
7337                 }
7338                 if (umin_ptr + umin_val < umin_ptr ||
7339                     umax_ptr + umax_val < umax_ptr) {
7340                         dst_reg->umin_value = 0;
7341                         dst_reg->umax_value = U64_MAX;
7342                 } else {
7343                         dst_reg->umin_value = umin_ptr + umin_val;
7344                         dst_reg->umax_value = umax_ptr + umax_val;
7345                 }
7346                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7347                 dst_reg->off = ptr_reg->off;
7348                 dst_reg->raw = ptr_reg->raw;
7349                 if (reg_is_pkt_pointer(ptr_reg)) {
7350                         dst_reg->id = ++env->id_gen;
7351                         /* something was added to pkt_ptr, set range to zero */
7352                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7353                 }
7354                 break;
7355         case BPF_SUB:
7356                 if (dst_reg == off_reg) {
7357                         /* scalar -= pointer.  Creates an unknown scalar */
7358                         verbose(env, "R%d tried to subtract pointer from scalar\n",
7359                                 dst);
7360                         return -EACCES;
7361                 }
7362                 /* We don't allow subtraction from FP, because (according to
7363                  * test_verifier.c test "invalid fp arithmetic", JITs might not
7364                  * be able to deal with it.
7365                  */
7366                 if (ptr_reg->type == PTR_TO_STACK) {
7367                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
7368                                 dst);
7369                         return -EACCES;
7370                 }
7371                 if (known && (ptr_reg->off - smin_val ==
7372                               (s64)(s32)(ptr_reg->off - smin_val))) {
7373                         /* pointer -= K.  Subtract it from fixed offset */
7374                         dst_reg->smin_value = smin_ptr;
7375                         dst_reg->smax_value = smax_ptr;
7376                         dst_reg->umin_value = umin_ptr;
7377                         dst_reg->umax_value = umax_ptr;
7378                         dst_reg->var_off = ptr_reg->var_off;
7379                         dst_reg->id = ptr_reg->id;
7380                         dst_reg->off = ptr_reg->off - smin_val;
7381                         dst_reg->raw = ptr_reg->raw;
7382                         break;
7383                 }
7384                 /* A new variable offset is created.  If the subtrahend is known
7385                  * nonnegative, then any reg->range we had before is still good.
7386                  */
7387                 if (signed_sub_overflows(smin_ptr, smax_val) ||
7388                     signed_sub_overflows(smax_ptr, smin_val)) {
7389                         /* Overflow possible, we know nothing */
7390                         dst_reg->smin_value = S64_MIN;
7391                         dst_reg->smax_value = S64_MAX;
7392                 } else {
7393                         dst_reg->smin_value = smin_ptr - smax_val;
7394                         dst_reg->smax_value = smax_ptr - smin_val;
7395                 }
7396                 if (umin_ptr < umax_val) {
7397                         /* Overflow possible, we know nothing */
7398                         dst_reg->umin_value = 0;
7399                         dst_reg->umax_value = U64_MAX;
7400                 } else {
7401                         /* Cannot overflow (as long as bounds are consistent) */
7402                         dst_reg->umin_value = umin_ptr - umax_val;
7403                         dst_reg->umax_value = umax_ptr - umin_val;
7404                 }
7405                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7406                 dst_reg->off = ptr_reg->off;
7407                 dst_reg->raw = ptr_reg->raw;
7408                 if (reg_is_pkt_pointer(ptr_reg)) {
7409                         dst_reg->id = ++env->id_gen;
7410                         /* something was added to pkt_ptr, set range to zero */
7411                         if (smin_val < 0)
7412                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7413                 }
7414                 break;
7415         case BPF_AND:
7416         case BPF_OR:
7417         case BPF_XOR:
7418                 /* bitwise ops on pointers are troublesome, prohibit. */
7419                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7420                         dst, bpf_alu_string[opcode >> 4]);
7421                 return -EACCES;
7422         default:
7423                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
7424                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7425                         dst, bpf_alu_string[opcode >> 4]);
7426                 return -EACCES;
7427         }
7428
7429         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7430                 return -EINVAL;
7431
7432         __update_reg_bounds(dst_reg);
7433         __reg_deduce_bounds(dst_reg);
7434         __reg_bound_offset(dst_reg);
7435
7436         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7437                 return -EACCES;
7438         if (sanitize_needed(opcode)) {
7439                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7440                                        &info, true);
7441                 if (ret < 0)
7442                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
7443         }
7444
7445         return 0;
7446 }
7447
7448 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7449                                  struct bpf_reg_state *src_reg)
7450 {
7451         s32 smin_val = src_reg->s32_min_value;
7452         s32 smax_val = src_reg->s32_max_value;
7453         u32 umin_val = src_reg->u32_min_value;
7454         u32 umax_val = src_reg->u32_max_value;
7455
7456         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7457             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7458                 dst_reg->s32_min_value = S32_MIN;
7459                 dst_reg->s32_max_value = S32_MAX;
7460         } else {
7461                 dst_reg->s32_min_value += smin_val;
7462                 dst_reg->s32_max_value += smax_val;
7463         }
7464         if (dst_reg->u32_min_value + umin_val < umin_val ||
7465             dst_reg->u32_max_value + umax_val < umax_val) {
7466                 dst_reg->u32_min_value = 0;
7467                 dst_reg->u32_max_value = U32_MAX;
7468         } else {
7469                 dst_reg->u32_min_value += umin_val;
7470                 dst_reg->u32_max_value += umax_val;
7471         }
7472 }
7473
7474 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7475                                struct bpf_reg_state *src_reg)
7476 {
7477         s64 smin_val = src_reg->smin_value;
7478         s64 smax_val = src_reg->smax_value;
7479         u64 umin_val = src_reg->umin_value;
7480         u64 umax_val = src_reg->umax_value;
7481
7482         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7483             signed_add_overflows(dst_reg->smax_value, smax_val)) {
7484                 dst_reg->smin_value = S64_MIN;
7485                 dst_reg->smax_value = S64_MAX;
7486         } else {
7487                 dst_reg->smin_value += smin_val;
7488                 dst_reg->smax_value += smax_val;
7489         }
7490         if (dst_reg->umin_value + umin_val < umin_val ||
7491             dst_reg->umax_value + umax_val < umax_val) {
7492                 dst_reg->umin_value = 0;
7493                 dst_reg->umax_value = U64_MAX;
7494         } else {
7495                 dst_reg->umin_value += umin_val;
7496                 dst_reg->umax_value += umax_val;
7497         }
7498 }
7499
7500 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7501                                  struct bpf_reg_state *src_reg)
7502 {
7503         s32 smin_val = src_reg->s32_min_value;
7504         s32 smax_val = src_reg->s32_max_value;
7505         u32 umin_val = src_reg->u32_min_value;
7506         u32 umax_val = src_reg->u32_max_value;
7507
7508         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7509             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7510                 /* Overflow possible, we know nothing */
7511                 dst_reg->s32_min_value = S32_MIN;
7512                 dst_reg->s32_max_value = S32_MAX;
7513         } else {
7514                 dst_reg->s32_min_value -= smax_val;
7515                 dst_reg->s32_max_value -= smin_val;
7516         }
7517         if (dst_reg->u32_min_value < umax_val) {
7518                 /* Overflow possible, we know nothing */
7519                 dst_reg->u32_min_value = 0;
7520                 dst_reg->u32_max_value = U32_MAX;
7521         } else {
7522                 /* Cannot overflow (as long as bounds are consistent) */
7523                 dst_reg->u32_min_value -= umax_val;
7524                 dst_reg->u32_max_value -= umin_val;
7525         }
7526 }
7527
7528 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7529                                struct bpf_reg_state *src_reg)
7530 {
7531         s64 smin_val = src_reg->smin_value;
7532         s64 smax_val = src_reg->smax_value;
7533         u64 umin_val = src_reg->umin_value;
7534         u64 umax_val = src_reg->umax_value;
7535
7536         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7537             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7538                 /* Overflow possible, we know nothing */
7539                 dst_reg->smin_value = S64_MIN;
7540                 dst_reg->smax_value = S64_MAX;
7541         } else {
7542                 dst_reg->smin_value -= smax_val;
7543                 dst_reg->smax_value -= smin_val;
7544         }
7545         if (dst_reg->umin_value < umax_val) {
7546                 /* Overflow possible, we know nothing */
7547                 dst_reg->umin_value = 0;
7548                 dst_reg->umax_value = U64_MAX;
7549         } else {
7550                 /* Cannot overflow (as long as bounds are consistent) */
7551                 dst_reg->umin_value -= umax_val;
7552                 dst_reg->umax_value -= umin_val;
7553         }
7554 }
7555
7556 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7557                                  struct bpf_reg_state *src_reg)
7558 {
7559         s32 smin_val = src_reg->s32_min_value;
7560         u32 umin_val = src_reg->u32_min_value;
7561         u32 umax_val = src_reg->u32_max_value;
7562
7563         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7564                 /* Ain't nobody got time to multiply that sign */
7565                 __mark_reg32_unbounded(dst_reg);
7566                 return;
7567         }
7568         /* Both values are positive, so we can work with unsigned and
7569          * copy the result to signed (unless it exceeds S32_MAX).
7570          */
7571         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7572                 /* Potential overflow, we know nothing */
7573                 __mark_reg32_unbounded(dst_reg);
7574                 return;
7575         }
7576         dst_reg->u32_min_value *= umin_val;
7577         dst_reg->u32_max_value *= umax_val;
7578         if (dst_reg->u32_max_value > S32_MAX) {
7579                 /* Overflow possible, we know nothing */
7580                 dst_reg->s32_min_value = S32_MIN;
7581                 dst_reg->s32_max_value = S32_MAX;
7582         } else {
7583                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7584                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7585         }
7586 }
7587
7588 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7589                                struct bpf_reg_state *src_reg)
7590 {
7591         s64 smin_val = src_reg->smin_value;
7592         u64 umin_val = src_reg->umin_value;
7593         u64 umax_val = src_reg->umax_value;
7594
7595         if (smin_val < 0 || dst_reg->smin_value < 0) {
7596                 /* Ain't nobody got time to multiply that sign */
7597                 __mark_reg64_unbounded(dst_reg);
7598                 return;
7599         }
7600         /* Both values are positive, so we can work with unsigned and
7601          * copy the result to signed (unless it exceeds S64_MAX).
7602          */
7603         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7604                 /* Potential overflow, we know nothing */
7605                 __mark_reg64_unbounded(dst_reg);
7606                 return;
7607         }
7608         dst_reg->umin_value *= umin_val;
7609         dst_reg->umax_value *= umax_val;
7610         if (dst_reg->umax_value > S64_MAX) {
7611                 /* Overflow possible, we know nothing */
7612                 dst_reg->smin_value = S64_MIN;
7613                 dst_reg->smax_value = S64_MAX;
7614         } else {
7615                 dst_reg->smin_value = dst_reg->umin_value;
7616                 dst_reg->smax_value = dst_reg->umax_value;
7617         }
7618 }
7619
7620 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7621                                  struct bpf_reg_state *src_reg)
7622 {
7623         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7624         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7625         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7626         s32 smin_val = src_reg->s32_min_value;
7627         u32 umax_val = src_reg->u32_max_value;
7628
7629         if (src_known && dst_known) {
7630                 __mark_reg32_known(dst_reg, var32_off.value);
7631                 return;
7632         }
7633
7634         /* We get our minimum from the var_off, since that's inherently
7635          * bitwise.  Our maximum is the minimum of the operands' maxima.
7636          */
7637         dst_reg->u32_min_value = var32_off.value;
7638         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7639         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7640                 /* Lose signed bounds when ANDing negative numbers,
7641                  * ain't nobody got time for that.
7642                  */
7643                 dst_reg->s32_min_value = S32_MIN;
7644                 dst_reg->s32_max_value = S32_MAX;
7645         } else {
7646                 /* ANDing two positives gives a positive, so safe to
7647                  * cast result into s64.
7648                  */
7649                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7650                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7651         }
7652 }
7653
7654 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7655                                struct bpf_reg_state *src_reg)
7656 {
7657         bool src_known = tnum_is_const(src_reg->var_off);
7658         bool dst_known = tnum_is_const(dst_reg->var_off);
7659         s64 smin_val = src_reg->smin_value;
7660         u64 umax_val = src_reg->umax_value;
7661
7662         if (src_known && dst_known) {
7663                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7664                 return;
7665         }
7666
7667         /* We get our minimum from the var_off, since that's inherently
7668          * bitwise.  Our maximum is the minimum of the operands' maxima.
7669          */
7670         dst_reg->umin_value = dst_reg->var_off.value;
7671         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7672         if (dst_reg->smin_value < 0 || smin_val < 0) {
7673                 /* Lose signed bounds when ANDing negative numbers,
7674                  * ain't nobody got time for that.
7675                  */
7676                 dst_reg->smin_value = S64_MIN;
7677                 dst_reg->smax_value = S64_MAX;
7678         } else {
7679                 /* ANDing two positives gives a positive, so safe to
7680                  * cast result into s64.
7681                  */
7682                 dst_reg->smin_value = dst_reg->umin_value;
7683                 dst_reg->smax_value = dst_reg->umax_value;
7684         }
7685         /* We may learn something more from the var_off */
7686         __update_reg_bounds(dst_reg);
7687 }
7688
7689 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7690                                 struct bpf_reg_state *src_reg)
7691 {
7692         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7693         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7694         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7695         s32 smin_val = src_reg->s32_min_value;
7696         u32 umin_val = src_reg->u32_min_value;
7697
7698         if (src_known && dst_known) {
7699                 __mark_reg32_known(dst_reg, var32_off.value);
7700                 return;
7701         }
7702
7703         /* We get our maximum from the var_off, and our minimum is the
7704          * maximum of the operands' minima
7705          */
7706         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7707         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7708         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7709                 /* Lose signed bounds when ORing negative numbers,
7710                  * ain't nobody got time for that.
7711                  */
7712                 dst_reg->s32_min_value = S32_MIN;
7713                 dst_reg->s32_max_value = S32_MAX;
7714         } else {
7715                 /* ORing two positives gives a positive, so safe to
7716                  * cast result into s64.
7717                  */
7718                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7719                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7720         }
7721 }
7722
7723 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7724                               struct bpf_reg_state *src_reg)
7725 {
7726         bool src_known = tnum_is_const(src_reg->var_off);
7727         bool dst_known = tnum_is_const(dst_reg->var_off);
7728         s64 smin_val = src_reg->smin_value;
7729         u64 umin_val = src_reg->umin_value;
7730
7731         if (src_known && dst_known) {
7732                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7733                 return;
7734         }
7735
7736         /* We get our maximum from the var_off, and our minimum is the
7737          * maximum of the operands' minima
7738          */
7739         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7740         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7741         if (dst_reg->smin_value < 0 || smin_val < 0) {
7742                 /* Lose signed bounds when ORing negative numbers,
7743                  * ain't nobody got time for that.
7744                  */
7745                 dst_reg->smin_value = S64_MIN;
7746                 dst_reg->smax_value = S64_MAX;
7747         } else {
7748                 /* ORing two positives gives a positive, so safe to
7749                  * cast result into s64.
7750                  */
7751                 dst_reg->smin_value = dst_reg->umin_value;
7752                 dst_reg->smax_value = dst_reg->umax_value;
7753         }
7754         /* We may learn something more from the var_off */
7755         __update_reg_bounds(dst_reg);
7756 }
7757
7758 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7759                                  struct bpf_reg_state *src_reg)
7760 {
7761         bool src_known = tnum_subreg_is_const(src_reg->var_off);
7762         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7763         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7764         s32 smin_val = src_reg->s32_min_value;
7765
7766         if (src_known && dst_known) {
7767                 __mark_reg32_known(dst_reg, var32_off.value);
7768                 return;
7769         }
7770
7771         /* We get both minimum and maximum from the var32_off. */
7772         dst_reg->u32_min_value = var32_off.value;
7773         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7774
7775         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7776                 /* XORing two positive sign numbers gives a positive,
7777                  * so safe to cast u32 result into s32.
7778                  */
7779                 dst_reg->s32_min_value = dst_reg->u32_min_value;
7780                 dst_reg->s32_max_value = dst_reg->u32_max_value;
7781         } else {
7782                 dst_reg->s32_min_value = S32_MIN;
7783                 dst_reg->s32_max_value = S32_MAX;
7784         }
7785 }
7786
7787 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7788                                struct bpf_reg_state *src_reg)
7789 {
7790         bool src_known = tnum_is_const(src_reg->var_off);
7791         bool dst_known = tnum_is_const(dst_reg->var_off);
7792         s64 smin_val = src_reg->smin_value;
7793
7794         if (src_known && dst_known) {
7795                 /* dst_reg->var_off.value has been updated earlier */
7796                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7797                 return;
7798         }
7799
7800         /* We get both minimum and maximum from the var_off. */
7801         dst_reg->umin_value = dst_reg->var_off.value;
7802         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7803
7804         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7805                 /* XORing two positive sign numbers gives a positive,
7806                  * so safe to cast u64 result into s64.
7807                  */
7808                 dst_reg->smin_value = dst_reg->umin_value;
7809                 dst_reg->smax_value = dst_reg->umax_value;
7810         } else {
7811                 dst_reg->smin_value = S64_MIN;
7812                 dst_reg->smax_value = S64_MAX;
7813         }
7814
7815         __update_reg_bounds(dst_reg);
7816 }
7817
7818 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7819                                    u64 umin_val, u64 umax_val)
7820 {
7821         /* We lose all sign bit information (except what we can pick
7822          * up from var_off)
7823          */
7824         dst_reg->s32_min_value = S32_MIN;
7825         dst_reg->s32_max_value = S32_MAX;
7826         /* If we might shift our top bit out, then we know nothing */
7827         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7828                 dst_reg->u32_min_value = 0;
7829                 dst_reg->u32_max_value = U32_MAX;
7830         } else {
7831                 dst_reg->u32_min_value <<= umin_val;
7832                 dst_reg->u32_max_value <<= umax_val;
7833         }
7834 }
7835
7836 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7837                                  struct bpf_reg_state *src_reg)
7838 {
7839         u32 umax_val = src_reg->u32_max_value;
7840         u32 umin_val = src_reg->u32_min_value;
7841         /* u32 alu operation will zext upper bits */
7842         struct tnum subreg = tnum_subreg(dst_reg->var_off);
7843
7844         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7845         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7846         /* Not required but being careful mark reg64 bounds as unknown so
7847          * that we are forced to pick them up from tnum and zext later and
7848          * if some path skips this step we are still safe.
7849          */
7850         __mark_reg64_unbounded(dst_reg);
7851         __update_reg32_bounds(dst_reg);
7852 }
7853
7854 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7855                                    u64 umin_val, u64 umax_val)
7856 {
7857         /* Special case <<32 because it is a common compiler pattern to sign
7858          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7859          * positive we know this shift will also be positive so we can track
7860          * bounds correctly. Otherwise we lose all sign bit information except
7861          * what we can pick up from var_off. Perhaps we can generalize this
7862          * later to shifts of any length.
7863          */
7864         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7865                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7866         else
7867                 dst_reg->smax_value = S64_MAX;
7868
7869         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7870                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7871         else
7872                 dst_reg->smin_value = S64_MIN;
7873
7874         /* If we might shift our top bit out, then we know nothing */
7875         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7876                 dst_reg->umin_value = 0;
7877                 dst_reg->umax_value = U64_MAX;
7878         } else {
7879                 dst_reg->umin_value <<= umin_val;
7880                 dst_reg->umax_value <<= umax_val;
7881         }
7882 }
7883
7884 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7885                                struct bpf_reg_state *src_reg)
7886 {
7887         u64 umax_val = src_reg->umax_value;
7888         u64 umin_val = src_reg->umin_value;
7889
7890         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7891         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7892         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7893
7894         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7895         /* We may learn something more from the var_off */
7896         __update_reg_bounds(dst_reg);
7897 }
7898
7899 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7900                                  struct bpf_reg_state *src_reg)
7901 {
7902         struct tnum subreg = tnum_subreg(dst_reg->var_off);
7903         u32 umax_val = src_reg->u32_max_value;
7904         u32 umin_val = src_reg->u32_min_value;
7905
7906         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7907          * be negative, then either:
7908          * 1) src_reg might be zero, so the sign bit of the result is
7909          *    unknown, so we lose our signed bounds
7910          * 2) it's known negative, thus the unsigned bounds capture the
7911          *    signed bounds
7912          * 3) the signed bounds cross zero, so they tell us nothing
7913          *    about the result
7914          * If the value in dst_reg is known nonnegative, then again the
7915          * unsigned bounds capture the signed bounds.
7916          * Thus, in all cases it suffices to blow away our signed bounds
7917          * and rely on inferring new ones from the unsigned bounds and
7918          * var_off of the result.
7919          */
7920         dst_reg->s32_min_value = S32_MIN;
7921         dst_reg->s32_max_value = S32_MAX;
7922
7923         dst_reg->var_off = tnum_rshift(subreg, umin_val);
7924         dst_reg->u32_min_value >>= umax_val;
7925         dst_reg->u32_max_value >>= umin_val;
7926
7927         __mark_reg64_unbounded(dst_reg);
7928         __update_reg32_bounds(dst_reg);
7929 }
7930
7931 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7932                                struct bpf_reg_state *src_reg)
7933 {
7934         u64 umax_val = src_reg->umax_value;
7935         u64 umin_val = src_reg->umin_value;
7936
7937         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7938          * be negative, then either:
7939          * 1) src_reg might be zero, so the sign bit of the result is
7940          *    unknown, so we lose our signed bounds
7941          * 2) it's known negative, thus the unsigned bounds capture the
7942          *    signed bounds
7943          * 3) the signed bounds cross zero, so they tell us nothing
7944          *    about the result
7945          * If the value in dst_reg is known nonnegative, then again the
7946          * unsigned bounds capture the signed bounds.
7947          * Thus, in all cases it suffices to blow away our signed bounds
7948          * and rely on inferring new ones from the unsigned bounds and
7949          * var_off of the result.
7950          */
7951         dst_reg->smin_value = S64_MIN;
7952         dst_reg->smax_value = S64_MAX;
7953         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7954         dst_reg->umin_value >>= umax_val;
7955         dst_reg->umax_value >>= umin_val;
7956
7957         /* Its not easy to operate on alu32 bounds here because it depends
7958          * on bits being shifted in. Take easy way out and mark unbounded
7959          * so we can recalculate later from tnum.
7960          */
7961         __mark_reg32_unbounded(dst_reg);
7962         __update_reg_bounds(dst_reg);
7963 }
7964
7965 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7966                                   struct bpf_reg_state *src_reg)
7967 {
7968         u64 umin_val = src_reg->u32_min_value;
7969
7970         /* Upon reaching here, src_known is true and
7971          * umax_val is equal to umin_val.
7972          */
7973         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7974         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7975
7976         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7977
7978         /* blow away the dst_reg umin_value/umax_value and rely on
7979          * dst_reg var_off to refine the result.
7980          */
7981         dst_reg->u32_min_value = 0;
7982         dst_reg->u32_max_value = U32_MAX;
7983
7984         __mark_reg64_unbounded(dst_reg);
7985         __update_reg32_bounds(dst_reg);
7986 }
7987
7988 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7989                                 struct bpf_reg_state *src_reg)
7990 {
7991         u64 umin_val = src_reg->umin_value;
7992
7993         /* Upon reaching here, src_known is true and umax_val is equal
7994          * to umin_val.
7995          */
7996         dst_reg->smin_value >>= umin_val;
7997         dst_reg->smax_value >>= umin_val;
7998
7999         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8000
8001         /* blow away the dst_reg umin_value/umax_value and rely on
8002          * dst_reg var_off to refine the result.
8003          */
8004         dst_reg->umin_value = 0;
8005         dst_reg->umax_value = U64_MAX;
8006
8007         /* Its not easy to operate on alu32 bounds here because it depends
8008          * on bits being shifted in from upper 32-bits. Take easy way out
8009          * and mark unbounded so we can recalculate later from tnum.
8010          */
8011         __mark_reg32_unbounded(dst_reg);
8012         __update_reg_bounds(dst_reg);
8013 }
8014
8015 /* WARNING: This function does calculations on 64-bit values, but the actual
8016  * execution may occur on 32-bit values. Therefore, things like bitshifts
8017  * need extra checks in the 32-bit case.
8018  */
8019 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8020                                       struct bpf_insn *insn,
8021                                       struct bpf_reg_state *dst_reg,
8022                                       struct bpf_reg_state src_reg)
8023 {
8024         struct bpf_reg_state *regs = cur_regs(env);
8025         u8 opcode = BPF_OP(insn->code);
8026         bool src_known;
8027         s64 smin_val, smax_val;
8028         u64 umin_val, umax_val;
8029         s32 s32_min_val, s32_max_val;
8030         u32 u32_min_val, u32_max_val;
8031         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8032         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
8033         int ret;
8034
8035         smin_val = src_reg.smin_value;
8036         smax_val = src_reg.smax_value;
8037         umin_val = src_reg.umin_value;
8038         umax_val = src_reg.umax_value;
8039
8040         s32_min_val = src_reg.s32_min_value;
8041         s32_max_val = src_reg.s32_max_value;
8042         u32_min_val = src_reg.u32_min_value;
8043         u32_max_val = src_reg.u32_max_value;
8044
8045         if (alu32) {
8046                 src_known = tnum_subreg_is_const(src_reg.var_off);
8047                 if ((src_known &&
8048                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8049                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8050                         /* Taint dst register if offset had invalid bounds
8051                          * derived from e.g. dead branches.
8052                          */
8053                         __mark_reg_unknown(env, dst_reg);
8054                         return 0;
8055                 }
8056         } else {
8057                 src_known = tnum_is_const(src_reg.var_off);
8058                 if ((src_known &&
8059                      (smin_val != smax_val || umin_val != umax_val)) ||
8060                     smin_val > smax_val || umin_val > umax_val) {
8061                         /* Taint dst register if offset had invalid bounds
8062                          * derived from e.g. dead branches.
8063                          */
8064                         __mark_reg_unknown(env, dst_reg);
8065                         return 0;
8066                 }
8067         }
8068
8069         if (!src_known &&
8070             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8071                 __mark_reg_unknown(env, dst_reg);
8072                 return 0;
8073         }
8074
8075         if (sanitize_needed(opcode)) {
8076                 ret = sanitize_val_alu(env, insn);
8077                 if (ret < 0)
8078                         return sanitize_err(env, insn, ret, NULL, NULL);
8079         }
8080
8081         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8082          * There are two classes of instructions: The first class we track both
8083          * alu32 and alu64 sign/unsigned bounds independently this provides the
8084          * greatest amount of precision when alu operations are mixed with jmp32
8085          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8086          * and BPF_OR. This is possible because these ops have fairly easy to
8087          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8088          * See alu32 verifier tests for examples. The second class of
8089          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8090          * with regards to tracking sign/unsigned bounds because the bits may
8091          * cross subreg boundaries in the alu64 case. When this happens we mark
8092          * the reg unbounded in the subreg bound space and use the resulting
8093          * tnum to calculate an approximation of the sign/unsigned bounds.
8094          */
8095         switch (opcode) {
8096         case BPF_ADD:
8097                 scalar32_min_max_add(dst_reg, &src_reg);
8098                 scalar_min_max_add(dst_reg, &src_reg);
8099                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8100                 break;
8101         case BPF_SUB:
8102                 scalar32_min_max_sub(dst_reg, &src_reg);
8103                 scalar_min_max_sub(dst_reg, &src_reg);
8104                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8105                 break;
8106         case BPF_MUL:
8107                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8108                 scalar32_min_max_mul(dst_reg, &src_reg);
8109                 scalar_min_max_mul(dst_reg, &src_reg);
8110                 break;
8111         case BPF_AND:
8112                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8113                 scalar32_min_max_and(dst_reg, &src_reg);
8114                 scalar_min_max_and(dst_reg, &src_reg);
8115                 break;
8116         case BPF_OR:
8117                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8118                 scalar32_min_max_or(dst_reg, &src_reg);
8119                 scalar_min_max_or(dst_reg, &src_reg);
8120                 break;
8121         case BPF_XOR:
8122                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8123                 scalar32_min_max_xor(dst_reg, &src_reg);
8124                 scalar_min_max_xor(dst_reg, &src_reg);
8125                 break;
8126         case BPF_LSH:
8127                 if (umax_val >= insn_bitness) {
8128                         /* Shifts greater than 31 or 63 are undefined.
8129                          * This includes shifts by a negative number.
8130                          */
8131                         mark_reg_unknown(env, regs, insn->dst_reg);
8132                         break;
8133                 }
8134                 if (alu32)
8135                         scalar32_min_max_lsh(dst_reg, &src_reg);
8136                 else
8137                         scalar_min_max_lsh(dst_reg, &src_reg);
8138                 break;
8139         case BPF_RSH:
8140                 if (umax_val >= insn_bitness) {
8141                         /* Shifts greater than 31 or 63 are undefined.
8142                          * This includes shifts by a negative number.
8143                          */
8144                         mark_reg_unknown(env, regs, insn->dst_reg);
8145                         break;
8146                 }
8147                 if (alu32)
8148                         scalar32_min_max_rsh(dst_reg, &src_reg);
8149                 else
8150                         scalar_min_max_rsh(dst_reg, &src_reg);
8151                 break;
8152         case BPF_ARSH:
8153                 if (umax_val >= insn_bitness) {
8154                         /* Shifts greater than 31 or 63 are undefined.
8155                          * This includes shifts by a negative number.
8156                          */
8157                         mark_reg_unknown(env, regs, insn->dst_reg);
8158                         break;
8159                 }
8160                 if (alu32)
8161                         scalar32_min_max_arsh(dst_reg, &src_reg);
8162                 else
8163                         scalar_min_max_arsh(dst_reg, &src_reg);
8164                 break;
8165         default:
8166                 mark_reg_unknown(env, regs, insn->dst_reg);
8167                 break;
8168         }
8169
8170         /* ALU32 ops are zero extended into 64bit register */
8171         if (alu32)
8172                 zext_32_to_64(dst_reg);
8173
8174         __update_reg_bounds(dst_reg);
8175         __reg_deduce_bounds(dst_reg);
8176         __reg_bound_offset(dst_reg);
8177         return 0;
8178 }
8179
8180 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
8181  * and var_off.
8182  */
8183 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
8184                                    struct bpf_insn *insn)
8185 {
8186         struct bpf_verifier_state *vstate = env->cur_state;
8187         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8188         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
8189         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
8190         u8 opcode = BPF_OP(insn->code);
8191         int err;
8192
8193         dst_reg = &regs[insn->dst_reg];
8194         src_reg = NULL;
8195         if (dst_reg->type != SCALAR_VALUE)
8196                 ptr_reg = dst_reg;
8197         else
8198                 /* Make sure ID is cleared otherwise dst_reg min/max could be
8199                  * incorrectly propagated into other registers by find_equal_scalars()
8200                  */
8201                 dst_reg->id = 0;
8202         if (BPF_SRC(insn->code) == BPF_X) {
8203                 src_reg = &regs[insn->src_reg];
8204                 if (src_reg->type != SCALAR_VALUE) {
8205                         if (dst_reg->type != SCALAR_VALUE) {
8206                                 /* Combining two pointers by any ALU op yields
8207                                  * an arbitrary scalar. Disallow all math except
8208                                  * pointer subtraction
8209                                  */
8210                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8211                                         mark_reg_unknown(env, regs, insn->dst_reg);
8212                                         return 0;
8213                                 }
8214                                 verbose(env, "R%d pointer %s pointer prohibited\n",
8215                                         insn->dst_reg,
8216                                         bpf_alu_string[opcode >> 4]);
8217                                 return -EACCES;
8218                         } else {
8219                                 /* scalar += pointer
8220                                  * This is legal, but we have to reverse our
8221                                  * src/dest handling in computing the range
8222                                  */
8223                                 err = mark_chain_precision(env, insn->dst_reg);
8224                                 if (err)
8225                                         return err;
8226                                 return adjust_ptr_min_max_vals(env, insn,
8227                                                                src_reg, dst_reg);
8228                         }
8229                 } else if (ptr_reg) {
8230                         /* pointer += scalar */
8231                         err = mark_chain_precision(env, insn->src_reg);
8232                         if (err)
8233                                 return err;
8234                         return adjust_ptr_min_max_vals(env, insn,
8235                                                        dst_reg, src_reg);
8236                 }
8237         } else {
8238                 /* Pretend the src is a reg with a known value, since we only
8239                  * need to be able to read from this state.
8240                  */
8241                 off_reg.type = SCALAR_VALUE;
8242                 __mark_reg_known(&off_reg, insn->imm);
8243                 src_reg = &off_reg;
8244                 if (ptr_reg) /* pointer += K */
8245                         return adjust_ptr_min_max_vals(env, insn,
8246                                                        ptr_reg, src_reg);
8247         }
8248
8249         /* Got here implies adding two SCALAR_VALUEs */
8250         if (WARN_ON_ONCE(ptr_reg)) {
8251                 print_verifier_state(env, state);
8252                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
8253                 return -EINVAL;
8254         }
8255         if (WARN_ON(!src_reg)) {
8256                 print_verifier_state(env, state);
8257                 verbose(env, "verifier internal error: no src_reg\n");
8258                 return -EINVAL;
8259         }
8260         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8261 }
8262
8263 /* check validity of 32-bit and 64-bit arithmetic operations */
8264 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8265 {
8266         struct bpf_reg_state *regs = cur_regs(env);
8267         u8 opcode = BPF_OP(insn->code);
8268         int err;
8269
8270         if (opcode == BPF_END || opcode == BPF_NEG) {
8271                 if (opcode == BPF_NEG) {
8272                         if (BPF_SRC(insn->code) != 0 ||
8273                             insn->src_reg != BPF_REG_0 ||
8274                             insn->off != 0 || insn->imm != 0) {
8275                                 verbose(env, "BPF_NEG uses reserved fields\n");
8276                                 return -EINVAL;
8277                         }
8278                 } else {
8279                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8280                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8281                             BPF_CLASS(insn->code) == BPF_ALU64) {
8282                                 verbose(env, "BPF_END uses reserved fields\n");
8283                                 return -EINVAL;
8284                         }
8285                 }
8286
8287                 /* check src operand */
8288                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8289                 if (err)
8290                         return err;
8291
8292                 if (is_pointer_value(env, insn->dst_reg)) {
8293                         verbose(env, "R%d pointer arithmetic prohibited\n",
8294                                 insn->dst_reg);
8295                         return -EACCES;
8296                 }
8297
8298                 /* check dest operand */
8299                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
8300                 if (err)
8301                         return err;
8302
8303         } else if (opcode == BPF_MOV) {
8304
8305                 if (BPF_SRC(insn->code) == BPF_X) {
8306                         if (insn->imm != 0 || insn->off != 0) {
8307                                 verbose(env, "BPF_MOV uses reserved fields\n");
8308                                 return -EINVAL;
8309                         }
8310
8311                         /* check src operand */
8312                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
8313                         if (err)
8314                                 return err;
8315                 } else {
8316                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8317                                 verbose(env, "BPF_MOV uses reserved fields\n");
8318                                 return -EINVAL;
8319                         }
8320                 }
8321
8322                 /* check dest operand, mark as required later */
8323                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8324                 if (err)
8325                         return err;
8326
8327                 if (BPF_SRC(insn->code) == BPF_X) {
8328                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
8329                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8330
8331                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
8332                                 /* case: R1 = R2
8333                                  * copy register state to dest reg
8334                                  */
8335                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8336                                         /* Assign src and dst registers the same ID
8337                                          * that will be used by find_equal_scalars()
8338                                          * to propagate min/max range.
8339                                          */
8340                                         src_reg->id = ++env->id_gen;
8341                                 *dst_reg = *src_reg;
8342                                 dst_reg->live |= REG_LIVE_WRITTEN;
8343                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
8344                         } else {
8345                                 /* R1 = (u32) R2 */
8346                                 if (is_pointer_value(env, insn->src_reg)) {
8347                                         verbose(env,
8348                                                 "R%d partial copy of pointer\n",
8349                                                 insn->src_reg);
8350                                         return -EACCES;
8351                                 } else if (src_reg->type == SCALAR_VALUE) {
8352                                         *dst_reg = *src_reg;
8353                                         /* Make sure ID is cleared otherwise
8354                                          * dst_reg min/max could be incorrectly
8355                                          * propagated into src_reg by find_equal_scalars()
8356                                          */
8357                                         dst_reg->id = 0;
8358                                         dst_reg->live |= REG_LIVE_WRITTEN;
8359                                         dst_reg->subreg_def = env->insn_idx + 1;
8360                                 } else {
8361                                         mark_reg_unknown(env, regs,
8362                                                          insn->dst_reg);
8363                                 }
8364                                 zext_32_to_64(dst_reg);
8365                         }
8366                 } else {
8367                         /* case: R = imm
8368                          * remember the value we stored into this reg
8369                          */
8370                         /* clear any state __mark_reg_known doesn't set */
8371                         mark_reg_unknown(env, regs, insn->dst_reg);
8372                         regs[insn->dst_reg].type = SCALAR_VALUE;
8373                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
8374                                 __mark_reg_known(regs + insn->dst_reg,
8375                                                  insn->imm);
8376                         } else {
8377                                 __mark_reg_known(regs + insn->dst_reg,
8378                                                  (u32)insn->imm);
8379                         }
8380                 }
8381
8382         } else if (opcode > BPF_END) {
8383                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8384                 return -EINVAL;
8385
8386         } else {        /* all other ALU ops: and, sub, xor, add, ... */
8387
8388                 if (BPF_SRC(insn->code) == BPF_X) {
8389                         if (insn->imm != 0 || insn->off != 0) {
8390                                 verbose(env, "BPF_ALU uses reserved fields\n");
8391                                 return -EINVAL;
8392                         }
8393                         /* check src1 operand */
8394                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
8395                         if (err)
8396                                 return err;
8397                 } else {
8398                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8399                                 verbose(env, "BPF_ALU uses reserved fields\n");
8400                                 return -EINVAL;
8401                         }
8402                 }
8403
8404                 /* check src2 operand */
8405                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8406                 if (err)
8407                         return err;
8408
8409                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8410                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8411                         verbose(env, "div by zero\n");
8412                         return -EINVAL;
8413                 }
8414
8415                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8416                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8417                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8418
8419                         if (insn->imm < 0 || insn->imm >= size) {
8420                                 verbose(env, "invalid shift %d\n", insn->imm);
8421                                 return -EINVAL;
8422                         }
8423                 }
8424
8425                 /* check dest operand */
8426                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8427                 if (err)
8428                         return err;
8429
8430                 return adjust_reg_min_max_vals(env, insn);
8431         }
8432
8433         return 0;
8434 }
8435
8436 static void __find_good_pkt_pointers(struct bpf_func_state *state,
8437                                      struct bpf_reg_state *dst_reg,
8438                                      enum bpf_reg_type type, int new_range)
8439 {
8440         struct bpf_reg_state *reg;
8441         int i;
8442
8443         for (i = 0; i < MAX_BPF_REG; i++) {
8444                 reg = &state->regs[i];
8445                 if (reg->type == type && reg->id == dst_reg->id)
8446                         /* keep the maximum range already checked */
8447                         reg->range = max(reg->range, new_range);
8448         }
8449
8450         bpf_for_each_spilled_reg(i, state, reg) {
8451                 if (!reg)
8452                         continue;
8453                 if (reg->type == type && reg->id == dst_reg->id)
8454                         reg->range = max(reg->range, new_range);
8455         }
8456 }
8457
8458 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8459                                    struct bpf_reg_state *dst_reg,
8460                                    enum bpf_reg_type type,
8461                                    bool range_right_open)
8462 {
8463         int new_range, i;
8464
8465         if (dst_reg->off < 0 ||
8466             (dst_reg->off == 0 && range_right_open))
8467                 /* This doesn't give us any range */
8468                 return;
8469
8470         if (dst_reg->umax_value > MAX_PACKET_OFF ||
8471             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8472                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
8473                  * than pkt_end, but that's because it's also less than pkt.
8474                  */
8475                 return;
8476
8477         new_range = dst_reg->off;
8478         if (range_right_open)
8479                 new_range++;
8480
8481         /* Examples for register markings:
8482          *
8483          * pkt_data in dst register:
8484          *
8485          *   r2 = r3;
8486          *   r2 += 8;
8487          *   if (r2 > pkt_end) goto <handle exception>
8488          *   <access okay>
8489          *
8490          *   r2 = r3;
8491          *   r2 += 8;
8492          *   if (r2 < pkt_end) goto <access okay>
8493          *   <handle exception>
8494          *
8495          *   Where:
8496          *     r2 == dst_reg, pkt_end == src_reg
8497          *     r2=pkt(id=n,off=8,r=0)
8498          *     r3=pkt(id=n,off=0,r=0)
8499          *
8500          * pkt_data in src register:
8501          *
8502          *   r2 = r3;
8503          *   r2 += 8;
8504          *   if (pkt_end >= r2) goto <access okay>
8505          *   <handle exception>
8506          *
8507          *   r2 = r3;
8508          *   r2 += 8;
8509          *   if (pkt_end <= r2) goto <handle exception>
8510          *   <access okay>
8511          *
8512          *   Where:
8513          *     pkt_end == dst_reg, r2 == src_reg
8514          *     r2=pkt(id=n,off=8,r=0)
8515          *     r3=pkt(id=n,off=0,r=0)
8516          *
8517          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8518          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8519          * and [r3, r3 + 8-1) respectively is safe to access depending on
8520          * the check.
8521          */
8522
8523         /* If our ids match, then we must have the same max_value.  And we
8524          * don't care about the other reg's fixed offset, since if it's too big
8525          * the range won't allow anything.
8526          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8527          */
8528         for (i = 0; i <= vstate->curframe; i++)
8529                 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8530                                          new_range);
8531 }
8532
8533 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8534 {
8535         struct tnum subreg = tnum_subreg(reg->var_off);
8536         s32 sval = (s32)val;
8537
8538         switch (opcode) {
8539         case BPF_JEQ:
8540                 if (tnum_is_const(subreg))
8541                         return !!tnum_equals_const(subreg, val);
8542                 break;
8543         case BPF_JNE:
8544                 if (tnum_is_const(subreg))
8545                         return !tnum_equals_const(subreg, val);
8546                 break;
8547         case BPF_JSET:
8548                 if ((~subreg.mask & subreg.value) & val)
8549                         return 1;
8550                 if (!((subreg.mask | subreg.value) & val))
8551                         return 0;
8552                 break;
8553         case BPF_JGT:
8554                 if (reg->u32_min_value > val)
8555                         return 1;
8556                 else if (reg->u32_max_value <= val)
8557                         return 0;
8558                 break;
8559         case BPF_JSGT:
8560                 if (reg->s32_min_value > sval)
8561                         return 1;
8562                 else if (reg->s32_max_value <= sval)
8563                         return 0;
8564                 break;
8565         case BPF_JLT:
8566                 if (reg->u32_max_value < val)
8567                         return 1;
8568                 else if (reg->u32_min_value >= val)
8569                         return 0;
8570                 break;
8571         case BPF_JSLT:
8572                 if (reg->s32_max_value < sval)
8573                         return 1;
8574                 else if (reg->s32_min_value >= sval)
8575                         return 0;
8576                 break;
8577         case BPF_JGE:
8578                 if (reg->u32_min_value >= val)
8579                         return 1;
8580                 else if (reg->u32_max_value < val)
8581                         return 0;
8582                 break;
8583         case BPF_JSGE:
8584                 if (reg->s32_min_value >= sval)
8585                         return 1;
8586                 else if (reg->s32_max_value < sval)
8587                         return 0;
8588                 break;
8589         case BPF_JLE:
8590                 if (reg->u32_max_value <= val)
8591                         return 1;
8592                 else if (reg->u32_min_value > val)
8593                         return 0;
8594                 break;
8595         case BPF_JSLE:
8596                 if (reg->s32_max_value <= sval)
8597                         return 1;
8598                 else if (reg->s32_min_value > sval)
8599                         return 0;
8600                 break;
8601         }
8602
8603         return -1;
8604 }
8605
8606
8607 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8608 {
8609         s64 sval = (s64)val;
8610
8611         switch (opcode) {
8612         case BPF_JEQ:
8613                 if (tnum_is_const(reg->var_off))
8614                         return !!tnum_equals_const(reg->var_off, val);
8615                 break;
8616         case BPF_JNE:
8617                 if (tnum_is_const(reg->var_off))
8618                         return !tnum_equals_const(reg->var_off, val);
8619                 break;
8620         case BPF_JSET:
8621                 if ((~reg->var_off.mask & reg->var_off.value) & val)
8622                         return 1;
8623                 if (!((reg->var_off.mask | reg->var_off.value) & val))
8624                         return 0;
8625                 break;
8626         case BPF_JGT:
8627                 if (reg->umin_value > val)
8628                         return 1;
8629                 else if (reg->umax_value <= val)
8630                         return 0;
8631                 break;
8632         case BPF_JSGT:
8633                 if (reg->smin_value > sval)
8634                         return 1;
8635                 else if (reg->smax_value <= sval)
8636                         return 0;
8637                 break;
8638         case BPF_JLT:
8639                 if (reg->umax_value < val)
8640                         return 1;
8641                 else if (reg->umin_value >= val)
8642                         return 0;
8643                 break;
8644         case BPF_JSLT:
8645                 if (reg->smax_value < sval)
8646                         return 1;
8647                 else if (reg->smin_value >= sval)
8648                         return 0;
8649                 break;
8650         case BPF_JGE:
8651                 if (reg->umin_value >= val)
8652                         return 1;
8653                 else if (reg->umax_value < val)
8654                         return 0;
8655                 break;
8656         case BPF_JSGE:
8657                 if (reg->smin_value >= sval)
8658                         return 1;
8659                 else if (reg->smax_value < sval)
8660                         return 0;
8661                 break;
8662         case BPF_JLE:
8663                 if (reg->umax_value <= val)
8664                         return 1;
8665                 else if (reg->umin_value > val)
8666                         return 0;
8667                 break;
8668         case BPF_JSLE:
8669                 if (reg->smax_value <= sval)
8670                         return 1;
8671                 else if (reg->smin_value > sval)
8672                         return 0;
8673                 break;
8674         }
8675
8676         return -1;
8677 }
8678
8679 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8680  * and return:
8681  *  1 - branch will be taken and "goto target" will be executed
8682  *  0 - branch will not be taken and fall-through to next insn
8683  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8684  *      range [0,10]
8685  */
8686 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8687                            bool is_jmp32)
8688 {
8689         if (__is_pointer_value(false, reg)) {
8690                 if (!reg_type_not_null(reg->type))
8691                         return -1;
8692
8693                 /* If pointer is valid tests against zero will fail so we can
8694                  * use this to direct branch taken.
8695                  */
8696                 if (val != 0)
8697                         return -1;
8698
8699                 switch (opcode) {
8700                 case BPF_JEQ:
8701                         return 0;
8702                 case BPF_JNE:
8703                         return 1;
8704                 default:
8705                         return -1;
8706                 }
8707         }
8708
8709         if (is_jmp32)
8710                 return is_branch32_taken(reg, val, opcode);
8711         return is_branch64_taken(reg, val, opcode);
8712 }
8713
8714 static int flip_opcode(u32 opcode)
8715 {
8716         /* How can we transform "a <op> b" into "b <op> a"? */
8717         static const u8 opcode_flip[16] = {
8718                 /* these stay the same */
8719                 [BPF_JEQ  >> 4] = BPF_JEQ,
8720                 [BPF_JNE  >> 4] = BPF_JNE,
8721                 [BPF_JSET >> 4] = BPF_JSET,
8722                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8723                 [BPF_JGE  >> 4] = BPF_JLE,
8724                 [BPF_JGT  >> 4] = BPF_JLT,
8725                 [BPF_JLE  >> 4] = BPF_JGE,
8726                 [BPF_JLT  >> 4] = BPF_JGT,
8727                 [BPF_JSGE >> 4] = BPF_JSLE,
8728                 [BPF_JSGT >> 4] = BPF_JSLT,
8729                 [BPF_JSLE >> 4] = BPF_JSGE,
8730                 [BPF_JSLT >> 4] = BPF_JSGT
8731         };
8732         return opcode_flip[opcode >> 4];
8733 }
8734
8735 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8736                                    struct bpf_reg_state *src_reg,
8737                                    u8 opcode)
8738 {
8739         struct bpf_reg_state *pkt;
8740
8741         if (src_reg->type == PTR_TO_PACKET_END) {
8742                 pkt = dst_reg;
8743         } else if (dst_reg->type == PTR_TO_PACKET_END) {
8744                 pkt = src_reg;
8745                 opcode = flip_opcode(opcode);
8746         } else {
8747                 return -1;
8748         }
8749
8750         if (pkt->range >= 0)
8751                 return -1;
8752
8753         switch (opcode) {
8754         case BPF_JLE:
8755                 /* pkt <= pkt_end */
8756                 fallthrough;
8757         case BPF_JGT:
8758                 /* pkt > pkt_end */
8759                 if (pkt->range == BEYOND_PKT_END)
8760                         /* pkt has at last one extra byte beyond pkt_end */
8761                         return opcode == BPF_JGT;
8762                 break;
8763         case BPF_JLT:
8764                 /* pkt < pkt_end */
8765                 fallthrough;
8766         case BPF_JGE:
8767                 /* pkt >= pkt_end */
8768                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8769                         return opcode == BPF_JGE;
8770                 break;
8771         }
8772         return -1;
8773 }
8774
8775 /* Adjusts the register min/max values in the case that the dst_reg is the
8776  * variable register that we are working on, and src_reg is a constant or we're
8777  * simply doing a BPF_K check.
8778  * In JEQ/JNE cases we also adjust the var_off values.
8779  */
8780 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8781                             struct bpf_reg_state *false_reg,
8782                             u64 val, u32 val32,
8783                             u8 opcode, bool is_jmp32)
8784 {
8785         struct tnum false_32off = tnum_subreg(false_reg->var_off);
8786         struct tnum false_64off = false_reg->var_off;
8787         struct tnum true_32off = tnum_subreg(true_reg->var_off);
8788         struct tnum true_64off = true_reg->var_off;
8789         s64 sval = (s64)val;
8790         s32 sval32 = (s32)val32;
8791
8792         /* If the dst_reg is a pointer, we can't learn anything about its
8793          * variable offset from the compare (unless src_reg were a pointer into
8794          * the same object, but we don't bother with that.
8795          * Since false_reg and true_reg have the same type by construction, we
8796          * only need to check one of them for pointerness.
8797          */
8798         if (__is_pointer_value(false, false_reg))
8799                 return;
8800
8801         switch (opcode) {
8802         case BPF_JEQ:
8803         case BPF_JNE:
8804         {
8805                 struct bpf_reg_state *reg =
8806                         opcode == BPF_JEQ ? true_reg : false_reg;
8807
8808                 /* JEQ/JNE comparison doesn't change the register equivalence.
8809                  * r1 = r2;
8810                  * if (r1 == 42) goto label;
8811                  * ...
8812                  * label: // here both r1 and r2 are known to be 42.
8813                  *
8814                  * Hence when marking register as known preserve it's ID.
8815                  */
8816                 if (is_jmp32)
8817                         __mark_reg32_known(reg, val32);
8818                 else
8819                         ___mark_reg_known(reg, val);
8820                 break;
8821         }
8822         case BPF_JSET:
8823                 if (is_jmp32) {
8824                         false_32off = tnum_and(false_32off, tnum_const(~val32));
8825                         if (is_power_of_2(val32))
8826                                 true_32off = tnum_or(true_32off,
8827                                                      tnum_const(val32));
8828                 } else {
8829                         false_64off = tnum_and(false_64off, tnum_const(~val));
8830                         if (is_power_of_2(val))
8831                                 true_64off = tnum_or(true_64off,
8832                                                      tnum_const(val));
8833                 }
8834                 break;
8835         case BPF_JGE:
8836         case BPF_JGT:
8837         {
8838                 if (is_jmp32) {
8839                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8840                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8841
8842                         false_reg->u32_max_value = min(false_reg->u32_max_value,
8843                                                        false_umax);
8844                         true_reg->u32_min_value = max(true_reg->u32_min_value,
8845                                                       true_umin);
8846                 } else {
8847                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8848                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8849
8850                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
8851                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
8852                 }
8853                 break;
8854         }
8855         case BPF_JSGE:
8856         case BPF_JSGT:
8857         {
8858                 if (is_jmp32) {
8859                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8860                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8861
8862                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8863                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8864                 } else {
8865                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8866                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8867
8868                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
8869                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
8870                 }
8871                 break;
8872         }
8873         case BPF_JLE:
8874         case BPF_JLT:
8875         {
8876                 if (is_jmp32) {
8877                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8878                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8879
8880                         false_reg->u32_min_value = max(false_reg->u32_min_value,
8881                                                        false_umin);
8882                         true_reg->u32_max_value = min(true_reg->u32_max_value,
8883                                                       true_umax);
8884                 } else {
8885                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8886                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8887
8888                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
8889                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
8890                 }
8891                 break;
8892         }
8893         case BPF_JSLE:
8894         case BPF_JSLT:
8895         {
8896                 if (is_jmp32) {
8897                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8898                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8899
8900                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8901                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8902                 } else {
8903                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8904                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8905
8906                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
8907                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
8908                 }
8909                 break;
8910         }
8911         default:
8912                 return;
8913         }
8914
8915         if (is_jmp32) {
8916                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8917                                              tnum_subreg(false_32off));
8918                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8919                                             tnum_subreg(true_32off));
8920                 __reg_combine_32_into_64(false_reg);
8921                 __reg_combine_32_into_64(true_reg);
8922         } else {
8923                 false_reg->var_off = false_64off;
8924                 true_reg->var_off = true_64off;
8925                 __reg_combine_64_into_32(false_reg);
8926                 __reg_combine_64_into_32(true_reg);
8927         }
8928 }
8929
8930 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8931  * the variable reg.
8932  */
8933 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8934                                 struct bpf_reg_state *false_reg,
8935                                 u64 val, u32 val32,
8936                                 u8 opcode, bool is_jmp32)
8937 {
8938         opcode = flip_opcode(opcode);
8939         /* This uses zero as "not present in table"; luckily the zero opcode,
8940          * BPF_JA, can't get here.
8941          */
8942         if (opcode)
8943                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8944 }
8945
8946 /* Regs are known to be equal, so intersect their min/max/var_off */
8947 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8948                                   struct bpf_reg_state *dst_reg)
8949 {
8950         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8951                                                         dst_reg->umin_value);
8952         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8953                                                         dst_reg->umax_value);
8954         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8955                                                         dst_reg->smin_value);
8956         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8957                                                         dst_reg->smax_value);
8958         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8959                                                              dst_reg->var_off);
8960         /* We might have learned new bounds from the var_off. */
8961         __update_reg_bounds(src_reg);
8962         __update_reg_bounds(dst_reg);
8963         /* We might have learned something about the sign bit. */
8964         __reg_deduce_bounds(src_reg);
8965         __reg_deduce_bounds(dst_reg);
8966         /* We might have learned some bits from the bounds. */
8967         __reg_bound_offset(src_reg);
8968         __reg_bound_offset(dst_reg);
8969         /* Intersecting with the old var_off might have improved our bounds
8970          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8971          * then new var_off is (0; 0x7f...fc) which improves our umax.
8972          */
8973         __update_reg_bounds(src_reg);
8974         __update_reg_bounds(dst_reg);
8975 }
8976
8977 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8978                                 struct bpf_reg_state *true_dst,
8979                                 struct bpf_reg_state *false_src,
8980                                 struct bpf_reg_state *false_dst,
8981                                 u8 opcode)
8982 {
8983         switch (opcode) {
8984         case BPF_JEQ:
8985                 __reg_combine_min_max(true_src, true_dst);
8986                 break;
8987         case BPF_JNE:
8988                 __reg_combine_min_max(false_src, false_dst);
8989                 break;
8990         }
8991 }
8992
8993 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8994                                  struct bpf_reg_state *reg, u32 id,
8995                                  bool is_null)
8996 {
8997         if (reg_type_may_be_null(reg->type) && reg->id == id &&
8998             !WARN_ON_ONCE(!reg->id)) {
8999                 /* Old offset (both fixed and variable parts) should
9000                  * have been known-zero, because we don't allow pointer
9001                  * arithmetic on pointers that might be NULL.
9002                  */
9003                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9004                                  !tnum_equals_const(reg->var_off, 0) ||
9005                                  reg->off)) {
9006                         __mark_reg_known_zero(reg);
9007                         reg->off = 0;
9008                 }
9009                 if (is_null) {
9010                         reg->type = SCALAR_VALUE;
9011                         /* We don't need id and ref_obj_id from this point
9012                          * onwards anymore, thus we should better reset it,
9013                          * so that state pruning has chances to take effect.
9014                          */
9015                         reg->id = 0;
9016                         reg->ref_obj_id = 0;
9017
9018                         return;
9019                 }
9020
9021                 mark_ptr_not_null_reg(reg);
9022
9023                 if (!reg_may_point_to_spin_lock(reg)) {
9024                         /* For not-NULL ptr, reg->ref_obj_id will be reset
9025                          * in release_reg_references().
9026                          *
9027                          * reg->id is still used by spin_lock ptr. Other
9028                          * than spin_lock ptr type, reg->id can be reset.
9029                          */
9030                         reg->id = 0;
9031                 }
9032         }
9033 }
9034
9035 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
9036                                     bool is_null)
9037 {
9038         struct bpf_reg_state *reg;
9039         int i;
9040
9041         for (i = 0; i < MAX_BPF_REG; i++)
9042                 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
9043
9044         bpf_for_each_spilled_reg(i, state, reg) {
9045                 if (!reg)
9046                         continue;
9047                 mark_ptr_or_null_reg(state, reg, id, is_null);
9048         }
9049 }
9050
9051 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9052  * be folded together at some point.
9053  */
9054 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9055                                   bool is_null)
9056 {
9057         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9058         struct bpf_reg_state *regs = state->regs;
9059         u32 ref_obj_id = regs[regno].ref_obj_id;
9060         u32 id = regs[regno].id;
9061         int i;
9062
9063         if (ref_obj_id && ref_obj_id == id && is_null)
9064                 /* regs[regno] is in the " == NULL" branch.
9065                  * No one could have freed the reference state before
9066                  * doing the NULL check.
9067                  */
9068                 WARN_ON_ONCE(release_reference_state(state, id));
9069
9070         for (i = 0; i <= vstate->curframe; i++)
9071                 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
9072 }
9073
9074 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9075                                    struct bpf_reg_state *dst_reg,
9076                                    struct bpf_reg_state *src_reg,
9077                                    struct bpf_verifier_state *this_branch,
9078                                    struct bpf_verifier_state *other_branch)
9079 {
9080         if (BPF_SRC(insn->code) != BPF_X)
9081                 return false;
9082
9083         /* Pointers are always 64-bit. */
9084         if (BPF_CLASS(insn->code) == BPF_JMP32)
9085                 return false;
9086
9087         switch (BPF_OP(insn->code)) {
9088         case BPF_JGT:
9089                 if ((dst_reg->type == PTR_TO_PACKET &&
9090                      src_reg->type == PTR_TO_PACKET_END) ||
9091                     (dst_reg->type == PTR_TO_PACKET_META &&
9092                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9093                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9094                         find_good_pkt_pointers(this_branch, dst_reg,
9095                                                dst_reg->type, false);
9096                         mark_pkt_end(other_branch, insn->dst_reg, true);
9097                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9098                             src_reg->type == PTR_TO_PACKET) ||
9099                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9100                             src_reg->type == PTR_TO_PACKET_META)) {
9101                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
9102                         find_good_pkt_pointers(other_branch, src_reg,
9103                                                src_reg->type, true);
9104                         mark_pkt_end(this_branch, insn->src_reg, false);
9105                 } else {
9106                         return false;
9107                 }
9108                 break;
9109         case BPF_JLT:
9110                 if ((dst_reg->type == PTR_TO_PACKET &&
9111                      src_reg->type == PTR_TO_PACKET_END) ||
9112                     (dst_reg->type == PTR_TO_PACKET_META &&
9113                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9114                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9115                         find_good_pkt_pointers(other_branch, dst_reg,
9116                                                dst_reg->type, true);
9117                         mark_pkt_end(this_branch, insn->dst_reg, false);
9118                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9119                             src_reg->type == PTR_TO_PACKET) ||
9120                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9121                             src_reg->type == PTR_TO_PACKET_META)) {
9122                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
9123                         find_good_pkt_pointers(this_branch, src_reg,
9124                                                src_reg->type, false);
9125                         mark_pkt_end(other_branch, insn->src_reg, true);
9126                 } else {
9127                         return false;
9128                 }
9129                 break;
9130         case BPF_JGE:
9131                 if ((dst_reg->type == PTR_TO_PACKET &&
9132                      src_reg->type == PTR_TO_PACKET_END) ||
9133                     (dst_reg->type == PTR_TO_PACKET_META &&
9134                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9135                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9136                         find_good_pkt_pointers(this_branch, dst_reg,
9137                                                dst_reg->type, true);
9138                         mark_pkt_end(other_branch, insn->dst_reg, false);
9139                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9140                             src_reg->type == PTR_TO_PACKET) ||
9141                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9142                             src_reg->type == PTR_TO_PACKET_META)) {
9143                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9144                         find_good_pkt_pointers(other_branch, src_reg,
9145                                                src_reg->type, false);
9146                         mark_pkt_end(this_branch, insn->src_reg, true);
9147                 } else {
9148                         return false;
9149                 }
9150                 break;
9151         case BPF_JLE:
9152                 if ((dst_reg->type == PTR_TO_PACKET &&
9153                      src_reg->type == PTR_TO_PACKET_END) ||
9154                     (dst_reg->type == PTR_TO_PACKET_META &&
9155                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9156                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9157                         find_good_pkt_pointers(other_branch, dst_reg,
9158                                                dst_reg->type, false);
9159                         mark_pkt_end(this_branch, insn->dst_reg, true);
9160                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9161                             src_reg->type == PTR_TO_PACKET) ||
9162                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9163                             src_reg->type == PTR_TO_PACKET_META)) {
9164                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9165                         find_good_pkt_pointers(this_branch, src_reg,
9166                                                src_reg->type, true);
9167                         mark_pkt_end(other_branch, insn->src_reg, false);
9168                 } else {
9169                         return false;
9170                 }
9171                 break;
9172         default:
9173                 return false;
9174         }
9175
9176         return true;
9177 }
9178
9179 static void find_equal_scalars(struct bpf_verifier_state *vstate,
9180                                struct bpf_reg_state *known_reg)
9181 {
9182         struct bpf_func_state *state;
9183         struct bpf_reg_state *reg;
9184         int i, j;
9185
9186         for (i = 0; i <= vstate->curframe; i++) {
9187                 state = vstate->frame[i];
9188                 for (j = 0; j < MAX_BPF_REG; j++) {
9189                         reg = &state->regs[j];
9190                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9191                                 *reg = *known_reg;
9192                 }
9193
9194                 bpf_for_each_spilled_reg(j, state, reg) {
9195                         if (!reg)
9196                                 continue;
9197                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9198                                 *reg = *known_reg;
9199                 }
9200         }
9201 }
9202
9203 static int check_cond_jmp_op(struct bpf_verifier_env *env,
9204                              struct bpf_insn *insn, int *insn_idx)
9205 {
9206         struct bpf_verifier_state *this_branch = env->cur_state;
9207         struct bpf_verifier_state *other_branch;
9208         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
9209         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
9210         u8 opcode = BPF_OP(insn->code);
9211         bool is_jmp32;
9212         int pred = -1;
9213         int err;
9214
9215         /* Only conditional jumps are expected to reach here. */
9216         if (opcode == BPF_JA || opcode > BPF_JSLE) {
9217                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
9218                 return -EINVAL;
9219         }
9220
9221         if (BPF_SRC(insn->code) == BPF_X) {
9222                 if (insn->imm != 0) {
9223                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9224                         return -EINVAL;
9225                 }
9226
9227                 /* check src1 operand */
9228                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9229                 if (err)
9230                         return err;
9231
9232                 if (is_pointer_value(env, insn->src_reg)) {
9233                         verbose(env, "R%d pointer comparison prohibited\n",
9234                                 insn->src_reg);
9235                         return -EACCES;
9236                 }
9237                 src_reg = &regs[insn->src_reg];
9238         } else {
9239                 if (insn->src_reg != BPF_REG_0) {
9240                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9241                         return -EINVAL;
9242                 }
9243         }
9244
9245         /* check src2 operand */
9246         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9247         if (err)
9248                 return err;
9249
9250         dst_reg = &regs[insn->dst_reg];
9251         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9252
9253         if (BPF_SRC(insn->code) == BPF_K) {
9254                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9255         } else if (src_reg->type == SCALAR_VALUE &&
9256                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9257                 pred = is_branch_taken(dst_reg,
9258                                        tnum_subreg(src_reg->var_off).value,
9259                                        opcode,
9260                                        is_jmp32);
9261         } else if (src_reg->type == SCALAR_VALUE &&
9262                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9263                 pred = is_branch_taken(dst_reg,
9264                                        src_reg->var_off.value,
9265                                        opcode,
9266                                        is_jmp32);
9267         } else if (reg_is_pkt_pointer_any(dst_reg) &&
9268                    reg_is_pkt_pointer_any(src_reg) &&
9269                    !is_jmp32) {
9270                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9271         }
9272
9273         if (pred >= 0) {
9274                 /* If we get here with a dst_reg pointer type it is because
9275                  * above is_branch_taken() special cased the 0 comparison.
9276                  */
9277                 if (!__is_pointer_value(false, dst_reg))
9278                         err = mark_chain_precision(env, insn->dst_reg);
9279                 if (BPF_SRC(insn->code) == BPF_X && !err &&
9280                     !__is_pointer_value(false, src_reg))
9281                         err = mark_chain_precision(env, insn->src_reg);
9282                 if (err)
9283                         return err;
9284         }
9285
9286         if (pred == 1) {
9287                 /* Only follow the goto, ignore fall-through. If needed, push
9288                  * the fall-through branch for simulation under speculative
9289                  * execution.
9290                  */
9291                 if (!env->bypass_spec_v1 &&
9292                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
9293                                                *insn_idx))
9294                         return -EFAULT;
9295                 *insn_idx += insn->off;
9296                 return 0;
9297         } else if (pred == 0) {
9298                 /* Only follow the fall-through branch, since that's where the
9299                  * program will go. If needed, push the goto branch for
9300                  * simulation under speculative execution.
9301                  */
9302                 if (!env->bypass_spec_v1 &&
9303                     !sanitize_speculative_path(env, insn,
9304                                                *insn_idx + insn->off + 1,
9305                                                *insn_idx))
9306                         return -EFAULT;
9307                 return 0;
9308         }
9309
9310         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9311                                   false);
9312         if (!other_branch)
9313                 return -EFAULT;
9314         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9315
9316         /* detect if we are comparing against a constant value so we can adjust
9317          * our min/max values for our dst register.
9318          * this is only legit if both are scalars (or pointers to the same
9319          * object, I suppose, but we don't support that right now), because
9320          * otherwise the different base pointers mean the offsets aren't
9321          * comparable.
9322          */
9323         if (BPF_SRC(insn->code) == BPF_X) {
9324                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9325
9326                 if (dst_reg->type == SCALAR_VALUE &&
9327                     src_reg->type == SCALAR_VALUE) {
9328                         if (tnum_is_const(src_reg->var_off) ||
9329                             (is_jmp32 &&
9330                              tnum_is_const(tnum_subreg(src_reg->var_off))))
9331                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
9332                                                 dst_reg,
9333                                                 src_reg->var_off.value,
9334                                                 tnum_subreg(src_reg->var_off).value,
9335                                                 opcode, is_jmp32);
9336                         else if (tnum_is_const(dst_reg->var_off) ||
9337                                  (is_jmp32 &&
9338                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
9339                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9340                                                     src_reg,
9341                                                     dst_reg->var_off.value,
9342                                                     tnum_subreg(dst_reg->var_off).value,
9343                                                     opcode, is_jmp32);
9344                         else if (!is_jmp32 &&
9345                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
9346                                 /* Comparing for equality, we can combine knowledge */
9347                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
9348                                                     &other_branch_regs[insn->dst_reg],
9349                                                     src_reg, dst_reg, opcode);
9350                         if (src_reg->id &&
9351                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9352                                 find_equal_scalars(this_branch, src_reg);
9353                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9354                         }
9355
9356                 }
9357         } else if (dst_reg->type == SCALAR_VALUE) {
9358                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
9359                                         dst_reg, insn->imm, (u32)insn->imm,
9360                                         opcode, is_jmp32);
9361         }
9362
9363         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9364             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9365                 find_equal_scalars(this_branch, dst_reg);
9366                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9367         }
9368
9369         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9370          * NOTE: these optimizations below are related with pointer comparison
9371          *       which will never be JMP32.
9372          */
9373         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9374             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9375             reg_type_may_be_null(dst_reg->type)) {
9376                 /* Mark all identical registers in each branch as either
9377                  * safe or unknown depending R == 0 or R != 0 conditional.
9378                  */
9379                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9380                                       opcode == BPF_JNE);
9381                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9382                                       opcode == BPF_JEQ);
9383         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9384                                            this_branch, other_branch) &&
9385                    is_pointer_value(env, insn->dst_reg)) {
9386                 verbose(env, "R%d pointer comparison prohibited\n",
9387                         insn->dst_reg);
9388                 return -EACCES;
9389         }
9390         if (env->log.level & BPF_LOG_LEVEL)
9391                 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9392         return 0;
9393 }
9394
9395 /* verify BPF_LD_IMM64 instruction */
9396 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9397 {
9398         struct bpf_insn_aux_data *aux = cur_aux(env);
9399         struct bpf_reg_state *regs = cur_regs(env);
9400         struct bpf_reg_state *dst_reg;
9401         struct bpf_map *map;
9402         int err;
9403
9404         if (BPF_SIZE(insn->code) != BPF_DW) {
9405                 verbose(env, "invalid BPF_LD_IMM insn\n");
9406                 return -EINVAL;
9407         }
9408         if (insn->off != 0) {
9409                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9410                 return -EINVAL;
9411         }
9412
9413         err = check_reg_arg(env, insn->dst_reg, DST_OP);
9414         if (err)
9415                 return err;
9416
9417         dst_reg = &regs[insn->dst_reg];
9418         if (insn->src_reg == 0) {
9419                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9420
9421                 dst_reg->type = SCALAR_VALUE;
9422                 __mark_reg_known(&regs[insn->dst_reg], imm);
9423                 return 0;
9424         }
9425
9426         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9427                 mark_reg_known_zero(env, regs, insn->dst_reg);
9428
9429                 dst_reg->type = aux->btf_var.reg_type;
9430                 switch (dst_reg->type) {
9431                 case PTR_TO_MEM:
9432                         dst_reg->mem_size = aux->btf_var.mem_size;
9433                         break;
9434                 case PTR_TO_BTF_ID:
9435                 case PTR_TO_PERCPU_BTF_ID:
9436                         dst_reg->btf = aux->btf_var.btf;
9437                         dst_reg->btf_id = aux->btf_var.btf_id;
9438                         break;
9439                 default:
9440                         verbose(env, "bpf verifier is misconfigured\n");
9441                         return -EFAULT;
9442                 }
9443                 return 0;
9444         }
9445
9446         if (insn->src_reg == BPF_PSEUDO_FUNC) {
9447                 struct bpf_prog_aux *aux = env->prog->aux;
9448                 u32 subprogno = find_subprog(env,
9449                                              env->insn_idx + insn->imm + 1);
9450
9451                 if (!aux->func_info) {
9452                         verbose(env, "missing btf func_info\n");
9453                         return -EINVAL;
9454                 }
9455                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9456                         verbose(env, "callback function not static\n");
9457                         return -EINVAL;
9458                 }
9459
9460                 dst_reg->type = PTR_TO_FUNC;
9461                 dst_reg->subprogno = subprogno;
9462                 return 0;
9463         }
9464
9465         map = env->used_maps[aux->map_index];
9466         mark_reg_known_zero(env, regs, insn->dst_reg);
9467         dst_reg->map_ptr = map;
9468
9469         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9470             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9471                 dst_reg->type = PTR_TO_MAP_VALUE;
9472                 dst_reg->off = aux->map_off;
9473                 if (map_value_has_spin_lock(map))
9474                         dst_reg->id = ++env->id_gen;
9475         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9476                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9477                 dst_reg->type = CONST_PTR_TO_MAP;
9478         } else {
9479                 verbose(env, "bpf verifier is misconfigured\n");
9480                 return -EINVAL;
9481         }
9482
9483         return 0;
9484 }
9485
9486 static bool may_access_skb(enum bpf_prog_type type)
9487 {
9488         switch (type) {
9489         case BPF_PROG_TYPE_SOCKET_FILTER:
9490         case BPF_PROG_TYPE_SCHED_CLS:
9491         case BPF_PROG_TYPE_SCHED_ACT:
9492                 return true;
9493         default:
9494                 return false;
9495         }
9496 }
9497
9498 /* verify safety of LD_ABS|LD_IND instructions:
9499  * - they can only appear in the programs where ctx == skb
9500  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9501  *   preserve R6-R9, and store return value into R0
9502  *
9503  * Implicit input:
9504  *   ctx == skb == R6 == CTX
9505  *
9506  * Explicit input:
9507  *   SRC == any register
9508  *   IMM == 32-bit immediate
9509  *
9510  * Output:
9511  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9512  */
9513 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9514 {
9515         struct bpf_reg_state *regs = cur_regs(env);
9516         static const int ctx_reg = BPF_REG_6;
9517         u8 mode = BPF_MODE(insn->code);
9518         int i, err;
9519
9520         if (!may_access_skb(resolve_prog_type(env->prog))) {
9521                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9522                 return -EINVAL;
9523         }
9524
9525         if (!env->ops->gen_ld_abs) {
9526                 verbose(env, "bpf verifier is misconfigured\n");
9527                 return -EINVAL;
9528         }
9529
9530         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9531             BPF_SIZE(insn->code) == BPF_DW ||
9532             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9533                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9534                 return -EINVAL;
9535         }
9536
9537         /* check whether implicit source operand (register R6) is readable */
9538         err = check_reg_arg(env, ctx_reg, SRC_OP);
9539         if (err)
9540                 return err;
9541
9542         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9543          * gen_ld_abs() may terminate the program at runtime, leading to
9544          * reference leak.
9545          */
9546         err = check_reference_leak(env);
9547         if (err) {
9548                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9549                 return err;
9550         }
9551
9552         if (env->cur_state->active_spin_lock) {
9553                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9554                 return -EINVAL;
9555         }
9556
9557         if (regs[ctx_reg].type != PTR_TO_CTX) {
9558                 verbose(env,
9559                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9560                 return -EINVAL;
9561         }
9562
9563         if (mode == BPF_IND) {
9564                 /* check explicit source operand */
9565                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9566                 if (err)
9567                         return err;
9568         }
9569
9570         err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9571         if (err < 0)
9572                 return err;
9573
9574         /* reset caller saved regs to unreadable */
9575         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9576                 mark_reg_not_init(env, regs, caller_saved[i]);
9577                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9578         }
9579
9580         /* mark destination R0 register as readable, since it contains
9581          * the value fetched from the packet.
9582          * Already marked as written above.
9583          */
9584         mark_reg_unknown(env, regs, BPF_REG_0);
9585         /* ld_abs load up to 32-bit skb data. */
9586         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9587         return 0;
9588 }
9589
9590 static int check_return_code(struct bpf_verifier_env *env)
9591 {
9592         struct tnum enforce_attach_type_range = tnum_unknown;
9593         const struct bpf_prog *prog = env->prog;
9594         struct bpf_reg_state *reg;
9595         struct tnum range = tnum_range(0, 1);
9596         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9597         int err;
9598         struct bpf_func_state *frame = env->cur_state->frame[0];
9599         const bool is_subprog = frame->subprogno;
9600
9601         /* LSM and struct_ops func-ptr's return type could be "void" */
9602         if (!is_subprog &&
9603             (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9604              prog_type == BPF_PROG_TYPE_LSM) &&
9605             !prog->aux->attach_func_proto->type)
9606                 return 0;
9607
9608         /* eBPF calling convention is such that R0 is used
9609          * to return the value from eBPF program.
9610          * Make sure that it's readable at this time
9611          * of bpf_exit, which means that program wrote
9612          * something into it earlier
9613          */
9614         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9615         if (err)
9616                 return err;
9617
9618         if (is_pointer_value(env, BPF_REG_0)) {
9619                 verbose(env, "R0 leaks addr as return value\n");
9620                 return -EACCES;
9621         }
9622
9623         reg = cur_regs(env) + BPF_REG_0;
9624
9625         if (frame->in_async_callback_fn) {
9626                 /* enforce return zero from async callbacks like timer */
9627                 if (reg->type != SCALAR_VALUE) {
9628                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9629                                 reg_type_str[reg->type]);
9630                         return -EINVAL;
9631                 }
9632
9633                 if (!tnum_in(tnum_const(0), reg->var_off)) {
9634                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9635                         return -EINVAL;
9636                 }
9637                 return 0;
9638         }
9639
9640         if (is_subprog) {
9641                 if (reg->type != SCALAR_VALUE) {
9642                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9643                                 reg_type_str[reg->type]);
9644                         return -EINVAL;
9645                 }
9646                 return 0;
9647         }
9648
9649         switch (prog_type) {
9650         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9651                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9652                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9653                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9654                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9655                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9656                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9657                         range = tnum_range(1, 1);
9658                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9659                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9660                         range = tnum_range(0, 3);
9661                 break;
9662         case BPF_PROG_TYPE_CGROUP_SKB:
9663                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9664                         range = tnum_range(0, 3);
9665                         enforce_attach_type_range = tnum_range(2, 3);
9666                 }
9667                 break;
9668         case BPF_PROG_TYPE_CGROUP_SOCK:
9669         case BPF_PROG_TYPE_SOCK_OPS:
9670         case BPF_PROG_TYPE_CGROUP_DEVICE:
9671         case BPF_PROG_TYPE_CGROUP_SYSCTL:
9672         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9673                 break;
9674         case BPF_PROG_TYPE_RAW_TRACEPOINT:
9675                 if (!env->prog->aux->attach_btf_id)
9676                         return 0;
9677                 range = tnum_const(0);
9678                 break;
9679         case BPF_PROG_TYPE_TRACING:
9680                 switch (env->prog->expected_attach_type) {
9681                 case BPF_TRACE_FENTRY:
9682                 case BPF_TRACE_FEXIT:
9683                         range = tnum_const(0);
9684                         break;
9685                 case BPF_TRACE_RAW_TP:
9686                 case BPF_MODIFY_RETURN:
9687                         return 0;
9688                 case BPF_TRACE_ITER:
9689                         break;
9690                 default:
9691                         return -ENOTSUPP;
9692                 }
9693                 break;
9694         case BPF_PROG_TYPE_SK_LOOKUP:
9695                 range = tnum_range(SK_DROP, SK_PASS);
9696                 break;
9697         case BPF_PROG_TYPE_EXT:
9698                 /* freplace program can return anything as its return value
9699                  * depends on the to-be-replaced kernel func or bpf program.
9700                  */
9701         default:
9702                 return 0;
9703         }
9704
9705         if (reg->type != SCALAR_VALUE) {
9706                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9707                         reg_type_str[reg->type]);
9708                 return -EINVAL;
9709         }
9710
9711         if (!tnum_in(range, reg->var_off)) {
9712                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9713                 return -EINVAL;
9714         }
9715
9716         if (!tnum_is_unknown(enforce_attach_type_range) &&
9717             tnum_in(enforce_attach_type_range, reg->var_off))
9718                 env->prog->enforce_expected_attach_type = 1;
9719         return 0;
9720 }
9721
9722 /* non-recursive DFS pseudo code
9723  * 1  procedure DFS-iterative(G,v):
9724  * 2      label v as discovered
9725  * 3      let S be a stack
9726  * 4      S.push(v)
9727  * 5      while S is not empty
9728  * 6            t <- S.pop()
9729  * 7            if t is what we're looking for:
9730  * 8                return t
9731  * 9            for all edges e in G.adjacentEdges(t) do
9732  * 10               if edge e is already labelled
9733  * 11                   continue with the next edge
9734  * 12               w <- G.adjacentVertex(t,e)
9735  * 13               if vertex w is not discovered and not explored
9736  * 14                   label e as tree-edge
9737  * 15                   label w as discovered
9738  * 16                   S.push(w)
9739  * 17                   continue at 5
9740  * 18               else if vertex w is discovered
9741  * 19                   label e as back-edge
9742  * 20               else
9743  * 21                   // vertex w is explored
9744  * 22                   label e as forward- or cross-edge
9745  * 23           label t as explored
9746  * 24           S.pop()
9747  *
9748  * convention:
9749  * 0x10 - discovered
9750  * 0x11 - discovered and fall-through edge labelled
9751  * 0x12 - discovered and fall-through and branch edges labelled
9752  * 0x20 - explored
9753  */
9754
9755 enum {
9756         DISCOVERED = 0x10,
9757         EXPLORED = 0x20,
9758         FALLTHROUGH = 1,
9759         BRANCH = 2,
9760 };
9761
9762 static u32 state_htab_size(struct bpf_verifier_env *env)
9763 {
9764         return env->prog->len;
9765 }
9766
9767 static struct bpf_verifier_state_list **explored_state(
9768                                         struct bpf_verifier_env *env,
9769                                         int idx)
9770 {
9771         struct bpf_verifier_state *cur = env->cur_state;
9772         struct bpf_func_state *state = cur->frame[cur->curframe];
9773
9774         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9775 }
9776
9777 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9778 {
9779         env->insn_aux_data[idx].prune_point = true;
9780 }
9781
9782 enum {
9783         DONE_EXPLORING = 0,
9784         KEEP_EXPLORING = 1,
9785 };
9786
9787 /* t, w, e - match pseudo-code above:
9788  * t - index of current instruction
9789  * w - next instruction
9790  * e - edge
9791  */
9792 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9793                      bool loop_ok)
9794 {
9795         int *insn_stack = env->cfg.insn_stack;
9796         int *insn_state = env->cfg.insn_state;
9797
9798         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9799                 return DONE_EXPLORING;
9800
9801         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9802                 return DONE_EXPLORING;
9803
9804         if (w < 0 || w >= env->prog->len) {
9805                 verbose_linfo(env, t, "%d: ", t);
9806                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
9807                 return -EINVAL;
9808         }
9809
9810         if (e == BRANCH)
9811                 /* mark branch target for state pruning */
9812                 init_explored_state(env, w);
9813
9814         if (insn_state[w] == 0) {
9815                 /* tree-edge */
9816                 insn_state[t] = DISCOVERED | e;
9817                 insn_state[w] = DISCOVERED;
9818                 if (env->cfg.cur_stack >= env->prog->len)
9819                         return -E2BIG;
9820                 insn_stack[env->cfg.cur_stack++] = w;
9821                 return KEEP_EXPLORING;
9822         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9823                 if (loop_ok && env->bpf_capable)
9824                         return DONE_EXPLORING;
9825                 verbose_linfo(env, t, "%d: ", t);
9826                 verbose_linfo(env, w, "%d: ", w);
9827                 verbose(env, "back-edge from insn %d to %d\n", t, w);
9828                 return -EINVAL;
9829         } else if (insn_state[w] == EXPLORED) {
9830                 /* forward- or cross-edge */
9831                 insn_state[t] = DISCOVERED | e;
9832         } else {
9833                 verbose(env, "insn state internal bug\n");
9834                 return -EFAULT;
9835         }
9836         return DONE_EXPLORING;
9837 }
9838
9839 static int visit_func_call_insn(int t, int insn_cnt,
9840                                 struct bpf_insn *insns,
9841                                 struct bpf_verifier_env *env,
9842                                 bool visit_callee)
9843 {
9844         int ret;
9845
9846         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9847         if (ret)
9848                 return ret;
9849
9850         if (t + 1 < insn_cnt)
9851                 init_explored_state(env, t + 1);
9852         if (visit_callee) {
9853                 init_explored_state(env, t);
9854                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9855                                 /* It's ok to allow recursion from CFG point of
9856                                  * view. __check_func_call() will do the actual
9857                                  * check.
9858                                  */
9859                                 bpf_pseudo_func(insns + t));
9860         }
9861         return ret;
9862 }
9863
9864 /* Visits the instruction at index t and returns one of the following:
9865  *  < 0 - an error occurred
9866  *  DONE_EXPLORING - the instruction was fully explored
9867  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9868  */
9869 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9870 {
9871         struct bpf_insn *insns = env->prog->insnsi;
9872         int ret;
9873
9874         if (bpf_pseudo_func(insns + t))
9875                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9876
9877         /* All non-branch instructions have a single fall-through edge. */
9878         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9879             BPF_CLASS(insns[t].code) != BPF_JMP32)
9880                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9881
9882         switch (BPF_OP(insns[t].code)) {
9883         case BPF_EXIT:
9884                 return DONE_EXPLORING;
9885
9886         case BPF_CALL:
9887                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
9888                         /* Mark this call insn to trigger is_state_visited() check
9889                          * before call itself is processed by __check_func_call().
9890                          * Otherwise new async state will be pushed for further
9891                          * exploration.
9892                          */
9893                         init_explored_state(env, t);
9894                 return visit_func_call_insn(t, insn_cnt, insns, env,
9895                                             insns[t].src_reg == BPF_PSEUDO_CALL);
9896
9897         case BPF_JA:
9898                 if (BPF_SRC(insns[t].code) != BPF_K)
9899                         return -EINVAL;
9900
9901                 /* unconditional jump with single edge */
9902                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9903                                 true);
9904                 if (ret)
9905                         return ret;
9906
9907                 /* unconditional jmp is not a good pruning point,
9908                  * but it's marked, since backtracking needs
9909                  * to record jmp history in is_state_visited().
9910                  */
9911                 init_explored_state(env, t + insns[t].off + 1);
9912                 /* tell verifier to check for equivalent states
9913                  * after every call and jump
9914                  */
9915                 if (t + 1 < insn_cnt)
9916                         init_explored_state(env, t + 1);
9917
9918                 return ret;
9919
9920         default:
9921                 /* conditional jump with two edges */
9922                 init_explored_state(env, t);
9923                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9924                 if (ret)
9925                         return ret;
9926
9927                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9928         }
9929 }
9930
9931 /* non-recursive depth-first-search to detect loops in BPF program
9932  * loop == back-edge in directed graph
9933  */
9934 static int check_cfg(struct bpf_verifier_env *env)
9935 {
9936         int insn_cnt = env->prog->len;
9937         int *insn_stack, *insn_state;
9938         int ret = 0;
9939         int i;
9940
9941         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9942         if (!insn_state)
9943                 return -ENOMEM;
9944
9945         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9946         if (!insn_stack) {
9947                 kvfree(insn_state);
9948                 return -ENOMEM;
9949         }
9950
9951         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9952         insn_stack[0] = 0; /* 0 is the first instruction */
9953         env->cfg.cur_stack = 1;
9954
9955         while (env->cfg.cur_stack > 0) {
9956                 int t = insn_stack[env->cfg.cur_stack - 1];
9957
9958                 ret = visit_insn(t, insn_cnt, env);
9959                 switch (ret) {
9960                 case DONE_EXPLORING:
9961                         insn_state[t] = EXPLORED;
9962                         env->cfg.cur_stack--;
9963                         break;
9964                 case KEEP_EXPLORING:
9965                         break;
9966                 default:
9967                         if (ret > 0) {
9968                                 verbose(env, "visit_insn internal bug\n");
9969                                 ret = -EFAULT;
9970                         }
9971                         goto err_free;
9972                 }
9973         }
9974
9975         if (env->cfg.cur_stack < 0) {
9976                 verbose(env, "pop stack internal bug\n");
9977                 ret = -EFAULT;
9978                 goto err_free;
9979         }
9980
9981         for (i = 0; i < insn_cnt; i++) {
9982                 if (insn_state[i] != EXPLORED) {
9983                         verbose(env, "unreachable insn %d\n", i);
9984                         ret = -EINVAL;
9985                         goto err_free;
9986                 }
9987         }
9988         ret = 0; /* cfg looks good */
9989
9990 err_free:
9991         kvfree(insn_state);
9992         kvfree(insn_stack);
9993         env->cfg.insn_state = env->cfg.insn_stack = NULL;
9994         return ret;
9995 }
9996
9997 static int check_abnormal_return(struct bpf_verifier_env *env)
9998 {
9999         int i;
10000
10001         for (i = 1; i < env->subprog_cnt; i++) {
10002                 if (env->subprog_info[i].has_ld_abs) {
10003                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10004                         return -EINVAL;
10005                 }
10006                 if (env->subprog_info[i].has_tail_call) {
10007                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10008                         return -EINVAL;
10009                 }
10010         }
10011         return 0;
10012 }
10013
10014 /* The minimum supported BTF func info size */
10015 #define MIN_BPF_FUNCINFO_SIZE   8
10016 #define MAX_FUNCINFO_REC_SIZE   252
10017
10018 static int check_btf_func(struct bpf_verifier_env *env,
10019                           const union bpf_attr *attr,
10020                           bpfptr_t uattr)
10021 {
10022         const struct btf_type *type, *func_proto, *ret_type;
10023         u32 i, nfuncs, urec_size, min_size;
10024         u32 krec_size = sizeof(struct bpf_func_info);
10025         struct bpf_func_info *krecord;
10026         struct bpf_func_info_aux *info_aux = NULL;
10027         struct bpf_prog *prog;
10028         const struct btf *btf;
10029         bpfptr_t urecord;
10030         u32 prev_offset = 0;
10031         bool scalar_return;
10032         int ret = -ENOMEM;
10033
10034         nfuncs = attr->func_info_cnt;
10035         if (!nfuncs) {
10036                 if (check_abnormal_return(env))
10037                         return -EINVAL;
10038                 return 0;
10039         }
10040
10041         if (nfuncs != env->subprog_cnt) {
10042                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10043                 return -EINVAL;
10044         }
10045
10046         urec_size = attr->func_info_rec_size;
10047         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10048             urec_size > MAX_FUNCINFO_REC_SIZE ||
10049             urec_size % sizeof(u32)) {
10050                 verbose(env, "invalid func info rec size %u\n", urec_size);
10051                 return -EINVAL;
10052         }
10053
10054         prog = env->prog;
10055         btf = prog->aux->btf;
10056
10057         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10058         min_size = min_t(u32, krec_size, urec_size);
10059
10060         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10061         if (!krecord)
10062                 return -ENOMEM;
10063         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10064         if (!info_aux)
10065                 goto err_free;
10066
10067         for (i = 0; i < nfuncs; i++) {
10068                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10069                 if (ret) {
10070                         if (ret == -E2BIG) {
10071                                 verbose(env, "nonzero tailing record in func info");
10072                                 /* set the size kernel expects so loader can zero
10073                                  * out the rest of the record.
10074                                  */
10075                                 if (copy_to_bpfptr_offset(uattr,
10076                                                           offsetof(union bpf_attr, func_info_rec_size),
10077                                                           &min_size, sizeof(min_size)))
10078                                         ret = -EFAULT;
10079                         }
10080                         goto err_free;
10081                 }
10082
10083                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10084                         ret = -EFAULT;
10085                         goto err_free;
10086                 }
10087
10088                 /* check insn_off */
10089                 ret = -EINVAL;
10090                 if (i == 0) {
10091                         if (krecord[i].insn_off) {
10092                                 verbose(env,
10093                                         "nonzero insn_off %u for the first func info record",
10094                                         krecord[i].insn_off);
10095                                 goto err_free;
10096                         }
10097                 } else if (krecord[i].insn_off <= prev_offset) {
10098                         verbose(env,
10099                                 "same or smaller insn offset (%u) than previous func info record (%u)",
10100                                 krecord[i].insn_off, prev_offset);
10101                         goto err_free;
10102                 }
10103
10104                 if (env->subprog_info[i].start != krecord[i].insn_off) {
10105                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10106                         goto err_free;
10107                 }
10108
10109                 /* check type_id */
10110                 type = btf_type_by_id(btf, krecord[i].type_id);
10111                 if (!type || !btf_type_is_func(type)) {
10112                         verbose(env, "invalid type id %d in func info",
10113                                 krecord[i].type_id);
10114                         goto err_free;
10115                 }
10116                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10117
10118                 func_proto = btf_type_by_id(btf, type->type);
10119                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10120                         /* btf_func_check() already verified it during BTF load */
10121                         goto err_free;
10122                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10123                 scalar_return =
10124                         btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
10125                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10126                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10127                         goto err_free;
10128                 }
10129                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10130                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10131                         goto err_free;
10132                 }
10133
10134                 prev_offset = krecord[i].insn_off;
10135                 bpfptr_add(&urecord, urec_size);
10136         }
10137
10138         prog->aux->func_info = krecord;
10139         prog->aux->func_info_cnt = nfuncs;
10140         prog->aux->func_info_aux = info_aux;
10141         return 0;
10142
10143 err_free:
10144         kvfree(krecord);
10145         kfree(info_aux);
10146         return ret;
10147 }
10148
10149 static void adjust_btf_func(struct bpf_verifier_env *env)
10150 {
10151         struct bpf_prog_aux *aux = env->prog->aux;
10152         int i;
10153
10154         if (!aux->func_info)
10155                 return;
10156
10157         for (i = 0; i < env->subprog_cnt; i++)
10158                 aux->func_info[i].insn_off = env->subprog_info[i].start;
10159 }
10160
10161 #define MIN_BPF_LINEINFO_SIZE   (offsetof(struct bpf_line_info, line_col) + \
10162                 sizeof(((struct bpf_line_info *)(0))->line_col))
10163 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
10164
10165 static int check_btf_line(struct bpf_verifier_env *env,
10166                           const union bpf_attr *attr,
10167                           bpfptr_t uattr)
10168 {
10169         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
10170         struct bpf_subprog_info *sub;
10171         struct bpf_line_info *linfo;
10172         struct bpf_prog *prog;
10173         const struct btf *btf;
10174         bpfptr_t ulinfo;
10175         int err;
10176
10177         nr_linfo = attr->line_info_cnt;
10178         if (!nr_linfo)
10179                 return 0;
10180         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
10181                 return -EINVAL;
10182
10183         rec_size = attr->line_info_rec_size;
10184         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
10185             rec_size > MAX_LINEINFO_REC_SIZE ||
10186             rec_size & (sizeof(u32) - 1))
10187                 return -EINVAL;
10188
10189         /* Need to zero it in case the userspace may
10190          * pass in a smaller bpf_line_info object.
10191          */
10192         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
10193                          GFP_KERNEL | __GFP_NOWARN);
10194         if (!linfo)
10195                 return -ENOMEM;
10196
10197         prog = env->prog;
10198         btf = prog->aux->btf;
10199
10200         s = 0;
10201         sub = env->subprog_info;
10202         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
10203         expected_size = sizeof(struct bpf_line_info);
10204         ncopy = min_t(u32, expected_size, rec_size);
10205         for (i = 0; i < nr_linfo; i++) {
10206                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10207                 if (err) {
10208                         if (err == -E2BIG) {
10209                                 verbose(env, "nonzero tailing record in line_info");
10210                                 if (copy_to_bpfptr_offset(uattr,
10211                                                           offsetof(union bpf_attr, line_info_rec_size),
10212                                                           &expected_size, sizeof(expected_size)))
10213                                         err = -EFAULT;
10214                         }
10215                         goto err_free;
10216                 }
10217
10218                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
10219                         err = -EFAULT;
10220                         goto err_free;
10221                 }
10222
10223                 /*
10224                  * Check insn_off to ensure
10225                  * 1) strictly increasing AND
10226                  * 2) bounded by prog->len
10227                  *
10228                  * The linfo[0].insn_off == 0 check logically falls into
10229                  * the later "missing bpf_line_info for func..." case
10230                  * because the first linfo[0].insn_off must be the
10231                  * first sub also and the first sub must have
10232                  * subprog_info[0].start == 0.
10233                  */
10234                 if ((i && linfo[i].insn_off <= prev_offset) ||
10235                     linfo[i].insn_off >= prog->len) {
10236                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10237                                 i, linfo[i].insn_off, prev_offset,
10238                                 prog->len);
10239                         err = -EINVAL;
10240                         goto err_free;
10241                 }
10242
10243                 if (!prog->insnsi[linfo[i].insn_off].code) {
10244                         verbose(env,
10245                                 "Invalid insn code at line_info[%u].insn_off\n",
10246                                 i);
10247                         err = -EINVAL;
10248                         goto err_free;
10249                 }
10250
10251                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10252                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10253                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10254                         err = -EINVAL;
10255                         goto err_free;
10256                 }
10257
10258                 if (s != env->subprog_cnt) {
10259                         if (linfo[i].insn_off == sub[s].start) {
10260                                 sub[s].linfo_idx = i;
10261                                 s++;
10262                         } else if (sub[s].start < linfo[i].insn_off) {
10263                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
10264                                 err = -EINVAL;
10265                                 goto err_free;
10266                         }
10267                 }
10268
10269                 prev_offset = linfo[i].insn_off;
10270                 bpfptr_add(&ulinfo, rec_size);
10271         }
10272
10273         if (s != env->subprog_cnt) {
10274                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10275                         env->subprog_cnt - s, s);
10276                 err = -EINVAL;
10277                 goto err_free;
10278         }
10279
10280         prog->aux->linfo = linfo;
10281         prog->aux->nr_linfo = nr_linfo;
10282
10283         return 0;
10284
10285 err_free:
10286         kvfree(linfo);
10287         return err;
10288 }
10289
10290 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
10291 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
10292
10293 static int check_core_relo(struct bpf_verifier_env *env,
10294                            const union bpf_attr *attr,
10295                            bpfptr_t uattr)
10296 {
10297         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
10298         struct bpf_core_relo core_relo = {};
10299         struct bpf_prog *prog = env->prog;
10300         const struct btf *btf = prog->aux->btf;
10301         struct bpf_core_ctx ctx = {
10302                 .log = &env->log,
10303                 .btf = btf,
10304         };
10305         bpfptr_t u_core_relo;
10306         int err;
10307
10308         nr_core_relo = attr->core_relo_cnt;
10309         if (!nr_core_relo)
10310                 return 0;
10311         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
10312                 return -EINVAL;
10313
10314         rec_size = attr->core_relo_rec_size;
10315         if (rec_size < MIN_CORE_RELO_SIZE ||
10316             rec_size > MAX_CORE_RELO_SIZE ||
10317             rec_size % sizeof(u32))
10318                 return -EINVAL;
10319
10320         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
10321         expected_size = sizeof(struct bpf_core_relo);
10322         ncopy = min_t(u32, expected_size, rec_size);
10323
10324         /* Unlike func_info and line_info, copy and apply each CO-RE
10325          * relocation record one at a time.
10326          */
10327         for (i = 0; i < nr_core_relo; i++) {
10328                 /* future proofing when sizeof(bpf_core_relo) changes */
10329                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
10330                 if (err) {
10331                         if (err == -E2BIG) {
10332                                 verbose(env, "nonzero tailing record in core_relo");
10333                                 if (copy_to_bpfptr_offset(uattr,
10334                                                           offsetof(union bpf_attr, core_relo_rec_size),
10335                                                           &expected_size, sizeof(expected_size)))
10336                                         err = -EFAULT;
10337                         }
10338                         break;
10339                 }
10340
10341                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
10342                         err = -EFAULT;
10343                         break;
10344                 }
10345
10346                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
10347                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
10348                                 i, core_relo.insn_off, prog->len);
10349                         err = -EINVAL;
10350                         break;
10351                 }
10352
10353                 err = bpf_core_apply(&ctx, &core_relo, i,
10354                                      &prog->insnsi[core_relo.insn_off / 8]);
10355                 if (err)
10356                         break;
10357                 bpfptr_add(&u_core_relo, rec_size);
10358         }
10359         return err;
10360 }
10361
10362 static int check_btf_info(struct bpf_verifier_env *env,
10363                           const union bpf_attr *attr,
10364                           bpfptr_t uattr)
10365 {
10366         struct btf *btf;
10367         int err;
10368
10369         if (!attr->func_info_cnt && !attr->line_info_cnt) {
10370                 if (check_abnormal_return(env))
10371                         return -EINVAL;
10372                 return 0;
10373         }
10374
10375         btf = btf_get_by_fd(attr->prog_btf_fd);
10376         if (IS_ERR(btf))
10377                 return PTR_ERR(btf);
10378         if (btf_is_kernel(btf)) {
10379                 btf_put(btf);
10380                 return -EACCES;
10381         }
10382         env->prog->aux->btf = btf;
10383
10384         err = check_btf_func(env, attr, uattr);
10385         if (err)
10386                 return err;
10387
10388         err = check_btf_line(env, attr, uattr);
10389         if (err)
10390                 return err;
10391
10392         err = check_core_relo(env, attr, uattr);
10393         if (err)
10394                 return err;
10395
10396         return 0;
10397 }
10398
10399 /* check %cur's range satisfies %old's */
10400 static bool range_within(struct bpf_reg_state *old,
10401                          struct bpf_reg_state *cur)
10402 {
10403         return old->umin_value <= cur->umin_value &&
10404                old->umax_value >= cur->umax_value &&
10405                old->smin_value <= cur->smin_value &&
10406                old->smax_value >= cur->smax_value &&
10407                old->u32_min_value <= cur->u32_min_value &&
10408                old->u32_max_value >= cur->u32_max_value &&
10409                old->s32_min_value <= cur->s32_min_value &&
10410                old->s32_max_value >= cur->s32_max_value;
10411 }
10412
10413 /* If in the old state two registers had the same id, then they need to have
10414  * the same id in the new state as well.  But that id could be different from
10415  * the old state, so we need to track the mapping from old to new ids.
10416  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10417  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10418  * regs with a different old id could still have new id 9, we don't care about
10419  * that.
10420  * So we look through our idmap to see if this old id has been seen before.  If
10421  * so, we require the new id to match; otherwise, we add the id pair to the map.
10422  */
10423 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10424 {
10425         unsigned int i;
10426
10427         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10428                 if (!idmap[i].old) {
10429                         /* Reached an empty slot; haven't seen this id before */
10430                         idmap[i].old = old_id;
10431                         idmap[i].cur = cur_id;
10432                         return true;
10433                 }
10434                 if (idmap[i].old == old_id)
10435                         return idmap[i].cur == cur_id;
10436         }
10437         /* We ran out of idmap slots, which should be impossible */
10438         WARN_ON_ONCE(1);
10439         return false;
10440 }
10441
10442 static void clean_func_state(struct bpf_verifier_env *env,
10443                              struct bpf_func_state *st)
10444 {
10445         enum bpf_reg_liveness live;
10446         int i, j;
10447
10448         for (i = 0; i < BPF_REG_FP; i++) {
10449                 live = st->regs[i].live;
10450                 /* liveness must not touch this register anymore */
10451                 st->regs[i].live |= REG_LIVE_DONE;
10452                 if (!(live & REG_LIVE_READ))
10453                         /* since the register is unused, clear its state
10454                          * to make further comparison simpler
10455                          */
10456                         __mark_reg_not_init(env, &st->regs[i]);
10457         }
10458
10459         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10460                 live = st->stack[i].spilled_ptr.live;
10461                 /* liveness must not touch this stack slot anymore */
10462                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10463                 if (!(live & REG_LIVE_READ)) {
10464                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10465                         for (j = 0; j < BPF_REG_SIZE; j++)
10466                                 st->stack[i].slot_type[j] = STACK_INVALID;
10467                 }
10468         }
10469 }
10470
10471 static void clean_verifier_state(struct bpf_verifier_env *env,
10472                                  struct bpf_verifier_state *st)
10473 {
10474         int i;
10475
10476         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10477                 /* all regs in this state in all frames were already marked */
10478                 return;
10479
10480         for (i = 0; i <= st->curframe; i++)
10481                 clean_func_state(env, st->frame[i]);
10482 }
10483
10484 /* the parentage chains form a tree.
10485  * the verifier states are added to state lists at given insn and
10486  * pushed into state stack for future exploration.
10487  * when the verifier reaches bpf_exit insn some of the verifer states
10488  * stored in the state lists have their final liveness state already,
10489  * but a lot of states will get revised from liveness point of view when
10490  * the verifier explores other branches.
10491  * Example:
10492  * 1: r0 = 1
10493  * 2: if r1 == 100 goto pc+1
10494  * 3: r0 = 2
10495  * 4: exit
10496  * when the verifier reaches exit insn the register r0 in the state list of
10497  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10498  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10499  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10500  *
10501  * Since the verifier pushes the branch states as it sees them while exploring
10502  * the program the condition of walking the branch instruction for the second
10503  * time means that all states below this branch were already explored and
10504  * their final liveness marks are already propagated.
10505  * Hence when the verifier completes the search of state list in is_state_visited()
10506  * we can call this clean_live_states() function to mark all liveness states
10507  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10508  * will not be used.
10509  * This function also clears the registers and stack for states that !READ
10510  * to simplify state merging.
10511  *
10512  * Important note here that walking the same branch instruction in the callee
10513  * doesn't meant that the states are DONE. The verifier has to compare
10514  * the callsites
10515  */
10516 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10517                               struct bpf_verifier_state *cur)
10518 {
10519         struct bpf_verifier_state_list *sl;
10520         int i;
10521
10522         sl = *explored_state(env, insn);
10523         while (sl) {
10524                 if (sl->state.branches)
10525                         goto next;
10526                 if (sl->state.insn_idx != insn ||
10527                     sl->state.curframe != cur->curframe)
10528                         goto next;
10529                 for (i = 0; i <= cur->curframe; i++)
10530                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10531                                 goto next;
10532                 clean_verifier_state(env, &sl->state);
10533 next:
10534                 sl = sl->next;
10535         }
10536 }
10537
10538 /* Returns true if (rold safe implies rcur safe) */
10539 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10540                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10541 {
10542         bool equal;
10543
10544         if (!(rold->live & REG_LIVE_READ))
10545                 /* explored state didn't use this */
10546                 return true;
10547
10548         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10549
10550         if (rold->type == PTR_TO_STACK)
10551                 /* two stack pointers are equal only if they're pointing to
10552                  * the same stack frame, since fp-8 in foo != fp-8 in bar
10553                  */
10554                 return equal && rold->frameno == rcur->frameno;
10555
10556         if (equal)
10557                 return true;
10558
10559         if (rold->type == NOT_INIT)
10560                 /* explored state can't have used this */
10561                 return true;
10562         if (rcur->type == NOT_INIT)
10563                 return false;
10564         switch (rold->type) {
10565         case SCALAR_VALUE:
10566                 if (env->explore_alu_limits)
10567                         return false;
10568                 if (rcur->type == SCALAR_VALUE) {
10569                         if (!rold->precise && !rcur->precise)
10570                                 return true;
10571                         /* new val must satisfy old val knowledge */
10572                         return range_within(rold, rcur) &&
10573                                tnum_in(rold->var_off, rcur->var_off);
10574                 } else {
10575                         /* We're trying to use a pointer in place of a scalar.
10576                          * Even if the scalar was unbounded, this could lead to
10577                          * pointer leaks because scalars are allowed to leak
10578                          * while pointers are not. We could make this safe in
10579                          * special cases if root is calling us, but it's
10580                          * probably not worth the hassle.
10581                          */
10582                         return false;
10583                 }
10584         case PTR_TO_MAP_KEY:
10585         case PTR_TO_MAP_VALUE:
10586                 /* If the new min/max/var_off satisfy the old ones and
10587                  * everything else matches, we are OK.
10588                  * 'id' is not compared, since it's only used for maps with
10589                  * bpf_spin_lock inside map element and in such cases if
10590                  * the rest of the prog is valid for one map element then
10591                  * it's valid for all map elements regardless of the key
10592                  * used in bpf_map_lookup()
10593                  */
10594                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10595                        range_within(rold, rcur) &&
10596                        tnum_in(rold->var_off, rcur->var_off);
10597         case PTR_TO_MAP_VALUE_OR_NULL:
10598                 /* a PTR_TO_MAP_VALUE could be safe to use as a
10599                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10600                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10601                  * checked, doing so could have affected others with the same
10602                  * id, and we can't check for that because we lost the id when
10603                  * we converted to a PTR_TO_MAP_VALUE.
10604                  */
10605                 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
10606                         return false;
10607                 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10608                         return false;
10609                 /* Check our ids match any regs they're supposed to */
10610                 return check_ids(rold->id, rcur->id, idmap);
10611         case PTR_TO_PACKET_META:
10612         case PTR_TO_PACKET:
10613                 if (rcur->type != rold->type)
10614                         return false;
10615                 /* We must have at least as much range as the old ptr
10616                  * did, so that any accesses which were safe before are
10617                  * still safe.  This is true even if old range < old off,
10618                  * since someone could have accessed through (ptr - k), or
10619                  * even done ptr -= k in a register, to get a safe access.
10620                  */
10621                 if (rold->range > rcur->range)
10622                         return false;
10623                 /* If the offsets don't match, we can't trust our alignment;
10624                  * nor can we be sure that we won't fall out of range.
10625                  */
10626                 if (rold->off != rcur->off)
10627                         return false;
10628                 /* id relations must be preserved */
10629                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10630                         return false;
10631                 /* new val must satisfy old val knowledge */
10632                 return range_within(rold, rcur) &&
10633                        tnum_in(rold->var_off, rcur->var_off);
10634         case PTR_TO_CTX:
10635         case CONST_PTR_TO_MAP:
10636         case PTR_TO_PACKET_END:
10637         case PTR_TO_FLOW_KEYS:
10638         case PTR_TO_SOCKET:
10639         case PTR_TO_SOCKET_OR_NULL:
10640         case PTR_TO_SOCK_COMMON:
10641         case PTR_TO_SOCK_COMMON_OR_NULL:
10642         case PTR_TO_TCP_SOCK:
10643         case PTR_TO_TCP_SOCK_OR_NULL:
10644         case PTR_TO_XDP_SOCK:
10645                 /* Only valid matches are exact, which memcmp() above
10646                  * would have accepted
10647                  */
10648         default:
10649                 /* Don't know what's going on, just say it's not safe */
10650                 return false;
10651         }
10652
10653         /* Shouldn't get here; if we do, say it's not safe */
10654         WARN_ON_ONCE(1);
10655         return false;
10656 }
10657
10658 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10659                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10660 {
10661         int i, spi;
10662
10663         /* walk slots of the explored stack and ignore any additional
10664          * slots in the current stack, since explored(safe) state
10665          * didn't use them
10666          */
10667         for (i = 0; i < old->allocated_stack; i++) {
10668                 spi = i / BPF_REG_SIZE;
10669
10670                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10671                         i += BPF_REG_SIZE - 1;
10672                         /* explored state didn't use this */
10673                         continue;
10674                 }
10675
10676                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10677                         continue;
10678
10679                 /* explored stack has more populated slots than current stack
10680                  * and these slots were used
10681                  */
10682                 if (i >= cur->allocated_stack)
10683                         return false;
10684
10685                 /* if old state was safe with misc data in the stack
10686                  * it will be safe with zero-initialized stack.
10687                  * The opposite is not true
10688                  */
10689                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10690                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10691                         continue;
10692                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10693                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10694                         /* Ex: old explored (safe) state has STACK_SPILL in
10695                          * this stack slot, but current has STACK_MISC ->
10696                          * this verifier states are not equivalent,
10697                          * return false to continue verification of this path
10698                          */
10699                         return false;
10700                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
10701                         continue;
10702                 if (!is_spilled_reg(&old->stack[spi]))
10703                         continue;
10704                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
10705                              &cur->stack[spi].spilled_ptr, idmap))
10706                         /* when explored and current stack slot are both storing
10707                          * spilled registers, check that stored pointers types
10708                          * are the same as well.
10709                          * Ex: explored safe path could have stored
10710                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10711                          * but current path has stored:
10712                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10713                          * such verifier states are not equivalent.
10714                          * return false to continue verification of this path
10715                          */
10716                         return false;
10717         }
10718         return true;
10719 }
10720
10721 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10722 {
10723         if (old->acquired_refs != cur->acquired_refs)
10724                 return false;
10725         return !memcmp(old->refs, cur->refs,
10726                        sizeof(*old->refs) * old->acquired_refs);
10727 }
10728
10729 /* compare two verifier states
10730  *
10731  * all states stored in state_list are known to be valid, since
10732  * verifier reached 'bpf_exit' instruction through them
10733  *
10734  * this function is called when verifier exploring different branches of
10735  * execution popped from the state stack. If it sees an old state that has
10736  * more strict register state and more strict stack state then this execution
10737  * branch doesn't need to be explored further, since verifier already
10738  * concluded that more strict state leads to valid finish.
10739  *
10740  * Therefore two states are equivalent if register state is more conservative
10741  * and explored stack state is more conservative than the current one.
10742  * Example:
10743  *       explored                   current
10744  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10745  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10746  *
10747  * In other words if current stack state (one being explored) has more
10748  * valid slots than old one that already passed validation, it means
10749  * the verifier can stop exploring and conclude that current state is valid too
10750  *
10751  * Similarly with registers. If explored state has register type as invalid
10752  * whereas register type in current state is meaningful, it means that
10753  * the current state will reach 'bpf_exit' instruction safely
10754  */
10755 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10756                               struct bpf_func_state *cur)
10757 {
10758         int i;
10759
10760         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10761         for (i = 0; i < MAX_BPF_REG; i++)
10762                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
10763                              env->idmap_scratch))
10764                         return false;
10765
10766         if (!stacksafe(env, old, cur, env->idmap_scratch))
10767                 return false;
10768
10769         if (!refsafe(old, cur))
10770                 return false;
10771
10772         return true;
10773 }
10774
10775 static bool states_equal(struct bpf_verifier_env *env,
10776                          struct bpf_verifier_state *old,
10777                          struct bpf_verifier_state *cur)
10778 {
10779         int i;
10780
10781         if (old->curframe != cur->curframe)
10782                 return false;
10783
10784         /* Verification state from speculative execution simulation
10785          * must never prune a non-speculative execution one.
10786          */
10787         if (old->speculative && !cur->speculative)
10788                 return false;
10789
10790         if (old->active_spin_lock != cur->active_spin_lock)
10791                 return false;
10792
10793         /* for states to be equal callsites have to be the same
10794          * and all frame states need to be equivalent
10795          */
10796         for (i = 0; i <= old->curframe; i++) {
10797                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10798                         return false;
10799                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10800                         return false;
10801         }
10802         return true;
10803 }
10804
10805 /* Return 0 if no propagation happened. Return negative error code if error
10806  * happened. Otherwise, return the propagated bit.
10807  */
10808 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10809                                   struct bpf_reg_state *reg,
10810                                   struct bpf_reg_state *parent_reg)
10811 {
10812         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10813         u8 flag = reg->live & REG_LIVE_READ;
10814         int err;
10815
10816         /* When comes here, read flags of PARENT_REG or REG could be any of
10817          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10818          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10819          */
10820         if (parent_flag == REG_LIVE_READ64 ||
10821             /* Or if there is no read flag from REG. */
10822             !flag ||
10823             /* Or if the read flag from REG is the same as PARENT_REG. */
10824             parent_flag == flag)
10825                 return 0;
10826
10827         err = mark_reg_read(env, reg, parent_reg, flag);
10828         if (err)
10829                 return err;
10830
10831         return flag;
10832 }
10833
10834 /* A write screens off any subsequent reads; but write marks come from the
10835  * straight-line code between a state and its parent.  When we arrive at an
10836  * equivalent state (jump target or such) we didn't arrive by the straight-line
10837  * code, so read marks in the state must propagate to the parent regardless
10838  * of the state's write marks. That's what 'parent == state->parent' comparison
10839  * in mark_reg_read() is for.
10840  */
10841 static int propagate_liveness(struct bpf_verifier_env *env,
10842                               const struct bpf_verifier_state *vstate,
10843                               struct bpf_verifier_state *vparent)
10844 {
10845         struct bpf_reg_state *state_reg, *parent_reg;
10846         struct bpf_func_state *state, *parent;
10847         int i, frame, err = 0;
10848
10849         if (vparent->curframe != vstate->curframe) {
10850                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10851                      vparent->curframe, vstate->curframe);
10852                 return -EFAULT;
10853         }
10854         /* Propagate read liveness of registers... */
10855         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10856         for (frame = 0; frame <= vstate->curframe; frame++) {
10857                 parent = vparent->frame[frame];
10858                 state = vstate->frame[frame];
10859                 parent_reg = parent->regs;
10860                 state_reg = state->regs;
10861                 /* We don't need to worry about FP liveness, it's read-only */
10862                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10863                         err = propagate_liveness_reg(env, &state_reg[i],
10864                                                      &parent_reg[i]);
10865                         if (err < 0)
10866                                 return err;
10867                         if (err == REG_LIVE_READ64)
10868                                 mark_insn_zext(env, &parent_reg[i]);
10869                 }
10870
10871                 /* Propagate stack slots. */
10872                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10873                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10874                         parent_reg = &parent->stack[i].spilled_ptr;
10875                         state_reg = &state->stack[i].spilled_ptr;
10876                         err = propagate_liveness_reg(env, state_reg,
10877                                                      parent_reg);
10878                         if (err < 0)
10879                                 return err;
10880                 }
10881         }
10882         return 0;
10883 }
10884
10885 /* find precise scalars in the previous equivalent state and
10886  * propagate them into the current state
10887  */
10888 static int propagate_precision(struct bpf_verifier_env *env,
10889                                const struct bpf_verifier_state *old)
10890 {
10891         struct bpf_reg_state *state_reg;
10892         struct bpf_func_state *state;
10893         int i, err = 0;
10894
10895         state = old->frame[old->curframe];
10896         state_reg = state->regs;
10897         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10898                 if (state_reg->type != SCALAR_VALUE ||
10899                     !state_reg->precise)
10900                         continue;
10901                 if (env->log.level & BPF_LOG_LEVEL2)
10902                         verbose(env, "propagating r%d\n", i);
10903                 err = mark_chain_precision(env, i);
10904                 if (err < 0)
10905                         return err;
10906         }
10907
10908         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10909                 if (!is_spilled_reg(&state->stack[i]))
10910                         continue;
10911                 state_reg = &state->stack[i].spilled_ptr;
10912                 if (state_reg->type != SCALAR_VALUE ||
10913                     !state_reg->precise)
10914                         continue;
10915                 if (env->log.level & BPF_LOG_LEVEL2)
10916                         verbose(env, "propagating fp%d\n",
10917                                 (-i - 1) * BPF_REG_SIZE);
10918                 err = mark_chain_precision_stack(env, i);
10919                 if (err < 0)
10920                         return err;
10921         }
10922         return 0;
10923 }
10924
10925 static bool states_maybe_looping(struct bpf_verifier_state *old,
10926                                  struct bpf_verifier_state *cur)
10927 {
10928         struct bpf_func_state *fold, *fcur;
10929         int i, fr = cur->curframe;
10930
10931         if (old->curframe != fr)
10932                 return false;
10933
10934         fold = old->frame[fr];
10935         fcur = cur->frame[fr];
10936         for (i = 0; i < MAX_BPF_REG; i++)
10937                 if (memcmp(&fold->regs[i], &fcur->regs[i],
10938                            offsetof(struct bpf_reg_state, parent)))
10939                         return false;
10940         return true;
10941 }
10942
10943
10944 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10945 {
10946         struct bpf_verifier_state_list *new_sl;
10947         struct bpf_verifier_state_list *sl, **pprev;
10948         struct bpf_verifier_state *cur = env->cur_state, *new;
10949         int i, j, err, states_cnt = 0;
10950         bool add_new_state = env->test_state_freq ? true : false;
10951
10952         cur->last_insn_idx = env->prev_insn_idx;
10953         if (!env->insn_aux_data[insn_idx].prune_point)
10954                 /* this 'insn_idx' instruction wasn't marked, so we will not
10955                  * be doing state search here
10956                  */
10957                 return 0;
10958
10959         /* bpf progs typically have pruning point every 4 instructions
10960          * http://vger.kernel.org/bpfconf2019.html#session-1
10961          * Do not add new state for future pruning if the verifier hasn't seen
10962          * at least 2 jumps and at least 8 instructions.
10963          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10964          * In tests that amounts to up to 50% reduction into total verifier
10965          * memory consumption and 20% verifier time speedup.
10966          */
10967         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10968             env->insn_processed - env->prev_insn_processed >= 8)
10969                 add_new_state = true;
10970
10971         pprev = explored_state(env, insn_idx);
10972         sl = *pprev;
10973
10974         clean_live_states(env, insn_idx, cur);
10975
10976         while (sl) {
10977                 states_cnt++;
10978                 if (sl->state.insn_idx != insn_idx)
10979                         goto next;
10980
10981                 if (sl->state.branches) {
10982                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
10983
10984                         if (frame->in_async_callback_fn &&
10985                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
10986                                 /* Different async_entry_cnt means that the verifier is
10987                                  * processing another entry into async callback.
10988                                  * Seeing the same state is not an indication of infinite
10989                                  * loop or infinite recursion.
10990                                  * But finding the same state doesn't mean that it's safe
10991                                  * to stop processing the current state. The previous state
10992                                  * hasn't yet reached bpf_exit, since state.branches > 0.
10993                                  * Checking in_async_callback_fn alone is not enough either.
10994                                  * Since the verifier still needs to catch infinite loops
10995                                  * inside async callbacks.
10996                                  */
10997                         } else if (states_maybe_looping(&sl->state, cur) &&
10998                                    states_equal(env, &sl->state, cur)) {
10999                                 verbose_linfo(env, insn_idx, "; ");
11000                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11001                                 return -EINVAL;
11002                         }
11003                         /* if the verifier is processing a loop, avoid adding new state
11004                          * too often, since different loop iterations have distinct
11005                          * states and may not help future pruning.
11006                          * This threshold shouldn't be too low to make sure that
11007                          * a loop with large bound will be rejected quickly.
11008                          * The most abusive loop will be:
11009                          * r1 += 1
11010                          * if r1 < 1000000 goto pc-2
11011                          * 1M insn_procssed limit / 100 == 10k peak states.
11012                          * This threshold shouldn't be too high either, since states
11013                          * at the end of the loop are likely to be useful in pruning.
11014                          */
11015                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11016                             env->insn_processed - env->prev_insn_processed < 100)
11017                                 add_new_state = false;
11018                         goto miss;
11019                 }
11020                 if (states_equal(env, &sl->state, cur)) {
11021                         sl->hit_cnt++;
11022                         /* reached equivalent register/stack state,
11023                          * prune the search.
11024                          * Registers read by the continuation are read by us.
11025                          * If we have any write marks in env->cur_state, they
11026                          * will prevent corresponding reads in the continuation
11027                          * from reaching our parent (an explored_state).  Our
11028                          * own state will get the read marks recorded, but
11029                          * they'll be immediately forgotten as we're pruning
11030                          * this state and will pop a new one.
11031                          */
11032                         err = propagate_liveness(env, &sl->state, cur);
11033
11034                         /* if previous state reached the exit with precision and
11035                          * current state is equivalent to it (except precsion marks)
11036                          * the precision needs to be propagated back in
11037                          * the current state.
11038                          */
11039                         err = err ? : push_jmp_history(env, cur);
11040                         err = err ? : propagate_precision(env, &sl->state);
11041                         if (err)
11042                                 return err;
11043                         return 1;
11044                 }
11045 miss:
11046                 /* when new state is not going to be added do not increase miss count.
11047                  * Otherwise several loop iterations will remove the state
11048                  * recorded earlier. The goal of these heuristics is to have
11049                  * states from some iterations of the loop (some in the beginning
11050                  * and some at the end) to help pruning.
11051                  */
11052                 if (add_new_state)
11053                         sl->miss_cnt++;
11054                 /* heuristic to determine whether this state is beneficial
11055                  * to keep checking from state equivalence point of view.
11056                  * Higher numbers increase max_states_per_insn and verification time,
11057                  * but do not meaningfully decrease insn_processed.
11058                  */
11059                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
11060                         /* the state is unlikely to be useful. Remove it to
11061                          * speed up verification
11062                          */
11063                         *pprev = sl->next;
11064                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
11065                                 u32 br = sl->state.branches;
11066
11067                                 WARN_ONCE(br,
11068                                           "BUG live_done but branches_to_explore %d\n",
11069                                           br);
11070                                 free_verifier_state(&sl->state, false);
11071                                 kfree(sl);
11072                                 env->peak_states--;
11073                         } else {
11074                                 /* cannot free this state, since parentage chain may
11075                                  * walk it later. Add it for free_list instead to
11076                                  * be freed at the end of verification
11077                                  */
11078                                 sl->next = env->free_list;
11079                                 env->free_list = sl;
11080                         }
11081                         sl = *pprev;
11082                         continue;
11083                 }
11084 next:
11085                 pprev = &sl->next;
11086                 sl = *pprev;
11087         }
11088
11089         if (env->max_states_per_insn < states_cnt)
11090                 env->max_states_per_insn = states_cnt;
11091
11092         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
11093                 return push_jmp_history(env, cur);
11094
11095         if (!add_new_state)
11096                 return push_jmp_history(env, cur);
11097
11098         /* There were no equivalent states, remember the current one.
11099          * Technically the current state is not proven to be safe yet,
11100          * but it will either reach outer most bpf_exit (which means it's safe)
11101          * or it will be rejected. When there are no loops the verifier won't be
11102          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
11103          * again on the way to bpf_exit.
11104          * When looping the sl->state.branches will be > 0 and this state
11105          * will not be considered for equivalence until branches == 0.
11106          */
11107         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
11108         if (!new_sl)
11109                 return -ENOMEM;
11110         env->total_states++;
11111         env->peak_states++;
11112         env->prev_jmps_processed = env->jmps_processed;
11113         env->prev_insn_processed = env->insn_processed;
11114
11115         /* add new state to the head of linked list */
11116         new = &new_sl->state;
11117         err = copy_verifier_state(new, cur);
11118         if (err) {
11119                 free_verifier_state(new, false);
11120                 kfree(new_sl);
11121                 return err;
11122         }
11123         new->insn_idx = insn_idx;
11124         WARN_ONCE(new->branches != 1,
11125                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
11126
11127         cur->parent = new;
11128         cur->first_insn_idx = insn_idx;
11129         clear_jmp_history(cur);
11130         new_sl->next = *explored_state(env, insn_idx);
11131         *explored_state(env, insn_idx) = new_sl;
11132         /* connect new state to parentage chain. Current frame needs all
11133          * registers connected. Only r6 - r9 of the callers are alive (pushed
11134          * to the stack implicitly by JITs) so in callers' frames connect just
11135          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
11136          * the state of the call instruction (with WRITTEN set), and r0 comes
11137          * from callee with its full parentage chain, anyway.
11138          */
11139         /* clear write marks in current state: the writes we did are not writes
11140          * our child did, so they don't screen off its reads from us.
11141          * (There are no read marks in current state, because reads always mark
11142          * their parent and current state never has children yet.  Only
11143          * explored_states can get read marks.)
11144          */
11145         for (j = 0; j <= cur->curframe; j++) {
11146                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
11147                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
11148                 for (i = 0; i < BPF_REG_FP; i++)
11149                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
11150         }
11151
11152         /* all stack frames are accessible from callee, clear them all */
11153         for (j = 0; j <= cur->curframe; j++) {
11154                 struct bpf_func_state *frame = cur->frame[j];
11155                 struct bpf_func_state *newframe = new->frame[j];
11156
11157                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
11158                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
11159                         frame->stack[i].spilled_ptr.parent =
11160                                                 &newframe->stack[i].spilled_ptr;
11161                 }
11162         }
11163         return 0;
11164 }
11165
11166 /* Return true if it's OK to have the same insn return a different type. */
11167 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
11168 {
11169         switch (type) {
11170         case PTR_TO_CTX:
11171         case PTR_TO_SOCKET:
11172         case PTR_TO_SOCKET_OR_NULL:
11173         case PTR_TO_SOCK_COMMON:
11174         case PTR_TO_SOCK_COMMON_OR_NULL:
11175         case PTR_TO_TCP_SOCK:
11176         case PTR_TO_TCP_SOCK_OR_NULL:
11177         case PTR_TO_XDP_SOCK:
11178         case PTR_TO_BTF_ID:
11179         case PTR_TO_BTF_ID_OR_NULL:
11180                 return false;
11181         default:
11182                 return true;
11183         }
11184 }
11185
11186 /* If an instruction was previously used with particular pointer types, then we
11187  * need to be careful to avoid cases such as the below, where it may be ok
11188  * for one branch accessing the pointer, but not ok for the other branch:
11189  *
11190  * R1 = sock_ptr
11191  * goto X;
11192  * ...
11193  * R1 = some_other_valid_ptr;
11194  * goto X;
11195  * ...
11196  * R2 = *(u32 *)(R1 + 0);
11197  */
11198 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
11199 {
11200         return src != prev && (!reg_type_mismatch_ok(src) ||
11201                                !reg_type_mismatch_ok(prev));
11202 }
11203
11204 static int do_check(struct bpf_verifier_env *env)
11205 {
11206         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11207         struct bpf_verifier_state *state = env->cur_state;
11208         struct bpf_insn *insns = env->prog->insnsi;
11209         struct bpf_reg_state *regs;
11210         int insn_cnt = env->prog->len;
11211         bool do_print_state = false;
11212         int prev_insn_idx = -1;
11213
11214         for (;;) {
11215                 struct bpf_insn *insn;
11216                 u8 class;
11217                 int err;
11218
11219                 env->prev_insn_idx = prev_insn_idx;
11220                 if (env->insn_idx >= insn_cnt) {
11221                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
11222                                 env->insn_idx, insn_cnt);
11223                         return -EFAULT;
11224                 }
11225
11226                 insn = &insns[env->insn_idx];
11227                 class = BPF_CLASS(insn->code);
11228
11229                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
11230                         verbose(env,
11231                                 "BPF program is too large. Processed %d insn\n",
11232                                 env->insn_processed);
11233                         return -E2BIG;
11234                 }
11235
11236                 err = is_state_visited(env, env->insn_idx);
11237                 if (err < 0)
11238                         return err;
11239                 if (err == 1) {
11240                         /* found equivalent state, can prune the search */
11241                         if (env->log.level & BPF_LOG_LEVEL) {
11242                                 if (do_print_state)
11243                                         verbose(env, "\nfrom %d to %d%s: safe\n",
11244                                                 env->prev_insn_idx, env->insn_idx,
11245                                                 env->cur_state->speculative ?
11246                                                 " (speculative execution)" : "");
11247                                 else
11248                                         verbose(env, "%d: safe\n", env->insn_idx);
11249                         }
11250                         goto process_bpf_exit;
11251                 }
11252
11253                 if (signal_pending(current))
11254                         return -EAGAIN;
11255
11256                 if (need_resched())
11257                         cond_resched();
11258
11259                 if (env->log.level & BPF_LOG_LEVEL2 ||
11260                     (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
11261                         if (env->log.level & BPF_LOG_LEVEL2)
11262                                 verbose(env, "%d:", env->insn_idx);
11263                         else
11264                                 verbose(env, "\nfrom %d to %d%s:",
11265                                         env->prev_insn_idx, env->insn_idx,
11266                                         env->cur_state->speculative ?
11267                                         " (speculative execution)" : "");
11268                         print_verifier_state(env, state->frame[state->curframe]);
11269                         do_print_state = false;
11270                 }
11271
11272                 if (env->log.level & BPF_LOG_LEVEL) {
11273                         const struct bpf_insn_cbs cbs = {
11274                                 .cb_call        = disasm_kfunc_name,
11275                                 .cb_print       = verbose,
11276                                 .private_data   = env,
11277                         };
11278
11279                         verbose_linfo(env, env->insn_idx, "; ");
11280                         verbose(env, "%d: ", env->insn_idx);
11281                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
11282                 }
11283
11284                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
11285                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
11286                                                            env->prev_insn_idx);
11287                         if (err)
11288                                 return err;
11289                 }
11290
11291                 regs = cur_regs(env);
11292                 sanitize_mark_insn_seen(env);
11293                 prev_insn_idx = env->insn_idx;
11294
11295                 if (class == BPF_ALU || class == BPF_ALU64) {
11296                         err = check_alu_op(env, insn);
11297                         if (err)
11298                                 return err;
11299
11300                 } else if (class == BPF_LDX) {
11301                         enum bpf_reg_type *prev_src_type, src_reg_type;
11302
11303                         /* check for reserved fields is already done */
11304
11305                         /* check src operand */
11306                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
11307                         if (err)
11308                                 return err;
11309
11310                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11311                         if (err)
11312                                 return err;
11313
11314                         src_reg_type = regs[insn->src_reg].type;
11315
11316                         /* check that memory (src_reg + off) is readable,
11317                          * the state of dst_reg will be updated by this func
11318                          */
11319                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
11320                                                insn->off, BPF_SIZE(insn->code),
11321                                                BPF_READ, insn->dst_reg, false);
11322                         if (err)
11323                                 return err;
11324
11325                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11326
11327                         if (*prev_src_type == NOT_INIT) {
11328                                 /* saw a valid insn
11329                                  * dst_reg = *(u32 *)(src_reg + off)
11330                                  * save type to validate intersecting paths
11331                                  */
11332                                 *prev_src_type = src_reg_type;
11333
11334                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11335                                 /* ABuser program is trying to use the same insn
11336                                  * dst_reg = *(u32*) (src_reg + off)
11337                                  * with different pointer types:
11338                                  * src_reg == ctx in one branch and
11339                                  * src_reg == stack|map in some other branch.
11340                                  * Reject it.
11341                                  */
11342                                 verbose(env, "same insn cannot be used with different pointers\n");
11343                                 return -EINVAL;
11344                         }
11345
11346                 } else if (class == BPF_STX) {
11347                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
11348
11349                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11350                                 err = check_atomic(env, env->insn_idx, insn);
11351                                 if (err)
11352                                         return err;
11353                                 env->insn_idx++;
11354                                 continue;
11355                         }
11356
11357                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11358                                 verbose(env, "BPF_STX uses reserved fields\n");
11359                                 return -EINVAL;
11360                         }
11361
11362                         /* check src1 operand */
11363                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
11364                         if (err)
11365                                 return err;
11366                         /* check src2 operand */
11367                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11368                         if (err)
11369                                 return err;
11370
11371                         dst_reg_type = regs[insn->dst_reg].type;
11372
11373                         /* check that memory (dst_reg + off) is writeable */
11374                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11375                                                insn->off, BPF_SIZE(insn->code),
11376                                                BPF_WRITE, insn->src_reg, false);
11377                         if (err)
11378                                 return err;
11379
11380                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11381
11382                         if (*prev_dst_type == NOT_INIT) {
11383                                 *prev_dst_type = dst_reg_type;
11384                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11385                                 verbose(env, "same insn cannot be used with different pointers\n");
11386                                 return -EINVAL;
11387                         }
11388
11389                 } else if (class == BPF_ST) {
11390                         if (BPF_MODE(insn->code) != BPF_MEM ||
11391                             insn->src_reg != BPF_REG_0) {
11392                                 verbose(env, "BPF_ST uses reserved fields\n");
11393                                 return -EINVAL;
11394                         }
11395                         /* check src operand */
11396                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11397                         if (err)
11398                                 return err;
11399
11400                         if (is_ctx_reg(env, insn->dst_reg)) {
11401                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11402                                         insn->dst_reg,
11403                                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
11404                                 return -EACCES;
11405                         }
11406
11407                         /* check that memory (dst_reg + off) is writeable */
11408                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11409                                                insn->off, BPF_SIZE(insn->code),
11410                                                BPF_WRITE, -1, false);
11411                         if (err)
11412                                 return err;
11413
11414                 } else if (class == BPF_JMP || class == BPF_JMP32) {
11415                         u8 opcode = BPF_OP(insn->code);
11416
11417                         env->jmps_processed++;
11418                         if (opcode == BPF_CALL) {
11419                                 if (BPF_SRC(insn->code) != BPF_K ||
11420                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
11421                                      && insn->off != 0) ||
11422                                     (insn->src_reg != BPF_REG_0 &&
11423                                      insn->src_reg != BPF_PSEUDO_CALL &&
11424                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11425                                     insn->dst_reg != BPF_REG_0 ||
11426                                     class == BPF_JMP32) {
11427                                         verbose(env, "BPF_CALL uses reserved fields\n");
11428                                         return -EINVAL;
11429                                 }
11430
11431                                 if (env->cur_state->active_spin_lock &&
11432                                     (insn->src_reg == BPF_PSEUDO_CALL ||
11433                                      insn->imm != BPF_FUNC_spin_unlock)) {
11434                                         verbose(env, "function calls are not allowed while holding a lock\n");
11435                                         return -EINVAL;
11436                                 }
11437                                 if (insn->src_reg == BPF_PSEUDO_CALL)
11438                                         err = check_func_call(env, insn, &env->insn_idx);
11439                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11440                                         err = check_kfunc_call(env, insn);
11441                                 else
11442                                         err = check_helper_call(env, insn, &env->insn_idx);
11443                                 if (err)
11444                                         return err;
11445                         } else if (opcode == BPF_JA) {
11446                                 if (BPF_SRC(insn->code) != BPF_K ||
11447                                     insn->imm != 0 ||
11448                                     insn->src_reg != BPF_REG_0 ||
11449                                     insn->dst_reg != BPF_REG_0 ||
11450                                     class == BPF_JMP32) {
11451                                         verbose(env, "BPF_JA uses reserved fields\n");
11452                                         return -EINVAL;
11453                                 }
11454
11455                                 env->insn_idx += insn->off + 1;
11456                                 continue;
11457
11458                         } else if (opcode == BPF_EXIT) {
11459                                 if (BPF_SRC(insn->code) != BPF_K ||
11460                                     insn->imm != 0 ||
11461                                     insn->src_reg != BPF_REG_0 ||
11462                                     insn->dst_reg != BPF_REG_0 ||
11463                                     class == BPF_JMP32) {
11464                                         verbose(env, "BPF_EXIT uses reserved fields\n");
11465                                         return -EINVAL;
11466                                 }
11467
11468                                 if (env->cur_state->active_spin_lock) {
11469                                         verbose(env, "bpf_spin_unlock is missing\n");
11470                                         return -EINVAL;
11471                                 }
11472
11473                                 if (state->curframe) {
11474                                         /* exit from nested function */
11475                                         err = prepare_func_exit(env, &env->insn_idx);
11476                                         if (err)
11477                                                 return err;
11478                                         do_print_state = true;
11479                                         continue;
11480                                 }
11481
11482                                 err = check_reference_leak(env);
11483                                 if (err)
11484                                         return err;
11485
11486                                 err = check_return_code(env);
11487                                 if (err)
11488                                         return err;
11489 process_bpf_exit:
11490                                 update_branch_counts(env, env->cur_state);
11491                                 err = pop_stack(env, &prev_insn_idx,
11492                                                 &env->insn_idx, pop_log);
11493                                 if (err < 0) {
11494                                         if (err != -ENOENT)
11495                                                 return err;
11496                                         break;
11497                                 } else {
11498                                         do_print_state = true;
11499                                         continue;
11500                                 }
11501                         } else {
11502                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
11503                                 if (err)
11504                                         return err;
11505                         }
11506                 } else if (class == BPF_LD) {
11507                         u8 mode = BPF_MODE(insn->code);
11508
11509                         if (mode == BPF_ABS || mode == BPF_IND) {
11510                                 err = check_ld_abs(env, insn);
11511                                 if (err)
11512                                         return err;
11513
11514                         } else if (mode == BPF_IMM) {
11515                                 err = check_ld_imm(env, insn);
11516                                 if (err)
11517                                         return err;
11518
11519                                 env->insn_idx++;
11520                                 sanitize_mark_insn_seen(env);
11521                         } else {
11522                                 verbose(env, "invalid BPF_LD mode\n");
11523                                 return -EINVAL;
11524                         }
11525                 } else {
11526                         verbose(env, "unknown insn class %d\n", class);
11527                         return -EINVAL;
11528                 }
11529
11530                 env->insn_idx++;
11531         }
11532
11533         return 0;
11534 }
11535
11536 static int find_btf_percpu_datasec(struct btf *btf)
11537 {
11538         const struct btf_type *t;
11539         const char *tname;
11540         int i, n;
11541
11542         /*
11543          * Both vmlinux and module each have their own ".data..percpu"
11544          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11545          * types to look at only module's own BTF types.
11546          */
11547         n = btf_nr_types(btf);
11548         if (btf_is_module(btf))
11549                 i = btf_nr_types(btf_vmlinux);
11550         else
11551                 i = 1;
11552
11553         for(; i < n; i++) {
11554                 t = btf_type_by_id(btf, i);
11555                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11556                         continue;
11557
11558                 tname = btf_name_by_offset(btf, t->name_off);
11559                 if (!strcmp(tname, ".data..percpu"))
11560                         return i;
11561         }
11562
11563         return -ENOENT;
11564 }
11565
11566 /* replace pseudo btf_id with kernel symbol address */
11567 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11568                                struct bpf_insn *insn,
11569                                struct bpf_insn_aux_data *aux)
11570 {
11571         const struct btf_var_secinfo *vsi;
11572         const struct btf_type *datasec;
11573         struct btf_mod_pair *btf_mod;
11574         const struct btf_type *t;
11575         const char *sym_name;
11576         bool percpu = false;
11577         u32 type, id = insn->imm;
11578         struct btf *btf;
11579         s32 datasec_id;
11580         u64 addr;
11581         int i, btf_fd, err;
11582
11583         btf_fd = insn[1].imm;
11584         if (btf_fd) {
11585                 btf = btf_get_by_fd(btf_fd);
11586                 if (IS_ERR(btf)) {
11587                         verbose(env, "invalid module BTF object FD specified.\n");
11588                         return -EINVAL;
11589                 }
11590         } else {
11591                 if (!btf_vmlinux) {
11592                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11593                         return -EINVAL;
11594                 }
11595                 btf = btf_vmlinux;
11596                 btf_get(btf);
11597         }
11598
11599         t = btf_type_by_id(btf, id);
11600         if (!t) {
11601                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11602                 err = -ENOENT;
11603                 goto err_put;
11604         }
11605
11606         if (!btf_type_is_var(t)) {
11607                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11608                 err = -EINVAL;
11609                 goto err_put;
11610         }
11611
11612         sym_name = btf_name_by_offset(btf, t->name_off);
11613         addr = kallsyms_lookup_name(sym_name);
11614         if (!addr) {
11615                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11616                         sym_name);
11617                 err = -ENOENT;
11618                 goto err_put;
11619         }
11620
11621         datasec_id = find_btf_percpu_datasec(btf);
11622         if (datasec_id > 0) {
11623                 datasec = btf_type_by_id(btf, datasec_id);
11624                 for_each_vsi(i, datasec, vsi) {
11625                         if (vsi->type == id) {
11626                                 percpu = true;
11627                                 break;
11628                         }
11629                 }
11630         }
11631
11632         insn[0].imm = (u32)addr;
11633         insn[1].imm = addr >> 32;
11634
11635         type = t->type;
11636         t = btf_type_skip_modifiers(btf, type, NULL);
11637         if (percpu) {
11638                 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11639                 aux->btf_var.btf = btf;
11640                 aux->btf_var.btf_id = type;
11641         } else if (!btf_type_is_struct(t)) {
11642                 const struct btf_type *ret;
11643                 const char *tname;
11644                 u32 tsize;
11645
11646                 /* resolve the type size of ksym. */
11647                 ret = btf_resolve_size(btf, t, &tsize);
11648                 if (IS_ERR(ret)) {
11649                         tname = btf_name_by_offset(btf, t->name_off);
11650                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11651                                 tname, PTR_ERR(ret));
11652                         err = -EINVAL;
11653                         goto err_put;
11654                 }
11655                 aux->btf_var.reg_type = PTR_TO_MEM;
11656                 aux->btf_var.mem_size = tsize;
11657         } else {
11658                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
11659                 aux->btf_var.btf = btf;
11660                 aux->btf_var.btf_id = type;
11661         }
11662
11663         /* check whether we recorded this BTF (and maybe module) already */
11664         for (i = 0; i < env->used_btf_cnt; i++) {
11665                 if (env->used_btfs[i].btf == btf) {
11666                         btf_put(btf);
11667                         return 0;
11668                 }
11669         }
11670
11671         if (env->used_btf_cnt >= MAX_USED_BTFS) {
11672                 err = -E2BIG;
11673                 goto err_put;
11674         }
11675
11676         btf_mod = &env->used_btfs[env->used_btf_cnt];
11677         btf_mod->btf = btf;
11678         btf_mod->module = NULL;
11679
11680         /* if we reference variables from kernel module, bump its refcount */
11681         if (btf_is_module(btf)) {
11682                 btf_mod->module = btf_try_get_module(btf);
11683                 if (!btf_mod->module) {
11684                         err = -ENXIO;
11685                         goto err_put;
11686                 }
11687         }
11688
11689         env->used_btf_cnt++;
11690
11691         return 0;
11692 err_put:
11693         btf_put(btf);
11694         return err;
11695 }
11696
11697 static int check_map_prealloc(struct bpf_map *map)
11698 {
11699         return (map->map_type != BPF_MAP_TYPE_HASH &&
11700                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11701                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11702                 !(map->map_flags & BPF_F_NO_PREALLOC);
11703 }
11704
11705 static bool is_tracing_prog_type(enum bpf_prog_type type)
11706 {
11707         switch (type) {
11708         case BPF_PROG_TYPE_KPROBE:
11709         case BPF_PROG_TYPE_TRACEPOINT:
11710         case BPF_PROG_TYPE_PERF_EVENT:
11711         case BPF_PROG_TYPE_RAW_TRACEPOINT:
11712                 return true;
11713         default:
11714                 return false;
11715         }
11716 }
11717
11718 static bool is_preallocated_map(struct bpf_map *map)
11719 {
11720         if (!check_map_prealloc(map))
11721                 return false;
11722         if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11723                 return false;
11724         return true;
11725 }
11726
11727 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11728                                         struct bpf_map *map,
11729                                         struct bpf_prog *prog)
11730
11731 {
11732         enum bpf_prog_type prog_type = resolve_prog_type(prog);
11733         /*
11734          * Validate that trace type programs use preallocated hash maps.
11735          *
11736          * For programs attached to PERF events this is mandatory as the
11737          * perf NMI can hit any arbitrary code sequence.
11738          *
11739          * All other trace types using preallocated hash maps are unsafe as
11740          * well because tracepoint or kprobes can be inside locked regions
11741          * of the memory allocator or at a place where a recursion into the
11742          * memory allocator would see inconsistent state.
11743          *
11744          * On RT enabled kernels run-time allocation of all trace type
11745          * programs is strictly prohibited due to lock type constraints. On
11746          * !RT kernels it is allowed for backwards compatibility reasons for
11747          * now, but warnings are emitted so developers are made aware of
11748          * the unsafety and can fix their programs before this is enforced.
11749          */
11750         if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11751                 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11752                         verbose(env, "perf_event programs can only use preallocated hash map\n");
11753                         return -EINVAL;
11754                 }
11755                 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11756                         verbose(env, "trace type programs can only use preallocated hash map\n");
11757                         return -EINVAL;
11758                 }
11759                 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11760                 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11761         }
11762
11763         if (map_value_has_spin_lock(map)) {
11764                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11765                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11766                         return -EINVAL;
11767                 }
11768
11769                 if (is_tracing_prog_type(prog_type)) {
11770                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11771                         return -EINVAL;
11772                 }
11773
11774                 if (prog->aux->sleepable) {
11775                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11776                         return -EINVAL;
11777                 }
11778         }
11779
11780         if (map_value_has_timer(map)) {
11781                 if (is_tracing_prog_type(prog_type)) {
11782                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
11783                         return -EINVAL;
11784                 }
11785         }
11786
11787         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11788             !bpf_offload_prog_map_match(prog, map)) {
11789                 verbose(env, "offload device mismatch between prog and map\n");
11790                 return -EINVAL;
11791         }
11792
11793         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11794                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11795                 return -EINVAL;
11796         }
11797
11798         if (prog->aux->sleepable)
11799                 switch (map->map_type) {
11800                 case BPF_MAP_TYPE_HASH:
11801                 case BPF_MAP_TYPE_LRU_HASH:
11802                 case BPF_MAP_TYPE_ARRAY:
11803                 case BPF_MAP_TYPE_PERCPU_HASH:
11804                 case BPF_MAP_TYPE_PERCPU_ARRAY:
11805                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11806                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11807                 case BPF_MAP_TYPE_HASH_OF_MAPS:
11808                         if (!is_preallocated_map(map)) {
11809                                 verbose(env,
11810                                         "Sleepable programs can only use preallocated maps\n");
11811                                 return -EINVAL;
11812                         }
11813                         break;
11814                 case BPF_MAP_TYPE_RINGBUF:
11815                         break;
11816                 default:
11817                         verbose(env,
11818                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
11819                         return -EINVAL;
11820                 }
11821
11822         return 0;
11823 }
11824
11825 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11826 {
11827         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11828                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11829 }
11830
11831 /* find and rewrite pseudo imm in ld_imm64 instructions:
11832  *
11833  * 1. if it accesses map FD, replace it with actual map pointer.
11834  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11835  *
11836  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11837  */
11838 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11839 {
11840         struct bpf_insn *insn = env->prog->insnsi;
11841         int insn_cnt = env->prog->len;
11842         int i, j, err;
11843
11844         err = bpf_prog_calc_tag(env->prog);
11845         if (err)
11846                 return err;
11847
11848         for (i = 0; i < insn_cnt; i++, insn++) {
11849                 if (BPF_CLASS(insn->code) == BPF_LDX &&
11850                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11851                         verbose(env, "BPF_LDX uses reserved fields\n");
11852                         return -EINVAL;
11853                 }
11854
11855                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11856                         struct bpf_insn_aux_data *aux;
11857                         struct bpf_map *map;
11858                         struct fd f;
11859                         u64 addr;
11860                         u32 fd;
11861
11862                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
11863                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11864                             insn[1].off != 0) {
11865                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
11866                                 return -EINVAL;
11867                         }
11868
11869                         if (insn[0].src_reg == 0)
11870                                 /* valid generic load 64-bit imm */
11871                                 goto next_insn;
11872
11873                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11874                                 aux = &env->insn_aux_data[i];
11875                                 err = check_pseudo_btf_id(env, insn, aux);
11876                                 if (err)
11877                                         return err;
11878                                 goto next_insn;
11879                         }
11880
11881                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11882                                 aux = &env->insn_aux_data[i];
11883                                 aux->ptr_type = PTR_TO_FUNC;
11884                                 goto next_insn;
11885                         }
11886
11887                         /* In final convert_pseudo_ld_imm64() step, this is
11888                          * converted into regular 64-bit imm load insn.
11889                          */
11890                         switch (insn[0].src_reg) {
11891                         case BPF_PSEUDO_MAP_VALUE:
11892                         case BPF_PSEUDO_MAP_IDX_VALUE:
11893                                 break;
11894                         case BPF_PSEUDO_MAP_FD:
11895                         case BPF_PSEUDO_MAP_IDX:
11896                                 if (insn[1].imm == 0)
11897                                         break;
11898                                 fallthrough;
11899                         default:
11900                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11901                                 return -EINVAL;
11902                         }
11903
11904                         switch (insn[0].src_reg) {
11905                         case BPF_PSEUDO_MAP_IDX_VALUE:
11906                         case BPF_PSEUDO_MAP_IDX:
11907                                 if (bpfptr_is_null(env->fd_array)) {
11908                                         verbose(env, "fd_idx without fd_array is invalid\n");
11909                                         return -EPROTO;
11910                                 }
11911                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
11912                                                             insn[0].imm * sizeof(fd),
11913                                                             sizeof(fd)))
11914                                         return -EFAULT;
11915                                 break;
11916                         default:
11917                                 fd = insn[0].imm;
11918                                 break;
11919                         }
11920
11921                         f = fdget(fd);
11922                         map = __bpf_map_get(f);
11923                         if (IS_ERR(map)) {
11924                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
11925                                         insn[0].imm);
11926                                 return PTR_ERR(map);
11927                         }
11928
11929                         err = check_map_prog_compatibility(env, map, env->prog);
11930                         if (err) {
11931                                 fdput(f);
11932                                 return err;
11933                         }
11934
11935                         aux = &env->insn_aux_data[i];
11936                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11937                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11938                                 addr = (unsigned long)map;
11939                         } else {
11940                                 u32 off = insn[1].imm;
11941
11942                                 if (off >= BPF_MAX_VAR_OFF) {
11943                                         verbose(env, "direct value offset of %u is not allowed\n", off);
11944                                         fdput(f);
11945                                         return -EINVAL;
11946                                 }
11947
11948                                 if (!map->ops->map_direct_value_addr) {
11949                                         verbose(env, "no direct value access support for this map type\n");
11950                                         fdput(f);
11951                                         return -EINVAL;
11952                                 }
11953
11954                                 err = map->ops->map_direct_value_addr(map, &addr, off);
11955                                 if (err) {
11956                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11957                                                 map->value_size, off);
11958                                         fdput(f);
11959                                         return err;
11960                                 }
11961
11962                                 aux->map_off = off;
11963                                 addr += off;
11964                         }
11965
11966                         insn[0].imm = (u32)addr;
11967                         insn[1].imm = addr >> 32;
11968
11969                         /* check whether we recorded this map already */
11970                         for (j = 0; j < env->used_map_cnt; j++) {
11971                                 if (env->used_maps[j] == map) {
11972                                         aux->map_index = j;
11973                                         fdput(f);
11974                                         goto next_insn;
11975                                 }
11976                         }
11977
11978                         if (env->used_map_cnt >= MAX_USED_MAPS) {
11979                                 fdput(f);
11980                                 return -E2BIG;
11981                         }
11982
11983                         /* hold the map. If the program is rejected by verifier,
11984                          * the map will be released by release_maps() or it
11985                          * will be used by the valid program until it's unloaded
11986                          * and all maps are released in free_used_maps()
11987                          */
11988                         bpf_map_inc(map);
11989
11990                         aux->map_index = env->used_map_cnt;
11991                         env->used_maps[env->used_map_cnt++] = map;
11992
11993                         if (bpf_map_is_cgroup_storage(map) &&
11994                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
11995                                 verbose(env, "only one cgroup storage of each type is allowed\n");
11996                                 fdput(f);
11997                                 return -EBUSY;
11998                         }
11999
12000                         fdput(f);
12001 next_insn:
12002                         insn++;
12003                         i++;
12004                         continue;
12005                 }
12006
12007                 /* Basic sanity check before we invest more work here. */
12008                 if (!bpf_opcode_in_insntable(insn->code)) {
12009                         verbose(env, "unknown opcode %02x\n", insn->code);
12010                         return -EINVAL;
12011                 }
12012         }
12013
12014         /* now all pseudo BPF_LD_IMM64 instructions load valid
12015          * 'struct bpf_map *' into a register instead of user map_fd.
12016          * These pointers will be used later by verifier to validate map access.
12017          */
12018         return 0;
12019 }
12020
12021 /* drop refcnt of maps used by the rejected program */
12022 static void release_maps(struct bpf_verifier_env *env)
12023 {
12024         __bpf_free_used_maps(env->prog->aux, env->used_maps,
12025                              env->used_map_cnt);
12026 }
12027
12028 /* drop refcnt of maps used by the rejected program */
12029 static void release_btfs(struct bpf_verifier_env *env)
12030 {
12031         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12032                              env->used_btf_cnt);
12033 }
12034
12035 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12036 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12037 {
12038         struct bpf_insn *insn = env->prog->insnsi;
12039         int insn_cnt = env->prog->len;
12040         int i;
12041
12042         for (i = 0; i < insn_cnt; i++, insn++) {
12043                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12044                         continue;
12045                 if (insn->src_reg == BPF_PSEUDO_FUNC)
12046                         continue;
12047                 insn->src_reg = 0;
12048         }
12049 }
12050
12051 /* single env->prog->insni[off] instruction was replaced with the range
12052  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
12053  * [0, off) and [off, end) to new locations, so the patched range stays zero
12054  */
12055 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12056                                  struct bpf_insn_aux_data *new_data,
12057                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
12058 {
12059         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12060         struct bpf_insn *insn = new_prog->insnsi;
12061         u32 old_seen = old_data[off].seen;
12062         u32 prog_len;
12063         int i;
12064
12065         /* aux info at OFF always needs adjustment, no matter fast path
12066          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12067          * original insn at old prog.
12068          */
12069         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12070
12071         if (cnt == 1)
12072                 return;
12073         prog_len = new_prog->len;
12074
12075         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12076         memcpy(new_data + off + cnt - 1, old_data + off,
12077                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12078         for (i = off; i < off + cnt - 1; i++) {
12079                 /* Expand insni[off]'s seen count to the patched range. */
12080                 new_data[i].seen = old_seen;
12081                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
12082         }
12083         env->insn_aux_data = new_data;
12084         vfree(old_data);
12085 }
12086
12087 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12088 {
12089         int i;
12090
12091         if (len == 1)
12092                 return;
12093         /* NOTE: fake 'exit' subprog should be updated as well. */
12094         for (i = 0; i <= env->subprog_cnt; i++) {
12095                 if (env->subprog_info[i].start <= off)
12096                         continue;
12097                 env->subprog_info[i].start += len - 1;
12098         }
12099 }
12100
12101 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
12102 {
12103         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12104         int i, sz = prog->aux->size_poke_tab;
12105         struct bpf_jit_poke_descriptor *desc;
12106
12107         for (i = 0; i < sz; i++) {
12108                 desc = &tab[i];
12109                 if (desc->insn_idx <= off)
12110                         continue;
12111                 desc->insn_idx += len - 1;
12112         }
12113 }
12114
12115 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12116                                             const struct bpf_insn *patch, u32 len)
12117 {
12118         struct bpf_prog *new_prog;
12119         struct bpf_insn_aux_data *new_data = NULL;
12120
12121         if (len > 1) {
12122                 new_data = vzalloc(array_size(env->prog->len + len - 1,
12123                                               sizeof(struct bpf_insn_aux_data)));
12124                 if (!new_data)
12125                         return NULL;
12126         }
12127
12128         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
12129         if (IS_ERR(new_prog)) {
12130                 if (PTR_ERR(new_prog) == -ERANGE)
12131                         verbose(env,
12132                                 "insn %d cannot be patched due to 16-bit range\n",
12133                                 env->insn_aux_data[off].orig_idx);
12134                 vfree(new_data);
12135                 return NULL;
12136         }
12137         adjust_insn_aux_data(env, new_data, new_prog, off, len);
12138         adjust_subprog_starts(env, off, len);
12139         adjust_poke_descs(new_prog, off, len);
12140         return new_prog;
12141 }
12142
12143 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12144                                               u32 off, u32 cnt)
12145 {
12146         int i, j;
12147
12148         /* find first prog starting at or after off (first to remove) */
12149         for (i = 0; i < env->subprog_cnt; i++)
12150                 if (env->subprog_info[i].start >= off)
12151                         break;
12152         /* find first prog starting at or after off + cnt (first to stay) */
12153         for (j = i; j < env->subprog_cnt; j++)
12154                 if (env->subprog_info[j].start >= off + cnt)
12155                         break;
12156         /* if j doesn't start exactly at off + cnt, we are just removing
12157          * the front of previous prog
12158          */
12159         if (env->subprog_info[j].start != off + cnt)
12160                 j--;
12161
12162         if (j > i) {
12163                 struct bpf_prog_aux *aux = env->prog->aux;
12164                 int move;
12165
12166                 /* move fake 'exit' subprog as well */
12167                 move = env->subprog_cnt + 1 - j;
12168
12169                 memmove(env->subprog_info + i,
12170                         env->subprog_info + j,
12171                         sizeof(*env->subprog_info) * move);
12172                 env->subprog_cnt -= j - i;
12173
12174                 /* remove func_info */
12175                 if (aux->func_info) {
12176                         move = aux->func_info_cnt - j;
12177
12178                         memmove(aux->func_info + i,
12179                                 aux->func_info + j,
12180                                 sizeof(*aux->func_info) * move);
12181                         aux->func_info_cnt -= j - i;
12182                         /* func_info->insn_off is set after all code rewrites,
12183                          * in adjust_btf_func() - no need to adjust
12184                          */
12185                 }
12186         } else {
12187                 /* convert i from "first prog to remove" to "first to adjust" */
12188                 if (env->subprog_info[i].start == off)
12189                         i++;
12190         }
12191
12192         /* update fake 'exit' subprog as well */
12193         for (; i <= env->subprog_cnt; i++)
12194                 env->subprog_info[i].start -= cnt;
12195
12196         return 0;
12197 }
12198
12199 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
12200                                       u32 cnt)
12201 {
12202         struct bpf_prog *prog = env->prog;
12203         u32 i, l_off, l_cnt, nr_linfo;
12204         struct bpf_line_info *linfo;
12205
12206         nr_linfo = prog->aux->nr_linfo;
12207         if (!nr_linfo)
12208                 return 0;
12209
12210         linfo = prog->aux->linfo;
12211
12212         /* find first line info to remove, count lines to be removed */
12213         for (i = 0; i < nr_linfo; i++)
12214                 if (linfo[i].insn_off >= off)
12215                         break;
12216
12217         l_off = i;
12218         l_cnt = 0;
12219         for (; i < nr_linfo; i++)
12220                 if (linfo[i].insn_off < off + cnt)
12221                         l_cnt++;
12222                 else
12223                         break;
12224
12225         /* First live insn doesn't match first live linfo, it needs to "inherit"
12226          * last removed linfo.  prog is already modified, so prog->len == off
12227          * means no live instructions after (tail of the program was removed).
12228          */
12229         if (prog->len != off && l_cnt &&
12230             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
12231                 l_cnt--;
12232                 linfo[--i].insn_off = off + cnt;
12233         }
12234
12235         /* remove the line info which refer to the removed instructions */
12236         if (l_cnt) {
12237                 memmove(linfo + l_off, linfo + i,
12238                         sizeof(*linfo) * (nr_linfo - i));
12239
12240                 prog->aux->nr_linfo -= l_cnt;
12241                 nr_linfo = prog->aux->nr_linfo;
12242         }
12243
12244         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
12245         for (i = l_off; i < nr_linfo; i++)
12246                 linfo[i].insn_off -= cnt;
12247
12248         /* fix up all subprogs (incl. 'exit') which start >= off */
12249         for (i = 0; i <= env->subprog_cnt; i++)
12250                 if (env->subprog_info[i].linfo_idx > l_off) {
12251                         /* program may have started in the removed region but
12252                          * may not be fully removed
12253                          */
12254                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
12255                                 env->subprog_info[i].linfo_idx -= l_cnt;
12256                         else
12257                                 env->subprog_info[i].linfo_idx = l_off;
12258                 }
12259
12260         return 0;
12261 }
12262
12263 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
12264 {
12265         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12266         unsigned int orig_prog_len = env->prog->len;
12267         int err;
12268
12269         if (bpf_prog_is_dev_bound(env->prog->aux))
12270                 bpf_prog_offload_remove_insns(env, off, cnt);
12271
12272         err = bpf_remove_insns(env->prog, off, cnt);
12273         if (err)
12274                 return err;
12275
12276         err = adjust_subprog_starts_after_remove(env, off, cnt);
12277         if (err)
12278                 return err;
12279
12280         err = bpf_adj_linfo_after_remove(env, off, cnt);
12281         if (err)
12282                 return err;
12283
12284         memmove(aux_data + off, aux_data + off + cnt,
12285                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
12286
12287         return 0;
12288 }
12289
12290 /* The verifier does more data flow analysis than llvm and will not
12291  * explore branches that are dead at run time. Malicious programs can
12292  * have dead code too. Therefore replace all dead at-run-time code
12293  * with 'ja -1'.
12294  *
12295  * Just nops are not optimal, e.g. if they would sit at the end of the
12296  * program and through another bug we would manage to jump there, then
12297  * we'd execute beyond program memory otherwise. Returning exception
12298  * code also wouldn't work since we can have subprogs where the dead
12299  * code could be located.
12300  */
12301 static void sanitize_dead_code(struct bpf_verifier_env *env)
12302 {
12303         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12304         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
12305         struct bpf_insn *insn = env->prog->insnsi;
12306         const int insn_cnt = env->prog->len;
12307         int i;
12308
12309         for (i = 0; i < insn_cnt; i++) {
12310                 if (aux_data[i].seen)
12311                         continue;
12312                 memcpy(insn + i, &trap, sizeof(trap));
12313                 aux_data[i].zext_dst = false;
12314         }
12315 }
12316
12317 static bool insn_is_cond_jump(u8 code)
12318 {
12319         u8 op;
12320
12321         if (BPF_CLASS(code) == BPF_JMP32)
12322                 return true;
12323
12324         if (BPF_CLASS(code) != BPF_JMP)
12325                 return false;
12326
12327         op = BPF_OP(code);
12328         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12329 }
12330
12331 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12332 {
12333         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12334         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12335         struct bpf_insn *insn = env->prog->insnsi;
12336         const int insn_cnt = env->prog->len;
12337         int i;
12338
12339         for (i = 0; i < insn_cnt; i++, insn++) {
12340                 if (!insn_is_cond_jump(insn->code))
12341                         continue;
12342
12343                 if (!aux_data[i + 1].seen)
12344                         ja.off = insn->off;
12345                 else if (!aux_data[i + 1 + insn->off].seen)
12346                         ja.off = 0;
12347                 else
12348                         continue;
12349
12350                 if (bpf_prog_is_dev_bound(env->prog->aux))
12351                         bpf_prog_offload_replace_insn(env, i, &ja);
12352
12353                 memcpy(insn, &ja, sizeof(ja));
12354         }
12355 }
12356
12357 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12358 {
12359         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12360         int insn_cnt = env->prog->len;
12361         int i, err;
12362
12363         for (i = 0; i < insn_cnt; i++) {
12364                 int j;
12365
12366                 j = 0;
12367                 while (i + j < insn_cnt && !aux_data[i + j].seen)
12368                         j++;
12369                 if (!j)
12370                         continue;
12371
12372                 err = verifier_remove_insns(env, i, j);
12373                 if (err)
12374                         return err;
12375                 insn_cnt = env->prog->len;
12376         }
12377
12378         return 0;
12379 }
12380
12381 static int opt_remove_nops(struct bpf_verifier_env *env)
12382 {
12383         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12384         struct bpf_insn *insn = env->prog->insnsi;
12385         int insn_cnt = env->prog->len;
12386         int i, err;
12387
12388         for (i = 0; i < insn_cnt; i++) {
12389                 if (memcmp(&insn[i], &ja, sizeof(ja)))
12390                         continue;
12391
12392                 err = verifier_remove_insns(env, i, 1);
12393                 if (err)
12394                         return err;
12395                 insn_cnt--;
12396                 i--;
12397         }
12398
12399         return 0;
12400 }
12401
12402 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12403                                          const union bpf_attr *attr)
12404 {
12405         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12406         struct bpf_insn_aux_data *aux = env->insn_aux_data;
12407         int i, patch_len, delta = 0, len = env->prog->len;
12408         struct bpf_insn *insns = env->prog->insnsi;
12409         struct bpf_prog *new_prog;
12410         bool rnd_hi32;
12411
12412         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12413         zext_patch[1] = BPF_ZEXT_REG(0);
12414         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12415         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12416         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12417         for (i = 0; i < len; i++) {
12418                 int adj_idx = i + delta;
12419                 struct bpf_insn insn;
12420                 int load_reg;
12421
12422                 insn = insns[adj_idx];
12423                 load_reg = insn_def_regno(&insn);
12424                 if (!aux[adj_idx].zext_dst) {
12425                         u8 code, class;
12426                         u32 imm_rnd;
12427
12428                         if (!rnd_hi32)
12429                                 continue;
12430
12431                         code = insn.code;
12432                         class = BPF_CLASS(code);
12433                         if (load_reg == -1)
12434                                 continue;
12435
12436                         /* NOTE: arg "reg" (the fourth one) is only used for
12437                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
12438                          *       here.
12439                          */
12440                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12441                                 if (class == BPF_LD &&
12442                                     BPF_MODE(code) == BPF_IMM)
12443                                         i++;
12444                                 continue;
12445                         }
12446
12447                         /* ctx load could be transformed into wider load. */
12448                         if (class == BPF_LDX &&
12449                             aux[adj_idx].ptr_type == PTR_TO_CTX)
12450                                 continue;
12451
12452                         imm_rnd = get_random_int();
12453                         rnd_hi32_patch[0] = insn;
12454                         rnd_hi32_patch[1].imm = imm_rnd;
12455                         rnd_hi32_patch[3].dst_reg = load_reg;
12456                         patch = rnd_hi32_patch;
12457                         patch_len = 4;
12458                         goto apply_patch_buffer;
12459                 }
12460
12461                 /* Add in an zero-extend instruction if a) the JIT has requested
12462                  * it or b) it's a CMPXCHG.
12463                  *
12464                  * The latter is because: BPF_CMPXCHG always loads a value into
12465                  * R0, therefore always zero-extends. However some archs'
12466                  * equivalent instruction only does this load when the
12467                  * comparison is successful. This detail of CMPXCHG is
12468                  * orthogonal to the general zero-extension behaviour of the
12469                  * CPU, so it's treated independently of bpf_jit_needs_zext.
12470                  */
12471                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12472                         continue;
12473
12474                 if (WARN_ON(load_reg == -1)) {
12475                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12476                         return -EFAULT;
12477                 }
12478
12479                 zext_patch[0] = insn;
12480                 zext_patch[1].dst_reg = load_reg;
12481                 zext_patch[1].src_reg = load_reg;
12482                 patch = zext_patch;
12483                 patch_len = 2;
12484 apply_patch_buffer:
12485                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12486                 if (!new_prog)
12487                         return -ENOMEM;
12488                 env->prog = new_prog;
12489                 insns = new_prog->insnsi;
12490                 aux = env->insn_aux_data;
12491                 delta += patch_len - 1;
12492         }
12493
12494         return 0;
12495 }
12496
12497 /* convert load instructions that access fields of a context type into a
12498  * sequence of instructions that access fields of the underlying structure:
12499  *     struct __sk_buff    -> struct sk_buff
12500  *     struct bpf_sock_ops -> struct sock
12501  */
12502 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12503 {
12504         const struct bpf_verifier_ops *ops = env->ops;
12505         int i, cnt, size, ctx_field_size, delta = 0;
12506         const int insn_cnt = env->prog->len;
12507         struct bpf_insn insn_buf[16], *insn;
12508         u32 target_size, size_default, off;
12509         struct bpf_prog *new_prog;
12510         enum bpf_access_type type;
12511         bool is_narrower_load;
12512
12513         if (ops->gen_prologue || env->seen_direct_write) {
12514                 if (!ops->gen_prologue) {
12515                         verbose(env, "bpf verifier is misconfigured\n");
12516                         return -EINVAL;
12517                 }
12518                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12519                                         env->prog);
12520                 if (cnt >= ARRAY_SIZE(insn_buf)) {
12521                         verbose(env, "bpf verifier is misconfigured\n");
12522                         return -EINVAL;
12523                 } else if (cnt) {
12524                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12525                         if (!new_prog)
12526                                 return -ENOMEM;
12527
12528                         env->prog = new_prog;
12529                         delta += cnt - 1;
12530                 }
12531         }
12532
12533         if (bpf_prog_is_dev_bound(env->prog->aux))
12534                 return 0;
12535
12536         insn = env->prog->insnsi + delta;
12537
12538         for (i = 0; i < insn_cnt; i++, insn++) {
12539                 bpf_convert_ctx_access_t convert_ctx_access;
12540                 bool ctx_access;
12541
12542                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12543                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12544                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12545                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12546                         type = BPF_READ;
12547                         ctx_access = true;
12548                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12549                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12550                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12551                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12552                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12553                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12554                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12555                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12556                         type = BPF_WRITE;
12557                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12558                 } else {
12559                         continue;
12560                 }
12561
12562                 if (type == BPF_WRITE &&
12563                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
12564                         struct bpf_insn patch[] = {
12565                                 *insn,
12566                                 BPF_ST_NOSPEC(),
12567                         };
12568
12569                         cnt = ARRAY_SIZE(patch);
12570                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12571                         if (!new_prog)
12572                                 return -ENOMEM;
12573
12574                         delta    += cnt - 1;
12575                         env->prog = new_prog;
12576                         insn      = new_prog->insnsi + i + delta;
12577                         continue;
12578                 }
12579
12580                 if (!ctx_access)
12581                         continue;
12582
12583                 switch (env->insn_aux_data[i + delta].ptr_type) {
12584                 case PTR_TO_CTX:
12585                         if (!ops->convert_ctx_access)
12586                                 continue;
12587                         convert_ctx_access = ops->convert_ctx_access;
12588                         break;
12589                 case PTR_TO_SOCKET:
12590                 case PTR_TO_SOCK_COMMON:
12591                         convert_ctx_access = bpf_sock_convert_ctx_access;
12592                         break;
12593                 case PTR_TO_TCP_SOCK:
12594                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12595                         break;
12596                 case PTR_TO_XDP_SOCK:
12597                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12598                         break;
12599                 case PTR_TO_BTF_ID:
12600                         if (type == BPF_READ) {
12601                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
12602                                         BPF_SIZE((insn)->code);
12603                                 env->prog->aux->num_exentries++;
12604                         } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12605                                 verbose(env, "Writes through BTF pointers are not allowed\n");
12606                                 return -EINVAL;
12607                         }
12608                         continue;
12609                 default:
12610                         continue;
12611                 }
12612
12613                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12614                 size = BPF_LDST_BYTES(insn);
12615
12616                 /* If the read access is a narrower load of the field,
12617                  * convert to a 4/8-byte load, to minimum program type specific
12618                  * convert_ctx_access changes. If conversion is successful,
12619                  * we will apply proper mask to the result.
12620                  */
12621                 is_narrower_load = size < ctx_field_size;
12622                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12623                 off = insn->off;
12624                 if (is_narrower_load) {
12625                         u8 size_code;
12626
12627                         if (type == BPF_WRITE) {
12628                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12629                                 return -EINVAL;
12630                         }
12631
12632                         size_code = BPF_H;
12633                         if (ctx_field_size == 4)
12634                                 size_code = BPF_W;
12635                         else if (ctx_field_size == 8)
12636                                 size_code = BPF_DW;
12637
12638                         insn->off = off & ~(size_default - 1);
12639                         insn->code = BPF_LDX | BPF_MEM | size_code;
12640                 }
12641
12642                 target_size = 0;
12643                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12644                                          &target_size);
12645                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12646                     (ctx_field_size && !target_size)) {
12647                         verbose(env, "bpf verifier is misconfigured\n");
12648                         return -EINVAL;
12649                 }
12650
12651                 if (is_narrower_load && size < target_size) {
12652                         u8 shift = bpf_ctx_narrow_access_offset(
12653                                 off, size, size_default) * 8;
12654                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12655                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12656                                 return -EINVAL;
12657                         }
12658                         if (ctx_field_size <= 4) {
12659                                 if (shift)
12660                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12661                                                                         insn->dst_reg,
12662                                                                         shift);
12663                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12664                                                                 (1 << size * 8) - 1);
12665                         } else {
12666                                 if (shift)
12667                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12668                                                                         insn->dst_reg,
12669                                                                         shift);
12670                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12671                                                                 (1ULL << size * 8) - 1);
12672                         }
12673                 }
12674
12675                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12676                 if (!new_prog)
12677                         return -ENOMEM;
12678
12679                 delta += cnt - 1;
12680
12681                 /* keep walking new program and skip insns we just inserted */
12682                 env->prog = new_prog;
12683                 insn      = new_prog->insnsi + i + delta;
12684         }
12685
12686         return 0;
12687 }
12688
12689 static int jit_subprogs(struct bpf_verifier_env *env)
12690 {
12691         struct bpf_prog *prog = env->prog, **func, *tmp;
12692         int i, j, subprog_start, subprog_end = 0, len, subprog;
12693         struct bpf_map *map_ptr;
12694         struct bpf_insn *insn;
12695         void *old_bpf_func;
12696         int err, num_exentries;
12697
12698         if (env->subprog_cnt <= 1)
12699                 return 0;
12700
12701         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12702                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
12703                         continue;
12704
12705                 /* Upon error here we cannot fall back to interpreter but
12706                  * need a hard reject of the program. Thus -EFAULT is
12707                  * propagated in any case.
12708                  */
12709                 subprog = find_subprog(env, i + insn->imm + 1);
12710                 if (subprog < 0) {
12711                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12712                                   i + insn->imm + 1);
12713                         return -EFAULT;
12714                 }
12715                 /* temporarily remember subprog id inside insn instead of
12716                  * aux_data, since next loop will split up all insns into funcs
12717                  */
12718                 insn->off = subprog;
12719                 /* remember original imm in case JIT fails and fallback
12720                  * to interpreter will be needed
12721                  */
12722                 env->insn_aux_data[i].call_imm = insn->imm;
12723                 /* point imm to __bpf_call_base+1 from JITs point of view */
12724                 insn->imm = 1;
12725                 if (bpf_pseudo_func(insn))
12726                         /* jit (e.g. x86_64) may emit fewer instructions
12727                          * if it learns a u32 imm is the same as a u64 imm.
12728                          * Force a non zero here.
12729                          */
12730                         insn[1].imm = 1;
12731         }
12732
12733         err = bpf_prog_alloc_jited_linfo(prog);
12734         if (err)
12735                 goto out_undo_insn;
12736
12737         err = -ENOMEM;
12738         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12739         if (!func)
12740                 goto out_undo_insn;
12741
12742         for (i = 0; i < env->subprog_cnt; i++) {
12743                 subprog_start = subprog_end;
12744                 subprog_end = env->subprog_info[i + 1].start;
12745
12746                 len = subprog_end - subprog_start;
12747                 /* bpf_prog_run() doesn't call subprogs directly,
12748                  * hence main prog stats include the runtime of subprogs.
12749                  * subprogs don't have IDs and not reachable via prog_get_next_id
12750                  * func[i]->stats will never be accessed and stays NULL
12751                  */
12752                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12753                 if (!func[i])
12754                         goto out_free;
12755                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12756                        len * sizeof(struct bpf_insn));
12757                 func[i]->type = prog->type;
12758                 func[i]->len = len;
12759                 if (bpf_prog_calc_tag(func[i]))
12760                         goto out_free;
12761                 func[i]->is_func = 1;
12762                 func[i]->aux->func_idx = i;
12763                 /* Below members will be freed only at prog->aux */
12764                 func[i]->aux->btf = prog->aux->btf;
12765                 func[i]->aux->func_info = prog->aux->func_info;
12766                 func[i]->aux->poke_tab = prog->aux->poke_tab;
12767                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12768
12769                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
12770                         struct bpf_jit_poke_descriptor *poke;
12771
12772                         poke = &prog->aux->poke_tab[j];
12773                         if (poke->insn_idx < subprog_end &&
12774                             poke->insn_idx >= subprog_start)
12775                                 poke->aux = func[i]->aux;
12776                 }
12777
12778                 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12779                  * Long term would need debug info to populate names
12780                  */
12781                 func[i]->aux->name[0] = 'F';
12782                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12783                 func[i]->jit_requested = 1;
12784                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12785                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
12786                 func[i]->aux->linfo = prog->aux->linfo;
12787                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12788                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12789                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12790                 num_exentries = 0;
12791                 insn = func[i]->insnsi;
12792                 for (j = 0; j < func[i]->len; j++, insn++) {
12793                         if (BPF_CLASS(insn->code) == BPF_LDX &&
12794                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
12795                                 num_exentries++;
12796                 }
12797                 func[i]->aux->num_exentries = num_exentries;
12798                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12799                 func[i] = bpf_int_jit_compile(func[i]);
12800                 if (!func[i]->jited) {
12801                         err = -ENOTSUPP;
12802                         goto out_free;
12803                 }
12804                 cond_resched();
12805         }
12806
12807         /* at this point all bpf functions were successfully JITed
12808          * now populate all bpf_calls with correct addresses and
12809          * run last pass of JIT
12810          */
12811         for (i = 0; i < env->subprog_cnt; i++) {
12812                 insn = func[i]->insnsi;
12813                 for (j = 0; j < func[i]->len; j++, insn++) {
12814                         if (bpf_pseudo_func(insn)) {
12815                                 subprog = insn->off;
12816                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12817                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12818                                 continue;
12819                         }
12820                         if (!bpf_pseudo_call(insn))
12821                                 continue;
12822                         subprog = insn->off;
12823                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
12824                 }
12825
12826                 /* we use the aux data to keep a list of the start addresses
12827                  * of the JITed images for each function in the program
12828                  *
12829                  * for some architectures, such as powerpc64, the imm field
12830                  * might not be large enough to hold the offset of the start
12831                  * address of the callee's JITed image from __bpf_call_base
12832                  *
12833                  * in such cases, we can lookup the start address of a callee
12834                  * by using its subprog id, available from the off field of
12835                  * the call instruction, as an index for this list
12836                  */
12837                 func[i]->aux->func = func;
12838                 func[i]->aux->func_cnt = env->subprog_cnt;
12839         }
12840         for (i = 0; i < env->subprog_cnt; i++) {
12841                 old_bpf_func = func[i]->bpf_func;
12842                 tmp = bpf_int_jit_compile(func[i]);
12843                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12844                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12845                         err = -ENOTSUPP;
12846                         goto out_free;
12847                 }
12848                 cond_resched();
12849         }
12850
12851         /* finally lock prog and jit images for all functions and
12852          * populate kallsysm
12853          */
12854         for (i = 0; i < env->subprog_cnt; i++) {
12855                 bpf_prog_lock_ro(func[i]);
12856                 bpf_prog_kallsyms_add(func[i]);
12857         }
12858
12859         /* Last step: make now unused interpreter insns from main
12860          * prog consistent for later dump requests, so they can
12861          * later look the same as if they were interpreted only.
12862          */
12863         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12864                 if (bpf_pseudo_func(insn)) {
12865                         insn[0].imm = env->insn_aux_data[i].call_imm;
12866                         insn[1].imm = insn->off;
12867                         insn->off = 0;
12868                         continue;
12869                 }
12870                 if (!bpf_pseudo_call(insn))
12871                         continue;
12872                 insn->off = env->insn_aux_data[i].call_imm;
12873                 subprog = find_subprog(env, i + insn->off + 1);
12874                 insn->imm = subprog;
12875         }
12876
12877         prog->jited = 1;
12878         prog->bpf_func = func[0]->bpf_func;
12879         prog->aux->func = func;
12880         prog->aux->func_cnt = env->subprog_cnt;
12881         bpf_prog_jit_attempt_done(prog);
12882         return 0;
12883 out_free:
12884         /* We failed JIT'ing, so at this point we need to unregister poke
12885          * descriptors from subprogs, so that kernel is not attempting to
12886          * patch it anymore as we're freeing the subprog JIT memory.
12887          */
12888         for (i = 0; i < prog->aux->size_poke_tab; i++) {
12889                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12890                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12891         }
12892         /* At this point we're guaranteed that poke descriptors are not
12893          * live anymore. We can just unlink its descriptor table as it's
12894          * released with the main prog.
12895          */
12896         for (i = 0; i < env->subprog_cnt; i++) {
12897                 if (!func[i])
12898                         continue;
12899                 func[i]->aux->poke_tab = NULL;
12900                 bpf_jit_free(func[i]);
12901         }
12902         kfree(func);
12903 out_undo_insn:
12904         /* cleanup main prog to be interpreted */
12905         prog->jit_requested = 0;
12906         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12907                 if (!bpf_pseudo_call(insn))
12908                         continue;
12909                 insn->off = 0;
12910                 insn->imm = env->insn_aux_data[i].call_imm;
12911         }
12912         bpf_prog_jit_attempt_done(prog);
12913         return err;
12914 }
12915
12916 static int fixup_call_args(struct bpf_verifier_env *env)
12917 {
12918 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12919         struct bpf_prog *prog = env->prog;
12920         struct bpf_insn *insn = prog->insnsi;
12921         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12922         int i, depth;
12923 #endif
12924         int err = 0;
12925
12926         if (env->prog->jit_requested &&
12927             !bpf_prog_is_dev_bound(env->prog->aux)) {
12928                 err = jit_subprogs(env);
12929                 if (err == 0)
12930                         return 0;
12931                 if (err == -EFAULT)
12932                         return err;
12933         }
12934 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12935         if (has_kfunc_call) {
12936                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12937                 return -EINVAL;
12938         }
12939         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12940                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12941                  * have to be rejected, since interpreter doesn't support them yet.
12942                  */
12943                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12944                 return -EINVAL;
12945         }
12946         for (i = 0; i < prog->len; i++, insn++) {
12947                 if (bpf_pseudo_func(insn)) {
12948                         /* When JIT fails the progs with callback calls
12949                          * have to be rejected, since interpreter doesn't support them yet.
12950                          */
12951                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
12952                         return -EINVAL;
12953                 }
12954
12955                 if (!bpf_pseudo_call(insn))
12956                         continue;
12957                 depth = get_callee_stack_depth(env, insn, i);
12958                 if (depth < 0)
12959                         return depth;
12960                 bpf_patch_call_args(insn, depth);
12961         }
12962         err = 0;
12963 #endif
12964         return err;
12965 }
12966
12967 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12968                             struct bpf_insn *insn)
12969 {
12970         const struct bpf_kfunc_desc *desc;
12971
12972         if (!insn->imm) {
12973                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
12974                 return -EINVAL;
12975         }
12976
12977         /* insn->imm has the btf func_id. Replace it with
12978          * an address (relative to __bpf_base_call).
12979          */
12980         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
12981         if (!desc) {
12982                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12983                         insn->imm);
12984                 return -EFAULT;
12985         }
12986
12987         insn->imm = desc->imm;
12988
12989         return 0;
12990 }
12991
12992 /* Do various post-verification rewrites in a single program pass.
12993  * These rewrites simplify JIT and interpreter implementations.
12994  */
12995 static int do_misc_fixups(struct bpf_verifier_env *env)
12996 {
12997         struct bpf_prog *prog = env->prog;
12998         enum bpf_attach_type eatype = prog->expected_attach_type;
12999         bool expect_blinding = bpf_jit_blinding_enabled(prog);
13000         enum bpf_prog_type prog_type = resolve_prog_type(prog);
13001         struct bpf_insn *insn = prog->insnsi;
13002         const struct bpf_func_proto *fn;
13003         const int insn_cnt = prog->len;
13004         const struct bpf_map_ops *ops;
13005         struct bpf_insn_aux_data *aux;
13006         struct bpf_insn insn_buf[16];
13007         struct bpf_prog *new_prog;
13008         struct bpf_map *map_ptr;
13009         int i, ret, cnt, delta = 0;
13010
13011         for (i = 0; i < insn_cnt; i++, insn++) {
13012                 /* Make divide-by-zero exceptions impossible. */
13013                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13014                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13015                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13016                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13017                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13018                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13019                         struct bpf_insn *patchlet;
13020                         struct bpf_insn chk_and_div[] = {
13021                                 /* [R,W]x div 0 -> 0 */
13022                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13023                                              BPF_JNE | BPF_K, insn->src_reg,
13024                                              0, 2, 0),
13025                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13026                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13027                                 *insn,
13028                         };
13029                         struct bpf_insn chk_and_mod[] = {
13030                                 /* [R,W]x mod 0 -> [R,W]x */
13031                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13032                                              BPF_JEQ | BPF_K, insn->src_reg,
13033                                              0, 1 + (is64 ? 0 : 1), 0),
13034                                 *insn,
13035                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13036                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13037                         };
13038
13039                         patchlet = isdiv ? chk_and_div : chk_and_mod;
13040                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13041                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13042
13043                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13044                         if (!new_prog)
13045                                 return -ENOMEM;
13046
13047                         delta    += cnt - 1;
13048                         env->prog = prog = new_prog;
13049                         insn      = new_prog->insnsi + i + delta;
13050                         continue;
13051                 }
13052
13053                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13054                 if (BPF_CLASS(insn->code) == BPF_LD &&
13055                     (BPF_MODE(insn->code) == BPF_ABS ||
13056                      BPF_MODE(insn->code) == BPF_IND)) {
13057                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
13058                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13059                                 verbose(env, "bpf verifier is misconfigured\n");
13060                                 return -EINVAL;
13061                         }
13062
13063                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13064                         if (!new_prog)
13065                                 return -ENOMEM;
13066
13067                         delta    += cnt - 1;
13068                         env->prog = prog = new_prog;
13069                         insn      = new_prog->insnsi + i + delta;
13070                         continue;
13071                 }
13072
13073                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
13074                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13075                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13076                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13077                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13078                         struct bpf_insn *patch = &insn_buf[0];
13079                         bool issrc, isneg, isimm;
13080                         u32 off_reg;
13081
13082                         aux = &env->insn_aux_data[i + delta];
13083                         if (!aux->alu_state ||
13084                             aux->alu_state == BPF_ALU_NON_POINTER)
13085                                 continue;
13086
13087                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13088                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13089                                 BPF_ALU_SANITIZE_SRC;
13090                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
13091
13092                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
13093                         if (isimm) {
13094                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13095                         } else {
13096                                 if (isneg)
13097                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13098                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13099                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13100                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
13101                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
13102                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
13103                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
13104                         }
13105                         if (!issrc)
13106                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13107                         insn->src_reg = BPF_REG_AX;
13108                         if (isneg)
13109                                 insn->code = insn->code == code_add ?
13110                                              code_sub : code_add;
13111                         *patch++ = *insn;
13112                         if (issrc && isneg && !isimm)
13113                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13114                         cnt = patch - insn_buf;
13115
13116                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13117                         if (!new_prog)
13118                                 return -ENOMEM;
13119
13120                         delta    += cnt - 1;
13121                         env->prog = prog = new_prog;
13122                         insn      = new_prog->insnsi + i + delta;
13123                         continue;
13124                 }
13125
13126                 if (insn->code != (BPF_JMP | BPF_CALL))
13127                         continue;
13128                 if (insn->src_reg == BPF_PSEUDO_CALL)
13129                         continue;
13130                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
13131                         ret = fixup_kfunc_call(env, insn);
13132                         if (ret)
13133                                 return ret;
13134                         continue;
13135                 }
13136
13137                 if (insn->imm == BPF_FUNC_get_route_realm)
13138                         prog->dst_needed = 1;
13139                 if (insn->imm == BPF_FUNC_get_prandom_u32)
13140                         bpf_user_rnd_init_once();
13141                 if (insn->imm == BPF_FUNC_override_return)
13142                         prog->kprobe_override = 1;
13143                 if (insn->imm == BPF_FUNC_tail_call) {
13144                         /* If we tail call into other programs, we
13145                          * cannot make any assumptions since they can
13146                          * be replaced dynamically during runtime in
13147                          * the program array.
13148                          */
13149                         prog->cb_access = 1;
13150                         if (!allow_tail_call_in_subprogs(env))
13151                                 prog->aux->stack_depth = MAX_BPF_STACK;
13152                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
13153
13154                         /* mark bpf_tail_call as different opcode to avoid
13155                          * conditional branch in the interpreter for every normal
13156                          * call and to prevent accidental JITing by JIT compiler
13157                          * that doesn't support bpf_tail_call yet
13158                          */
13159                         insn->imm = 0;
13160                         insn->code = BPF_JMP | BPF_TAIL_CALL;
13161
13162                         aux = &env->insn_aux_data[i + delta];
13163                         if (env->bpf_capable && !expect_blinding &&
13164                             prog->jit_requested &&
13165                             !bpf_map_key_poisoned(aux) &&
13166                             !bpf_map_ptr_poisoned(aux) &&
13167                             !bpf_map_ptr_unpriv(aux)) {
13168                                 struct bpf_jit_poke_descriptor desc = {
13169                                         .reason = BPF_POKE_REASON_TAIL_CALL,
13170                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
13171                                         .tail_call.key = bpf_map_key_immediate(aux),
13172                                         .insn_idx = i + delta,
13173                                 };
13174
13175                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
13176                                 if (ret < 0) {
13177                                         verbose(env, "adding tail call poke descriptor failed\n");
13178                                         return ret;
13179                                 }
13180
13181                                 insn->imm = ret + 1;
13182                                 continue;
13183                         }
13184
13185                         if (!bpf_map_ptr_unpriv(aux))
13186                                 continue;
13187
13188                         /* instead of changing every JIT dealing with tail_call
13189                          * emit two extra insns:
13190                          * if (index >= max_entries) goto out;
13191                          * index &= array->index_mask;
13192                          * to avoid out-of-bounds cpu speculation
13193                          */
13194                         if (bpf_map_ptr_poisoned(aux)) {
13195                                 verbose(env, "tail_call abusing map_ptr\n");
13196                                 return -EINVAL;
13197                         }
13198
13199                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13200                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
13201                                                   map_ptr->max_entries, 2);
13202                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
13203                                                     container_of(map_ptr,
13204                                                                  struct bpf_array,
13205                                                                  map)->index_mask);
13206                         insn_buf[2] = *insn;
13207                         cnt = 3;
13208                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13209                         if (!new_prog)
13210                                 return -ENOMEM;
13211
13212                         delta    += cnt - 1;
13213                         env->prog = prog = new_prog;
13214                         insn      = new_prog->insnsi + i + delta;
13215                         continue;
13216                 }
13217
13218                 if (insn->imm == BPF_FUNC_timer_set_callback) {
13219                         /* The verifier will process callback_fn as many times as necessary
13220                          * with different maps and the register states prepared by
13221                          * set_timer_callback_state will be accurate.
13222                          *
13223                          * The following use case is valid:
13224                          *   map1 is shared by prog1, prog2, prog3.
13225                          *   prog1 calls bpf_timer_init for some map1 elements
13226                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
13227                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
13228                          *   prog3 calls bpf_timer_start for some map1 elements.
13229                          *     Those that were not both bpf_timer_init-ed and
13230                          *     bpf_timer_set_callback-ed will return -EINVAL.
13231                          */
13232                         struct bpf_insn ld_addrs[2] = {
13233                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
13234                         };
13235
13236                         insn_buf[0] = ld_addrs[0];
13237                         insn_buf[1] = ld_addrs[1];
13238                         insn_buf[2] = *insn;
13239                         cnt = 3;
13240
13241                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13242                         if (!new_prog)
13243                                 return -ENOMEM;
13244
13245                         delta    += cnt - 1;
13246                         env->prog = prog = new_prog;
13247                         insn      = new_prog->insnsi + i + delta;
13248                         goto patch_call_imm;
13249                 }
13250
13251                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
13252                  * and other inlining handlers are currently limited to 64 bit
13253                  * only.
13254                  */
13255                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
13256                     (insn->imm == BPF_FUNC_map_lookup_elem ||
13257                      insn->imm == BPF_FUNC_map_update_elem ||
13258                      insn->imm == BPF_FUNC_map_delete_elem ||
13259                      insn->imm == BPF_FUNC_map_push_elem   ||
13260                      insn->imm == BPF_FUNC_map_pop_elem    ||
13261                      insn->imm == BPF_FUNC_map_peek_elem   ||
13262                      insn->imm == BPF_FUNC_redirect_map    ||
13263                      insn->imm == BPF_FUNC_for_each_map_elem)) {
13264                         aux = &env->insn_aux_data[i + delta];
13265                         if (bpf_map_ptr_poisoned(aux))
13266                                 goto patch_call_imm;
13267
13268                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13269                         ops = map_ptr->ops;
13270                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
13271                             ops->map_gen_lookup) {
13272                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
13273                                 if (cnt == -EOPNOTSUPP)
13274                                         goto patch_map_ops_generic;
13275                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13276                                         verbose(env, "bpf verifier is misconfigured\n");
13277                                         return -EINVAL;
13278                                 }
13279
13280                                 new_prog = bpf_patch_insn_data(env, i + delta,
13281                                                                insn_buf, cnt);
13282                                 if (!new_prog)
13283                                         return -ENOMEM;
13284
13285                                 delta    += cnt - 1;
13286                                 env->prog = prog = new_prog;
13287                                 insn      = new_prog->insnsi + i + delta;
13288                                 continue;
13289                         }
13290
13291                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
13292                                      (void *(*)(struct bpf_map *map, void *key))NULL));
13293                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
13294                                      (int (*)(struct bpf_map *map, void *key))NULL));
13295                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
13296                                      (int (*)(struct bpf_map *map, void *key, void *value,
13297                                               u64 flags))NULL));
13298                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
13299                                      (int (*)(struct bpf_map *map, void *value,
13300                                               u64 flags))NULL));
13301                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13302                                      (int (*)(struct bpf_map *map, void *value))NULL));
13303                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13304                                      (int (*)(struct bpf_map *map, void *value))NULL));
13305                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
13306                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
13307                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
13308                                      (int (*)(struct bpf_map *map,
13309                                               bpf_callback_t callback_fn,
13310                                               void *callback_ctx,
13311                                               u64 flags))NULL));
13312
13313 patch_map_ops_generic:
13314                         switch (insn->imm) {
13315                         case BPF_FUNC_map_lookup_elem:
13316                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
13317                                 continue;
13318                         case BPF_FUNC_map_update_elem:
13319                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
13320                                 continue;
13321                         case BPF_FUNC_map_delete_elem:
13322                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
13323                                 continue;
13324                         case BPF_FUNC_map_push_elem:
13325                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
13326                                 continue;
13327                         case BPF_FUNC_map_pop_elem:
13328                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
13329                                 continue;
13330                         case BPF_FUNC_map_peek_elem:
13331                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
13332                                 continue;
13333                         case BPF_FUNC_redirect_map:
13334                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
13335                                 continue;
13336                         case BPF_FUNC_for_each_map_elem:
13337                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
13338                                 continue;
13339                         }
13340
13341                         goto patch_call_imm;
13342                 }
13343
13344                 /* Implement bpf_jiffies64 inline. */
13345                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
13346                     insn->imm == BPF_FUNC_jiffies64) {
13347                         struct bpf_insn ld_jiffies_addr[2] = {
13348                                 BPF_LD_IMM64(BPF_REG_0,
13349                                              (unsigned long)&jiffies),
13350                         };
13351
13352                         insn_buf[0] = ld_jiffies_addr[0];
13353                         insn_buf[1] = ld_jiffies_addr[1];
13354                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13355                                                   BPF_REG_0, 0);
13356                         cnt = 3;
13357
13358                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13359                                                        cnt);
13360                         if (!new_prog)
13361                                 return -ENOMEM;
13362
13363                         delta    += cnt - 1;
13364                         env->prog = prog = new_prog;
13365                         insn      = new_prog->insnsi + i + delta;
13366                         continue;
13367                 }
13368
13369                 /* Implement bpf_get_func_arg inline. */
13370                 if (prog_type == BPF_PROG_TYPE_TRACING &&
13371                     insn->imm == BPF_FUNC_get_func_arg) {
13372                         /* Load nr_args from ctx - 8 */
13373                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13374                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
13375                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
13376                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
13377                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
13378                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
13379                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
13380                         insn_buf[7] = BPF_JMP_A(1);
13381                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
13382                         cnt = 9;
13383
13384                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13385                         if (!new_prog)
13386                                 return -ENOMEM;
13387
13388                         delta    += cnt - 1;
13389                         env->prog = prog = new_prog;
13390                         insn      = new_prog->insnsi + i + delta;
13391                         continue;
13392                 }
13393
13394                 /* Implement bpf_get_func_ret inline. */
13395                 if (prog_type == BPF_PROG_TYPE_TRACING &&
13396                     insn->imm == BPF_FUNC_get_func_ret) {
13397                         if (eatype == BPF_TRACE_FEXIT ||
13398                             eatype == BPF_MODIFY_RETURN) {
13399                                 /* Load nr_args from ctx - 8 */
13400                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13401                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
13402                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
13403                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
13404                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
13405                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
13406                                 cnt = 6;
13407                         } else {
13408                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
13409                                 cnt = 1;
13410                         }
13411
13412                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13413                         if (!new_prog)
13414                                 return -ENOMEM;
13415
13416                         delta    += cnt - 1;
13417                         env->prog = prog = new_prog;
13418                         insn      = new_prog->insnsi + i + delta;
13419                         continue;
13420                 }
13421
13422                 /* Implement get_func_arg_cnt inline. */
13423                 if (prog_type == BPF_PROG_TYPE_TRACING &&
13424                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
13425                         /* Load nr_args from ctx - 8 */
13426                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13427
13428                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13429                         if (!new_prog)
13430                                 return -ENOMEM;
13431
13432                         env->prog = prog = new_prog;
13433                         insn      = new_prog->insnsi + i + delta;
13434                         continue;
13435                 }
13436
13437                 /* Implement bpf_get_func_ip inline. */
13438                 if (prog_type == BPF_PROG_TYPE_TRACING &&
13439                     insn->imm == BPF_FUNC_get_func_ip) {
13440                         /* Load IP address from ctx - 16 */
13441                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
13442
13443                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13444                         if (!new_prog)
13445                                 return -ENOMEM;
13446
13447                         env->prog = prog = new_prog;
13448                         insn      = new_prog->insnsi + i + delta;
13449                         continue;
13450                 }
13451
13452 patch_call_imm:
13453                 fn = env->ops->get_func_proto(insn->imm, env->prog);
13454                 /* all functions that have prototype and verifier allowed
13455                  * programs to call them, must be real in-kernel functions
13456                  */
13457                 if (!fn->func) {
13458                         verbose(env,
13459                                 "kernel subsystem misconfigured func %s#%d\n",
13460                                 func_id_name(insn->imm), insn->imm);
13461                         return -EFAULT;
13462                 }
13463                 insn->imm = fn->func - __bpf_call_base;
13464         }
13465
13466         /* Since poke tab is now finalized, publish aux to tracker. */
13467         for (i = 0; i < prog->aux->size_poke_tab; i++) {
13468                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13469                 if (!map_ptr->ops->map_poke_track ||
13470                     !map_ptr->ops->map_poke_untrack ||
13471                     !map_ptr->ops->map_poke_run) {
13472                         verbose(env, "bpf verifier is misconfigured\n");
13473                         return -EINVAL;
13474                 }
13475
13476                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13477                 if (ret < 0) {
13478                         verbose(env, "tracking tail call prog failed\n");
13479                         return ret;
13480                 }
13481         }
13482
13483         sort_kfunc_descs_by_imm(env->prog);
13484
13485         return 0;
13486 }
13487
13488 static void free_states(struct bpf_verifier_env *env)
13489 {
13490         struct bpf_verifier_state_list *sl, *sln;
13491         int i;
13492
13493         sl = env->free_list;
13494         while (sl) {
13495                 sln = sl->next;
13496                 free_verifier_state(&sl->state, false);
13497                 kfree(sl);
13498                 sl = sln;
13499         }
13500         env->free_list = NULL;
13501
13502         if (!env->explored_states)
13503                 return;
13504
13505         for (i = 0; i < state_htab_size(env); i++) {
13506                 sl = env->explored_states[i];
13507
13508                 while (sl) {
13509                         sln = sl->next;
13510                         free_verifier_state(&sl->state, false);
13511                         kfree(sl);
13512                         sl = sln;
13513                 }
13514                 env->explored_states[i] = NULL;
13515         }
13516 }
13517
13518 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13519 {
13520         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13521         struct bpf_verifier_state *state;
13522         struct bpf_reg_state *regs;
13523         int ret, i;
13524
13525         env->prev_linfo = NULL;
13526         env->pass_cnt++;
13527
13528         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13529         if (!state)
13530                 return -ENOMEM;
13531         state->curframe = 0;
13532         state->speculative = false;
13533         state->branches = 1;
13534         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13535         if (!state->frame[0]) {
13536                 kfree(state);
13537                 return -ENOMEM;
13538         }
13539         env->cur_state = state;
13540         init_func_state(env, state->frame[0],
13541                         BPF_MAIN_FUNC /* callsite */,
13542                         0 /* frameno */,
13543                         subprog);
13544
13545         regs = state->frame[state->curframe]->regs;
13546         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13547                 ret = btf_prepare_func_args(env, subprog, regs);
13548                 if (ret)
13549                         goto out;
13550                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13551                         if (regs[i].type == PTR_TO_CTX)
13552                                 mark_reg_known_zero(env, regs, i);
13553                         else if (regs[i].type == SCALAR_VALUE)
13554                                 mark_reg_unknown(env, regs, i);
13555                         else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
13556                                 const u32 mem_size = regs[i].mem_size;
13557
13558                                 mark_reg_known_zero(env, regs, i);
13559                                 regs[i].mem_size = mem_size;
13560                                 regs[i].id = ++env->id_gen;
13561                         }
13562                 }
13563         } else {
13564                 /* 1st arg to a function */
13565                 regs[BPF_REG_1].type = PTR_TO_CTX;
13566                 mark_reg_known_zero(env, regs, BPF_REG_1);
13567                 ret = btf_check_subprog_arg_match(env, subprog, regs);
13568                 if (ret == -EFAULT)
13569                         /* unlikely verifier bug. abort.
13570                          * ret == 0 and ret < 0 are sadly acceptable for
13571                          * main() function due to backward compatibility.
13572                          * Like socket filter program may be written as:
13573                          * int bpf_prog(struct pt_regs *ctx)
13574                          * and never dereference that ctx in the program.
13575                          * 'struct pt_regs' is a type mismatch for socket
13576                          * filter that should be using 'struct __sk_buff'.
13577                          */
13578                         goto out;
13579         }
13580
13581         ret = do_check(env);
13582 out:
13583         /* check for NULL is necessary, since cur_state can be freed inside
13584          * do_check() under memory pressure.
13585          */
13586         if (env->cur_state) {
13587                 free_verifier_state(env->cur_state, true);
13588                 env->cur_state = NULL;
13589         }
13590         while (!pop_stack(env, NULL, NULL, false));
13591         if (!ret && pop_log)
13592                 bpf_vlog_reset(&env->log, 0);
13593         free_states(env);
13594         return ret;
13595 }
13596
13597 /* Verify all global functions in a BPF program one by one based on their BTF.
13598  * All global functions must pass verification. Otherwise the whole program is rejected.
13599  * Consider:
13600  * int bar(int);
13601  * int foo(int f)
13602  * {
13603  *    return bar(f);
13604  * }
13605  * int bar(int b)
13606  * {
13607  *    ...
13608  * }
13609  * foo() will be verified first for R1=any_scalar_value. During verification it
13610  * will be assumed that bar() already verified successfully and call to bar()
13611  * from foo() will be checked for type match only. Later bar() will be verified
13612  * independently to check that it's safe for R1=any_scalar_value.
13613  */
13614 static int do_check_subprogs(struct bpf_verifier_env *env)
13615 {
13616         struct bpf_prog_aux *aux = env->prog->aux;
13617         int i, ret;
13618
13619         if (!aux->func_info)
13620                 return 0;
13621
13622         for (i = 1; i < env->subprog_cnt; i++) {
13623                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13624                         continue;
13625                 env->insn_idx = env->subprog_info[i].start;
13626                 WARN_ON_ONCE(env->insn_idx == 0);
13627                 ret = do_check_common(env, i);
13628                 if (ret) {
13629                         return ret;
13630                 } else if (env->log.level & BPF_LOG_LEVEL) {
13631                         verbose(env,
13632                                 "Func#%d is safe for any args that match its prototype\n",
13633                                 i);
13634                 }
13635         }
13636         return 0;
13637 }
13638
13639 static int do_check_main(struct bpf_verifier_env *env)
13640 {
13641         int ret;
13642
13643         env->insn_idx = 0;
13644         ret = do_check_common(env, 0);
13645         if (!ret)
13646                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13647         return ret;
13648 }
13649
13650
13651 static void print_verification_stats(struct bpf_verifier_env *env)
13652 {
13653         int i;
13654
13655         if (env->log.level & BPF_LOG_STATS) {
13656                 verbose(env, "verification time %lld usec\n",
13657                         div_u64(env->verification_time, 1000));
13658                 verbose(env, "stack depth ");
13659                 for (i = 0; i < env->subprog_cnt; i++) {
13660                         u32 depth = env->subprog_info[i].stack_depth;
13661
13662                         verbose(env, "%d", depth);
13663                         if (i + 1 < env->subprog_cnt)
13664                                 verbose(env, "+");
13665                 }
13666                 verbose(env, "\n");
13667         }
13668         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13669                 "total_states %d peak_states %d mark_read %d\n",
13670                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13671                 env->max_states_per_insn, env->total_states,
13672                 env->peak_states, env->longest_mark_read_walk);
13673 }
13674
13675 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13676 {
13677         const struct btf_type *t, *func_proto;
13678         const struct bpf_struct_ops *st_ops;
13679         const struct btf_member *member;
13680         struct bpf_prog *prog = env->prog;
13681         u32 btf_id, member_idx;
13682         const char *mname;
13683
13684         if (!prog->gpl_compatible) {
13685                 verbose(env, "struct ops programs must have a GPL compatible license\n");
13686                 return -EINVAL;
13687         }
13688
13689         btf_id = prog->aux->attach_btf_id;
13690         st_ops = bpf_struct_ops_find(btf_id);
13691         if (!st_ops) {
13692                 verbose(env, "attach_btf_id %u is not a supported struct\n",
13693                         btf_id);
13694                 return -ENOTSUPP;
13695         }
13696
13697         t = st_ops->type;
13698         member_idx = prog->expected_attach_type;
13699         if (member_idx >= btf_type_vlen(t)) {
13700                 verbose(env, "attach to invalid member idx %u of struct %s\n",
13701                         member_idx, st_ops->name);
13702                 return -EINVAL;
13703         }
13704
13705         member = &btf_type_member(t)[member_idx];
13706         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13707         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13708                                                NULL);
13709         if (!func_proto) {
13710                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13711                         mname, member_idx, st_ops->name);
13712                 return -EINVAL;
13713         }
13714
13715         if (st_ops->check_member) {
13716                 int err = st_ops->check_member(t, member);
13717
13718                 if (err) {
13719                         verbose(env, "attach to unsupported member %s of struct %s\n",
13720                                 mname, st_ops->name);
13721                         return err;
13722                 }
13723         }
13724
13725         prog->aux->attach_func_proto = func_proto;
13726         prog->aux->attach_func_name = mname;
13727         env->ops = st_ops->verifier_ops;
13728
13729         return 0;
13730 }
13731 #define SECURITY_PREFIX "security_"
13732
13733 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13734 {
13735         if (within_error_injection_list(addr) ||
13736             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13737                 return 0;
13738
13739         return -EINVAL;
13740 }
13741
13742 /* list of non-sleepable functions that are otherwise on
13743  * ALLOW_ERROR_INJECTION list
13744  */
13745 BTF_SET_START(btf_non_sleepable_error_inject)
13746 /* Three functions below can be called from sleepable and non-sleepable context.
13747  * Assume non-sleepable from bpf safety point of view.
13748  */
13749 BTF_ID(func, __filemap_add_folio)
13750 BTF_ID(func, should_fail_alloc_page)
13751 BTF_ID(func, should_failslab)
13752 BTF_SET_END(btf_non_sleepable_error_inject)
13753
13754 static int check_non_sleepable_error_inject(u32 btf_id)
13755 {
13756         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13757 }
13758
13759 int bpf_check_attach_target(struct bpf_verifier_log *log,
13760                             const struct bpf_prog *prog,
13761                             const struct bpf_prog *tgt_prog,
13762                             u32 btf_id,
13763                             struct bpf_attach_target_info *tgt_info)
13764 {
13765         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13766         const char prefix[] = "btf_trace_";
13767         int ret = 0, subprog = -1, i;
13768         const struct btf_type *t;
13769         bool conservative = true;
13770         const char *tname;
13771         struct btf *btf;
13772         long addr = 0;
13773
13774         if (!btf_id) {
13775                 bpf_log(log, "Tracing programs must provide btf_id\n");
13776                 return -EINVAL;
13777         }
13778         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13779         if (!btf) {
13780                 bpf_log(log,
13781                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13782                 return -EINVAL;
13783         }
13784         t = btf_type_by_id(btf, btf_id);
13785         if (!t) {
13786                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13787                 return -EINVAL;
13788         }
13789         tname = btf_name_by_offset(btf, t->name_off);
13790         if (!tname) {
13791                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13792                 return -EINVAL;
13793         }
13794         if (tgt_prog) {
13795                 struct bpf_prog_aux *aux = tgt_prog->aux;
13796
13797                 for (i = 0; i < aux->func_info_cnt; i++)
13798                         if (aux->func_info[i].type_id == btf_id) {
13799                                 subprog = i;
13800                                 break;
13801                         }
13802                 if (subprog == -1) {
13803                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
13804                         return -EINVAL;
13805                 }
13806                 conservative = aux->func_info_aux[subprog].unreliable;
13807                 if (prog_extension) {
13808                         if (conservative) {
13809                                 bpf_log(log,
13810                                         "Cannot replace static functions\n");
13811                                 return -EINVAL;
13812                         }
13813                         if (!prog->jit_requested) {
13814                                 bpf_log(log,
13815                                         "Extension programs should be JITed\n");
13816                                 return -EINVAL;
13817                         }
13818                 }
13819                 if (!tgt_prog->jited) {
13820                         bpf_log(log, "Can attach to only JITed progs\n");
13821                         return -EINVAL;
13822                 }
13823                 if (tgt_prog->type == prog->type) {
13824                         /* Cannot fentry/fexit another fentry/fexit program.
13825                          * Cannot attach program extension to another extension.
13826                          * It's ok to attach fentry/fexit to extension program.
13827                          */
13828                         bpf_log(log, "Cannot recursively attach\n");
13829                         return -EINVAL;
13830                 }
13831                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13832                     prog_extension &&
13833                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13834                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13835                         /* Program extensions can extend all program types
13836                          * except fentry/fexit. The reason is the following.
13837                          * The fentry/fexit programs are used for performance
13838                          * analysis, stats and can be attached to any program
13839                          * type except themselves. When extension program is
13840                          * replacing XDP function it is necessary to allow
13841                          * performance analysis of all functions. Both original
13842                          * XDP program and its program extension. Hence
13843                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13844                          * allowed. If extending of fentry/fexit was allowed it
13845                          * would be possible to create long call chain
13846                          * fentry->extension->fentry->extension beyond
13847                          * reasonable stack size. Hence extending fentry is not
13848                          * allowed.
13849                          */
13850                         bpf_log(log, "Cannot extend fentry/fexit\n");
13851                         return -EINVAL;
13852                 }
13853         } else {
13854                 if (prog_extension) {
13855                         bpf_log(log, "Cannot replace kernel functions\n");
13856                         return -EINVAL;
13857                 }
13858         }
13859
13860         switch (prog->expected_attach_type) {
13861         case BPF_TRACE_RAW_TP:
13862                 if (tgt_prog) {
13863                         bpf_log(log,
13864                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13865                         return -EINVAL;
13866                 }
13867                 if (!btf_type_is_typedef(t)) {
13868                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
13869                                 btf_id);
13870                         return -EINVAL;
13871                 }
13872                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13873                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13874                                 btf_id, tname);
13875                         return -EINVAL;
13876                 }
13877                 tname += sizeof(prefix) - 1;
13878                 t = btf_type_by_id(btf, t->type);
13879                 if (!btf_type_is_ptr(t))
13880                         /* should never happen in valid vmlinux build */
13881                         return -EINVAL;
13882                 t = btf_type_by_id(btf, t->type);
13883                 if (!btf_type_is_func_proto(t))
13884                         /* should never happen in valid vmlinux build */
13885                         return -EINVAL;
13886
13887                 break;
13888         case BPF_TRACE_ITER:
13889                 if (!btf_type_is_func(t)) {
13890                         bpf_log(log, "attach_btf_id %u is not a function\n",
13891                                 btf_id);
13892                         return -EINVAL;
13893                 }
13894                 t = btf_type_by_id(btf, t->type);
13895                 if (!btf_type_is_func_proto(t))
13896                         return -EINVAL;
13897                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13898                 if (ret)
13899                         return ret;
13900                 break;
13901         default:
13902                 if (!prog_extension)
13903                         return -EINVAL;
13904                 fallthrough;
13905         case BPF_MODIFY_RETURN:
13906         case BPF_LSM_MAC:
13907         case BPF_TRACE_FENTRY:
13908         case BPF_TRACE_FEXIT:
13909                 if (!btf_type_is_func(t)) {
13910                         bpf_log(log, "attach_btf_id %u is not a function\n",
13911                                 btf_id);
13912                         return -EINVAL;
13913                 }
13914                 if (prog_extension &&
13915                     btf_check_type_match(log, prog, btf, t))
13916                         return -EINVAL;
13917                 t = btf_type_by_id(btf, t->type);
13918                 if (!btf_type_is_func_proto(t))
13919                         return -EINVAL;
13920
13921                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13922                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13923                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13924                         return -EINVAL;
13925
13926                 if (tgt_prog && conservative)
13927                         t = NULL;
13928
13929                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13930                 if (ret < 0)
13931                         return ret;
13932
13933                 if (tgt_prog) {
13934                         if (subprog == 0)
13935                                 addr = (long) tgt_prog->bpf_func;
13936                         else
13937                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13938                 } else {
13939                         addr = kallsyms_lookup_name(tname);
13940                         if (!addr) {
13941                                 bpf_log(log,
13942                                         "The address of function %s cannot be found\n",
13943                                         tname);
13944                                 return -ENOENT;
13945                         }
13946                 }
13947
13948                 if (prog->aux->sleepable) {
13949                         ret = -EINVAL;
13950                         switch (prog->type) {
13951                         case BPF_PROG_TYPE_TRACING:
13952                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13953                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13954                                  */
13955                                 if (!check_non_sleepable_error_inject(btf_id) &&
13956                                     within_error_injection_list(addr))
13957                                         ret = 0;
13958                                 break;
13959                         case BPF_PROG_TYPE_LSM:
13960                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13961                                  * Only some of them are sleepable.
13962                                  */
13963                                 if (bpf_lsm_is_sleepable_hook(btf_id))
13964                                         ret = 0;
13965                                 break;
13966                         default:
13967                                 break;
13968                         }
13969                         if (ret) {
13970                                 bpf_log(log, "%s is not sleepable\n", tname);
13971                                 return ret;
13972                         }
13973                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13974                         if (tgt_prog) {
13975                                 bpf_log(log, "can't modify return codes of BPF programs\n");
13976                                 return -EINVAL;
13977                         }
13978                         ret = check_attach_modify_return(addr, tname);
13979                         if (ret) {
13980                                 bpf_log(log, "%s() is not modifiable\n", tname);
13981                                 return ret;
13982                         }
13983                 }
13984
13985                 break;
13986         }
13987         tgt_info->tgt_addr = addr;
13988         tgt_info->tgt_name = tname;
13989         tgt_info->tgt_type = t;
13990         return 0;
13991 }
13992
13993 BTF_SET_START(btf_id_deny)
13994 BTF_ID_UNUSED
13995 #ifdef CONFIG_SMP
13996 BTF_ID(func, migrate_disable)
13997 BTF_ID(func, migrate_enable)
13998 #endif
13999 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
14000 BTF_ID(func, rcu_read_unlock_strict)
14001 #endif
14002 BTF_SET_END(btf_id_deny)
14003
14004 static int check_attach_btf_id(struct bpf_verifier_env *env)
14005 {
14006         struct bpf_prog *prog = env->prog;
14007         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
14008         struct bpf_attach_target_info tgt_info = {};
14009         u32 btf_id = prog->aux->attach_btf_id;
14010         struct bpf_trampoline *tr;
14011         int ret;
14012         u64 key;
14013
14014         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
14015                 if (prog->aux->sleepable)
14016                         /* attach_btf_id checked to be zero already */
14017                         return 0;
14018                 verbose(env, "Syscall programs can only be sleepable\n");
14019                 return -EINVAL;
14020         }
14021
14022         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
14023             prog->type != BPF_PROG_TYPE_LSM) {
14024                 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
14025                 return -EINVAL;
14026         }
14027
14028         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
14029                 return check_struct_ops_btf_id(env);
14030
14031         if (prog->type != BPF_PROG_TYPE_TRACING &&
14032             prog->type != BPF_PROG_TYPE_LSM &&
14033             prog->type != BPF_PROG_TYPE_EXT)
14034                 return 0;
14035
14036         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
14037         if (ret)
14038                 return ret;
14039
14040         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
14041                 /* to make freplace equivalent to their targets, they need to
14042                  * inherit env->ops and expected_attach_type for the rest of the
14043                  * verification
14044                  */
14045                 env->ops = bpf_verifier_ops[tgt_prog->type];
14046                 prog->expected_attach_type = tgt_prog->expected_attach_type;
14047         }
14048
14049         /* store info about the attachment target that will be used later */
14050         prog->aux->attach_func_proto = tgt_info.tgt_type;
14051         prog->aux->attach_func_name = tgt_info.tgt_name;
14052
14053         if (tgt_prog) {
14054                 prog->aux->saved_dst_prog_type = tgt_prog->type;
14055                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
14056         }
14057
14058         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
14059                 prog->aux->attach_btf_trace = true;
14060                 return 0;
14061         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
14062                 if (!bpf_iter_prog_supported(prog))
14063                         return -EINVAL;
14064                 return 0;
14065         }
14066
14067         if (prog->type == BPF_PROG_TYPE_LSM) {
14068                 ret = bpf_lsm_verify_prog(&env->log, prog);
14069                 if (ret < 0)
14070                         return ret;
14071         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
14072                    btf_id_set_contains(&btf_id_deny, btf_id)) {
14073                 return -EINVAL;
14074         }
14075
14076         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
14077         tr = bpf_trampoline_get(key, &tgt_info);
14078         if (!tr)
14079                 return -ENOMEM;
14080
14081         prog->aux->dst_trampoline = tr;
14082         return 0;
14083 }
14084
14085 struct btf *bpf_get_btf_vmlinux(void)
14086 {
14087         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
14088                 mutex_lock(&bpf_verifier_lock);
14089                 if (!btf_vmlinux)
14090                         btf_vmlinux = btf_parse_vmlinux();
14091                 mutex_unlock(&bpf_verifier_lock);
14092         }
14093         return btf_vmlinux;
14094 }
14095
14096 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
14097 {
14098         u64 start_time = ktime_get_ns();
14099         struct bpf_verifier_env *env;
14100         struct bpf_verifier_log *log;
14101         int i, len, ret = -EINVAL;
14102         bool is_priv;
14103
14104         /* no program is valid */
14105         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
14106                 return -EINVAL;
14107
14108         /* 'struct bpf_verifier_env' can be global, but since it's not small,
14109          * allocate/free it every time bpf_check() is called
14110          */
14111         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
14112         if (!env)
14113                 return -ENOMEM;
14114         log = &env->log;
14115
14116         len = (*prog)->len;
14117         env->insn_aux_data =
14118                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
14119         ret = -ENOMEM;
14120         if (!env->insn_aux_data)
14121                 goto err_free_env;
14122         for (i = 0; i < len; i++)
14123                 env->insn_aux_data[i].orig_idx = i;
14124         env->prog = *prog;
14125         env->ops = bpf_verifier_ops[env->prog->type];
14126         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
14127         is_priv = bpf_capable();
14128
14129         bpf_get_btf_vmlinux();
14130
14131         /* grab the mutex to protect few globals used by verifier */
14132         if (!is_priv)
14133                 mutex_lock(&bpf_verifier_lock);
14134
14135         if (attr->log_level || attr->log_buf || attr->log_size) {
14136                 /* user requested verbose verifier output
14137                  * and supplied buffer to store the verification trace
14138                  */
14139                 log->level = attr->log_level;
14140                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
14141                 log->len_total = attr->log_size;
14142
14143                 /* log attributes have to be sane */
14144                 if (!bpf_verifier_log_attr_valid(log)) {
14145                         ret = -EINVAL;
14146                         goto err_unlock;
14147                 }
14148         }
14149
14150         if (IS_ERR(btf_vmlinux)) {
14151                 /* Either gcc or pahole or kernel are broken. */
14152                 verbose(env, "in-kernel BTF is malformed\n");
14153                 ret = PTR_ERR(btf_vmlinux);
14154                 goto skip_full_check;
14155         }
14156
14157         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
14158         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
14159                 env->strict_alignment = true;
14160         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
14161                 env->strict_alignment = false;
14162
14163         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
14164         env->allow_uninit_stack = bpf_allow_uninit_stack();
14165         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
14166         env->bypass_spec_v1 = bpf_bypass_spec_v1();
14167         env->bypass_spec_v4 = bpf_bypass_spec_v4();
14168         env->bpf_capable = bpf_capable();
14169
14170         if (is_priv)
14171                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
14172
14173         env->explored_states = kvcalloc(state_htab_size(env),
14174                                        sizeof(struct bpf_verifier_state_list *),
14175                                        GFP_USER);
14176         ret = -ENOMEM;
14177         if (!env->explored_states)
14178                 goto skip_full_check;
14179
14180         ret = add_subprog_and_kfunc(env);
14181         if (ret < 0)
14182                 goto skip_full_check;
14183
14184         ret = check_subprogs(env);
14185         if (ret < 0)
14186                 goto skip_full_check;
14187
14188         ret = check_btf_info(env, attr, uattr);
14189         if (ret < 0)
14190                 goto skip_full_check;
14191
14192         ret = check_attach_btf_id(env);
14193         if (ret)
14194                 goto skip_full_check;
14195
14196         ret = resolve_pseudo_ldimm64(env);
14197         if (ret < 0)
14198                 goto skip_full_check;
14199
14200         if (bpf_prog_is_dev_bound(env->prog->aux)) {
14201                 ret = bpf_prog_offload_verifier_prep(env->prog);
14202                 if (ret)
14203                         goto skip_full_check;
14204         }
14205
14206         ret = check_cfg(env);
14207         if (ret < 0)
14208                 goto skip_full_check;
14209
14210         ret = do_check_subprogs(env);
14211         ret = ret ?: do_check_main(env);
14212
14213         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
14214                 ret = bpf_prog_offload_finalize(env);
14215
14216 skip_full_check:
14217         kvfree(env->explored_states);
14218
14219         if (ret == 0)
14220                 ret = check_max_stack_depth(env);
14221
14222         /* instruction rewrites happen after this point */
14223         if (is_priv) {
14224                 if (ret == 0)
14225                         opt_hard_wire_dead_code_branches(env);
14226                 if (ret == 0)
14227                         ret = opt_remove_dead_code(env);
14228                 if (ret == 0)
14229                         ret = opt_remove_nops(env);
14230         } else {
14231                 if (ret == 0)
14232                         sanitize_dead_code(env);
14233         }
14234
14235         if (ret == 0)
14236                 /* program is valid, convert *(u32*)(ctx + off) accesses */
14237                 ret = convert_ctx_accesses(env);
14238
14239         if (ret == 0)
14240                 ret = do_misc_fixups(env);
14241
14242         /* do 32-bit optimization after insn patching has done so those patched
14243          * insns could be handled correctly.
14244          */
14245         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
14246                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
14247                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
14248                                                                      : false;
14249         }
14250
14251         if (ret == 0)
14252                 ret = fixup_call_args(env);
14253
14254         env->verification_time = ktime_get_ns() - start_time;
14255         print_verification_stats(env);
14256         env->prog->aux->verified_insns = env->insn_processed;
14257
14258         if (log->level && bpf_verifier_log_full(log))
14259                 ret = -ENOSPC;
14260         if (log->level && !log->ubuf) {
14261                 ret = -EFAULT;
14262                 goto err_release_maps;
14263         }
14264
14265         if (ret)
14266                 goto err_release_maps;
14267
14268         if (env->used_map_cnt) {
14269                 /* if program passed verifier, update used_maps in bpf_prog_info */
14270                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
14271                                                           sizeof(env->used_maps[0]),
14272                                                           GFP_KERNEL);
14273
14274                 if (!env->prog->aux->used_maps) {
14275                         ret = -ENOMEM;
14276                         goto err_release_maps;
14277                 }
14278
14279                 memcpy(env->prog->aux->used_maps, env->used_maps,
14280                        sizeof(env->used_maps[0]) * env->used_map_cnt);
14281                 env->prog->aux->used_map_cnt = env->used_map_cnt;
14282         }
14283         if (env->used_btf_cnt) {
14284                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
14285                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
14286                                                           sizeof(env->used_btfs[0]),
14287                                                           GFP_KERNEL);
14288                 if (!env->prog->aux->used_btfs) {
14289                         ret = -ENOMEM;
14290                         goto err_release_maps;
14291                 }
14292
14293                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
14294                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
14295                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
14296         }
14297         if (env->used_map_cnt || env->used_btf_cnt) {
14298                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
14299                  * bpf_ld_imm64 instructions
14300                  */
14301                 convert_pseudo_ld_imm64(env);
14302         }
14303
14304         adjust_btf_func(env);
14305
14306 err_release_maps:
14307         if (!env->prog->aux->used_maps)
14308                 /* if we didn't copy map pointers into bpf_prog_info, release
14309                  * them now. Otherwise free_used_maps() will release them.
14310                  */
14311                 release_maps(env);
14312         if (!env->prog->aux->used_btfs)
14313                 release_btfs(env);
14314
14315         /* extension progs temporarily inherit the attach_type of their targets
14316            for verification purposes, so set it back to zero before returning
14317          */
14318         if (env->prog->type == BPF_PROG_TYPE_EXT)
14319                 env->prog->expected_attach_type = 0;
14320
14321         *prog = env->prog;
14322 err_unlock:
14323         if (!is_priv)
14324                 mutex_unlock(&bpf_verifier_lock);
14325         vfree(env->insn_aux_data);
14326 err_free_env:
14327         kfree(env);
14328         return ret;
14329 }