bpf: Skip invalid kfunc call in backtrack_insn
[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/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27
28 #include "disasm.h"
29
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32         [_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168         /* verifer state is 'st'
169          * before processing instruction 'insn_idx'
170          * and after processing instruction 'prev_insn_idx'
171          */
172         struct bpf_verifier_state st;
173         int insn_idx;
174         int prev_insn_idx;
175         struct bpf_verifier_stack_elem *next;
176         /* length of verifier log at the time this state was pushed on stack */
177         u32 log_pos;
178 };
179
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
181 #define BPF_COMPLEXITY_LIMIT_STATES     64
182
183 #define BPF_MAP_KEY_POISON      (1ULL << 63)
184 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
185
186 #define BPF_MAP_PTR_UNPRIV      1UL
187 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
188                                           POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193
194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 {
196         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
197 }
198
199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 {
201         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
202 }
203
204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205                               const struct bpf_map *map, bool unpriv)
206 {
207         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208         unpriv |= bpf_map_ptr_unpriv(aux);
209         aux->map_ptr_state = (unsigned long)map |
210                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211 }
212
213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 {
215         return aux->map_key_state & BPF_MAP_KEY_POISON;
216 }
217
218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 {
220         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221 }
222
223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 {
225         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226 }
227
228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 {
230         bool poisoned = bpf_map_key_poisoned(aux);
231
232         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
234 }
235
236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 {
238         return insn->code == (BPF_JMP | BPF_CALL) &&
239                insn->src_reg == BPF_PSEUDO_CALL;
240 }
241
242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 {
244         return insn->code == (BPF_JMP | BPF_CALL) &&
245                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246 }
247
248 struct bpf_call_arg_meta {
249         struct bpf_map *map_ptr;
250         bool raw_mode;
251         bool pkt_access;
252         u8 release_regno;
253         int regno;
254         int access_size;
255         int mem_size;
256         u64 msize_max_value;
257         int ref_obj_id;
258         int map_uid;
259         int func_id;
260         struct btf *btf;
261         u32 btf_id;
262         struct btf *ret_btf;
263         u32 ret_btf_id;
264         u32 subprogno;
265         struct bpf_map_value_off_desc *kptr_off_desc;
266         u8 uninit_dynptr_regno;
267 };
268
269 struct btf *btf_vmlinux;
270
271 static DEFINE_MUTEX(bpf_verifier_lock);
272
273 static const struct bpf_line_info *
274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 {
276         const struct bpf_line_info *linfo;
277         const struct bpf_prog *prog;
278         u32 i, nr_linfo;
279
280         prog = env->prog;
281         nr_linfo = prog->aux->nr_linfo;
282
283         if (!nr_linfo || insn_off >= prog->len)
284                 return NULL;
285
286         linfo = prog->aux->linfo;
287         for (i = 1; i < nr_linfo; i++)
288                 if (insn_off < linfo[i].insn_off)
289                         break;
290
291         return &linfo[i - 1];
292 }
293
294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295                        va_list args)
296 {
297         unsigned int n;
298
299         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300
301         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302                   "verifier log line truncated - local buffer too short\n");
303
304         if (log->level == BPF_LOG_KERNEL) {
305                 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306
307                 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
308                 return;
309         }
310
311         n = min(log->len_total - log->len_used - 1, n);
312         log->kbuf[n] = '\0';
313         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314                 log->len_used += n;
315         else
316                 log->ubuf = NULL;
317 }
318
319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320 {
321         char zero = 0;
322
323         if (!bpf_verifier_log_needed(log))
324                 return;
325
326         log->len_used = new_pos;
327         if (put_user(zero, log->ubuf + new_pos))
328                 log->ubuf = NULL;
329 }
330
331 /* log_level controls verbosity level of eBPF verifier.
332  * bpf_verifier_log_write() is used to dump the verification trace to the log,
333  * so the user can figure out what's wrong with the program
334  */
335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336                                            const char *fmt, ...)
337 {
338         va_list args;
339
340         if (!bpf_verifier_log_needed(&env->log))
341                 return;
342
343         va_start(args, fmt);
344         bpf_verifier_vlog(&env->log, fmt, args);
345         va_end(args);
346 }
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348
349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 {
351         struct bpf_verifier_env *env = private_data;
352         va_list args;
353
354         if (!bpf_verifier_log_needed(&env->log))
355                 return;
356
357         va_start(args, fmt);
358         bpf_verifier_vlog(&env->log, fmt, args);
359         va_end(args);
360 }
361
362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363                             const char *fmt, ...)
364 {
365         va_list args;
366
367         if (!bpf_verifier_log_needed(log))
368                 return;
369
370         va_start(args, fmt);
371         bpf_verifier_vlog(log, fmt, args);
372         va_end(args);
373 }
374 EXPORT_SYMBOL_GPL(bpf_log);
375
376 static const char *ltrim(const char *s)
377 {
378         while (isspace(*s))
379                 s++;
380
381         return s;
382 }
383
384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385                                          u32 insn_off,
386                                          const char *prefix_fmt, ...)
387 {
388         const struct bpf_line_info *linfo;
389
390         if (!bpf_verifier_log_needed(&env->log))
391                 return;
392
393         linfo = find_linfo(env, insn_off);
394         if (!linfo || linfo == env->prev_linfo)
395                 return;
396
397         if (prefix_fmt) {
398                 va_list args;
399
400                 va_start(args, prefix_fmt);
401                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
402                 va_end(args);
403         }
404
405         verbose(env, "%s\n",
406                 ltrim(btf_name_by_offset(env->prog->aux->btf,
407                                          linfo->line_off)));
408
409         env->prev_linfo = linfo;
410 }
411
412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413                                    struct bpf_reg_state *reg,
414                                    struct tnum *range, const char *ctx,
415                                    const char *reg_name)
416 {
417         char tn_buf[48];
418
419         verbose(env, "At %s the register %s ", ctx, reg_name);
420         if (!tnum_is_unknown(reg->var_off)) {
421                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422                 verbose(env, "has value %s", tn_buf);
423         } else {
424                 verbose(env, "has unknown scalar value");
425         }
426         tnum_strn(tn_buf, sizeof(tn_buf), *range);
427         verbose(env, " should have been in %s\n", tn_buf);
428 }
429
430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
431 {
432         type = base_type(type);
433         return type == PTR_TO_PACKET ||
434                type == PTR_TO_PACKET_META;
435 }
436
437 static bool type_is_sk_pointer(enum bpf_reg_type type)
438 {
439         return type == PTR_TO_SOCKET ||
440                 type == PTR_TO_SOCK_COMMON ||
441                 type == PTR_TO_TCP_SOCK ||
442                 type == PTR_TO_XDP_SOCK;
443 }
444
445 static bool reg_type_not_null(enum bpf_reg_type type)
446 {
447         return type == PTR_TO_SOCKET ||
448                 type == PTR_TO_TCP_SOCK ||
449                 type == PTR_TO_MAP_VALUE ||
450                 type == PTR_TO_MAP_KEY ||
451                 type == PTR_TO_SOCK_COMMON;
452 }
453
454 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
455 {
456         return reg->type == PTR_TO_MAP_VALUE &&
457                 map_value_has_spin_lock(reg->map_ptr);
458 }
459
460 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
461 {
462         type = base_type(type);
463         return type == PTR_TO_SOCKET || type == PTR_TO_TCP_SOCK ||
464                 type == PTR_TO_MEM || type == PTR_TO_BTF_ID;
465 }
466
467 static bool type_is_rdonly_mem(u32 type)
468 {
469         return type & MEM_RDONLY;
470 }
471
472 static bool type_may_be_null(u32 type)
473 {
474         return type & PTR_MAYBE_NULL;
475 }
476
477 static bool is_acquire_function(enum bpf_func_id func_id,
478                                 const struct bpf_map *map)
479 {
480         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
481
482         if (func_id == BPF_FUNC_sk_lookup_tcp ||
483             func_id == BPF_FUNC_sk_lookup_udp ||
484             func_id == BPF_FUNC_skc_lookup_tcp ||
485             func_id == BPF_FUNC_ringbuf_reserve ||
486             func_id == BPF_FUNC_kptr_xchg)
487                 return true;
488
489         if (func_id == BPF_FUNC_map_lookup_elem &&
490             (map_type == BPF_MAP_TYPE_SOCKMAP ||
491              map_type == BPF_MAP_TYPE_SOCKHASH))
492                 return true;
493
494         return false;
495 }
496
497 static bool is_ptr_cast_function(enum bpf_func_id func_id)
498 {
499         return func_id == BPF_FUNC_tcp_sock ||
500                 func_id == BPF_FUNC_sk_fullsock ||
501                 func_id == BPF_FUNC_skc_to_tcp_sock ||
502                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
503                 func_id == BPF_FUNC_skc_to_udp6_sock ||
504                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
505                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
506                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
507 }
508
509 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
510 {
511         return func_id == BPF_FUNC_dynptr_data;
512 }
513
514 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
515                                         const struct bpf_map *map)
516 {
517         int ref_obj_uses = 0;
518
519         if (is_ptr_cast_function(func_id))
520                 ref_obj_uses++;
521         if (is_acquire_function(func_id, map))
522                 ref_obj_uses++;
523         if (is_dynptr_ref_function(func_id))
524                 ref_obj_uses++;
525
526         return ref_obj_uses > 1;
527 }
528
529 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
530 {
531         return BPF_CLASS(insn->code) == BPF_STX &&
532                BPF_MODE(insn->code) == BPF_ATOMIC &&
533                insn->imm == BPF_CMPXCHG;
534 }
535
536 /* string representation of 'enum bpf_reg_type'
537  *
538  * Note that reg_type_str() can not appear more than once in a single verbose()
539  * statement.
540  */
541 static const char *reg_type_str(struct bpf_verifier_env *env,
542                                 enum bpf_reg_type type)
543 {
544         char postfix[16] = {0}, prefix[32] = {0};
545         static const char * const str[] = {
546                 [NOT_INIT]              = "?",
547                 [SCALAR_VALUE]          = "scalar",
548                 [PTR_TO_CTX]            = "ctx",
549                 [CONST_PTR_TO_MAP]      = "map_ptr",
550                 [PTR_TO_MAP_VALUE]      = "map_value",
551                 [PTR_TO_STACK]          = "fp",
552                 [PTR_TO_PACKET]         = "pkt",
553                 [PTR_TO_PACKET_META]    = "pkt_meta",
554                 [PTR_TO_PACKET_END]     = "pkt_end",
555                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
556                 [PTR_TO_SOCKET]         = "sock",
557                 [PTR_TO_SOCK_COMMON]    = "sock_common",
558                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
559                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
560                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
561                 [PTR_TO_BTF_ID]         = "ptr_",
562                 [PTR_TO_MEM]            = "mem",
563                 [PTR_TO_BUF]            = "buf",
564                 [PTR_TO_FUNC]           = "func",
565                 [PTR_TO_MAP_KEY]        = "map_key",
566                 [PTR_TO_DYNPTR]         = "dynptr_ptr",
567         };
568
569         if (type & PTR_MAYBE_NULL) {
570                 if (base_type(type) == PTR_TO_BTF_ID)
571                         strncpy(postfix, "or_null_", 16);
572                 else
573                         strncpy(postfix, "_or_null", 16);
574         }
575
576         if (type & MEM_RDONLY)
577                 strncpy(prefix, "rdonly_", 32);
578         if (type & MEM_ALLOC)
579                 strncpy(prefix, "alloc_", 32);
580         if (type & MEM_USER)
581                 strncpy(prefix, "user_", 32);
582         if (type & MEM_PERCPU)
583                 strncpy(prefix, "percpu_", 32);
584         if (type & PTR_UNTRUSTED)
585                 strncpy(prefix, "untrusted_", 32);
586
587         snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
588                  prefix, str[base_type(type)], postfix);
589         return env->type_str_buf;
590 }
591
592 static char slot_type_char[] = {
593         [STACK_INVALID] = '?',
594         [STACK_SPILL]   = 'r',
595         [STACK_MISC]    = 'm',
596         [STACK_ZERO]    = '0',
597         [STACK_DYNPTR]  = 'd',
598 };
599
600 static void print_liveness(struct bpf_verifier_env *env,
601                            enum bpf_reg_liveness live)
602 {
603         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
604             verbose(env, "_");
605         if (live & REG_LIVE_READ)
606                 verbose(env, "r");
607         if (live & REG_LIVE_WRITTEN)
608                 verbose(env, "w");
609         if (live & REG_LIVE_DONE)
610                 verbose(env, "D");
611 }
612
613 static int get_spi(s32 off)
614 {
615         return (-off - 1) / BPF_REG_SIZE;
616 }
617
618 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
619 {
620         int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
621
622         /* We need to check that slots between [spi - nr_slots + 1, spi] are
623          * within [0, allocated_stack).
624          *
625          * Please note that the spi grows downwards. For example, a dynptr
626          * takes the size of two stack slots; the first slot will be at
627          * spi and the second slot will be at spi - 1.
628          */
629         return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
630 }
631
632 static struct bpf_func_state *func(struct bpf_verifier_env *env,
633                                    const struct bpf_reg_state *reg)
634 {
635         struct bpf_verifier_state *cur = env->cur_state;
636
637         return cur->frame[reg->frameno];
638 }
639
640 static const char *kernel_type_name(const struct btf* btf, u32 id)
641 {
642         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
643 }
644
645 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
646 {
647         env->scratched_regs |= 1U << regno;
648 }
649
650 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
651 {
652         env->scratched_stack_slots |= 1ULL << spi;
653 }
654
655 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
656 {
657         return (env->scratched_regs >> regno) & 1;
658 }
659
660 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
661 {
662         return (env->scratched_stack_slots >> regno) & 1;
663 }
664
665 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
666 {
667         return env->scratched_regs || env->scratched_stack_slots;
668 }
669
670 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
671 {
672         env->scratched_regs = 0U;
673         env->scratched_stack_slots = 0ULL;
674 }
675
676 /* Used for printing the entire verifier state. */
677 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
678 {
679         env->scratched_regs = ~0U;
680         env->scratched_stack_slots = ~0ULL;
681 }
682
683 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
684 {
685         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
686         case DYNPTR_TYPE_LOCAL:
687                 return BPF_DYNPTR_TYPE_LOCAL;
688         case DYNPTR_TYPE_RINGBUF:
689                 return BPF_DYNPTR_TYPE_RINGBUF;
690         default:
691                 return BPF_DYNPTR_TYPE_INVALID;
692         }
693 }
694
695 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
696 {
697         return type == BPF_DYNPTR_TYPE_RINGBUF;
698 }
699
700 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
701                                    enum bpf_arg_type arg_type, int insn_idx)
702 {
703         struct bpf_func_state *state = func(env, reg);
704         enum bpf_dynptr_type type;
705         int spi, i, id;
706
707         spi = get_spi(reg->off);
708
709         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
710                 return -EINVAL;
711
712         for (i = 0; i < BPF_REG_SIZE; i++) {
713                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
714                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
715         }
716
717         type = arg_to_dynptr_type(arg_type);
718         if (type == BPF_DYNPTR_TYPE_INVALID)
719                 return -EINVAL;
720
721         state->stack[spi].spilled_ptr.dynptr.first_slot = true;
722         state->stack[spi].spilled_ptr.dynptr.type = type;
723         state->stack[spi - 1].spilled_ptr.dynptr.type = type;
724
725         if (dynptr_type_refcounted(type)) {
726                 /* The id is used to track proper releasing */
727                 id = acquire_reference_state(env, insn_idx);
728                 if (id < 0)
729                         return id;
730
731                 state->stack[spi].spilled_ptr.id = id;
732                 state->stack[spi - 1].spilled_ptr.id = id;
733         }
734
735         return 0;
736 }
737
738 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
739 {
740         struct bpf_func_state *state = func(env, reg);
741         int spi, i;
742
743         spi = get_spi(reg->off);
744
745         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
746                 return -EINVAL;
747
748         for (i = 0; i < BPF_REG_SIZE; i++) {
749                 state->stack[spi].slot_type[i] = STACK_INVALID;
750                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
751         }
752
753         /* Invalidate any slices associated with this dynptr */
754         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
755                 release_reference(env, state->stack[spi].spilled_ptr.id);
756                 state->stack[spi].spilled_ptr.id = 0;
757                 state->stack[spi - 1].spilled_ptr.id = 0;
758         }
759
760         state->stack[spi].spilled_ptr.dynptr.first_slot = false;
761         state->stack[spi].spilled_ptr.dynptr.type = 0;
762         state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
763
764         return 0;
765 }
766
767 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
768 {
769         struct bpf_func_state *state = func(env, reg);
770         int spi = get_spi(reg->off);
771         int i;
772
773         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
774                 return true;
775
776         for (i = 0; i < BPF_REG_SIZE; i++) {
777                 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
778                     state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
779                         return false;
780         }
781
782         return true;
783 }
784
785 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
786                               struct bpf_reg_state *reg)
787 {
788         struct bpf_func_state *state = func(env, reg);
789         int spi = get_spi(reg->off);
790         int i;
791
792         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
793             !state->stack[spi].spilled_ptr.dynptr.first_slot)
794                 return false;
795
796         for (i = 0; i < BPF_REG_SIZE; i++) {
797                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
798                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
799                         return false;
800         }
801
802         return true;
803 }
804
805 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
806                              struct bpf_reg_state *reg,
807                              enum bpf_arg_type arg_type)
808 {
809         struct bpf_func_state *state = func(env, reg);
810         enum bpf_dynptr_type dynptr_type;
811         int spi = get_spi(reg->off);
812
813         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
814         if (arg_type == ARG_PTR_TO_DYNPTR)
815                 return true;
816
817         dynptr_type = arg_to_dynptr_type(arg_type);
818
819         return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
820 }
821
822 /* The reg state of a pointer or a bounded scalar was saved when
823  * it was spilled to the stack.
824  */
825 static bool is_spilled_reg(const struct bpf_stack_state *stack)
826 {
827         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
828 }
829
830 static void scrub_spilled_slot(u8 *stype)
831 {
832         if (*stype != STACK_INVALID)
833                 *stype = STACK_MISC;
834 }
835
836 static void print_verifier_state(struct bpf_verifier_env *env,
837                                  const struct bpf_func_state *state,
838                                  bool print_all)
839 {
840         const struct bpf_reg_state *reg;
841         enum bpf_reg_type t;
842         int i;
843
844         if (state->frameno)
845                 verbose(env, " frame%d:", state->frameno);
846         for (i = 0; i < MAX_BPF_REG; i++) {
847                 reg = &state->regs[i];
848                 t = reg->type;
849                 if (t == NOT_INIT)
850                         continue;
851                 if (!print_all && !reg_scratched(env, i))
852                         continue;
853                 verbose(env, " R%d", i);
854                 print_liveness(env, reg->live);
855                 verbose(env, "=");
856                 if (t == SCALAR_VALUE && reg->precise)
857                         verbose(env, "P");
858                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
859                     tnum_is_const(reg->var_off)) {
860                         /* reg->off should be 0 for SCALAR_VALUE */
861                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
862                         verbose(env, "%lld", reg->var_off.value + reg->off);
863                 } else {
864                         const char *sep = "";
865
866                         verbose(env, "%s", reg_type_str(env, t));
867                         if (base_type(t) == PTR_TO_BTF_ID)
868                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
869                         verbose(env, "(");
870 /*
871  * _a stands for append, was shortened to avoid multiline statements below.
872  * This macro is used to output a comma separated list of attributes.
873  */
874 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
875
876                         if (reg->id)
877                                 verbose_a("id=%d", reg->id);
878                         if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
879                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
880                         if (t != SCALAR_VALUE)
881                                 verbose_a("off=%d", reg->off);
882                         if (type_is_pkt_pointer(t))
883                                 verbose_a("r=%d", reg->range);
884                         else if (base_type(t) == CONST_PTR_TO_MAP ||
885                                  base_type(t) == PTR_TO_MAP_KEY ||
886                                  base_type(t) == PTR_TO_MAP_VALUE)
887                                 verbose_a("ks=%d,vs=%d",
888                                           reg->map_ptr->key_size,
889                                           reg->map_ptr->value_size);
890                         if (tnum_is_const(reg->var_off)) {
891                                 /* Typically an immediate SCALAR_VALUE, but
892                                  * could be a pointer whose offset is too big
893                                  * for reg->off
894                                  */
895                                 verbose_a("imm=%llx", reg->var_off.value);
896                         } else {
897                                 if (reg->smin_value != reg->umin_value &&
898                                     reg->smin_value != S64_MIN)
899                                         verbose_a("smin=%lld", (long long)reg->smin_value);
900                                 if (reg->smax_value != reg->umax_value &&
901                                     reg->smax_value != S64_MAX)
902                                         verbose_a("smax=%lld", (long long)reg->smax_value);
903                                 if (reg->umin_value != 0)
904                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
905                                 if (reg->umax_value != U64_MAX)
906                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
907                                 if (!tnum_is_unknown(reg->var_off)) {
908                                         char tn_buf[48];
909
910                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
911                                         verbose_a("var_off=%s", tn_buf);
912                                 }
913                                 if (reg->s32_min_value != reg->smin_value &&
914                                     reg->s32_min_value != S32_MIN)
915                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
916                                 if (reg->s32_max_value != reg->smax_value &&
917                                     reg->s32_max_value != S32_MAX)
918                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
919                                 if (reg->u32_min_value != reg->umin_value &&
920                                     reg->u32_min_value != U32_MIN)
921                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
922                                 if (reg->u32_max_value != reg->umax_value &&
923                                     reg->u32_max_value != U32_MAX)
924                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
925                         }
926 #undef verbose_a
927
928                         verbose(env, ")");
929                 }
930         }
931         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
932                 char types_buf[BPF_REG_SIZE + 1];
933                 bool valid = false;
934                 int j;
935
936                 for (j = 0; j < BPF_REG_SIZE; j++) {
937                         if (state->stack[i].slot_type[j] != STACK_INVALID)
938                                 valid = true;
939                         types_buf[j] = slot_type_char[
940                                         state->stack[i].slot_type[j]];
941                 }
942                 types_buf[BPF_REG_SIZE] = 0;
943                 if (!valid)
944                         continue;
945                 if (!print_all && !stack_slot_scratched(env, i))
946                         continue;
947                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
948                 print_liveness(env, state->stack[i].spilled_ptr.live);
949                 if (is_spilled_reg(&state->stack[i])) {
950                         reg = &state->stack[i].spilled_ptr;
951                         t = reg->type;
952                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
953                         if (t == SCALAR_VALUE && reg->precise)
954                                 verbose(env, "P");
955                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
956                                 verbose(env, "%lld", reg->var_off.value + reg->off);
957                 } else {
958                         verbose(env, "=%s", types_buf);
959                 }
960         }
961         if (state->acquired_refs && state->refs[0].id) {
962                 verbose(env, " refs=%d", state->refs[0].id);
963                 for (i = 1; i < state->acquired_refs; i++)
964                         if (state->refs[i].id)
965                                 verbose(env, ",%d", state->refs[i].id);
966         }
967         if (state->in_callback_fn)
968                 verbose(env, " cb");
969         if (state->in_async_callback_fn)
970                 verbose(env, " async_cb");
971         verbose(env, "\n");
972         mark_verifier_state_clean(env);
973 }
974
975 static inline u32 vlog_alignment(u32 pos)
976 {
977         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
978                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
979 }
980
981 static void print_insn_state(struct bpf_verifier_env *env,
982                              const struct bpf_func_state *state)
983 {
984         if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
985                 /* remove new line character */
986                 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
987                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
988         } else {
989                 verbose(env, "%d:", env->insn_idx);
990         }
991         print_verifier_state(env, state, false);
992 }
993
994 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
995  * small to hold src. This is different from krealloc since we don't want to preserve
996  * the contents of dst.
997  *
998  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
999  * not be allocated.
1000  */
1001 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1002 {
1003         size_t alloc_bytes;
1004         void *orig = dst;
1005         size_t bytes;
1006
1007         if (ZERO_OR_NULL_PTR(src))
1008                 goto out;
1009
1010         if (unlikely(check_mul_overflow(n, size, &bytes)))
1011                 return NULL;
1012
1013         alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1014         dst = krealloc(orig, alloc_bytes, flags);
1015         if (!dst) {
1016                 kfree(orig);
1017                 return NULL;
1018         }
1019
1020         memcpy(dst, src, bytes);
1021 out:
1022         return dst ? dst : ZERO_SIZE_PTR;
1023 }
1024
1025 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1026  * small to hold new_n items. new items are zeroed out if the array grows.
1027  *
1028  * Contrary to krealloc_array, does not free arr if new_n is zero.
1029  */
1030 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1031 {
1032         size_t alloc_size;
1033         void *new_arr;
1034
1035         if (!new_n || old_n == new_n)
1036                 goto out;
1037
1038         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1039         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1040         if (!new_arr) {
1041                 kfree(arr);
1042                 return NULL;
1043         }
1044         arr = new_arr;
1045
1046         if (new_n > old_n)
1047                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1048
1049 out:
1050         return arr ? arr : ZERO_SIZE_PTR;
1051 }
1052
1053 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1054 {
1055         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1056                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1057         if (!dst->refs)
1058                 return -ENOMEM;
1059
1060         dst->acquired_refs = src->acquired_refs;
1061         return 0;
1062 }
1063
1064 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1065 {
1066         size_t n = src->allocated_stack / BPF_REG_SIZE;
1067
1068         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1069                                 GFP_KERNEL);
1070         if (!dst->stack)
1071                 return -ENOMEM;
1072
1073         dst->allocated_stack = src->allocated_stack;
1074         return 0;
1075 }
1076
1077 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1078 {
1079         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1080                                     sizeof(struct bpf_reference_state));
1081         if (!state->refs)
1082                 return -ENOMEM;
1083
1084         state->acquired_refs = n;
1085         return 0;
1086 }
1087
1088 static int grow_stack_state(struct bpf_func_state *state, int size)
1089 {
1090         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1091
1092         if (old_n >= n)
1093                 return 0;
1094
1095         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1096         if (!state->stack)
1097                 return -ENOMEM;
1098
1099         state->allocated_stack = size;
1100         return 0;
1101 }
1102
1103 /* Acquire a pointer id from the env and update the state->refs to include
1104  * this new pointer reference.
1105  * On success, returns a valid pointer id to associate with the register
1106  * On failure, returns a negative errno.
1107  */
1108 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1109 {
1110         struct bpf_func_state *state = cur_func(env);
1111         int new_ofs = state->acquired_refs;
1112         int id, err;
1113
1114         err = resize_reference_state(state, state->acquired_refs + 1);
1115         if (err)
1116                 return err;
1117         id = ++env->id_gen;
1118         state->refs[new_ofs].id = id;
1119         state->refs[new_ofs].insn_idx = insn_idx;
1120         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1121
1122         return id;
1123 }
1124
1125 /* release function corresponding to acquire_reference_state(). Idempotent. */
1126 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1127 {
1128         int i, last_idx;
1129
1130         last_idx = state->acquired_refs - 1;
1131         for (i = 0; i < state->acquired_refs; i++) {
1132                 if (state->refs[i].id == ptr_id) {
1133                         /* Cannot release caller references in callbacks */
1134                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1135                                 return -EINVAL;
1136                         if (last_idx && i != last_idx)
1137                                 memcpy(&state->refs[i], &state->refs[last_idx],
1138                                        sizeof(*state->refs));
1139                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1140                         state->acquired_refs--;
1141                         return 0;
1142                 }
1143         }
1144         return -EINVAL;
1145 }
1146
1147 static void free_func_state(struct bpf_func_state *state)
1148 {
1149         if (!state)
1150                 return;
1151         kfree(state->refs);
1152         kfree(state->stack);
1153         kfree(state);
1154 }
1155
1156 static void clear_jmp_history(struct bpf_verifier_state *state)
1157 {
1158         kfree(state->jmp_history);
1159         state->jmp_history = NULL;
1160         state->jmp_history_cnt = 0;
1161 }
1162
1163 static void free_verifier_state(struct bpf_verifier_state *state,
1164                                 bool free_self)
1165 {
1166         int i;
1167
1168         for (i = 0; i <= state->curframe; i++) {
1169                 free_func_state(state->frame[i]);
1170                 state->frame[i] = NULL;
1171         }
1172         clear_jmp_history(state);
1173         if (free_self)
1174                 kfree(state);
1175 }
1176
1177 /* copy verifier state from src to dst growing dst stack space
1178  * when necessary to accommodate larger src stack
1179  */
1180 static int copy_func_state(struct bpf_func_state *dst,
1181                            const struct bpf_func_state *src)
1182 {
1183         int err;
1184
1185         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1186         err = copy_reference_state(dst, src);
1187         if (err)
1188                 return err;
1189         return copy_stack_state(dst, src);
1190 }
1191
1192 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1193                                const struct bpf_verifier_state *src)
1194 {
1195         struct bpf_func_state *dst;
1196         int i, err;
1197
1198         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1199                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1200                                             GFP_USER);
1201         if (!dst_state->jmp_history)
1202                 return -ENOMEM;
1203         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1204
1205         /* if dst has more stack frames then src frame, free them */
1206         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1207                 free_func_state(dst_state->frame[i]);
1208                 dst_state->frame[i] = NULL;
1209         }
1210         dst_state->speculative = src->speculative;
1211         dst_state->curframe = src->curframe;
1212         dst_state->active_spin_lock = src->active_spin_lock;
1213         dst_state->branches = src->branches;
1214         dst_state->parent = src->parent;
1215         dst_state->first_insn_idx = src->first_insn_idx;
1216         dst_state->last_insn_idx = src->last_insn_idx;
1217         for (i = 0; i <= src->curframe; i++) {
1218                 dst = dst_state->frame[i];
1219                 if (!dst) {
1220                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1221                         if (!dst)
1222                                 return -ENOMEM;
1223                         dst_state->frame[i] = dst;
1224                 }
1225                 err = copy_func_state(dst, src->frame[i]);
1226                 if (err)
1227                         return err;
1228         }
1229         return 0;
1230 }
1231
1232 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1233 {
1234         while (st) {
1235                 u32 br = --st->branches;
1236
1237                 /* WARN_ON(br > 1) technically makes sense here,
1238                  * but see comment in push_stack(), hence:
1239                  */
1240                 WARN_ONCE((int)br < 0,
1241                           "BUG update_branch_counts:branches_to_explore=%d\n",
1242                           br);
1243                 if (br)
1244                         break;
1245                 st = st->parent;
1246         }
1247 }
1248
1249 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1250                      int *insn_idx, bool pop_log)
1251 {
1252         struct bpf_verifier_state *cur = env->cur_state;
1253         struct bpf_verifier_stack_elem *elem, *head = env->head;
1254         int err;
1255
1256         if (env->head == NULL)
1257                 return -ENOENT;
1258
1259         if (cur) {
1260                 err = copy_verifier_state(cur, &head->st);
1261                 if (err)
1262                         return err;
1263         }
1264         if (pop_log)
1265                 bpf_vlog_reset(&env->log, head->log_pos);
1266         if (insn_idx)
1267                 *insn_idx = head->insn_idx;
1268         if (prev_insn_idx)
1269                 *prev_insn_idx = head->prev_insn_idx;
1270         elem = head->next;
1271         free_verifier_state(&head->st, false);
1272         kfree(head);
1273         env->head = elem;
1274         env->stack_size--;
1275         return 0;
1276 }
1277
1278 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1279                                              int insn_idx, int prev_insn_idx,
1280                                              bool speculative)
1281 {
1282         struct bpf_verifier_state *cur = env->cur_state;
1283         struct bpf_verifier_stack_elem *elem;
1284         int err;
1285
1286         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1287         if (!elem)
1288                 goto err;
1289
1290         elem->insn_idx = insn_idx;
1291         elem->prev_insn_idx = prev_insn_idx;
1292         elem->next = env->head;
1293         elem->log_pos = env->log.len_used;
1294         env->head = elem;
1295         env->stack_size++;
1296         err = copy_verifier_state(&elem->st, cur);
1297         if (err)
1298                 goto err;
1299         elem->st.speculative |= speculative;
1300         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1301                 verbose(env, "The sequence of %d jumps is too complex.\n",
1302                         env->stack_size);
1303                 goto err;
1304         }
1305         if (elem->st.parent) {
1306                 ++elem->st.parent->branches;
1307                 /* WARN_ON(branches > 2) technically makes sense here,
1308                  * but
1309                  * 1. speculative states will bump 'branches' for non-branch
1310                  * instructions
1311                  * 2. is_state_visited() heuristics may decide not to create
1312                  * a new state for a sequence of branches and all such current
1313                  * and cloned states will be pointing to a single parent state
1314                  * which might have large 'branches' count.
1315                  */
1316         }
1317         return &elem->st;
1318 err:
1319         free_verifier_state(env->cur_state, true);
1320         env->cur_state = NULL;
1321         /* pop all elements and return */
1322         while (!pop_stack(env, NULL, NULL, false));
1323         return NULL;
1324 }
1325
1326 #define CALLER_SAVED_REGS 6
1327 static const int caller_saved[CALLER_SAVED_REGS] = {
1328         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1329 };
1330
1331 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1332                                 struct bpf_reg_state *reg);
1333
1334 /* This helper doesn't clear reg->id */
1335 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1336 {
1337         reg->var_off = tnum_const(imm);
1338         reg->smin_value = (s64)imm;
1339         reg->smax_value = (s64)imm;
1340         reg->umin_value = imm;
1341         reg->umax_value = imm;
1342
1343         reg->s32_min_value = (s32)imm;
1344         reg->s32_max_value = (s32)imm;
1345         reg->u32_min_value = (u32)imm;
1346         reg->u32_max_value = (u32)imm;
1347 }
1348
1349 /* Mark the unknown part of a register (variable offset or scalar value) as
1350  * known to have the value @imm.
1351  */
1352 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1353 {
1354         /* Clear id, off, and union(map_ptr, range) */
1355         memset(((u8 *)reg) + sizeof(reg->type), 0,
1356                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1357         ___mark_reg_known(reg, imm);
1358 }
1359
1360 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1361 {
1362         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1363         reg->s32_min_value = (s32)imm;
1364         reg->s32_max_value = (s32)imm;
1365         reg->u32_min_value = (u32)imm;
1366         reg->u32_max_value = (u32)imm;
1367 }
1368
1369 /* Mark the 'variable offset' part of a register as zero.  This should be
1370  * used only on registers holding a pointer type.
1371  */
1372 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1373 {
1374         __mark_reg_known(reg, 0);
1375 }
1376
1377 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1378 {
1379         __mark_reg_known(reg, 0);
1380         reg->type = SCALAR_VALUE;
1381 }
1382
1383 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1384                                 struct bpf_reg_state *regs, u32 regno)
1385 {
1386         if (WARN_ON(regno >= MAX_BPF_REG)) {
1387                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1388                 /* Something bad happened, let's kill all regs */
1389                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1390                         __mark_reg_not_init(env, regs + regno);
1391                 return;
1392         }
1393         __mark_reg_known_zero(regs + regno);
1394 }
1395
1396 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1397 {
1398         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1399                 const struct bpf_map *map = reg->map_ptr;
1400
1401                 if (map->inner_map_meta) {
1402                         reg->type = CONST_PTR_TO_MAP;
1403                         reg->map_ptr = map->inner_map_meta;
1404                         /* transfer reg's id which is unique for every map_lookup_elem
1405                          * as UID of the inner map.
1406                          */
1407                         if (map_value_has_timer(map->inner_map_meta))
1408                                 reg->map_uid = reg->id;
1409                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1410                         reg->type = PTR_TO_XDP_SOCK;
1411                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1412                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1413                         reg->type = PTR_TO_SOCKET;
1414                 } else {
1415                         reg->type = PTR_TO_MAP_VALUE;
1416                 }
1417                 return;
1418         }
1419
1420         reg->type &= ~PTR_MAYBE_NULL;
1421 }
1422
1423 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1424 {
1425         return type_is_pkt_pointer(reg->type);
1426 }
1427
1428 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1429 {
1430         return reg_is_pkt_pointer(reg) ||
1431                reg->type == PTR_TO_PACKET_END;
1432 }
1433
1434 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1435 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1436                                     enum bpf_reg_type which)
1437 {
1438         /* The register can already have a range from prior markings.
1439          * This is fine as long as it hasn't been advanced from its
1440          * origin.
1441          */
1442         return reg->type == which &&
1443                reg->id == 0 &&
1444                reg->off == 0 &&
1445                tnum_equals_const(reg->var_off, 0);
1446 }
1447
1448 /* Reset the min/max bounds of a register */
1449 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1450 {
1451         reg->smin_value = S64_MIN;
1452         reg->smax_value = S64_MAX;
1453         reg->umin_value = 0;
1454         reg->umax_value = U64_MAX;
1455
1456         reg->s32_min_value = S32_MIN;
1457         reg->s32_max_value = S32_MAX;
1458         reg->u32_min_value = 0;
1459         reg->u32_max_value = U32_MAX;
1460 }
1461
1462 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1463 {
1464         reg->smin_value = S64_MIN;
1465         reg->smax_value = S64_MAX;
1466         reg->umin_value = 0;
1467         reg->umax_value = U64_MAX;
1468 }
1469
1470 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1471 {
1472         reg->s32_min_value = S32_MIN;
1473         reg->s32_max_value = S32_MAX;
1474         reg->u32_min_value = 0;
1475         reg->u32_max_value = U32_MAX;
1476 }
1477
1478 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1479 {
1480         struct tnum var32_off = tnum_subreg(reg->var_off);
1481
1482         /* min signed is max(sign bit) | min(other bits) */
1483         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1484                         var32_off.value | (var32_off.mask & S32_MIN));
1485         /* max signed is min(sign bit) | max(other bits) */
1486         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1487                         var32_off.value | (var32_off.mask & S32_MAX));
1488         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1489         reg->u32_max_value = min(reg->u32_max_value,
1490                                  (u32)(var32_off.value | var32_off.mask));
1491 }
1492
1493 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1494 {
1495         /* min signed is max(sign bit) | min(other bits) */
1496         reg->smin_value = max_t(s64, reg->smin_value,
1497                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1498         /* max signed is min(sign bit) | max(other bits) */
1499         reg->smax_value = min_t(s64, reg->smax_value,
1500                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1501         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1502         reg->umax_value = min(reg->umax_value,
1503                               reg->var_off.value | reg->var_off.mask);
1504 }
1505
1506 static void __update_reg_bounds(struct bpf_reg_state *reg)
1507 {
1508         __update_reg32_bounds(reg);
1509         __update_reg64_bounds(reg);
1510 }
1511
1512 /* Uses signed min/max values to inform unsigned, and vice-versa */
1513 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1514 {
1515         /* Learn sign from signed bounds.
1516          * If we cannot cross the sign boundary, then signed and unsigned bounds
1517          * are the same, so combine.  This works even in the negative case, e.g.
1518          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1519          */
1520         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1521                 reg->s32_min_value = reg->u32_min_value =
1522                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1523                 reg->s32_max_value = reg->u32_max_value =
1524                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1525                 return;
1526         }
1527         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1528          * boundary, so we must be careful.
1529          */
1530         if ((s32)reg->u32_max_value >= 0) {
1531                 /* Positive.  We can't learn anything from the smin, but smax
1532                  * is positive, hence safe.
1533                  */
1534                 reg->s32_min_value = reg->u32_min_value;
1535                 reg->s32_max_value = reg->u32_max_value =
1536                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1537         } else if ((s32)reg->u32_min_value < 0) {
1538                 /* Negative.  We can't learn anything from the smax, but smin
1539                  * is negative, hence safe.
1540                  */
1541                 reg->s32_min_value = reg->u32_min_value =
1542                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1543                 reg->s32_max_value = reg->u32_max_value;
1544         }
1545 }
1546
1547 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1548 {
1549         /* Learn sign from signed bounds.
1550          * If we cannot cross the sign boundary, then signed and unsigned bounds
1551          * are the same, so combine.  This works even in the negative case, e.g.
1552          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1553          */
1554         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1555                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1556                                                           reg->umin_value);
1557                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1558                                                           reg->umax_value);
1559                 return;
1560         }
1561         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1562          * boundary, so we must be careful.
1563          */
1564         if ((s64)reg->umax_value >= 0) {
1565                 /* Positive.  We can't learn anything from the smin, but smax
1566                  * is positive, hence safe.
1567                  */
1568                 reg->smin_value = reg->umin_value;
1569                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1570                                                           reg->umax_value);
1571         } else if ((s64)reg->umin_value < 0) {
1572                 /* Negative.  We can't learn anything from the smax, but smin
1573                  * is negative, hence safe.
1574                  */
1575                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1576                                                           reg->umin_value);
1577                 reg->smax_value = reg->umax_value;
1578         }
1579 }
1580
1581 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1582 {
1583         __reg32_deduce_bounds(reg);
1584         __reg64_deduce_bounds(reg);
1585 }
1586
1587 /* Attempts to improve var_off based on unsigned min/max information */
1588 static void __reg_bound_offset(struct bpf_reg_state *reg)
1589 {
1590         struct tnum var64_off = tnum_intersect(reg->var_off,
1591                                                tnum_range(reg->umin_value,
1592                                                           reg->umax_value));
1593         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1594                                                 tnum_range(reg->u32_min_value,
1595                                                            reg->u32_max_value));
1596
1597         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1598 }
1599
1600 static void reg_bounds_sync(struct bpf_reg_state *reg)
1601 {
1602         /* We might have learned new bounds from the var_off. */
1603         __update_reg_bounds(reg);
1604         /* We might have learned something about the sign bit. */
1605         __reg_deduce_bounds(reg);
1606         /* We might have learned some bits from the bounds. */
1607         __reg_bound_offset(reg);
1608         /* Intersecting with the old var_off might have improved our bounds
1609          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1610          * then new var_off is (0; 0x7f...fc) which improves our umax.
1611          */
1612         __update_reg_bounds(reg);
1613 }
1614
1615 static bool __reg32_bound_s64(s32 a)
1616 {
1617         return a >= 0 && a <= S32_MAX;
1618 }
1619
1620 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1621 {
1622         reg->umin_value = reg->u32_min_value;
1623         reg->umax_value = reg->u32_max_value;
1624
1625         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1626          * be positive otherwise set to worse case bounds and refine later
1627          * from tnum.
1628          */
1629         if (__reg32_bound_s64(reg->s32_min_value) &&
1630             __reg32_bound_s64(reg->s32_max_value)) {
1631                 reg->smin_value = reg->s32_min_value;
1632                 reg->smax_value = reg->s32_max_value;
1633         } else {
1634                 reg->smin_value = 0;
1635                 reg->smax_value = U32_MAX;
1636         }
1637 }
1638
1639 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1640 {
1641         /* special case when 64-bit register has upper 32-bit register
1642          * zeroed. Typically happens after zext or <<32, >>32 sequence
1643          * allowing us to use 32-bit bounds directly,
1644          */
1645         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1646                 __reg_assign_32_into_64(reg);
1647         } else {
1648                 /* Otherwise the best we can do is push lower 32bit known and
1649                  * unknown bits into register (var_off set from jmp logic)
1650                  * then learn as much as possible from the 64-bit tnum
1651                  * known and unknown bits. The previous smin/smax bounds are
1652                  * invalid here because of jmp32 compare so mark them unknown
1653                  * so they do not impact tnum bounds calculation.
1654                  */
1655                 __mark_reg64_unbounded(reg);
1656         }
1657         reg_bounds_sync(reg);
1658 }
1659
1660 static bool __reg64_bound_s32(s64 a)
1661 {
1662         return a >= S32_MIN && a <= S32_MAX;
1663 }
1664
1665 static bool __reg64_bound_u32(u64 a)
1666 {
1667         return a >= U32_MIN && a <= U32_MAX;
1668 }
1669
1670 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1671 {
1672         __mark_reg32_unbounded(reg);
1673         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1674                 reg->s32_min_value = (s32)reg->smin_value;
1675                 reg->s32_max_value = (s32)reg->smax_value;
1676         }
1677         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1678                 reg->u32_min_value = (u32)reg->umin_value;
1679                 reg->u32_max_value = (u32)reg->umax_value;
1680         }
1681         reg_bounds_sync(reg);
1682 }
1683
1684 /* Mark a register as having a completely unknown (scalar) value. */
1685 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1686                                struct bpf_reg_state *reg)
1687 {
1688         /*
1689          * Clear type, id, off, and union(map_ptr, range) and
1690          * padding between 'type' and union
1691          */
1692         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1693         reg->type = SCALAR_VALUE;
1694         reg->var_off = tnum_unknown;
1695         reg->frameno = 0;
1696         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1697         __mark_reg_unbounded(reg);
1698 }
1699
1700 static void mark_reg_unknown(struct bpf_verifier_env *env,
1701                              struct bpf_reg_state *regs, u32 regno)
1702 {
1703         if (WARN_ON(regno >= MAX_BPF_REG)) {
1704                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1705                 /* Something bad happened, let's kill all regs except FP */
1706                 for (regno = 0; regno < BPF_REG_FP; regno++)
1707                         __mark_reg_not_init(env, regs + regno);
1708                 return;
1709         }
1710         __mark_reg_unknown(env, regs + regno);
1711 }
1712
1713 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1714                                 struct bpf_reg_state *reg)
1715 {
1716         __mark_reg_unknown(env, reg);
1717         reg->type = NOT_INIT;
1718 }
1719
1720 static void mark_reg_not_init(struct bpf_verifier_env *env,
1721                               struct bpf_reg_state *regs, u32 regno)
1722 {
1723         if (WARN_ON(regno >= MAX_BPF_REG)) {
1724                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1725                 /* Something bad happened, let's kill all regs except FP */
1726                 for (regno = 0; regno < BPF_REG_FP; regno++)
1727                         __mark_reg_not_init(env, regs + regno);
1728                 return;
1729         }
1730         __mark_reg_not_init(env, regs + regno);
1731 }
1732
1733 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1734                             struct bpf_reg_state *regs, u32 regno,
1735                             enum bpf_reg_type reg_type,
1736                             struct btf *btf, u32 btf_id,
1737                             enum bpf_type_flag flag)
1738 {
1739         if (reg_type == SCALAR_VALUE) {
1740                 mark_reg_unknown(env, regs, regno);
1741                 return;
1742         }
1743         mark_reg_known_zero(env, regs, regno);
1744         regs[regno].type = PTR_TO_BTF_ID | flag;
1745         regs[regno].btf = btf;
1746         regs[regno].btf_id = btf_id;
1747 }
1748
1749 #define DEF_NOT_SUBREG  (0)
1750 static void init_reg_state(struct bpf_verifier_env *env,
1751                            struct bpf_func_state *state)
1752 {
1753         struct bpf_reg_state *regs = state->regs;
1754         int i;
1755
1756         for (i = 0; i < MAX_BPF_REG; i++) {
1757                 mark_reg_not_init(env, regs, i);
1758                 regs[i].live = REG_LIVE_NONE;
1759                 regs[i].parent = NULL;
1760                 regs[i].subreg_def = DEF_NOT_SUBREG;
1761         }
1762
1763         /* frame pointer */
1764         regs[BPF_REG_FP].type = PTR_TO_STACK;
1765         mark_reg_known_zero(env, regs, BPF_REG_FP);
1766         regs[BPF_REG_FP].frameno = state->frameno;
1767 }
1768
1769 #define BPF_MAIN_FUNC (-1)
1770 static void init_func_state(struct bpf_verifier_env *env,
1771                             struct bpf_func_state *state,
1772                             int callsite, int frameno, int subprogno)
1773 {
1774         state->callsite = callsite;
1775         state->frameno = frameno;
1776         state->subprogno = subprogno;
1777         state->callback_ret_range = tnum_range(0, 0);
1778         init_reg_state(env, state);
1779         mark_verifier_state_scratched(env);
1780 }
1781
1782 /* Similar to push_stack(), but for async callbacks */
1783 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1784                                                 int insn_idx, int prev_insn_idx,
1785                                                 int subprog)
1786 {
1787         struct bpf_verifier_stack_elem *elem;
1788         struct bpf_func_state *frame;
1789
1790         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1791         if (!elem)
1792                 goto err;
1793
1794         elem->insn_idx = insn_idx;
1795         elem->prev_insn_idx = prev_insn_idx;
1796         elem->next = env->head;
1797         elem->log_pos = env->log.len_used;
1798         env->head = elem;
1799         env->stack_size++;
1800         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1801                 verbose(env,
1802                         "The sequence of %d jumps is too complex for async cb.\n",
1803                         env->stack_size);
1804                 goto err;
1805         }
1806         /* Unlike push_stack() do not copy_verifier_state().
1807          * The caller state doesn't matter.
1808          * This is async callback. It starts in a fresh stack.
1809          * Initialize it similar to do_check_common().
1810          */
1811         elem->st.branches = 1;
1812         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1813         if (!frame)
1814                 goto err;
1815         init_func_state(env, frame,
1816                         BPF_MAIN_FUNC /* callsite */,
1817                         0 /* frameno within this callchain */,
1818                         subprog /* subprog number within this prog */);
1819         elem->st.frame[0] = frame;
1820         return &elem->st;
1821 err:
1822         free_verifier_state(env->cur_state, true);
1823         env->cur_state = NULL;
1824         /* pop all elements and return */
1825         while (!pop_stack(env, NULL, NULL, false));
1826         return NULL;
1827 }
1828
1829
1830 enum reg_arg_type {
1831         SRC_OP,         /* register is used as source operand */
1832         DST_OP,         /* register is used as destination operand */
1833         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1834 };
1835
1836 static int cmp_subprogs(const void *a, const void *b)
1837 {
1838         return ((struct bpf_subprog_info *)a)->start -
1839                ((struct bpf_subprog_info *)b)->start;
1840 }
1841
1842 static int find_subprog(struct bpf_verifier_env *env, int off)
1843 {
1844         struct bpf_subprog_info *p;
1845
1846         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1847                     sizeof(env->subprog_info[0]), cmp_subprogs);
1848         if (!p)
1849                 return -ENOENT;
1850         return p - env->subprog_info;
1851
1852 }
1853
1854 static int add_subprog(struct bpf_verifier_env *env, int off)
1855 {
1856         int insn_cnt = env->prog->len;
1857         int ret;
1858
1859         if (off >= insn_cnt || off < 0) {
1860                 verbose(env, "call to invalid destination\n");
1861                 return -EINVAL;
1862         }
1863         ret = find_subprog(env, off);
1864         if (ret >= 0)
1865                 return ret;
1866         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1867                 verbose(env, "too many subprograms\n");
1868                 return -E2BIG;
1869         }
1870         /* determine subprog starts. The end is one before the next starts */
1871         env->subprog_info[env->subprog_cnt++].start = off;
1872         sort(env->subprog_info, env->subprog_cnt,
1873              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1874         return env->subprog_cnt - 1;
1875 }
1876
1877 #define MAX_KFUNC_DESCS 256
1878 #define MAX_KFUNC_BTFS  256
1879
1880 struct bpf_kfunc_desc {
1881         struct btf_func_model func_model;
1882         u32 func_id;
1883         s32 imm;
1884         u16 offset;
1885 };
1886
1887 struct bpf_kfunc_btf {
1888         struct btf *btf;
1889         struct module *module;
1890         u16 offset;
1891 };
1892
1893 struct bpf_kfunc_desc_tab {
1894         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1895         u32 nr_descs;
1896 };
1897
1898 struct bpf_kfunc_btf_tab {
1899         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1900         u32 nr_descs;
1901 };
1902
1903 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1904 {
1905         const struct bpf_kfunc_desc *d0 = a;
1906         const struct bpf_kfunc_desc *d1 = b;
1907
1908         /* func_id is not greater than BTF_MAX_TYPE */
1909         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1910 }
1911
1912 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1913 {
1914         const struct bpf_kfunc_btf *d0 = a;
1915         const struct bpf_kfunc_btf *d1 = b;
1916
1917         return d0->offset - d1->offset;
1918 }
1919
1920 static const struct bpf_kfunc_desc *
1921 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1922 {
1923         struct bpf_kfunc_desc desc = {
1924                 .func_id = func_id,
1925                 .offset = offset,
1926         };
1927         struct bpf_kfunc_desc_tab *tab;
1928
1929         tab = prog->aux->kfunc_tab;
1930         return bsearch(&desc, tab->descs, tab->nr_descs,
1931                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1932 }
1933
1934 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1935                                          s16 offset)
1936 {
1937         struct bpf_kfunc_btf kf_btf = { .offset = offset };
1938         struct bpf_kfunc_btf_tab *tab;
1939         struct bpf_kfunc_btf *b;
1940         struct module *mod;
1941         struct btf *btf;
1942         int btf_fd;
1943
1944         tab = env->prog->aux->kfunc_btf_tab;
1945         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1946                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1947         if (!b) {
1948                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1949                         verbose(env, "too many different module BTFs\n");
1950                         return ERR_PTR(-E2BIG);
1951                 }
1952
1953                 if (bpfptr_is_null(env->fd_array)) {
1954                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1955                         return ERR_PTR(-EPROTO);
1956                 }
1957
1958                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1959                                             offset * sizeof(btf_fd),
1960                                             sizeof(btf_fd)))
1961                         return ERR_PTR(-EFAULT);
1962
1963                 btf = btf_get_by_fd(btf_fd);
1964                 if (IS_ERR(btf)) {
1965                         verbose(env, "invalid module BTF fd specified\n");
1966                         return btf;
1967                 }
1968
1969                 if (!btf_is_module(btf)) {
1970                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
1971                         btf_put(btf);
1972                         return ERR_PTR(-EINVAL);
1973                 }
1974
1975                 mod = btf_try_get_module(btf);
1976                 if (!mod) {
1977                         btf_put(btf);
1978                         return ERR_PTR(-ENXIO);
1979                 }
1980
1981                 b = &tab->descs[tab->nr_descs++];
1982                 b->btf = btf;
1983                 b->module = mod;
1984                 b->offset = offset;
1985
1986                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1987                      kfunc_btf_cmp_by_off, NULL);
1988         }
1989         return b->btf;
1990 }
1991
1992 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1993 {
1994         if (!tab)
1995                 return;
1996
1997         while (tab->nr_descs--) {
1998                 module_put(tab->descs[tab->nr_descs].module);
1999                 btf_put(tab->descs[tab->nr_descs].btf);
2000         }
2001         kfree(tab);
2002 }
2003
2004 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2005 {
2006         if (offset) {
2007                 if (offset < 0) {
2008                         /* In the future, this can be allowed to increase limit
2009                          * of fd index into fd_array, interpreted as u16.
2010                          */
2011                         verbose(env, "negative offset disallowed for kernel module function call\n");
2012                         return ERR_PTR(-EINVAL);
2013                 }
2014
2015                 return __find_kfunc_desc_btf(env, offset);
2016         }
2017         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2018 }
2019
2020 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2021 {
2022         const struct btf_type *func, *func_proto;
2023         struct bpf_kfunc_btf_tab *btf_tab;
2024         struct bpf_kfunc_desc_tab *tab;
2025         struct bpf_prog_aux *prog_aux;
2026         struct bpf_kfunc_desc *desc;
2027         const char *func_name;
2028         struct btf *desc_btf;
2029         unsigned long call_imm;
2030         unsigned long addr;
2031         int err;
2032
2033         prog_aux = env->prog->aux;
2034         tab = prog_aux->kfunc_tab;
2035         btf_tab = prog_aux->kfunc_btf_tab;
2036         if (!tab) {
2037                 if (!btf_vmlinux) {
2038                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2039                         return -ENOTSUPP;
2040                 }
2041
2042                 if (!env->prog->jit_requested) {
2043                         verbose(env, "JIT is required for calling kernel function\n");
2044                         return -ENOTSUPP;
2045                 }
2046
2047                 if (!bpf_jit_supports_kfunc_call()) {
2048                         verbose(env, "JIT does not support calling kernel function\n");
2049                         return -ENOTSUPP;
2050                 }
2051
2052                 if (!env->prog->gpl_compatible) {
2053                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2054                         return -EINVAL;
2055                 }
2056
2057                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2058                 if (!tab)
2059                         return -ENOMEM;
2060                 prog_aux->kfunc_tab = tab;
2061         }
2062
2063         /* func_id == 0 is always invalid, but instead of returning an error, be
2064          * conservative and wait until the code elimination pass before returning
2065          * error, so that invalid calls that get pruned out can be in BPF programs
2066          * loaded from userspace.  It is also required that offset be untouched
2067          * for such calls.
2068          */
2069         if (!func_id && !offset)
2070                 return 0;
2071
2072         if (!btf_tab && offset) {
2073                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2074                 if (!btf_tab)
2075                         return -ENOMEM;
2076                 prog_aux->kfunc_btf_tab = btf_tab;
2077         }
2078
2079         desc_btf = find_kfunc_desc_btf(env, offset);
2080         if (IS_ERR(desc_btf)) {
2081                 verbose(env, "failed to find BTF for kernel function\n");
2082                 return PTR_ERR(desc_btf);
2083         }
2084
2085         if (find_kfunc_desc(env->prog, func_id, offset))
2086                 return 0;
2087
2088         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2089                 verbose(env, "too many different kernel function calls\n");
2090                 return -E2BIG;
2091         }
2092
2093         func = btf_type_by_id(desc_btf, func_id);
2094         if (!func || !btf_type_is_func(func)) {
2095                 verbose(env, "kernel btf_id %u is not a function\n",
2096                         func_id);
2097                 return -EINVAL;
2098         }
2099         func_proto = btf_type_by_id(desc_btf, func->type);
2100         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2101                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2102                         func_id);
2103                 return -EINVAL;
2104         }
2105
2106         func_name = btf_name_by_offset(desc_btf, func->name_off);
2107         addr = kallsyms_lookup_name(func_name);
2108         if (!addr) {
2109                 verbose(env, "cannot find address for kernel function %s\n",
2110                         func_name);
2111                 return -EINVAL;
2112         }
2113
2114         call_imm = BPF_CALL_IMM(addr);
2115         /* Check whether or not the relative offset overflows desc->imm */
2116         if ((unsigned long)(s32)call_imm != call_imm) {
2117                 verbose(env, "address of kernel function %s is out of range\n",
2118                         func_name);
2119                 return -EINVAL;
2120         }
2121
2122         desc = &tab->descs[tab->nr_descs++];
2123         desc->func_id = func_id;
2124         desc->imm = call_imm;
2125         desc->offset = offset;
2126         err = btf_distill_func_proto(&env->log, desc_btf,
2127                                      func_proto, func_name,
2128                                      &desc->func_model);
2129         if (!err)
2130                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2131                      kfunc_desc_cmp_by_id_off, NULL);
2132         return err;
2133 }
2134
2135 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2136 {
2137         const struct bpf_kfunc_desc *d0 = a;
2138         const struct bpf_kfunc_desc *d1 = b;
2139
2140         if (d0->imm > d1->imm)
2141                 return 1;
2142         else if (d0->imm < d1->imm)
2143                 return -1;
2144         return 0;
2145 }
2146
2147 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2148 {
2149         struct bpf_kfunc_desc_tab *tab;
2150
2151         tab = prog->aux->kfunc_tab;
2152         if (!tab)
2153                 return;
2154
2155         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2156              kfunc_desc_cmp_by_imm, NULL);
2157 }
2158
2159 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2160 {
2161         return !!prog->aux->kfunc_tab;
2162 }
2163
2164 const struct btf_func_model *
2165 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2166                          const struct bpf_insn *insn)
2167 {
2168         const struct bpf_kfunc_desc desc = {
2169                 .imm = insn->imm,
2170         };
2171         const struct bpf_kfunc_desc *res;
2172         struct bpf_kfunc_desc_tab *tab;
2173
2174         tab = prog->aux->kfunc_tab;
2175         res = bsearch(&desc, tab->descs, tab->nr_descs,
2176                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2177
2178         return res ? &res->func_model : NULL;
2179 }
2180
2181 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2182 {
2183         struct bpf_subprog_info *subprog = env->subprog_info;
2184         struct bpf_insn *insn = env->prog->insnsi;
2185         int i, ret, insn_cnt = env->prog->len;
2186
2187         /* Add entry function. */
2188         ret = add_subprog(env, 0);
2189         if (ret)
2190                 return ret;
2191
2192         for (i = 0; i < insn_cnt; i++, insn++) {
2193                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2194                     !bpf_pseudo_kfunc_call(insn))
2195                         continue;
2196
2197                 if (!env->bpf_capable) {
2198                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2199                         return -EPERM;
2200                 }
2201
2202                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2203                         ret = add_subprog(env, i + insn->imm + 1);
2204                 else
2205                         ret = add_kfunc_call(env, insn->imm, insn->off);
2206
2207                 if (ret < 0)
2208                         return ret;
2209         }
2210
2211         /* Add a fake 'exit' subprog which could simplify subprog iteration
2212          * logic. 'subprog_cnt' should not be increased.
2213          */
2214         subprog[env->subprog_cnt].start = insn_cnt;
2215
2216         if (env->log.level & BPF_LOG_LEVEL2)
2217                 for (i = 0; i < env->subprog_cnt; i++)
2218                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2219
2220         return 0;
2221 }
2222
2223 static int check_subprogs(struct bpf_verifier_env *env)
2224 {
2225         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2226         struct bpf_subprog_info *subprog = env->subprog_info;
2227         struct bpf_insn *insn = env->prog->insnsi;
2228         int insn_cnt = env->prog->len;
2229
2230         /* now check that all jumps are within the same subprog */
2231         subprog_start = subprog[cur_subprog].start;
2232         subprog_end = subprog[cur_subprog + 1].start;
2233         for (i = 0; i < insn_cnt; i++) {
2234                 u8 code = insn[i].code;
2235
2236                 if (code == (BPF_JMP | BPF_CALL) &&
2237                     insn[i].imm == BPF_FUNC_tail_call &&
2238                     insn[i].src_reg != BPF_PSEUDO_CALL)
2239                         subprog[cur_subprog].has_tail_call = true;
2240                 if (BPF_CLASS(code) == BPF_LD &&
2241                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2242                         subprog[cur_subprog].has_ld_abs = true;
2243                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2244                         goto next;
2245                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2246                         goto next;
2247                 off = i + insn[i].off + 1;
2248                 if (off < subprog_start || off >= subprog_end) {
2249                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2250                         return -EINVAL;
2251                 }
2252 next:
2253                 if (i == subprog_end - 1) {
2254                         /* to avoid fall-through from one subprog into another
2255                          * the last insn of the subprog should be either exit
2256                          * or unconditional jump back
2257                          */
2258                         if (code != (BPF_JMP | BPF_EXIT) &&
2259                             code != (BPF_JMP | BPF_JA)) {
2260                                 verbose(env, "last insn is not an exit or jmp\n");
2261                                 return -EINVAL;
2262                         }
2263                         subprog_start = subprog_end;
2264                         cur_subprog++;
2265                         if (cur_subprog < env->subprog_cnt)
2266                                 subprog_end = subprog[cur_subprog + 1].start;
2267                 }
2268         }
2269         return 0;
2270 }
2271
2272 /* Parentage chain of this register (or stack slot) should take care of all
2273  * issues like callee-saved registers, stack slot allocation time, etc.
2274  */
2275 static int mark_reg_read(struct bpf_verifier_env *env,
2276                          const struct bpf_reg_state *state,
2277                          struct bpf_reg_state *parent, u8 flag)
2278 {
2279         bool writes = parent == state->parent; /* Observe write marks */
2280         int cnt = 0;
2281
2282         while (parent) {
2283                 /* if read wasn't screened by an earlier write ... */
2284                 if (writes && state->live & REG_LIVE_WRITTEN)
2285                         break;
2286                 if (parent->live & REG_LIVE_DONE) {
2287                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2288                                 reg_type_str(env, parent->type),
2289                                 parent->var_off.value, parent->off);
2290                         return -EFAULT;
2291                 }
2292                 /* The first condition is more likely to be true than the
2293                  * second, checked it first.
2294                  */
2295                 if ((parent->live & REG_LIVE_READ) == flag ||
2296                     parent->live & REG_LIVE_READ64)
2297                         /* The parentage chain never changes and
2298                          * this parent was already marked as LIVE_READ.
2299                          * There is no need to keep walking the chain again and
2300                          * keep re-marking all parents as LIVE_READ.
2301                          * This case happens when the same register is read
2302                          * multiple times without writes into it in-between.
2303                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2304                          * then no need to set the weak REG_LIVE_READ32.
2305                          */
2306                         break;
2307                 /* ... then we depend on parent's value */
2308                 parent->live |= flag;
2309                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2310                 if (flag == REG_LIVE_READ64)
2311                         parent->live &= ~REG_LIVE_READ32;
2312                 state = parent;
2313                 parent = state->parent;
2314                 writes = true;
2315                 cnt++;
2316         }
2317
2318         if (env->longest_mark_read_walk < cnt)
2319                 env->longest_mark_read_walk = cnt;
2320         return 0;
2321 }
2322
2323 /* This function is supposed to be used by the following 32-bit optimization
2324  * code only. It returns TRUE if the source or destination register operates
2325  * on 64-bit, otherwise return FALSE.
2326  */
2327 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2328                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2329 {
2330         u8 code, class, op;
2331
2332         code = insn->code;
2333         class = BPF_CLASS(code);
2334         op = BPF_OP(code);
2335         if (class == BPF_JMP) {
2336                 /* BPF_EXIT for "main" will reach here. Return TRUE
2337                  * conservatively.
2338                  */
2339                 if (op == BPF_EXIT)
2340                         return true;
2341                 if (op == BPF_CALL) {
2342                         /* BPF to BPF call will reach here because of marking
2343                          * caller saved clobber with DST_OP_NO_MARK for which we
2344                          * don't care the register def because they are anyway
2345                          * marked as NOT_INIT already.
2346                          */
2347                         if (insn->src_reg == BPF_PSEUDO_CALL)
2348                                 return false;
2349                         /* Helper call will reach here because of arg type
2350                          * check, conservatively return TRUE.
2351                          */
2352                         if (t == SRC_OP)
2353                                 return true;
2354
2355                         return false;
2356                 }
2357         }
2358
2359         if (class == BPF_ALU64 || class == BPF_JMP ||
2360             /* BPF_END always use BPF_ALU class. */
2361             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2362                 return true;
2363
2364         if (class == BPF_ALU || class == BPF_JMP32)
2365                 return false;
2366
2367         if (class == BPF_LDX) {
2368                 if (t != SRC_OP)
2369                         return BPF_SIZE(code) == BPF_DW;
2370                 /* LDX source must be ptr. */
2371                 return true;
2372         }
2373
2374         if (class == BPF_STX) {
2375                 /* BPF_STX (including atomic variants) has multiple source
2376                  * operands, one of which is a ptr. Check whether the caller is
2377                  * asking about it.
2378                  */
2379                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2380                         return true;
2381                 return BPF_SIZE(code) == BPF_DW;
2382         }
2383
2384         if (class == BPF_LD) {
2385                 u8 mode = BPF_MODE(code);
2386
2387                 /* LD_IMM64 */
2388                 if (mode == BPF_IMM)
2389                         return true;
2390
2391                 /* Both LD_IND and LD_ABS return 32-bit data. */
2392                 if (t != SRC_OP)
2393                         return  false;
2394
2395                 /* Implicit ctx ptr. */
2396                 if (regno == BPF_REG_6)
2397                         return true;
2398
2399                 /* Explicit source could be any width. */
2400                 return true;
2401         }
2402
2403         if (class == BPF_ST)
2404                 /* The only source register for BPF_ST is a ptr. */
2405                 return true;
2406
2407         /* Conservatively return true at default. */
2408         return true;
2409 }
2410
2411 /* Return the regno defined by the insn, or -1. */
2412 static int insn_def_regno(const struct bpf_insn *insn)
2413 {
2414         switch (BPF_CLASS(insn->code)) {
2415         case BPF_JMP:
2416         case BPF_JMP32:
2417         case BPF_ST:
2418                 return -1;
2419         case BPF_STX:
2420                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2421                     (insn->imm & BPF_FETCH)) {
2422                         if (insn->imm == BPF_CMPXCHG)
2423                                 return BPF_REG_0;
2424                         else
2425                                 return insn->src_reg;
2426                 } else {
2427                         return -1;
2428                 }
2429         default:
2430                 return insn->dst_reg;
2431         }
2432 }
2433
2434 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2435 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2436 {
2437         int dst_reg = insn_def_regno(insn);
2438
2439         if (dst_reg == -1)
2440                 return false;
2441
2442         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2443 }
2444
2445 static void mark_insn_zext(struct bpf_verifier_env *env,
2446                            struct bpf_reg_state *reg)
2447 {
2448         s32 def_idx = reg->subreg_def;
2449
2450         if (def_idx == DEF_NOT_SUBREG)
2451                 return;
2452
2453         env->insn_aux_data[def_idx - 1].zext_dst = true;
2454         /* The dst will be zero extended, so won't be sub-register anymore. */
2455         reg->subreg_def = DEF_NOT_SUBREG;
2456 }
2457
2458 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2459                          enum reg_arg_type t)
2460 {
2461         struct bpf_verifier_state *vstate = env->cur_state;
2462         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2463         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2464         struct bpf_reg_state *reg, *regs = state->regs;
2465         bool rw64;
2466
2467         if (regno >= MAX_BPF_REG) {
2468                 verbose(env, "R%d is invalid\n", regno);
2469                 return -EINVAL;
2470         }
2471
2472         mark_reg_scratched(env, regno);
2473
2474         reg = &regs[regno];
2475         rw64 = is_reg64(env, insn, regno, reg, t);
2476         if (t == SRC_OP) {
2477                 /* check whether register used as source operand can be read */
2478                 if (reg->type == NOT_INIT) {
2479                         verbose(env, "R%d !read_ok\n", regno);
2480                         return -EACCES;
2481                 }
2482                 /* We don't need to worry about FP liveness because it's read-only */
2483                 if (regno == BPF_REG_FP)
2484                         return 0;
2485
2486                 if (rw64)
2487                         mark_insn_zext(env, reg);
2488
2489                 return mark_reg_read(env, reg, reg->parent,
2490                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2491         } else {
2492                 /* check whether register used as dest operand can be written to */
2493                 if (regno == BPF_REG_FP) {
2494                         verbose(env, "frame pointer is read only\n");
2495                         return -EACCES;
2496                 }
2497                 reg->live |= REG_LIVE_WRITTEN;
2498                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2499                 if (t == DST_OP)
2500                         mark_reg_unknown(env, regs, regno);
2501         }
2502         return 0;
2503 }
2504
2505 /* for any branch, call, exit record the history of jmps in the given state */
2506 static int push_jmp_history(struct bpf_verifier_env *env,
2507                             struct bpf_verifier_state *cur)
2508 {
2509         u32 cnt = cur->jmp_history_cnt;
2510         struct bpf_idx_pair *p;
2511         size_t alloc_size;
2512
2513         cnt++;
2514         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2515         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2516         if (!p)
2517                 return -ENOMEM;
2518         p[cnt - 1].idx = env->insn_idx;
2519         p[cnt - 1].prev_idx = env->prev_insn_idx;
2520         cur->jmp_history = p;
2521         cur->jmp_history_cnt = cnt;
2522         return 0;
2523 }
2524
2525 /* Backtrack one insn at a time. If idx is not at the top of recorded
2526  * history then previous instruction came from straight line execution.
2527  */
2528 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2529                              u32 *history)
2530 {
2531         u32 cnt = *history;
2532
2533         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2534                 i = st->jmp_history[cnt - 1].prev_idx;
2535                 (*history)--;
2536         } else {
2537                 i--;
2538         }
2539         return i;
2540 }
2541
2542 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2543 {
2544         const struct btf_type *func;
2545         struct btf *desc_btf;
2546
2547         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2548                 return NULL;
2549
2550         desc_btf = find_kfunc_desc_btf(data, insn->off);
2551         if (IS_ERR(desc_btf))
2552                 return "<error>";
2553
2554         func = btf_type_by_id(desc_btf, insn->imm);
2555         return btf_name_by_offset(desc_btf, func->name_off);
2556 }
2557
2558 /* For given verifier state backtrack_insn() is called from the last insn to
2559  * the first insn. Its purpose is to compute a bitmask of registers and
2560  * stack slots that needs precision in the parent verifier state.
2561  */
2562 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2563                           u32 *reg_mask, u64 *stack_mask)
2564 {
2565         const struct bpf_insn_cbs cbs = {
2566                 .cb_call        = disasm_kfunc_name,
2567                 .cb_print       = verbose,
2568                 .private_data   = env,
2569         };
2570         struct bpf_insn *insn = env->prog->insnsi + idx;
2571         u8 class = BPF_CLASS(insn->code);
2572         u8 opcode = BPF_OP(insn->code);
2573         u8 mode = BPF_MODE(insn->code);
2574         u32 dreg = 1u << insn->dst_reg;
2575         u32 sreg = 1u << insn->src_reg;
2576         u32 spi;
2577
2578         if (insn->code == 0)
2579                 return 0;
2580         if (env->log.level & BPF_LOG_LEVEL2) {
2581                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2582                 verbose(env, "%d: ", idx);
2583                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2584         }
2585
2586         if (class == BPF_ALU || class == BPF_ALU64) {
2587                 if (!(*reg_mask & dreg))
2588                         return 0;
2589                 if (opcode == BPF_MOV) {
2590                         if (BPF_SRC(insn->code) == BPF_X) {
2591                                 /* dreg = sreg
2592                                  * dreg needs precision after this insn
2593                                  * sreg needs precision before this insn
2594                                  */
2595                                 *reg_mask &= ~dreg;
2596                                 *reg_mask |= sreg;
2597                         } else {
2598                                 /* dreg = K
2599                                  * dreg needs precision after this insn.
2600                                  * Corresponding register is already marked
2601                                  * as precise=true in this verifier state.
2602                                  * No further markings in parent are necessary
2603                                  */
2604                                 *reg_mask &= ~dreg;
2605                         }
2606                 } else {
2607                         if (BPF_SRC(insn->code) == BPF_X) {
2608                                 /* dreg += sreg
2609                                  * both dreg and sreg need precision
2610                                  * before this insn
2611                                  */
2612                                 *reg_mask |= sreg;
2613                         } /* else dreg += K
2614                            * dreg still needs precision before this insn
2615                            */
2616                 }
2617         } else if (class == BPF_LDX) {
2618                 if (!(*reg_mask & dreg))
2619                         return 0;
2620                 *reg_mask &= ~dreg;
2621
2622                 /* scalars can only be spilled into stack w/o losing precision.
2623                  * Load from any other memory can be zero extended.
2624                  * The desire to keep that precision is already indicated
2625                  * by 'precise' mark in corresponding register of this state.
2626                  * No further tracking necessary.
2627                  */
2628                 if (insn->src_reg != BPF_REG_FP)
2629                         return 0;
2630
2631                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2632                  * that [fp - off] slot contains scalar that needs to be
2633                  * tracked with precision
2634                  */
2635                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2636                 if (spi >= 64) {
2637                         verbose(env, "BUG spi %d\n", spi);
2638                         WARN_ONCE(1, "verifier backtracking bug");
2639                         return -EFAULT;
2640                 }
2641                 *stack_mask |= 1ull << spi;
2642         } else if (class == BPF_STX || class == BPF_ST) {
2643                 if (*reg_mask & dreg)
2644                         /* stx & st shouldn't be using _scalar_ dst_reg
2645                          * to access memory. It means backtracking
2646                          * encountered a case of pointer subtraction.
2647                          */
2648                         return -ENOTSUPP;
2649                 /* scalars can only be spilled into stack */
2650                 if (insn->dst_reg != BPF_REG_FP)
2651                         return 0;
2652                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2653                 if (spi >= 64) {
2654                         verbose(env, "BUG spi %d\n", spi);
2655                         WARN_ONCE(1, "verifier backtracking bug");
2656                         return -EFAULT;
2657                 }
2658                 if (!(*stack_mask & (1ull << spi)))
2659                         return 0;
2660                 *stack_mask &= ~(1ull << spi);
2661                 if (class == BPF_STX)
2662                         *reg_mask |= sreg;
2663         } else if (class == BPF_JMP || class == BPF_JMP32) {
2664                 if (opcode == BPF_CALL) {
2665                         if (insn->src_reg == BPF_PSEUDO_CALL)
2666                                 return -ENOTSUPP;
2667                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
2668                          * catch this error later. Make backtracking conservative
2669                          * with ENOTSUPP.
2670                          */
2671                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2672                                 return -ENOTSUPP;
2673                         /* regular helper call sets R0 */
2674                         *reg_mask &= ~1;
2675                         if (*reg_mask & 0x3f) {
2676                                 /* if backtracing was looking for registers R1-R5
2677                                  * they should have been found already.
2678                                  */
2679                                 verbose(env, "BUG regs %x\n", *reg_mask);
2680                                 WARN_ONCE(1, "verifier backtracking bug");
2681                                 return -EFAULT;
2682                         }
2683                 } else if (opcode == BPF_EXIT) {
2684                         return -ENOTSUPP;
2685                 }
2686         } else if (class == BPF_LD) {
2687                 if (!(*reg_mask & dreg))
2688                         return 0;
2689                 *reg_mask &= ~dreg;
2690                 /* It's ld_imm64 or ld_abs or ld_ind.
2691                  * For ld_imm64 no further tracking of precision
2692                  * into parent is necessary
2693                  */
2694                 if (mode == BPF_IND || mode == BPF_ABS)
2695                         /* to be analyzed */
2696                         return -ENOTSUPP;
2697         }
2698         return 0;
2699 }
2700
2701 /* the scalar precision tracking algorithm:
2702  * . at the start all registers have precise=false.
2703  * . scalar ranges are tracked as normal through alu and jmp insns.
2704  * . once precise value of the scalar register is used in:
2705  *   .  ptr + scalar alu
2706  *   . if (scalar cond K|scalar)
2707  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2708  *   backtrack through the verifier states and mark all registers and
2709  *   stack slots with spilled constants that these scalar regisers
2710  *   should be precise.
2711  * . during state pruning two registers (or spilled stack slots)
2712  *   are equivalent if both are not precise.
2713  *
2714  * Note the verifier cannot simply walk register parentage chain,
2715  * since many different registers and stack slots could have been
2716  * used to compute single precise scalar.
2717  *
2718  * The approach of starting with precise=true for all registers and then
2719  * backtrack to mark a register as not precise when the verifier detects
2720  * that program doesn't care about specific value (e.g., when helper
2721  * takes register as ARG_ANYTHING parameter) is not safe.
2722  *
2723  * It's ok to walk single parentage chain of the verifier states.
2724  * It's possible that this backtracking will go all the way till 1st insn.
2725  * All other branches will be explored for needing precision later.
2726  *
2727  * The backtracking needs to deal with cases like:
2728  *   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)
2729  * r9 -= r8
2730  * r5 = r9
2731  * if r5 > 0x79f goto pc+7
2732  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2733  * r5 += 1
2734  * ...
2735  * call bpf_perf_event_output#25
2736  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2737  *
2738  * and this case:
2739  * r6 = 1
2740  * call foo // uses callee's r6 inside to compute r0
2741  * r0 += r6
2742  * if r0 == 0 goto
2743  *
2744  * to track above reg_mask/stack_mask needs to be independent for each frame.
2745  *
2746  * Also if parent's curframe > frame where backtracking started,
2747  * the verifier need to mark registers in both frames, otherwise callees
2748  * may incorrectly prune callers. This is similar to
2749  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2750  *
2751  * For now backtracking falls back into conservative marking.
2752  */
2753 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2754                                      struct bpf_verifier_state *st)
2755 {
2756         struct bpf_func_state *func;
2757         struct bpf_reg_state *reg;
2758         int i, j;
2759
2760         /* big hammer: mark all scalars precise in this path.
2761          * pop_stack may still get !precise scalars.
2762          */
2763         for (; st; st = st->parent)
2764                 for (i = 0; i <= st->curframe; i++) {
2765                         func = st->frame[i];
2766                         for (j = 0; j < BPF_REG_FP; j++) {
2767                                 reg = &func->regs[j];
2768                                 if (reg->type != SCALAR_VALUE)
2769                                         continue;
2770                                 reg->precise = true;
2771                         }
2772                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2773                                 if (!is_spilled_reg(&func->stack[j]))
2774                                         continue;
2775                                 reg = &func->stack[j].spilled_ptr;
2776                                 if (reg->type != SCALAR_VALUE)
2777                                         continue;
2778                                 reg->precise = true;
2779                         }
2780                 }
2781 }
2782
2783 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2784                                   int spi)
2785 {
2786         struct bpf_verifier_state *st = env->cur_state;
2787         int first_idx = st->first_insn_idx;
2788         int last_idx = env->insn_idx;
2789         struct bpf_func_state *func;
2790         struct bpf_reg_state *reg;
2791         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2792         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2793         bool skip_first = true;
2794         bool new_marks = false;
2795         int i, err;
2796
2797         if (!env->bpf_capable)
2798                 return 0;
2799
2800         func = st->frame[frame];
2801         if (regno >= 0) {
2802                 reg = &func->regs[regno];
2803                 if (reg->type != SCALAR_VALUE) {
2804                         WARN_ONCE(1, "backtracing misuse");
2805                         return -EFAULT;
2806                 }
2807                 if (!reg->precise)
2808                         new_marks = true;
2809                 else
2810                         reg_mask = 0;
2811                 reg->precise = true;
2812         }
2813
2814         while (spi >= 0) {
2815                 if (!is_spilled_reg(&func->stack[spi])) {
2816                         stack_mask = 0;
2817                         break;
2818                 }
2819                 reg = &func->stack[spi].spilled_ptr;
2820                 if (reg->type != SCALAR_VALUE) {
2821                         stack_mask = 0;
2822                         break;
2823                 }
2824                 if (!reg->precise)
2825                         new_marks = true;
2826                 else
2827                         stack_mask = 0;
2828                 reg->precise = true;
2829                 break;
2830         }
2831
2832         if (!new_marks)
2833                 return 0;
2834         if (!reg_mask && !stack_mask)
2835                 return 0;
2836         for (;;) {
2837                 DECLARE_BITMAP(mask, 64);
2838                 u32 history = st->jmp_history_cnt;
2839
2840                 if (env->log.level & BPF_LOG_LEVEL2)
2841                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2842                 for (i = last_idx;;) {
2843                         if (skip_first) {
2844                                 err = 0;
2845                                 skip_first = false;
2846                         } else {
2847                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2848                         }
2849                         if (err == -ENOTSUPP) {
2850                                 mark_all_scalars_precise(env, st);
2851                                 return 0;
2852                         } else if (err) {
2853                                 return err;
2854                         }
2855                         if (!reg_mask && !stack_mask)
2856                                 /* Found assignment(s) into tracked register in this state.
2857                                  * Since this state is already marked, just return.
2858                                  * Nothing to be tracked further in the parent state.
2859                                  */
2860                                 return 0;
2861                         if (i == first_idx)
2862                                 break;
2863                         i = get_prev_insn_idx(st, i, &history);
2864                         if (i >= env->prog->len) {
2865                                 /* This can happen if backtracking reached insn 0
2866                                  * and there are still reg_mask or stack_mask
2867                                  * to backtrack.
2868                                  * It means the backtracking missed the spot where
2869                                  * particular register was initialized with a constant.
2870                                  */
2871                                 verbose(env, "BUG backtracking idx %d\n", i);
2872                                 WARN_ONCE(1, "verifier backtracking bug");
2873                                 return -EFAULT;
2874                         }
2875                 }
2876                 st = st->parent;
2877                 if (!st)
2878                         break;
2879
2880                 new_marks = false;
2881                 func = st->frame[frame];
2882                 bitmap_from_u64(mask, reg_mask);
2883                 for_each_set_bit(i, mask, 32) {
2884                         reg = &func->regs[i];
2885                         if (reg->type != SCALAR_VALUE) {
2886                                 reg_mask &= ~(1u << i);
2887                                 continue;
2888                         }
2889                         if (!reg->precise)
2890                                 new_marks = true;
2891                         reg->precise = true;
2892                 }
2893
2894                 bitmap_from_u64(mask, stack_mask);
2895                 for_each_set_bit(i, mask, 64) {
2896                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2897                                 /* the sequence of instructions:
2898                                  * 2: (bf) r3 = r10
2899                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2900                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2901                                  * doesn't contain jmps. It's backtracked
2902                                  * as a single block.
2903                                  * During backtracking insn 3 is not recognized as
2904                                  * stack access, so at the end of backtracking
2905                                  * stack slot fp-8 is still marked in stack_mask.
2906                                  * However the parent state may not have accessed
2907                                  * fp-8 and it's "unallocated" stack space.
2908                                  * In such case fallback to conservative.
2909                                  */
2910                                 mark_all_scalars_precise(env, st);
2911                                 return 0;
2912                         }
2913
2914                         if (!is_spilled_reg(&func->stack[i])) {
2915                                 stack_mask &= ~(1ull << i);
2916                                 continue;
2917                         }
2918                         reg = &func->stack[i].spilled_ptr;
2919                         if (reg->type != SCALAR_VALUE) {
2920                                 stack_mask &= ~(1ull << i);
2921                                 continue;
2922                         }
2923                         if (!reg->precise)
2924                                 new_marks = true;
2925                         reg->precise = true;
2926                 }
2927                 if (env->log.level & BPF_LOG_LEVEL2) {
2928                         verbose(env, "parent %s regs=%x stack=%llx marks:",
2929                                 new_marks ? "didn't have" : "already had",
2930                                 reg_mask, stack_mask);
2931                         print_verifier_state(env, func, true);
2932                 }
2933
2934                 if (!reg_mask && !stack_mask)
2935                         break;
2936                 if (!new_marks)
2937                         break;
2938
2939                 last_idx = st->last_insn_idx;
2940                 first_idx = st->first_insn_idx;
2941         }
2942         return 0;
2943 }
2944
2945 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2946 {
2947         return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2948 }
2949
2950 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2951 {
2952         return __mark_chain_precision(env, frame, regno, -1);
2953 }
2954
2955 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2956 {
2957         return __mark_chain_precision(env, frame, -1, spi);
2958 }
2959
2960 static bool is_spillable_regtype(enum bpf_reg_type type)
2961 {
2962         switch (base_type(type)) {
2963         case PTR_TO_MAP_VALUE:
2964         case PTR_TO_STACK:
2965         case PTR_TO_CTX:
2966         case PTR_TO_PACKET:
2967         case PTR_TO_PACKET_META:
2968         case PTR_TO_PACKET_END:
2969         case PTR_TO_FLOW_KEYS:
2970         case CONST_PTR_TO_MAP:
2971         case PTR_TO_SOCKET:
2972         case PTR_TO_SOCK_COMMON:
2973         case PTR_TO_TCP_SOCK:
2974         case PTR_TO_XDP_SOCK:
2975         case PTR_TO_BTF_ID:
2976         case PTR_TO_BUF:
2977         case PTR_TO_MEM:
2978         case PTR_TO_FUNC:
2979         case PTR_TO_MAP_KEY:
2980                 return true;
2981         default:
2982                 return false;
2983         }
2984 }
2985
2986 /* Does this register contain a constant zero? */
2987 static bool register_is_null(struct bpf_reg_state *reg)
2988 {
2989         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2990 }
2991
2992 static bool register_is_const(struct bpf_reg_state *reg)
2993 {
2994         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2995 }
2996
2997 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2998 {
2999         return tnum_is_unknown(reg->var_off) &&
3000                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3001                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3002                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3003                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3004 }
3005
3006 static bool register_is_bounded(struct bpf_reg_state *reg)
3007 {
3008         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3009 }
3010
3011 static bool __is_pointer_value(bool allow_ptr_leaks,
3012                                const struct bpf_reg_state *reg)
3013 {
3014         if (allow_ptr_leaks)
3015                 return false;
3016
3017         return reg->type != SCALAR_VALUE;
3018 }
3019
3020 /* Copy src state preserving dst->parent and dst->live fields */
3021 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3022 {
3023         struct bpf_reg_state *parent = dst->parent;
3024         enum bpf_reg_liveness live = dst->live;
3025
3026         *dst = *src;
3027         dst->parent = parent;
3028         dst->live = live;
3029 }
3030
3031 static void save_register_state(struct bpf_func_state *state,
3032                                 int spi, struct bpf_reg_state *reg,
3033                                 int size)
3034 {
3035         int i;
3036
3037         copy_register_state(&state->stack[spi].spilled_ptr, reg);
3038         if (size == BPF_REG_SIZE)
3039                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3040
3041         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3042                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3043
3044         /* size < 8 bytes spill */
3045         for (; i; i--)
3046                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3047 }
3048
3049 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3050  * stack boundary and alignment are checked in check_mem_access()
3051  */
3052 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3053                                        /* stack frame we're writing to */
3054                                        struct bpf_func_state *state,
3055                                        int off, int size, int value_regno,
3056                                        int insn_idx)
3057 {
3058         struct bpf_func_state *cur; /* state of the current function */
3059         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3060         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3061         struct bpf_reg_state *reg = NULL;
3062
3063         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3064         if (err)
3065                 return err;
3066         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3067          * so it's aligned access and [off, off + size) are within stack limits
3068          */
3069         if (!env->allow_ptr_leaks &&
3070             state->stack[spi].slot_type[0] == STACK_SPILL &&
3071             size != BPF_REG_SIZE) {
3072                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3073                 return -EACCES;
3074         }
3075
3076         cur = env->cur_state->frame[env->cur_state->curframe];
3077         if (value_regno >= 0)
3078                 reg = &cur->regs[value_regno];
3079         if (!env->bypass_spec_v4) {
3080                 bool sanitize = reg && is_spillable_regtype(reg->type);
3081
3082                 for (i = 0; i < size; i++) {
3083                         u8 type = state->stack[spi].slot_type[i];
3084
3085                         if (type != STACK_MISC && type != STACK_ZERO) {
3086                                 sanitize = true;
3087                                 break;
3088                         }
3089                 }
3090
3091                 if (sanitize)
3092                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3093         }
3094
3095         mark_stack_slot_scratched(env, spi);
3096         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3097             !register_is_null(reg) && env->bpf_capable) {
3098                 if (dst_reg != BPF_REG_FP) {
3099                         /* The backtracking logic can only recognize explicit
3100                          * stack slot address like [fp - 8]. Other spill of
3101                          * scalar via different register has to be conservative.
3102                          * Backtrack from here and mark all registers as precise
3103                          * that contributed into 'reg' being a constant.
3104                          */
3105                         err = mark_chain_precision(env, value_regno);
3106                         if (err)
3107                                 return err;
3108                 }
3109                 save_register_state(state, spi, reg, size);
3110         } else if (reg && is_spillable_regtype(reg->type)) {
3111                 /* register containing pointer is being spilled into stack */
3112                 if (size != BPF_REG_SIZE) {
3113                         verbose_linfo(env, insn_idx, "; ");
3114                         verbose(env, "invalid size of register spill\n");
3115                         return -EACCES;
3116                 }
3117                 if (state != cur && reg->type == PTR_TO_STACK) {
3118                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3119                         return -EINVAL;
3120                 }
3121                 save_register_state(state, spi, reg, size);
3122         } else {
3123                 u8 type = STACK_MISC;
3124
3125                 /* regular write of data into stack destroys any spilled ptr */
3126                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3127                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3128                 if (is_spilled_reg(&state->stack[spi]))
3129                         for (i = 0; i < BPF_REG_SIZE; i++)
3130                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3131
3132                 /* only mark the slot as written if all 8 bytes were written
3133                  * otherwise read propagation may incorrectly stop too soon
3134                  * when stack slots are partially written.
3135                  * This heuristic means that read propagation will be
3136                  * conservative, since it will add reg_live_read marks
3137                  * to stack slots all the way to first state when programs
3138                  * writes+reads less than 8 bytes
3139                  */
3140                 if (size == BPF_REG_SIZE)
3141                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3142
3143                 /* when we zero initialize stack slots mark them as such */
3144                 if (reg && register_is_null(reg)) {
3145                         /* backtracking doesn't work for STACK_ZERO yet. */
3146                         err = mark_chain_precision(env, value_regno);
3147                         if (err)
3148                                 return err;
3149                         type = STACK_ZERO;
3150                 }
3151
3152                 /* Mark slots affected by this stack write. */
3153                 for (i = 0; i < size; i++)
3154                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3155                                 type;
3156         }
3157         return 0;
3158 }
3159
3160 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3161  * known to contain a variable offset.
3162  * This function checks whether the write is permitted and conservatively
3163  * tracks the effects of the write, considering that each stack slot in the
3164  * dynamic range is potentially written to.
3165  *
3166  * 'off' includes 'regno->off'.
3167  * 'value_regno' can be -1, meaning that an unknown value is being written to
3168  * the stack.
3169  *
3170  * Spilled pointers in range are not marked as written because we don't know
3171  * what's going to be actually written. This means that read propagation for
3172  * future reads cannot be terminated by this write.
3173  *
3174  * For privileged programs, uninitialized stack slots are considered
3175  * initialized by this write (even though we don't know exactly what offsets
3176  * are going to be written to). The idea is that we don't want the verifier to
3177  * reject future reads that access slots written to through variable offsets.
3178  */
3179 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3180                                      /* func where register points to */
3181                                      struct bpf_func_state *state,
3182                                      int ptr_regno, int off, int size,
3183                                      int value_regno, int insn_idx)
3184 {
3185         struct bpf_func_state *cur; /* state of the current function */
3186         int min_off, max_off;
3187         int i, err;
3188         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3189         bool writing_zero = false;
3190         /* set if the fact that we're writing a zero is used to let any
3191          * stack slots remain STACK_ZERO
3192          */
3193         bool zero_used = false;
3194
3195         cur = env->cur_state->frame[env->cur_state->curframe];
3196         ptr_reg = &cur->regs[ptr_regno];
3197         min_off = ptr_reg->smin_value + off;
3198         max_off = ptr_reg->smax_value + off + size;
3199         if (value_regno >= 0)
3200                 value_reg = &cur->regs[value_regno];
3201         if (value_reg && register_is_null(value_reg))
3202                 writing_zero = true;
3203
3204         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3205         if (err)
3206                 return err;
3207
3208
3209         /* Variable offset writes destroy any spilled pointers in range. */
3210         for (i = min_off; i < max_off; i++) {
3211                 u8 new_type, *stype;
3212                 int slot, spi;
3213
3214                 slot = -i - 1;
3215                 spi = slot / BPF_REG_SIZE;
3216                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3217                 mark_stack_slot_scratched(env, spi);
3218
3219                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3220                         /* Reject the write if range we may write to has not
3221                          * been initialized beforehand. If we didn't reject
3222                          * here, the ptr status would be erased below (even
3223                          * though not all slots are actually overwritten),
3224                          * possibly opening the door to leaks.
3225                          *
3226                          * We do however catch STACK_INVALID case below, and
3227                          * only allow reading possibly uninitialized memory
3228                          * later for CAP_PERFMON, as the write may not happen to
3229                          * that slot.
3230                          */
3231                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3232                                 insn_idx, i);
3233                         return -EINVAL;
3234                 }
3235
3236                 /* Erase all spilled pointers. */
3237                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3238
3239                 /* Update the slot type. */
3240                 new_type = STACK_MISC;
3241                 if (writing_zero && *stype == STACK_ZERO) {
3242                         new_type = STACK_ZERO;
3243                         zero_used = true;
3244                 }
3245                 /* If the slot is STACK_INVALID, we check whether it's OK to
3246                  * pretend that it will be initialized by this write. The slot
3247                  * might not actually be written to, and so if we mark it as
3248                  * initialized future reads might leak uninitialized memory.
3249                  * For privileged programs, we will accept such reads to slots
3250                  * that may or may not be written because, if we're reject
3251                  * them, the error would be too confusing.
3252                  */
3253                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3254                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3255                                         insn_idx, i);
3256                         return -EINVAL;
3257                 }
3258                 *stype = new_type;
3259         }
3260         if (zero_used) {
3261                 /* backtracking doesn't work for STACK_ZERO yet. */
3262                 err = mark_chain_precision(env, value_regno);
3263                 if (err)
3264                         return err;
3265         }
3266         return 0;
3267 }
3268
3269 /* When register 'dst_regno' is assigned some values from stack[min_off,
3270  * max_off), we set the register's type according to the types of the
3271  * respective stack slots. If all the stack values are known to be zeros, then
3272  * so is the destination reg. Otherwise, the register is considered to be
3273  * SCALAR. This function does not deal with register filling; the caller must
3274  * ensure that all spilled registers in the stack range have been marked as
3275  * read.
3276  */
3277 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3278                                 /* func where src register points to */
3279                                 struct bpf_func_state *ptr_state,
3280                                 int min_off, int max_off, int dst_regno)
3281 {
3282         struct bpf_verifier_state *vstate = env->cur_state;
3283         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3284         int i, slot, spi;
3285         u8 *stype;
3286         int zeros = 0;
3287
3288         for (i = min_off; i < max_off; i++) {
3289                 slot = -i - 1;
3290                 spi = slot / BPF_REG_SIZE;
3291                 stype = ptr_state->stack[spi].slot_type;
3292                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3293                         break;
3294                 zeros++;
3295         }
3296         if (zeros == max_off - min_off) {
3297                 /* any access_size read into register is zero extended,
3298                  * so the whole register == const_zero
3299                  */
3300                 __mark_reg_const_zero(&state->regs[dst_regno]);
3301                 /* backtracking doesn't support STACK_ZERO yet,
3302                  * so mark it precise here, so that later
3303                  * backtracking can stop here.
3304                  * Backtracking may not need this if this register
3305                  * doesn't participate in pointer adjustment.
3306                  * Forward propagation of precise flag is not
3307                  * necessary either. This mark is only to stop
3308                  * backtracking. Any register that contributed
3309                  * to const 0 was marked precise before spill.
3310                  */
3311                 state->regs[dst_regno].precise = true;
3312         } else {
3313                 /* have read misc data from the stack */
3314                 mark_reg_unknown(env, state->regs, dst_regno);
3315         }
3316         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3317 }
3318
3319 /* Read the stack at 'off' and put the results into the register indicated by
3320  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3321  * spilled reg.
3322  *
3323  * 'dst_regno' can be -1, meaning that the read value is not going to a
3324  * register.
3325  *
3326  * The access is assumed to be within the current stack bounds.
3327  */
3328 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3329                                       /* func where src register points to */
3330                                       struct bpf_func_state *reg_state,
3331                                       int off, int size, int dst_regno)
3332 {
3333         struct bpf_verifier_state *vstate = env->cur_state;
3334         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3335         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3336         struct bpf_reg_state *reg;
3337         u8 *stype, type;
3338
3339         stype = reg_state->stack[spi].slot_type;
3340         reg = &reg_state->stack[spi].spilled_ptr;
3341
3342         if (is_spilled_reg(&reg_state->stack[spi])) {
3343                 u8 spill_size = 1;
3344
3345                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3346                         spill_size++;
3347
3348                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3349                         if (reg->type != SCALAR_VALUE) {
3350                                 verbose_linfo(env, env->insn_idx, "; ");
3351                                 verbose(env, "invalid size of register fill\n");
3352                                 return -EACCES;
3353                         }
3354
3355                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3356                         if (dst_regno < 0)
3357                                 return 0;
3358
3359                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
3360                                 /* The earlier check_reg_arg() has decided the
3361                                  * subreg_def for this insn.  Save it first.
3362                                  */
3363                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
3364
3365                                 copy_register_state(&state->regs[dst_regno], reg);
3366                                 state->regs[dst_regno].subreg_def = subreg_def;
3367                         } else {
3368                                 for (i = 0; i < size; i++) {
3369                                         type = stype[(slot - i) % BPF_REG_SIZE];
3370                                         if (type == STACK_SPILL)
3371                                                 continue;
3372                                         if (type == STACK_MISC)
3373                                                 continue;
3374                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3375                                                 off, i, size);
3376                                         return -EACCES;
3377                                 }
3378                                 mark_reg_unknown(env, state->regs, dst_regno);
3379                         }
3380                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3381                         return 0;
3382                 }
3383
3384                 if (dst_regno >= 0) {
3385                         /* restore register state from stack */
3386                         copy_register_state(&state->regs[dst_regno], reg);
3387                         /* mark reg as written since spilled pointer state likely
3388                          * has its liveness marks cleared by is_state_visited()
3389                          * which resets stack/reg liveness for state transitions
3390                          */
3391                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3392                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3393                         /* If dst_regno==-1, the caller is asking us whether
3394                          * it is acceptable to use this value as a SCALAR_VALUE
3395                          * (e.g. for XADD).
3396                          * We must not allow unprivileged callers to do that
3397                          * with spilled pointers.
3398                          */
3399                         verbose(env, "leaking pointer from stack off %d\n",
3400                                 off);
3401                         return -EACCES;
3402                 }
3403                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3404         } else {
3405                 for (i = 0; i < size; i++) {
3406                         type = stype[(slot - i) % BPF_REG_SIZE];
3407                         if (type == STACK_MISC)
3408                                 continue;
3409                         if (type == STACK_ZERO)
3410                                 continue;
3411                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3412                                 off, i, size);
3413                         return -EACCES;
3414                 }
3415                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3416                 if (dst_regno >= 0)
3417                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3418         }
3419         return 0;
3420 }
3421
3422 enum bpf_access_src {
3423         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3424         ACCESS_HELPER = 2,  /* the access is performed by a helper */
3425 };
3426
3427 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3428                                          int regno, int off, int access_size,
3429                                          bool zero_size_allowed,
3430                                          enum bpf_access_src type,
3431                                          struct bpf_call_arg_meta *meta);
3432
3433 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3434 {
3435         return cur_regs(env) + regno;
3436 }
3437
3438 /* Read the stack at 'ptr_regno + off' and put the result into the register
3439  * 'dst_regno'.
3440  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3441  * but not its variable offset.
3442  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3443  *
3444  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3445  * filling registers (i.e. reads of spilled register cannot be detected when
3446  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3447  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3448  * offset; for a fixed offset check_stack_read_fixed_off should be used
3449  * instead.
3450  */
3451 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3452                                     int ptr_regno, int off, int size, int dst_regno)
3453 {
3454         /* The state of the source register. */
3455         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3456         struct bpf_func_state *ptr_state = func(env, reg);
3457         int err;
3458         int min_off, max_off;
3459
3460         /* Note that we pass a NULL meta, so raw access will not be permitted.
3461          */
3462         err = check_stack_range_initialized(env, ptr_regno, off, size,
3463                                             false, ACCESS_DIRECT, NULL);
3464         if (err)
3465                 return err;
3466
3467         min_off = reg->smin_value + off;
3468         max_off = reg->smax_value + off;
3469         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3470         return 0;
3471 }
3472
3473 /* check_stack_read dispatches to check_stack_read_fixed_off or
3474  * check_stack_read_var_off.
3475  *
3476  * The caller must ensure that the offset falls within the allocated stack
3477  * bounds.
3478  *
3479  * 'dst_regno' is a register which will receive the value from the stack. It
3480  * can be -1, meaning that the read value is not going to a register.
3481  */
3482 static int check_stack_read(struct bpf_verifier_env *env,
3483                             int ptr_regno, int off, int size,
3484                             int dst_regno)
3485 {
3486         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3487         struct bpf_func_state *state = func(env, reg);
3488         int err;
3489         /* Some accesses are only permitted with a static offset. */
3490         bool var_off = !tnum_is_const(reg->var_off);
3491
3492         /* The offset is required to be static when reads don't go to a
3493          * register, in order to not leak pointers (see
3494          * check_stack_read_fixed_off).
3495          */
3496         if (dst_regno < 0 && var_off) {
3497                 char tn_buf[48];
3498
3499                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3500                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3501                         tn_buf, off, size);
3502                 return -EACCES;
3503         }
3504         /* Variable offset is prohibited for unprivileged mode for simplicity
3505          * since it requires corresponding support in Spectre masking for stack
3506          * ALU. See also retrieve_ptr_limit().
3507          */
3508         if (!env->bypass_spec_v1 && var_off) {
3509                 char tn_buf[48];
3510
3511                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3512                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3513                                 ptr_regno, tn_buf);
3514                 return -EACCES;
3515         }
3516
3517         if (!var_off) {
3518                 off += reg->var_off.value;
3519                 err = check_stack_read_fixed_off(env, state, off, size,
3520                                                  dst_regno);
3521         } else {
3522                 /* Variable offset stack reads need more conservative handling
3523                  * than fixed offset ones. Note that dst_regno >= 0 on this
3524                  * branch.
3525                  */
3526                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3527                                                dst_regno);
3528         }
3529         return err;
3530 }
3531
3532
3533 /* check_stack_write dispatches to check_stack_write_fixed_off or
3534  * check_stack_write_var_off.
3535  *
3536  * 'ptr_regno' is the register used as a pointer into the stack.
3537  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3538  * 'value_regno' is the register whose value we're writing to the stack. It can
3539  * be -1, meaning that we're not writing from a register.
3540  *
3541  * The caller must ensure that the offset falls within the maximum stack size.
3542  */
3543 static int check_stack_write(struct bpf_verifier_env *env,
3544                              int ptr_regno, int off, int size,
3545                              int value_regno, int insn_idx)
3546 {
3547         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3548         struct bpf_func_state *state = func(env, reg);
3549         int err;
3550
3551         if (tnum_is_const(reg->var_off)) {
3552                 off += reg->var_off.value;
3553                 err = check_stack_write_fixed_off(env, state, off, size,
3554                                                   value_regno, insn_idx);
3555         } else {
3556                 /* Variable offset stack reads need more conservative handling
3557                  * than fixed offset ones.
3558                  */
3559                 err = check_stack_write_var_off(env, state,
3560                                                 ptr_regno, off, size,
3561                                                 value_regno, insn_idx);
3562         }
3563         return err;
3564 }
3565
3566 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3567                                  int off, int size, enum bpf_access_type type)
3568 {
3569         struct bpf_reg_state *regs = cur_regs(env);
3570         struct bpf_map *map = regs[regno].map_ptr;
3571         u32 cap = bpf_map_flags_to_cap(map);
3572
3573         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3574                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3575                         map->value_size, off, size);
3576                 return -EACCES;
3577         }
3578
3579         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3580                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3581                         map->value_size, off, size);
3582                 return -EACCES;
3583         }
3584
3585         return 0;
3586 }
3587
3588 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3589 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3590                               int off, int size, u32 mem_size,
3591                               bool zero_size_allowed)
3592 {
3593         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3594         struct bpf_reg_state *reg;
3595
3596         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3597                 return 0;
3598
3599         reg = &cur_regs(env)[regno];
3600         switch (reg->type) {
3601         case PTR_TO_MAP_KEY:
3602                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3603                         mem_size, off, size);
3604                 break;
3605         case PTR_TO_MAP_VALUE:
3606                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3607                         mem_size, off, size);
3608                 break;
3609         case PTR_TO_PACKET:
3610         case PTR_TO_PACKET_META:
3611         case PTR_TO_PACKET_END:
3612                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3613                         off, size, regno, reg->id, off, mem_size);
3614                 break;
3615         case PTR_TO_MEM:
3616         default:
3617                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3618                         mem_size, off, size);
3619         }
3620
3621         return -EACCES;
3622 }
3623
3624 /* check read/write into a memory region with possible variable offset */
3625 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3626                                    int off, int size, u32 mem_size,
3627                                    bool zero_size_allowed)
3628 {
3629         struct bpf_verifier_state *vstate = env->cur_state;
3630         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3631         struct bpf_reg_state *reg = &state->regs[regno];
3632         int err;
3633
3634         /* We may have adjusted the register pointing to memory region, so we
3635          * need to try adding each of min_value and max_value to off
3636          * to make sure our theoretical access will be safe.
3637          *
3638          * The minimum value is only important with signed
3639          * comparisons where we can't assume the floor of a
3640          * value is 0.  If we are using signed variables for our
3641          * index'es we need to make sure that whatever we use
3642          * will have a set floor within our range.
3643          */
3644         if (reg->smin_value < 0 &&
3645             (reg->smin_value == S64_MIN ||
3646              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3647               reg->smin_value + off < 0)) {
3648                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3649                         regno);
3650                 return -EACCES;
3651         }
3652         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3653                                  mem_size, zero_size_allowed);
3654         if (err) {
3655                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3656                         regno);
3657                 return err;
3658         }
3659
3660         /* If we haven't set a max value then we need to bail since we can't be
3661          * sure we won't do bad things.
3662          * If reg->umax_value + off could overflow, treat that as unbounded too.
3663          */
3664         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3665                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3666                         regno);
3667                 return -EACCES;
3668         }
3669         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3670                                  mem_size, zero_size_allowed);
3671         if (err) {
3672                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3673                         regno);
3674                 return err;
3675         }
3676
3677         return 0;
3678 }
3679
3680 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3681                                const struct bpf_reg_state *reg, int regno,
3682                                bool fixed_off_ok)
3683 {
3684         /* Access to this pointer-typed register or passing it to a helper
3685          * is only allowed in its original, unmodified form.
3686          */
3687
3688         if (reg->off < 0) {
3689                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3690                         reg_type_str(env, reg->type), regno, reg->off);
3691                 return -EACCES;
3692         }
3693
3694         if (!fixed_off_ok && reg->off) {
3695                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3696                         reg_type_str(env, reg->type), regno, reg->off);
3697                 return -EACCES;
3698         }
3699
3700         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3701                 char tn_buf[48];
3702
3703                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3704                 verbose(env, "variable %s access var_off=%s disallowed\n",
3705                         reg_type_str(env, reg->type), tn_buf);
3706                 return -EACCES;
3707         }
3708
3709         return 0;
3710 }
3711
3712 int check_ptr_off_reg(struct bpf_verifier_env *env,
3713                       const struct bpf_reg_state *reg, int regno)
3714 {
3715         return __check_ptr_off_reg(env, reg, regno, false);
3716 }
3717
3718 static int map_kptr_match_type(struct bpf_verifier_env *env,
3719                                struct bpf_map_value_off_desc *off_desc,
3720                                struct bpf_reg_state *reg, u32 regno)
3721 {
3722         const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3723         int perm_flags = PTR_MAYBE_NULL;
3724         const char *reg_name = "";
3725
3726         /* Only unreferenced case accepts untrusted pointers */
3727         if (off_desc->type == BPF_KPTR_UNREF)
3728                 perm_flags |= PTR_UNTRUSTED;
3729
3730         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3731                 goto bad_type;
3732
3733         if (!btf_is_kernel(reg->btf)) {
3734                 verbose(env, "R%d must point to kernel BTF\n", regno);
3735                 return -EINVAL;
3736         }
3737         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3738         reg_name = kernel_type_name(reg->btf, reg->btf_id);
3739
3740         /* For ref_ptr case, release function check should ensure we get one
3741          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3742          * normal store of unreferenced kptr, we must ensure var_off is zero.
3743          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3744          * reg->off and reg->ref_obj_id are not needed here.
3745          */
3746         if (__check_ptr_off_reg(env, reg, regno, true))
3747                 return -EACCES;
3748
3749         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3750          * we also need to take into account the reg->off.
3751          *
3752          * We want to support cases like:
3753          *
3754          * struct foo {
3755          *         struct bar br;
3756          *         struct baz bz;
3757          * };
3758          *
3759          * struct foo *v;
3760          * v = func();        // PTR_TO_BTF_ID
3761          * val->foo = v;      // reg->off is zero, btf and btf_id match type
3762          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3763          *                    // first member type of struct after comparison fails
3764          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3765          *                    // to match type
3766          *
3767          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3768          * is zero. We must also ensure that btf_struct_ids_match does not walk
3769          * the struct to match type against first member of struct, i.e. reject
3770          * second case from above. Hence, when type is BPF_KPTR_REF, we set
3771          * strict mode to true for type match.
3772          */
3773         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3774                                   off_desc->kptr.btf, off_desc->kptr.btf_id,
3775                                   off_desc->type == BPF_KPTR_REF))
3776                 goto bad_type;
3777         return 0;
3778 bad_type:
3779         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3780                 reg_type_str(env, reg->type), reg_name);
3781         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3782         if (off_desc->type == BPF_KPTR_UNREF)
3783                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3784                         targ_name);
3785         else
3786                 verbose(env, "\n");
3787         return -EINVAL;
3788 }
3789
3790 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3791                                  int value_regno, int insn_idx,
3792                                  struct bpf_map_value_off_desc *off_desc)
3793 {
3794         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3795         int class = BPF_CLASS(insn->code);
3796         struct bpf_reg_state *val_reg;
3797
3798         /* Things we already checked for in check_map_access and caller:
3799          *  - Reject cases where variable offset may touch kptr
3800          *  - size of access (must be BPF_DW)
3801          *  - tnum_is_const(reg->var_off)
3802          *  - off_desc->offset == off + reg->var_off.value
3803          */
3804         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3805         if (BPF_MODE(insn->code) != BPF_MEM) {
3806                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3807                 return -EACCES;
3808         }
3809
3810         /* We only allow loading referenced kptr, since it will be marked as
3811          * untrusted, similar to unreferenced kptr.
3812          */
3813         if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3814                 verbose(env, "store to referenced kptr disallowed\n");
3815                 return -EACCES;
3816         }
3817
3818         if (class == BPF_LDX) {
3819                 val_reg = reg_state(env, value_regno);
3820                 /* We can simply mark the value_regno receiving the pointer
3821                  * value from map as PTR_TO_BTF_ID, with the correct type.
3822                  */
3823                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3824                                 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3825                 /* For mark_ptr_or_null_reg */
3826                 val_reg->id = ++env->id_gen;
3827         } else if (class == BPF_STX) {
3828                 val_reg = reg_state(env, value_regno);
3829                 if (!register_is_null(val_reg) &&
3830                     map_kptr_match_type(env, off_desc, val_reg, value_regno))
3831                         return -EACCES;
3832         } else if (class == BPF_ST) {
3833                 if (insn->imm) {
3834                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3835                                 off_desc->offset);
3836                         return -EACCES;
3837                 }
3838         } else {
3839                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3840                 return -EACCES;
3841         }
3842         return 0;
3843 }
3844
3845 /* check read/write into a map element with possible variable offset */
3846 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3847                             int off, int size, bool zero_size_allowed,
3848                             enum bpf_access_src src)
3849 {
3850         struct bpf_verifier_state *vstate = env->cur_state;
3851         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3852         struct bpf_reg_state *reg = &state->regs[regno];
3853         struct bpf_map *map = reg->map_ptr;
3854         int err;
3855
3856         err = check_mem_region_access(env, regno, off, size, map->value_size,
3857                                       zero_size_allowed);
3858         if (err)
3859                 return err;
3860
3861         if (map_value_has_spin_lock(map)) {
3862                 u32 lock = map->spin_lock_off;
3863
3864                 /* if any part of struct bpf_spin_lock can be touched by
3865                  * load/store reject this program.
3866                  * To check that [x1, x2) overlaps with [y1, y2)
3867                  * it is sufficient to check x1 < y2 && y1 < x2.
3868                  */
3869                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3870                      lock < reg->umax_value + off + size) {
3871                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3872                         return -EACCES;
3873                 }
3874         }
3875         if (map_value_has_timer(map)) {
3876                 u32 t = map->timer_off;
3877
3878                 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3879                      t < reg->umax_value + off + size) {
3880                         verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3881                         return -EACCES;
3882                 }
3883         }
3884         if (map_value_has_kptrs(map)) {
3885                 struct bpf_map_value_off *tab = map->kptr_off_tab;
3886                 int i;
3887
3888                 for (i = 0; i < tab->nr_off; i++) {
3889                         u32 p = tab->off[i].offset;
3890
3891                         if (reg->smin_value + off < p + sizeof(u64) &&
3892                             p < reg->umax_value + off + size) {
3893                                 if (src != ACCESS_DIRECT) {
3894                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
3895                                         return -EACCES;
3896                                 }
3897                                 if (!tnum_is_const(reg->var_off)) {
3898                                         verbose(env, "kptr access cannot have variable offset\n");
3899                                         return -EACCES;
3900                                 }
3901                                 if (p != off + reg->var_off.value) {
3902                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3903                                                 p, off + reg->var_off.value);
3904                                         return -EACCES;
3905                                 }
3906                                 if (size != bpf_size_to_bytes(BPF_DW)) {
3907                                         verbose(env, "kptr access size must be BPF_DW\n");
3908                                         return -EACCES;
3909                                 }
3910                                 break;
3911                         }
3912                 }
3913         }
3914         return err;
3915 }
3916
3917 #define MAX_PACKET_OFF 0xffff
3918
3919 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3920                                        const struct bpf_call_arg_meta *meta,
3921                                        enum bpf_access_type t)
3922 {
3923         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3924
3925         switch (prog_type) {
3926         /* Program types only with direct read access go here! */
3927         case BPF_PROG_TYPE_LWT_IN:
3928         case BPF_PROG_TYPE_LWT_OUT:
3929         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3930         case BPF_PROG_TYPE_SK_REUSEPORT:
3931         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3932         case BPF_PROG_TYPE_CGROUP_SKB:
3933                 if (t == BPF_WRITE)
3934                         return false;
3935                 fallthrough;
3936
3937         /* Program types with direct read + write access go here! */
3938         case BPF_PROG_TYPE_SCHED_CLS:
3939         case BPF_PROG_TYPE_SCHED_ACT:
3940         case BPF_PROG_TYPE_XDP:
3941         case BPF_PROG_TYPE_LWT_XMIT:
3942         case BPF_PROG_TYPE_SK_SKB:
3943         case BPF_PROG_TYPE_SK_MSG:
3944                 if (meta)
3945                         return meta->pkt_access;
3946
3947                 env->seen_direct_write = true;
3948                 return true;
3949
3950         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3951                 if (t == BPF_WRITE)
3952                         env->seen_direct_write = true;
3953
3954                 return true;
3955
3956         default:
3957                 return false;
3958         }
3959 }
3960
3961 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3962                                int size, bool zero_size_allowed)
3963 {
3964         struct bpf_reg_state *regs = cur_regs(env);
3965         struct bpf_reg_state *reg = &regs[regno];
3966         int err;
3967
3968         /* We may have added a variable offset to the packet pointer; but any
3969          * reg->range we have comes after that.  We are only checking the fixed
3970          * offset.
3971          */
3972
3973         /* We don't allow negative numbers, because we aren't tracking enough
3974          * detail to prove they're safe.
3975          */
3976         if (reg->smin_value < 0) {
3977                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3978                         regno);
3979                 return -EACCES;
3980         }
3981
3982         err = reg->range < 0 ? -EINVAL :
3983               __check_mem_access(env, regno, off, size, reg->range,
3984                                  zero_size_allowed);
3985         if (err) {
3986                 verbose(env, "R%d offset is outside of the packet\n", regno);
3987                 return err;
3988         }
3989
3990         /* __check_mem_access has made sure "off + size - 1" is within u16.
3991          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3992          * otherwise find_good_pkt_pointers would have refused to set range info
3993          * that __check_mem_access would have rejected this pkt access.
3994          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3995          */
3996         env->prog->aux->max_pkt_offset =
3997                 max_t(u32, env->prog->aux->max_pkt_offset,
3998                       off + reg->umax_value + size - 1);
3999
4000         return err;
4001 }
4002
4003 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4004 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4005                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
4006                             struct btf **btf, u32 *btf_id)
4007 {
4008         struct bpf_insn_access_aux info = {
4009                 .reg_type = *reg_type,
4010                 .log = &env->log,
4011         };
4012
4013         if (env->ops->is_valid_access &&
4014             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4015                 /* A non zero info.ctx_field_size indicates that this field is a
4016                  * candidate for later verifier transformation to load the whole
4017                  * field and then apply a mask when accessed with a narrower
4018                  * access than actual ctx access size. A zero info.ctx_field_size
4019                  * will only allow for whole field access and rejects any other
4020                  * type of narrower access.
4021                  */
4022                 *reg_type = info.reg_type;
4023
4024                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4025                         *btf = info.btf;
4026                         *btf_id = info.btf_id;
4027                 } else {
4028                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4029                 }
4030                 /* remember the offset of last byte accessed in ctx */
4031                 if (env->prog->aux->max_ctx_offset < off + size)
4032                         env->prog->aux->max_ctx_offset = off + size;
4033                 return 0;
4034         }
4035
4036         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4037         return -EACCES;
4038 }
4039
4040 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4041                                   int size)
4042 {
4043         if (size < 0 || off < 0 ||
4044             (u64)off + size > sizeof(struct bpf_flow_keys)) {
4045                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4046                         off, size);
4047                 return -EACCES;
4048         }
4049         return 0;
4050 }
4051
4052 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4053                              u32 regno, int off, int size,
4054                              enum bpf_access_type t)
4055 {
4056         struct bpf_reg_state *regs = cur_regs(env);
4057         struct bpf_reg_state *reg = &regs[regno];
4058         struct bpf_insn_access_aux info = {};
4059         bool valid;
4060
4061         if (reg->smin_value < 0) {
4062                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4063                         regno);
4064                 return -EACCES;
4065         }
4066
4067         switch (reg->type) {
4068         case PTR_TO_SOCK_COMMON:
4069                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4070                 break;
4071         case PTR_TO_SOCKET:
4072                 valid = bpf_sock_is_valid_access(off, size, t, &info);
4073                 break;
4074         case PTR_TO_TCP_SOCK:
4075                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4076                 break;
4077         case PTR_TO_XDP_SOCK:
4078                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4079                 break;
4080         default:
4081                 valid = false;
4082         }
4083
4084
4085         if (valid) {
4086                 env->insn_aux_data[insn_idx].ctx_field_size =
4087                         info.ctx_field_size;
4088                 return 0;
4089         }
4090
4091         verbose(env, "R%d invalid %s access off=%d size=%d\n",
4092                 regno, reg_type_str(env, reg->type), off, size);
4093
4094         return -EACCES;
4095 }
4096
4097 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4098 {
4099         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4100 }
4101
4102 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4103 {
4104         const struct bpf_reg_state *reg = reg_state(env, regno);
4105
4106         return reg->type == PTR_TO_CTX;
4107 }
4108
4109 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4110 {
4111         const struct bpf_reg_state *reg = reg_state(env, regno);
4112
4113         return type_is_sk_pointer(reg->type);
4114 }
4115
4116 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4117 {
4118         const struct bpf_reg_state *reg = reg_state(env, regno);
4119
4120         return type_is_pkt_pointer(reg->type);
4121 }
4122
4123 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4124 {
4125         const struct bpf_reg_state *reg = reg_state(env, regno);
4126
4127         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4128         return reg->type == PTR_TO_FLOW_KEYS;
4129 }
4130
4131 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4132                                    const struct bpf_reg_state *reg,
4133                                    int off, int size, bool strict)
4134 {
4135         struct tnum reg_off;
4136         int ip_align;
4137
4138         /* Byte size accesses are always allowed. */
4139         if (!strict || size == 1)
4140                 return 0;
4141
4142         /* For platforms that do not have a Kconfig enabling
4143          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4144          * NET_IP_ALIGN is universally set to '2'.  And on platforms
4145          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4146          * to this code only in strict mode where we want to emulate
4147          * the NET_IP_ALIGN==2 checking.  Therefore use an
4148          * unconditional IP align value of '2'.
4149          */
4150         ip_align = 2;
4151
4152         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4153         if (!tnum_is_aligned(reg_off, size)) {
4154                 char tn_buf[48];
4155
4156                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4157                 verbose(env,
4158                         "misaligned packet access off %d+%s+%d+%d size %d\n",
4159                         ip_align, tn_buf, reg->off, off, size);
4160                 return -EACCES;
4161         }
4162
4163         return 0;
4164 }
4165
4166 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4167                                        const struct bpf_reg_state *reg,
4168                                        const char *pointer_desc,
4169                                        int off, int size, bool strict)
4170 {
4171         struct tnum reg_off;
4172
4173         /* Byte size accesses are always allowed. */
4174         if (!strict || size == 1)
4175                 return 0;
4176
4177         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4178         if (!tnum_is_aligned(reg_off, size)) {
4179                 char tn_buf[48];
4180
4181                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4182                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4183                         pointer_desc, tn_buf, reg->off, off, size);
4184                 return -EACCES;
4185         }
4186
4187         return 0;
4188 }
4189
4190 static int check_ptr_alignment(struct bpf_verifier_env *env,
4191                                const struct bpf_reg_state *reg, int off,
4192                                int size, bool strict_alignment_once)
4193 {
4194         bool strict = env->strict_alignment || strict_alignment_once;
4195         const char *pointer_desc = "";
4196
4197         switch (reg->type) {
4198         case PTR_TO_PACKET:
4199         case PTR_TO_PACKET_META:
4200                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4201                  * right in front, treat it the very same way.
4202                  */
4203                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4204         case PTR_TO_FLOW_KEYS:
4205                 pointer_desc = "flow keys ";
4206                 break;
4207         case PTR_TO_MAP_KEY:
4208                 pointer_desc = "key ";
4209                 break;
4210         case PTR_TO_MAP_VALUE:
4211                 pointer_desc = "value ";
4212                 break;
4213         case PTR_TO_CTX:
4214                 pointer_desc = "context ";
4215                 break;
4216         case PTR_TO_STACK:
4217                 pointer_desc = "stack ";
4218                 /* The stack spill tracking logic in check_stack_write_fixed_off()
4219                  * and check_stack_read_fixed_off() relies on stack accesses being
4220                  * aligned.
4221                  */
4222                 strict = true;
4223                 break;
4224         case PTR_TO_SOCKET:
4225                 pointer_desc = "sock ";
4226                 break;
4227         case PTR_TO_SOCK_COMMON:
4228                 pointer_desc = "sock_common ";
4229                 break;
4230         case PTR_TO_TCP_SOCK:
4231                 pointer_desc = "tcp_sock ";
4232                 break;
4233         case PTR_TO_XDP_SOCK:
4234                 pointer_desc = "xdp_sock ";
4235                 break;
4236         default:
4237                 break;
4238         }
4239         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4240                                            strict);
4241 }
4242
4243 static int update_stack_depth(struct bpf_verifier_env *env,
4244                               const struct bpf_func_state *func,
4245                               int off)
4246 {
4247         u16 stack = env->subprog_info[func->subprogno].stack_depth;
4248
4249         if (stack >= -off)
4250                 return 0;
4251
4252         /* update known max for given subprogram */
4253         env->subprog_info[func->subprogno].stack_depth = -off;
4254         return 0;
4255 }
4256
4257 /* starting from main bpf function walk all instructions of the function
4258  * and recursively walk all callees that given function can call.
4259  * Ignore jump and exit insns.
4260  * Since recursion is prevented by check_cfg() this algorithm
4261  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4262  */
4263 static int check_max_stack_depth(struct bpf_verifier_env *env)
4264 {
4265         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4266         struct bpf_subprog_info *subprog = env->subprog_info;
4267         struct bpf_insn *insn = env->prog->insnsi;
4268         bool tail_call_reachable = false;
4269         int ret_insn[MAX_CALL_FRAMES];
4270         int ret_prog[MAX_CALL_FRAMES];
4271         int j;
4272
4273 process_func:
4274         /* protect against potential stack overflow that might happen when
4275          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4276          * depth for such case down to 256 so that the worst case scenario
4277          * would result in 8k stack size (32 which is tailcall limit * 256 =
4278          * 8k).
4279          *
4280          * To get the idea what might happen, see an example:
4281          * func1 -> sub rsp, 128
4282          *  subfunc1 -> sub rsp, 256
4283          *  tailcall1 -> add rsp, 256
4284          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4285          *   subfunc2 -> sub rsp, 64
4286          *   subfunc22 -> sub rsp, 128
4287          *   tailcall2 -> add rsp, 128
4288          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4289          *
4290          * tailcall will unwind the current stack frame but it will not get rid
4291          * of caller's stack as shown on the example above.
4292          */
4293         if (idx && subprog[idx].has_tail_call && depth >= 256) {
4294                 verbose(env,
4295                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4296                         depth);
4297                 return -EACCES;
4298         }
4299         /* round up to 32-bytes, since this is granularity
4300          * of interpreter stack size
4301          */
4302         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4303         if (depth > MAX_BPF_STACK) {
4304                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4305                         frame + 1, depth);
4306                 return -EACCES;
4307         }
4308 continue_func:
4309         subprog_end = subprog[idx + 1].start;
4310         for (; i < subprog_end; i++) {
4311                 int next_insn;
4312
4313                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4314                         continue;
4315                 /* remember insn and function to return to */
4316                 ret_insn[frame] = i + 1;
4317                 ret_prog[frame] = idx;
4318
4319                 /* find the callee */
4320                 next_insn = i + insn[i].imm + 1;
4321                 idx = find_subprog(env, next_insn);
4322                 if (idx < 0) {
4323                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4324                                   next_insn);
4325                         return -EFAULT;
4326                 }
4327                 if (subprog[idx].is_async_cb) {
4328                         if (subprog[idx].has_tail_call) {
4329                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4330                                 return -EFAULT;
4331                         }
4332                          /* async callbacks don't increase bpf prog stack size */
4333                         continue;
4334                 }
4335                 i = next_insn;
4336
4337                 if (subprog[idx].has_tail_call)
4338                         tail_call_reachable = true;
4339
4340                 frame++;
4341                 if (frame >= MAX_CALL_FRAMES) {
4342                         verbose(env, "the call stack of %d frames is too deep !\n",
4343                                 frame);
4344                         return -E2BIG;
4345                 }
4346                 goto process_func;
4347         }
4348         /* if tail call got detected across bpf2bpf calls then mark each of the
4349          * currently present subprog frames as tail call reachable subprogs;
4350          * this info will be utilized by JIT so that we will be preserving the
4351          * tail call counter throughout bpf2bpf calls combined with tailcalls
4352          */
4353         if (tail_call_reachable)
4354                 for (j = 0; j < frame; j++)
4355                         subprog[ret_prog[j]].tail_call_reachable = true;
4356         if (subprog[0].tail_call_reachable)
4357                 env->prog->aux->tail_call_reachable = true;
4358
4359         /* end of for() loop means the last insn of the 'subprog'
4360          * was reached. Doesn't matter whether it was JA or EXIT
4361          */
4362         if (frame == 0)
4363                 return 0;
4364         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4365         frame--;
4366         i = ret_insn[frame];
4367         idx = ret_prog[frame];
4368         goto continue_func;
4369 }
4370
4371 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4372 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4373                                   const struct bpf_insn *insn, int idx)
4374 {
4375         int start = idx + insn->imm + 1, subprog;
4376
4377         subprog = find_subprog(env, start);
4378         if (subprog < 0) {
4379                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4380                           start);
4381                 return -EFAULT;
4382         }
4383         return env->subprog_info[subprog].stack_depth;
4384 }
4385 #endif
4386
4387 static int __check_buffer_access(struct bpf_verifier_env *env,
4388                                  const char *buf_info,
4389                                  const struct bpf_reg_state *reg,
4390                                  int regno, int off, int size)
4391 {
4392         if (off < 0) {
4393                 verbose(env,
4394                         "R%d invalid %s buffer access: off=%d, size=%d\n",
4395                         regno, buf_info, off, size);
4396                 return -EACCES;
4397         }
4398         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4399                 char tn_buf[48];
4400
4401                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4402                 verbose(env,
4403                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4404                         regno, off, tn_buf);
4405                 return -EACCES;
4406         }
4407
4408         return 0;
4409 }
4410
4411 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4412                                   const struct bpf_reg_state *reg,
4413                                   int regno, int off, int size)
4414 {
4415         int err;
4416
4417         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4418         if (err)
4419                 return err;
4420
4421         if (off + size > env->prog->aux->max_tp_access)
4422                 env->prog->aux->max_tp_access = off + size;
4423
4424         return 0;
4425 }
4426
4427 static int check_buffer_access(struct bpf_verifier_env *env,
4428                                const struct bpf_reg_state *reg,
4429                                int regno, int off, int size,
4430                                bool zero_size_allowed,
4431                                u32 *max_access)
4432 {
4433         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4434         int err;
4435
4436         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4437         if (err)
4438                 return err;
4439
4440         if (off + size > *max_access)
4441                 *max_access = off + size;
4442
4443         return 0;
4444 }
4445
4446 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4447 static void zext_32_to_64(struct bpf_reg_state *reg)
4448 {
4449         reg->var_off = tnum_subreg(reg->var_off);
4450         __reg_assign_32_into_64(reg);
4451 }
4452
4453 /* truncate register to smaller size (in bytes)
4454  * must be called with size < BPF_REG_SIZE
4455  */
4456 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4457 {
4458         u64 mask;
4459
4460         /* clear high bits in bit representation */
4461         reg->var_off = tnum_cast(reg->var_off, size);
4462
4463         /* fix arithmetic bounds */
4464         mask = ((u64)1 << (size * 8)) - 1;
4465         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4466                 reg->umin_value &= mask;
4467                 reg->umax_value &= mask;
4468         } else {
4469                 reg->umin_value = 0;
4470                 reg->umax_value = mask;
4471         }
4472         reg->smin_value = reg->umin_value;
4473         reg->smax_value = reg->umax_value;
4474
4475         /* If size is smaller than 32bit register the 32bit register
4476          * values are also truncated so we push 64-bit bounds into
4477          * 32-bit bounds. Above were truncated < 32-bits already.
4478          */
4479         if (size >= 4)
4480                 return;
4481         __reg_combine_64_into_32(reg);
4482 }
4483
4484 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4485 {
4486         /* A map is considered read-only if the following condition are true:
4487          *
4488          * 1) BPF program side cannot change any of the map content. The
4489          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4490          *    and was set at map creation time.
4491          * 2) The map value(s) have been initialized from user space by a
4492          *    loader and then "frozen", such that no new map update/delete
4493          *    operations from syscall side are possible for the rest of
4494          *    the map's lifetime from that point onwards.
4495          * 3) Any parallel/pending map update/delete operations from syscall
4496          *    side have been completed. Only after that point, it's safe to
4497          *    assume that map value(s) are immutable.
4498          */
4499         return (map->map_flags & BPF_F_RDONLY_PROG) &&
4500                READ_ONCE(map->frozen) &&
4501                !bpf_map_write_active(map);
4502 }
4503
4504 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4505 {
4506         void *ptr;
4507         u64 addr;
4508         int err;
4509
4510         err = map->ops->map_direct_value_addr(map, &addr, off);
4511         if (err)
4512                 return err;
4513         ptr = (void *)(long)addr + off;
4514
4515         switch (size) {
4516         case sizeof(u8):
4517                 *val = (u64)*(u8 *)ptr;
4518                 break;
4519         case sizeof(u16):
4520                 *val = (u64)*(u16 *)ptr;
4521                 break;
4522         case sizeof(u32):
4523                 *val = (u64)*(u32 *)ptr;
4524                 break;
4525         case sizeof(u64):
4526                 *val = *(u64 *)ptr;
4527                 break;
4528         default:
4529                 return -EINVAL;
4530         }
4531         return 0;
4532 }
4533
4534 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4535                                    struct bpf_reg_state *regs,
4536                                    int regno, int off, int size,
4537                                    enum bpf_access_type atype,
4538                                    int value_regno)
4539 {
4540         struct bpf_reg_state *reg = regs + regno;
4541         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4542         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4543         enum bpf_type_flag flag = 0;
4544         u32 btf_id;
4545         int ret;
4546
4547         if (off < 0) {
4548                 verbose(env,
4549                         "R%d is ptr_%s invalid negative access: off=%d\n",
4550                         regno, tname, off);
4551                 return -EACCES;
4552         }
4553         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4554                 char tn_buf[48];
4555
4556                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4557                 verbose(env,
4558                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4559                         regno, tname, off, tn_buf);
4560                 return -EACCES;
4561         }
4562
4563         if (reg->type & MEM_USER) {
4564                 verbose(env,
4565                         "R%d is ptr_%s access user memory: off=%d\n",
4566                         regno, tname, off);
4567                 return -EACCES;
4568         }
4569
4570         if (reg->type & MEM_PERCPU) {
4571                 verbose(env,
4572                         "R%d is ptr_%s access percpu memory: off=%d\n",
4573                         regno, tname, off);
4574                 return -EACCES;
4575         }
4576
4577         if (env->ops->btf_struct_access) {
4578                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4579                                                   off, size, atype, &btf_id, &flag);
4580         } else {
4581                 if (atype != BPF_READ) {
4582                         verbose(env, "only read is supported\n");
4583                         return -EACCES;
4584                 }
4585
4586                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4587                                         atype, &btf_id, &flag);
4588         }
4589
4590         if (ret < 0)
4591                 return ret;
4592
4593         /* If this is an untrusted pointer, all pointers formed by walking it
4594          * also inherit the untrusted flag.
4595          */
4596         if (type_flag(reg->type) & PTR_UNTRUSTED)
4597                 flag |= PTR_UNTRUSTED;
4598
4599         if (atype == BPF_READ && value_regno >= 0)
4600                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4601
4602         return 0;
4603 }
4604
4605 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4606                                    struct bpf_reg_state *regs,
4607                                    int regno, int off, int size,
4608                                    enum bpf_access_type atype,
4609                                    int value_regno)
4610 {
4611         struct bpf_reg_state *reg = regs + regno;
4612         struct bpf_map *map = reg->map_ptr;
4613         enum bpf_type_flag flag = 0;
4614         const struct btf_type *t;
4615         const char *tname;
4616         u32 btf_id;
4617         int ret;
4618
4619         if (!btf_vmlinux) {
4620                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4621                 return -ENOTSUPP;
4622         }
4623
4624         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4625                 verbose(env, "map_ptr access not supported for map type %d\n",
4626                         map->map_type);
4627                 return -ENOTSUPP;
4628         }
4629
4630         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4631         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4632
4633         if (!env->allow_ptr_to_map_access) {
4634                 verbose(env,
4635                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4636                         tname);
4637                 return -EPERM;
4638         }
4639
4640         if (off < 0) {
4641                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4642                         regno, tname, off);
4643                 return -EACCES;
4644         }
4645
4646         if (atype != BPF_READ) {
4647                 verbose(env, "only read from %s is supported\n", tname);
4648                 return -EACCES;
4649         }
4650
4651         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4652         if (ret < 0)
4653                 return ret;
4654
4655         if (value_regno >= 0)
4656                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4657
4658         return 0;
4659 }
4660
4661 /* Check that the stack access at the given offset is within bounds. The
4662  * maximum valid offset is -1.
4663  *
4664  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4665  * -state->allocated_stack for reads.
4666  */
4667 static int check_stack_slot_within_bounds(int off,
4668                                           struct bpf_func_state *state,
4669                                           enum bpf_access_type t)
4670 {
4671         int min_valid_off;
4672
4673         if (t == BPF_WRITE)
4674                 min_valid_off = -MAX_BPF_STACK;
4675         else
4676                 min_valid_off = -state->allocated_stack;
4677
4678         if (off < min_valid_off || off > -1)
4679                 return -EACCES;
4680         return 0;
4681 }
4682
4683 /* Check that the stack access at 'regno + off' falls within the maximum stack
4684  * bounds.
4685  *
4686  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4687  */
4688 static int check_stack_access_within_bounds(
4689                 struct bpf_verifier_env *env,
4690                 int regno, int off, int access_size,
4691                 enum bpf_access_src src, enum bpf_access_type type)
4692 {
4693         struct bpf_reg_state *regs = cur_regs(env);
4694         struct bpf_reg_state *reg = regs + regno;
4695         struct bpf_func_state *state = func(env, reg);
4696         int min_off, max_off;
4697         int err;
4698         char *err_extra;
4699
4700         if (src == ACCESS_HELPER)
4701                 /* We don't know if helpers are reading or writing (or both). */
4702                 err_extra = " indirect access to";
4703         else if (type == BPF_READ)
4704                 err_extra = " read from";
4705         else
4706                 err_extra = " write to";
4707
4708         if (tnum_is_const(reg->var_off)) {
4709                 min_off = reg->var_off.value + off;
4710                 if (access_size > 0)
4711                         max_off = min_off + access_size - 1;
4712                 else
4713                         max_off = min_off;
4714         } else {
4715                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4716                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4717                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4718                                 err_extra, regno);
4719                         return -EACCES;
4720                 }
4721                 min_off = reg->smin_value + off;
4722                 if (access_size > 0)
4723                         max_off = reg->smax_value + off + access_size - 1;
4724                 else
4725                         max_off = min_off;
4726         }
4727
4728         err = check_stack_slot_within_bounds(min_off, state, type);
4729         if (!err)
4730                 err = check_stack_slot_within_bounds(max_off, state, type);
4731
4732         if (err) {
4733                 if (tnum_is_const(reg->var_off)) {
4734                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4735                                 err_extra, regno, off, access_size);
4736                 } else {
4737                         char tn_buf[48];
4738
4739                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4740                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4741                                 err_extra, regno, tn_buf, access_size);
4742                 }
4743         }
4744         return err;
4745 }
4746
4747 /* check whether memory at (regno + off) is accessible for t = (read | write)
4748  * if t==write, value_regno is a register which value is stored into memory
4749  * if t==read, value_regno is a register which will receive the value from memory
4750  * if t==write && value_regno==-1, some unknown value is stored into memory
4751  * if t==read && value_regno==-1, don't care what we read from memory
4752  */
4753 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4754                             int off, int bpf_size, enum bpf_access_type t,
4755                             int value_regno, bool strict_alignment_once)
4756 {
4757         struct bpf_reg_state *regs = cur_regs(env);
4758         struct bpf_reg_state *reg = regs + regno;
4759         struct bpf_func_state *state;
4760         int size, err = 0;
4761
4762         size = bpf_size_to_bytes(bpf_size);
4763         if (size < 0)
4764                 return size;
4765
4766         /* alignment checks will add in reg->off themselves */
4767         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4768         if (err)
4769                 return err;
4770
4771         /* for access checks, reg->off is just part of off */
4772         off += reg->off;
4773
4774         if (reg->type == PTR_TO_MAP_KEY) {
4775                 if (t == BPF_WRITE) {
4776                         verbose(env, "write to change key R%d not allowed\n", regno);
4777                         return -EACCES;
4778                 }
4779
4780                 err = check_mem_region_access(env, regno, off, size,
4781                                               reg->map_ptr->key_size, false);
4782                 if (err)
4783                         return err;
4784                 if (value_regno >= 0)
4785                         mark_reg_unknown(env, regs, value_regno);
4786         } else if (reg->type == PTR_TO_MAP_VALUE) {
4787                 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4788
4789                 if (t == BPF_WRITE && value_regno >= 0 &&
4790                     is_pointer_value(env, value_regno)) {
4791                         verbose(env, "R%d leaks addr into map\n", value_regno);
4792                         return -EACCES;
4793                 }
4794                 err = check_map_access_type(env, regno, off, size, t);
4795                 if (err)
4796                         return err;
4797                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4798                 if (err)
4799                         return err;
4800                 if (tnum_is_const(reg->var_off))
4801                         kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4802                                                                   off + reg->var_off.value);
4803                 if (kptr_off_desc) {
4804                         err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4805                                                     kptr_off_desc);
4806                 } else if (t == BPF_READ && value_regno >= 0) {
4807                         struct bpf_map *map = reg->map_ptr;
4808
4809                         /* if map is read-only, track its contents as scalars */
4810                         if (tnum_is_const(reg->var_off) &&
4811                             bpf_map_is_rdonly(map) &&
4812                             map->ops->map_direct_value_addr) {
4813                                 int map_off = off + reg->var_off.value;
4814                                 u64 val = 0;
4815
4816                                 err = bpf_map_direct_read(map, map_off, size,
4817                                                           &val);
4818                                 if (err)
4819                                         return err;
4820
4821                                 regs[value_regno].type = SCALAR_VALUE;
4822                                 __mark_reg_known(&regs[value_regno], val);
4823                         } else {
4824                                 mark_reg_unknown(env, regs, value_regno);
4825                         }
4826                 }
4827         } else if (base_type(reg->type) == PTR_TO_MEM) {
4828                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4829
4830                 if (type_may_be_null(reg->type)) {
4831                         verbose(env, "R%d invalid mem access '%s'\n", regno,
4832                                 reg_type_str(env, reg->type));
4833                         return -EACCES;
4834                 }
4835
4836                 if (t == BPF_WRITE && rdonly_mem) {
4837                         verbose(env, "R%d cannot write into %s\n",
4838                                 regno, reg_type_str(env, reg->type));
4839                         return -EACCES;
4840                 }
4841
4842                 if (t == BPF_WRITE && value_regno >= 0 &&
4843                     is_pointer_value(env, value_regno)) {
4844                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4845                         return -EACCES;
4846                 }
4847
4848                 err = check_mem_region_access(env, regno, off, size,
4849                                               reg->mem_size, false);
4850                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4851                         mark_reg_unknown(env, regs, value_regno);
4852         } else if (reg->type == PTR_TO_CTX) {
4853                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4854                 struct btf *btf = NULL;
4855                 u32 btf_id = 0;
4856
4857                 if (t == BPF_WRITE && value_regno >= 0 &&
4858                     is_pointer_value(env, value_regno)) {
4859                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4860                         return -EACCES;
4861                 }
4862
4863                 err = check_ptr_off_reg(env, reg, regno);
4864                 if (err < 0)
4865                         return err;
4866
4867                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4868                                        &btf_id);
4869                 if (err)
4870                         verbose_linfo(env, insn_idx, "; ");
4871                 if (!err && t == BPF_READ && value_regno >= 0) {
4872                         /* ctx access returns either a scalar, or a
4873                          * PTR_TO_PACKET[_META,_END]. In the latter
4874                          * case, we know the offset is zero.
4875                          */
4876                         if (reg_type == SCALAR_VALUE) {
4877                                 mark_reg_unknown(env, regs, value_regno);
4878                         } else {
4879                                 mark_reg_known_zero(env, regs,
4880                                                     value_regno);
4881                                 if (type_may_be_null(reg_type))
4882                                         regs[value_regno].id = ++env->id_gen;
4883                                 /* A load of ctx field could have different
4884                                  * actual load size with the one encoded in the
4885                                  * insn. When the dst is PTR, it is for sure not
4886                                  * a sub-register.
4887                                  */
4888                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4889                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4890                                         regs[value_regno].btf = btf;
4891                                         regs[value_regno].btf_id = btf_id;
4892                                 }
4893                         }
4894                         regs[value_regno].type = reg_type;
4895                 }
4896
4897         } else if (reg->type == PTR_TO_STACK) {
4898                 /* Basic bounds checks. */
4899                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4900                 if (err)
4901                         return err;
4902
4903                 state = func(env, reg);
4904                 err = update_stack_depth(env, state, off);
4905                 if (err)
4906                         return err;
4907
4908                 if (t == BPF_READ)
4909                         err = check_stack_read(env, regno, off, size,
4910                                                value_regno);
4911                 else
4912                         err = check_stack_write(env, regno, off, size,
4913                                                 value_regno, insn_idx);
4914         } else if (reg_is_pkt_pointer(reg)) {
4915                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4916                         verbose(env, "cannot write into packet\n");
4917                         return -EACCES;
4918                 }
4919                 if (t == BPF_WRITE && value_regno >= 0 &&
4920                     is_pointer_value(env, value_regno)) {
4921                         verbose(env, "R%d leaks addr into packet\n",
4922                                 value_regno);
4923                         return -EACCES;
4924                 }
4925                 err = check_packet_access(env, regno, off, size, false);
4926                 if (!err && t == BPF_READ && value_regno >= 0)
4927                         mark_reg_unknown(env, regs, value_regno);
4928         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4929                 if (t == BPF_WRITE && value_regno >= 0 &&
4930                     is_pointer_value(env, value_regno)) {
4931                         verbose(env, "R%d leaks addr into flow keys\n",
4932                                 value_regno);
4933                         return -EACCES;
4934                 }
4935
4936                 err = check_flow_keys_access(env, off, size);
4937                 if (!err && t == BPF_READ && value_regno >= 0)
4938                         mark_reg_unknown(env, regs, value_regno);
4939         } else if (type_is_sk_pointer(reg->type)) {
4940                 if (t == BPF_WRITE) {
4941                         verbose(env, "R%d cannot write into %s\n",
4942                                 regno, reg_type_str(env, reg->type));
4943                         return -EACCES;
4944                 }
4945                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4946                 if (!err && value_regno >= 0)
4947                         mark_reg_unknown(env, regs, value_regno);
4948         } else if (reg->type == PTR_TO_TP_BUFFER) {
4949                 err = check_tp_buffer_access(env, reg, regno, off, size);
4950                 if (!err && t == BPF_READ && value_regno >= 0)
4951                         mark_reg_unknown(env, regs, value_regno);
4952         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4953                    !type_may_be_null(reg->type)) {
4954                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4955                                               value_regno);
4956         } else if (reg->type == CONST_PTR_TO_MAP) {
4957                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4958                                               value_regno);
4959         } else if (base_type(reg->type) == PTR_TO_BUF) {
4960                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4961                 u32 *max_access;
4962
4963                 if (rdonly_mem) {
4964                         if (t == BPF_WRITE) {
4965                                 verbose(env, "R%d cannot write into %s\n",
4966                                         regno, reg_type_str(env, reg->type));
4967                                 return -EACCES;
4968                         }
4969                         max_access = &env->prog->aux->max_rdonly_access;
4970                 } else {
4971                         max_access = &env->prog->aux->max_rdwr_access;
4972                 }
4973
4974                 err = check_buffer_access(env, reg, regno, off, size, false,
4975                                           max_access);
4976
4977                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4978                         mark_reg_unknown(env, regs, value_regno);
4979         } else {
4980                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4981                         reg_type_str(env, reg->type));
4982                 return -EACCES;
4983         }
4984
4985         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4986             regs[value_regno].type == SCALAR_VALUE) {
4987                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4988                 coerce_reg_to_size(&regs[value_regno], size);
4989         }
4990         return err;
4991 }
4992
4993 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4994 {
4995         int load_reg;
4996         int err;
4997
4998         switch (insn->imm) {
4999         case BPF_ADD:
5000         case BPF_ADD | BPF_FETCH:
5001         case BPF_AND:
5002         case BPF_AND | BPF_FETCH:
5003         case BPF_OR:
5004         case BPF_OR | BPF_FETCH:
5005         case BPF_XOR:
5006         case BPF_XOR | BPF_FETCH:
5007         case BPF_XCHG:
5008         case BPF_CMPXCHG:
5009                 break;
5010         default:
5011                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5012                 return -EINVAL;
5013         }
5014
5015         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5016                 verbose(env, "invalid atomic operand size\n");
5017                 return -EINVAL;
5018         }
5019
5020         /* check src1 operand */
5021         err = check_reg_arg(env, insn->src_reg, SRC_OP);
5022         if (err)
5023                 return err;
5024
5025         /* check src2 operand */
5026         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5027         if (err)
5028                 return err;
5029
5030         if (insn->imm == BPF_CMPXCHG) {
5031                 /* Check comparison of R0 with memory location */
5032                 const u32 aux_reg = BPF_REG_0;
5033
5034                 err = check_reg_arg(env, aux_reg, SRC_OP);
5035                 if (err)
5036                         return err;
5037
5038                 if (is_pointer_value(env, aux_reg)) {
5039                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
5040                         return -EACCES;
5041                 }
5042         }
5043
5044         if (is_pointer_value(env, insn->src_reg)) {
5045                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5046                 return -EACCES;
5047         }
5048
5049         if (is_ctx_reg(env, insn->dst_reg) ||
5050             is_pkt_reg(env, insn->dst_reg) ||
5051             is_flow_key_reg(env, insn->dst_reg) ||
5052             is_sk_reg(env, insn->dst_reg)) {
5053                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5054                         insn->dst_reg,
5055                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5056                 return -EACCES;
5057         }
5058
5059         if (insn->imm & BPF_FETCH) {
5060                 if (insn->imm == BPF_CMPXCHG)
5061                         load_reg = BPF_REG_0;
5062                 else
5063                         load_reg = insn->src_reg;
5064
5065                 /* check and record load of old value */
5066                 err = check_reg_arg(env, load_reg, DST_OP);
5067                 if (err)
5068                         return err;
5069         } else {
5070                 /* This instruction accesses a memory location but doesn't
5071                  * actually load it into a register.
5072                  */
5073                 load_reg = -1;
5074         }
5075
5076         /* Check whether we can read the memory, with second call for fetch
5077          * case to simulate the register fill.
5078          */
5079         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5080                                BPF_SIZE(insn->code), BPF_READ, -1, true);
5081         if (!err && load_reg >= 0)
5082                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5083                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
5084                                        true);
5085         if (err)
5086                 return err;
5087
5088         /* Check whether we can write into the same memory. */
5089         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5090                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5091         if (err)
5092                 return err;
5093
5094         return 0;
5095 }
5096
5097 /* When register 'regno' is used to read the stack (either directly or through
5098  * a helper function) make sure that it's within stack boundary and, depending
5099  * on the access type, that all elements of the stack are initialized.
5100  *
5101  * 'off' includes 'regno->off', but not its dynamic part (if any).
5102  *
5103  * All registers that have been spilled on the stack in the slots within the
5104  * read offsets are marked as read.
5105  */
5106 static int check_stack_range_initialized(
5107                 struct bpf_verifier_env *env, int regno, int off,
5108                 int access_size, bool zero_size_allowed,
5109                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5110 {
5111         struct bpf_reg_state *reg = reg_state(env, regno);
5112         struct bpf_func_state *state = func(env, reg);
5113         int err, min_off, max_off, i, j, slot, spi;
5114         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5115         enum bpf_access_type bounds_check_type;
5116         /* Some accesses can write anything into the stack, others are
5117          * read-only.
5118          */
5119         bool clobber = false;
5120
5121         if (access_size == 0 && !zero_size_allowed) {
5122                 verbose(env, "invalid zero-sized read\n");
5123                 return -EACCES;
5124         }
5125
5126         if (type == ACCESS_HELPER) {
5127                 /* The bounds checks for writes are more permissive than for
5128                  * reads. However, if raw_mode is not set, we'll do extra
5129                  * checks below.
5130                  */
5131                 bounds_check_type = BPF_WRITE;
5132                 clobber = true;
5133         } else {
5134                 bounds_check_type = BPF_READ;
5135         }
5136         err = check_stack_access_within_bounds(env, regno, off, access_size,
5137                                                type, bounds_check_type);
5138         if (err)
5139                 return err;
5140
5141
5142         if (tnum_is_const(reg->var_off)) {
5143                 min_off = max_off = reg->var_off.value + off;
5144         } else {
5145                 /* Variable offset is prohibited for unprivileged mode for
5146                  * simplicity since it requires corresponding support in
5147                  * Spectre masking for stack ALU.
5148                  * See also retrieve_ptr_limit().
5149                  */
5150                 if (!env->bypass_spec_v1) {
5151                         char tn_buf[48];
5152
5153                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5154                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5155                                 regno, err_extra, tn_buf);
5156                         return -EACCES;
5157                 }
5158                 /* Only initialized buffer on stack is allowed to be accessed
5159                  * with variable offset. With uninitialized buffer it's hard to
5160                  * guarantee that whole memory is marked as initialized on
5161                  * helper return since specific bounds are unknown what may
5162                  * cause uninitialized stack leaking.
5163                  */
5164                 if (meta && meta->raw_mode)
5165                         meta = NULL;
5166
5167                 min_off = reg->smin_value + off;
5168                 max_off = reg->smax_value + off;
5169         }
5170
5171         if (meta && meta->raw_mode) {
5172                 meta->access_size = access_size;
5173                 meta->regno = regno;
5174                 return 0;
5175         }
5176
5177         for (i = min_off; i < max_off + access_size; i++) {
5178                 u8 *stype;
5179
5180                 slot = -i - 1;
5181                 spi = slot / BPF_REG_SIZE;
5182                 if (state->allocated_stack <= slot)
5183                         goto err;
5184                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5185                 if (*stype == STACK_MISC)
5186                         goto mark;
5187                 if (*stype == STACK_ZERO) {
5188                         if (clobber) {
5189                                 /* helper can write anything into the stack */
5190                                 *stype = STACK_MISC;
5191                         }
5192                         goto mark;
5193                 }
5194
5195                 if (is_spilled_reg(&state->stack[spi]) &&
5196                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5197                      env->allow_ptr_leaks)) {
5198                         if (clobber) {
5199                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5200                                 for (j = 0; j < BPF_REG_SIZE; j++)
5201                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5202                         }
5203                         goto mark;
5204                 }
5205
5206 err:
5207                 if (tnum_is_const(reg->var_off)) {
5208                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5209                                 err_extra, regno, min_off, i - min_off, access_size);
5210                 } else {
5211                         char tn_buf[48];
5212
5213                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5214                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5215                                 err_extra, regno, tn_buf, i - min_off, access_size);
5216                 }
5217                 return -EACCES;
5218 mark:
5219                 /* reading any byte out of 8-byte 'spill_slot' will cause
5220                  * the whole slot to be marked as 'read'
5221                  */
5222                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5223                               state->stack[spi].spilled_ptr.parent,
5224                               REG_LIVE_READ64);
5225                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5226                  * be sure that whether stack slot is written to or not. Hence,
5227                  * we must still conservatively propagate reads upwards even if
5228                  * helper may write to the entire memory range.
5229                  */
5230         }
5231         return update_stack_depth(env, state, min_off);
5232 }
5233
5234 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5235                                    int access_size, bool zero_size_allowed,
5236                                    struct bpf_call_arg_meta *meta)
5237 {
5238         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5239         u32 *max_access;
5240
5241         switch (base_type(reg->type)) {
5242         case PTR_TO_PACKET:
5243         case PTR_TO_PACKET_META:
5244                 return check_packet_access(env, regno, reg->off, access_size,
5245                                            zero_size_allowed);
5246         case PTR_TO_MAP_KEY:
5247                 if (meta && meta->raw_mode) {
5248                         verbose(env, "R%d cannot write into %s\n", regno,
5249                                 reg_type_str(env, reg->type));
5250                         return -EACCES;
5251                 }
5252                 return check_mem_region_access(env, regno, reg->off, access_size,
5253                                                reg->map_ptr->key_size, false);
5254         case PTR_TO_MAP_VALUE:
5255                 if (check_map_access_type(env, regno, reg->off, access_size,
5256                                           meta && meta->raw_mode ? BPF_WRITE :
5257                                           BPF_READ))
5258                         return -EACCES;
5259                 return check_map_access(env, regno, reg->off, access_size,
5260                                         zero_size_allowed, ACCESS_HELPER);
5261         case PTR_TO_MEM:
5262                 if (type_is_rdonly_mem(reg->type)) {
5263                         if (meta && meta->raw_mode) {
5264                                 verbose(env, "R%d cannot write into %s\n", regno,
5265                                         reg_type_str(env, reg->type));
5266                                 return -EACCES;
5267                         }
5268                 }
5269                 return check_mem_region_access(env, regno, reg->off,
5270                                                access_size, reg->mem_size,
5271                                                zero_size_allowed);
5272         case PTR_TO_BUF:
5273                 if (type_is_rdonly_mem(reg->type)) {
5274                         if (meta && meta->raw_mode) {
5275                                 verbose(env, "R%d cannot write into %s\n", regno,
5276                                         reg_type_str(env, reg->type));
5277                                 return -EACCES;
5278                         }
5279
5280                         max_access = &env->prog->aux->max_rdonly_access;
5281                 } else {
5282                         max_access = &env->prog->aux->max_rdwr_access;
5283                 }
5284                 return check_buffer_access(env, reg, regno, reg->off,
5285                                            access_size, zero_size_allowed,
5286                                            max_access);
5287         case PTR_TO_STACK:
5288                 return check_stack_range_initialized(
5289                                 env,
5290                                 regno, reg->off, access_size,
5291                                 zero_size_allowed, ACCESS_HELPER, meta);
5292         case PTR_TO_CTX:
5293                 /* in case the function doesn't know how to access the context,
5294                  * (because we are in a program of type SYSCALL for example), we
5295                  * can not statically check its size.
5296                  * Dynamically check it now.
5297                  */
5298                 if (!env->ops->convert_ctx_access) {
5299                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5300                         int offset = access_size - 1;
5301
5302                         /* Allow zero-byte read from PTR_TO_CTX */
5303                         if (access_size == 0)
5304                                 return zero_size_allowed ? 0 : -EACCES;
5305
5306                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5307                                                 atype, -1, false);
5308                 }
5309
5310                 fallthrough;
5311         default: /* scalar_value or invalid ptr */
5312                 /* Allow zero-byte read from NULL, regardless of pointer type */
5313                 if (zero_size_allowed && access_size == 0 &&
5314                     register_is_null(reg))
5315                         return 0;
5316
5317                 verbose(env, "R%d type=%s ", regno,
5318                         reg_type_str(env, reg->type));
5319                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5320                 return -EACCES;
5321         }
5322 }
5323
5324 static int check_mem_size_reg(struct bpf_verifier_env *env,
5325                               struct bpf_reg_state *reg, u32 regno,
5326                               bool zero_size_allowed,
5327                               struct bpf_call_arg_meta *meta)
5328 {
5329         int err;
5330
5331         /* This is used to refine r0 return value bounds for helpers
5332          * that enforce this value as an upper bound on return values.
5333          * See do_refine_retval_range() for helpers that can refine
5334          * the return value. C type of helper is u32 so we pull register
5335          * bound from umax_value however, if negative verifier errors
5336          * out. Only upper bounds can be learned because retval is an
5337          * int type and negative retvals are allowed.
5338          */
5339         meta->msize_max_value = reg->umax_value;
5340
5341         /* The register is SCALAR_VALUE; the access check
5342          * happens using its boundaries.
5343          */
5344         if (!tnum_is_const(reg->var_off))
5345                 /* For unprivileged variable accesses, disable raw
5346                  * mode so that the program is required to
5347                  * initialize all the memory that the helper could
5348                  * just partially fill up.
5349                  */
5350                 meta = NULL;
5351
5352         if (reg->smin_value < 0) {
5353                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5354                         regno);
5355                 return -EACCES;
5356         }
5357
5358         if (reg->umin_value == 0) {
5359                 err = check_helper_mem_access(env, regno - 1, 0,
5360                                               zero_size_allowed,
5361                                               meta);
5362                 if (err)
5363                         return err;
5364         }
5365
5366         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5367                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5368                         regno);
5369                 return -EACCES;
5370         }
5371         err = check_helper_mem_access(env, regno - 1,
5372                                       reg->umax_value,
5373                                       zero_size_allowed, meta);
5374         if (!err)
5375                 err = mark_chain_precision(env, regno);
5376         return err;
5377 }
5378
5379 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5380                    u32 regno, u32 mem_size)
5381 {
5382         bool may_be_null = type_may_be_null(reg->type);
5383         struct bpf_reg_state saved_reg;
5384         struct bpf_call_arg_meta meta;
5385         int err;
5386
5387         if (register_is_null(reg))
5388                 return 0;
5389
5390         memset(&meta, 0, sizeof(meta));
5391         /* Assuming that the register contains a value check if the memory
5392          * access is safe. Temporarily save and restore the register's state as
5393          * the conversion shouldn't be visible to a caller.
5394          */
5395         if (may_be_null) {
5396                 saved_reg = *reg;
5397                 mark_ptr_not_null_reg(reg);
5398         }
5399
5400         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5401         /* Check access for BPF_WRITE */
5402         meta.raw_mode = true;
5403         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5404
5405         if (may_be_null)
5406                 *reg = saved_reg;
5407
5408         return err;
5409 }
5410
5411 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5412                              u32 regno)
5413 {
5414         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5415         bool may_be_null = type_may_be_null(mem_reg->type);
5416         struct bpf_reg_state saved_reg;
5417         struct bpf_call_arg_meta meta;
5418         int err;
5419
5420         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5421
5422         memset(&meta, 0, sizeof(meta));
5423
5424         if (may_be_null) {
5425                 saved_reg = *mem_reg;
5426                 mark_ptr_not_null_reg(mem_reg);
5427         }
5428
5429         err = check_mem_size_reg(env, reg, regno, true, &meta);
5430         /* Check access for BPF_WRITE */
5431         meta.raw_mode = true;
5432         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5433
5434         if (may_be_null)
5435                 *mem_reg = saved_reg;
5436         return err;
5437 }
5438
5439 /* Implementation details:
5440  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5441  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5442  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5443  * value_or_null->value transition, since the verifier only cares about
5444  * the range of access to valid map value pointer and doesn't care about actual
5445  * address of the map element.
5446  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5447  * reg->id > 0 after value_or_null->value transition. By doing so
5448  * two bpf_map_lookups will be considered two different pointers that
5449  * point to different bpf_spin_locks.
5450  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5451  * dead-locks.
5452  * Since only one bpf_spin_lock is allowed the checks are simpler than
5453  * reg_is_refcounted() logic. The verifier needs to remember only
5454  * one spin_lock instead of array of acquired_refs.
5455  * cur_state->active_spin_lock remembers which map value element got locked
5456  * and clears it after bpf_spin_unlock.
5457  */
5458 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5459                              bool is_lock)
5460 {
5461         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5462         struct bpf_verifier_state *cur = env->cur_state;
5463         bool is_const = tnum_is_const(reg->var_off);
5464         struct bpf_map *map = reg->map_ptr;
5465         u64 val = reg->var_off.value;
5466
5467         if (!is_const) {
5468                 verbose(env,
5469                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5470                         regno);
5471                 return -EINVAL;
5472         }
5473         if (!map->btf) {
5474                 verbose(env,
5475                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5476                         map->name);
5477                 return -EINVAL;
5478         }
5479         if (!map_value_has_spin_lock(map)) {
5480                 if (map->spin_lock_off == -E2BIG)
5481                         verbose(env,
5482                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5483                                 map->name);
5484                 else if (map->spin_lock_off == -ENOENT)
5485                         verbose(env,
5486                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5487                                 map->name);
5488                 else
5489                         verbose(env,
5490                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5491                                 map->name);
5492                 return -EINVAL;
5493         }
5494         if (map->spin_lock_off != val + reg->off) {
5495                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5496                         val + reg->off);
5497                 return -EINVAL;
5498         }
5499         if (is_lock) {
5500                 if (cur->active_spin_lock) {
5501                         verbose(env,
5502                                 "Locking two bpf_spin_locks are not allowed\n");
5503                         return -EINVAL;
5504                 }
5505                 cur->active_spin_lock = reg->id;
5506         } else {
5507                 if (!cur->active_spin_lock) {
5508                         verbose(env, "bpf_spin_unlock without taking a lock\n");
5509                         return -EINVAL;
5510                 }
5511                 if (cur->active_spin_lock != reg->id) {
5512                         verbose(env, "bpf_spin_unlock of different lock\n");
5513                         return -EINVAL;
5514                 }
5515                 cur->active_spin_lock = 0;
5516         }
5517         return 0;
5518 }
5519
5520 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5521                               struct bpf_call_arg_meta *meta)
5522 {
5523         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5524         bool is_const = tnum_is_const(reg->var_off);
5525         struct bpf_map *map = reg->map_ptr;
5526         u64 val = reg->var_off.value;
5527
5528         if (!is_const) {
5529                 verbose(env,
5530                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5531                         regno);
5532                 return -EINVAL;
5533         }
5534         if (!map->btf) {
5535                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5536                         map->name);
5537                 return -EINVAL;
5538         }
5539         if (!map_value_has_timer(map)) {
5540                 if (map->timer_off == -E2BIG)
5541                         verbose(env,
5542                                 "map '%s' has more than one 'struct bpf_timer'\n",
5543                                 map->name);
5544                 else if (map->timer_off == -ENOENT)
5545                         verbose(env,
5546                                 "map '%s' doesn't have 'struct bpf_timer'\n",
5547                                 map->name);
5548                 else
5549                         verbose(env,
5550                                 "map '%s' is not a struct type or bpf_timer is mangled\n",
5551                                 map->name);
5552                 return -EINVAL;
5553         }
5554         if (map->timer_off != val + reg->off) {
5555                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5556                         val + reg->off, map->timer_off);
5557                 return -EINVAL;
5558         }
5559         if (meta->map_ptr) {
5560                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5561                 return -EFAULT;
5562         }
5563         meta->map_uid = reg->map_uid;
5564         meta->map_ptr = map;
5565         return 0;
5566 }
5567
5568 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5569                              struct bpf_call_arg_meta *meta)
5570 {
5571         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5572         struct bpf_map_value_off_desc *off_desc;
5573         struct bpf_map *map_ptr = reg->map_ptr;
5574         u32 kptr_off;
5575         int ret;
5576
5577         if (!tnum_is_const(reg->var_off)) {
5578                 verbose(env,
5579                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5580                         regno);
5581                 return -EINVAL;
5582         }
5583         if (!map_ptr->btf) {
5584                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5585                         map_ptr->name);
5586                 return -EINVAL;
5587         }
5588         if (!map_value_has_kptrs(map_ptr)) {
5589                 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5590                 if (ret == -E2BIG)
5591                         verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5592                                 BPF_MAP_VALUE_OFF_MAX);
5593                 else if (ret == -EEXIST)
5594                         verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5595                 else
5596                         verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5597                 return -EINVAL;
5598         }
5599
5600         meta->map_ptr = map_ptr;
5601         kptr_off = reg->off + reg->var_off.value;
5602         off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5603         if (!off_desc) {
5604                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5605                 return -EACCES;
5606         }
5607         if (off_desc->type != BPF_KPTR_REF) {
5608                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5609                 return -EACCES;
5610         }
5611         meta->kptr_off_desc = off_desc;
5612         return 0;
5613 }
5614
5615 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5616 {
5617         return type == ARG_CONST_SIZE ||
5618                type == ARG_CONST_SIZE_OR_ZERO;
5619 }
5620
5621 static bool arg_type_is_release(enum bpf_arg_type type)
5622 {
5623         return type & OBJ_RELEASE;
5624 }
5625
5626 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5627 {
5628         return base_type(type) == ARG_PTR_TO_DYNPTR;
5629 }
5630
5631 static int int_ptr_type_to_size(enum bpf_arg_type type)
5632 {
5633         if (type == ARG_PTR_TO_INT)
5634                 return sizeof(u32);
5635         else if (type == ARG_PTR_TO_LONG)
5636                 return sizeof(u64);
5637
5638         return -EINVAL;
5639 }
5640
5641 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5642                                  const struct bpf_call_arg_meta *meta,
5643                                  enum bpf_arg_type *arg_type)
5644 {
5645         if (!meta->map_ptr) {
5646                 /* kernel subsystem misconfigured verifier */
5647                 verbose(env, "invalid map_ptr to access map->type\n");
5648                 return -EACCES;
5649         }
5650
5651         switch (meta->map_ptr->map_type) {
5652         case BPF_MAP_TYPE_SOCKMAP:
5653         case BPF_MAP_TYPE_SOCKHASH:
5654                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5655                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5656                 } else {
5657                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
5658                         return -EINVAL;
5659                 }
5660                 break;
5661         case BPF_MAP_TYPE_BLOOM_FILTER:
5662                 if (meta->func_id == BPF_FUNC_map_peek_elem)
5663                         *arg_type = ARG_PTR_TO_MAP_VALUE;
5664                 break;
5665         default:
5666                 break;
5667         }
5668         return 0;
5669 }
5670
5671 struct bpf_reg_types {
5672         const enum bpf_reg_type types[10];
5673         u32 *btf_id;
5674 };
5675
5676 static const struct bpf_reg_types map_key_value_types = {
5677         .types = {
5678                 PTR_TO_STACK,
5679                 PTR_TO_PACKET,
5680                 PTR_TO_PACKET_META,
5681                 PTR_TO_MAP_KEY,
5682                 PTR_TO_MAP_VALUE,
5683         },
5684 };
5685
5686 static const struct bpf_reg_types sock_types = {
5687         .types = {
5688                 PTR_TO_SOCK_COMMON,
5689                 PTR_TO_SOCKET,
5690                 PTR_TO_TCP_SOCK,
5691                 PTR_TO_XDP_SOCK,
5692         },
5693 };
5694
5695 #ifdef CONFIG_NET
5696 static const struct bpf_reg_types btf_id_sock_common_types = {
5697         .types = {
5698                 PTR_TO_SOCK_COMMON,
5699                 PTR_TO_SOCKET,
5700                 PTR_TO_TCP_SOCK,
5701                 PTR_TO_XDP_SOCK,
5702                 PTR_TO_BTF_ID,
5703         },
5704         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5705 };
5706 #endif
5707
5708 static const struct bpf_reg_types mem_types = {
5709         .types = {
5710                 PTR_TO_STACK,
5711                 PTR_TO_PACKET,
5712                 PTR_TO_PACKET_META,
5713                 PTR_TO_MAP_KEY,
5714                 PTR_TO_MAP_VALUE,
5715                 PTR_TO_MEM,
5716                 PTR_TO_MEM | MEM_ALLOC,
5717                 PTR_TO_BUF,
5718         },
5719 };
5720
5721 static const struct bpf_reg_types int_ptr_types = {
5722         .types = {
5723                 PTR_TO_STACK,
5724                 PTR_TO_PACKET,
5725                 PTR_TO_PACKET_META,
5726                 PTR_TO_MAP_KEY,
5727                 PTR_TO_MAP_VALUE,
5728         },
5729 };
5730
5731 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5732 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5733 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5734 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5735 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5736 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5737 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5738 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5739 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5740 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5741 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5742 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5743 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5744 static const struct bpf_reg_types dynptr_types = {
5745         .types = {
5746                 PTR_TO_STACK,
5747                 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5748         }
5749 };
5750
5751 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5752         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
5753         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
5754         [ARG_CONST_SIZE]                = &scalar_types,
5755         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
5756         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
5757         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
5758         [ARG_PTR_TO_CTX]                = &context_types,
5759         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
5760 #ifdef CONFIG_NET
5761         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5762 #endif
5763         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
5764         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
5765         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
5766         [ARG_PTR_TO_MEM]                = &mem_types,
5767         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
5768         [ARG_PTR_TO_INT]                = &int_ptr_types,
5769         [ARG_PTR_TO_LONG]               = &int_ptr_types,
5770         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
5771         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
5772         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
5773         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
5774         [ARG_PTR_TO_TIMER]              = &timer_types,
5775         [ARG_PTR_TO_KPTR]               = &kptr_types,
5776         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
5777 };
5778
5779 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5780                           enum bpf_arg_type arg_type,
5781                           const u32 *arg_btf_id,
5782                           struct bpf_call_arg_meta *meta)
5783 {
5784         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5785         enum bpf_reg_type expected, type = reg->type;
5786         const struct bpf_reg_types *compatible;
5787         int i, j;
5788
5789         compatible = compatible_reg_types[base_type(arg_type)];
5790         if (!compatible) {
5791                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5792                 return -EFAULT;
5793         }
5794
5795         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5796          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5797          *
5798          * Same for MAYBE_NULL:
5799          *
5800          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5801          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5802          *
5803          * Therefore we fold these flags depending on the arg_type before comparison.
5804          */
5805         if (arg_type & MEM_RDONLY)
5806                 type &= ~MEM_RDONLY;
5807         if (arg_type & PTR_MAYBE_NULL)
5808                 type &= ~PTR_MAYBE_NULL;
5809
5810         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5811                 expected = compatible->types[i];
5812                 if (expected == NOT_INIT)
5813                         break;
5814
5815                 if (type == expected)
5816                         goto found;
5817         }
5818
5819         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5820         for (j = 0; j + 1 < i; j++)
5821                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5822         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5823         return -EACCES;
5824
5825 found:
5826         if (reg->type == PTR_TO_BTF_ID) {
5827                 /* For bpf_sk_release, it needs to match against first member
5828                  * 'struct sock_common', hence make an exception for it. This
5829                  * allows bpf_sk_release to work for multiple socket types.
5830                  */
5831                 bool strict_type_match = arg_type_is_release(arg_type) &&
5832                                          meta->func_id != BPF_FUNC_sk_release;
5833
5834                 if (!arg_btf_id) {
5835                         if (!compatible->btf_id) {
5836                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5837                                 return -EFAULT;
5838                         }
5839                         arg_btf_id = compatible->btf_id;
5840                 }
5841
5842                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5843                         if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5844                                 return -EACCES;
5845                 } else {
5846                         if (arg_btf_id == BPF_PTR_POISON) {
5847                                 verbose(env, "verifier internal error:");
5848                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5849                                         regno);
5850                                 return -EACCES;
5851                         }
5852
5853                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5854                                                   btf_vmlinux, *arg_btf_id,
5855                                                   strict_type_match)) {
5856                                 verbose(env, "R%d is of type %s but %s is expected\n",
5857                                         regno, kernel_type_name(reg->btf, reg->btf_id),
5858                                         kernel_type_name(btf_vmlinux, *arg_btf_id));
5859                                 return -EACCES;
5860                         }
5861                 }
5862         }
5863
5864         return 0;
5865 }
5866
5867 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5868                            const struct bpf_reg_state *reg, int regno,
5869                            enum bpf_arg_type arg_type)
5870 {
5871         enum bpf_reg_type type = reg->type;
5872         bool fixed_off_ok = false;
5873
5874         switch ((u32)type) {
5875         /* Pointer types where reg offset is explicitly allowed: */
5876         case PTR_TO_STACK:
5877                 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5878                         verbose(env, "cannot pass in dynptr at an offset\n");
5879                         return -EINVAL;
5880                 }
5881                 fallthrough;
5882         case PTR_TO_PACKET:
5883         case PTR_TO_PACKET_META:
5884         case PTR_TO_MAP_KEY:
5885         case PTR_TO_MAP_VALUE:
5886         case PTR_TO_MEM:
5887         case PTR_TO_MEM | MEM_RDONLY:
5888         case PTR_TO_MEM | MEM_ALLOC:
5889         case PTR_TO_BUF:
5890         case PTR_TO_BUF | MEM_RDONLY:
5891         case SCALAR_VALUE:
5892                 /* Some of the argument types nevertheless require a
5893                  * zero register offset.
5894                  */
5895                 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5896                         return 0;
5897                 break;
5898         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5899          * fixed offset.
5900          */
5901         case PTR_TO_BTF_ID:
5902                 /* When referenced PTR_TO_BTF_ID is passed to release function,
5903                  * it's fixed offset must be 0. In the other cases, fixed offset
5904                  * can be non-zero.
5905                  */
5906                 if (arg_type_is_release(arg_type) && reg->off) {
5907                         verbose(env, "R%d must have zero offset when passed to release func\n",
5908                                 regno);
5909                         return -EINVAL;
5910                 }
5911                 /* For arg is release pointer, fixed_off_ok must be false, but
5912                  * we already checked and rejected reg->off != 0 above, so set
5913                  * to true to allow fixed offset for all other cases.
5914                  */
5915                 fixed_off_ok = true;
5916                 break;
5917         default:
5918                 break;
5919         }
5920         return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5921 }
5922
5923 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5924 {
5925         struct bpf_func_state *state = func(env, reg);
5926         int spi = get_spi(reg->off);
5927
5928         return state->stack[spi].spilled_ptr.id;
5929 }
5930
5931 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5932                           struct bpf_call_arg_meta *meta,
5933                           const struct bpf_func_proto *fn)
5934 {
5935         u32 regno = BPF_REG_1 + arg;
5936         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5937         enum bpf_arg_type arg_type = fn->arg_type[arg];
5938         enum bpf_reg_type type = reg->type;
5939         u32 *arg_btf_id = NULL;
5940         int err = 0;
5941
5942         if (arg_type == ARG_DONTCARE)
5943                 return 0;
5944
5945         err = check_reg_arg(env, regno, SRC_OP);
5946         if (err)
5947                 return err;
5948
5949         if (arg_type == ARG_ANYTHING) {
5950                 if (is_pointer_value(env, regno)) {
5951                         verbose(env, "R%d leaks addr into helper function\n",
5952                                 regno);
5953                         return -EACCES;
5954                 }
5955                 return 0;
5956         }
5957
5958         if (type_is_pkt_pointer(type) &&
5959             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5960                 verbose(env, "helper access to the packet is not allowed\n");
5961                 return -EACCES;
5962         }
5963
5964         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5965                 err = resolve_map_arg_type(env, meta, &arg_type);
5966                 if (err)
5967                         return err;
5968         }
5969
5970         if (register_is_null(reg) && type_may_be_null(arg_type))
5971                 /* A NULL register has a SCALAR_VALUE type, so skip
5972                  * type checking.
5973                  */
5974                 goto skip_type_check;
5975
5976         /* arg_btf_id and arg_size are in a union. */
5977         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5978                 arg_btf_id = fn->arg_btf_id[arg];
5979
5980         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5981         if (err)
5982                 return err;
5983
5984         err = check_func_arg_reg_off(env, reg, regno, arg_type);
5985         if (err)
5986                 return err;
5987
5988 skip_type_check:
5989         if (arg_type_is_release(arg_type)) {
5990                 if (arg_type_is_dynptr(arg_type)) {
5991                         struct bpf_func_state *state = func(env, reg);
5992                         int spi = get_spi(reg->off);
5993
5994                         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
5995                             !state->stack[spi].spilled_ptr.id) {
5996                                 verbose(env, "arg %d is an unacquired reference\n", regno);
5997                                 return -EINVAL;
5998                         }
5999                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6000                         verbose(env, "R%d must be referenced when passed to release function\n",
6001                                 regno);
6002                         return -EINVAL;
6003                 }
6004                 if (meta->release_regno) {
6005                         verbose(env, "verifier internal error: more than one release argument\n");
6006                         return -EFAULT;
6007                 }
6008                 meta->release_regno = regno;
6009         }
6010
6011         if (reg->ref_obj_id) {
6012                 if (meta->ref_obj_id) {
6013                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6014                                 regno, reg->ref_obj_id,
6015                                 meta->ref_obj_id);
6016                         return -EFAULT;
6017                 }
6018                 meta->ref_obj_id = reg->ref_obj_id;
6019         }
6020
6021         switch (base_type(arg_type)) {
6022         case ARG_CONST_MAP_PTR:
6023                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6024                 if (meta->map_ptr) {
6025                         /* Use map_uid (which is unique id of inner map) to reject:
6026                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6027                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6028                          * if (inner_map1 && inner_map2) {
6029                          *     timer = bpf_map_lookup_elem(inner_map1);
6030                          *     if (timer)
6031                          *         // mismatch would have been allowed
6032                          *         bpf_timer_init(timer, inner_map2);
6033                          * }
6034                          *
6035                          * Comparing map_ptr is enough to distinguish normal and outer maps.
6036                          */
6037                         if (meta->map_ptr != reg->map_ptr ||
6038                             meta->map_uid != reg->map_uid) {
6039                                 verbose(env,
6040                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6041                                         meta->map_uid, reg->map_uid);
6042                                 return -EINVAL;
6043                         }
6044                 }
6045                 meta->map_ptr = reg->map_ptr;
6046                 meta->map_uid = reg->map_uid;
6047                 break;
6048         case ARG_PTR_TO_MAP_KEY:
6049                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6050                  * check that [key, key + map->key_size) are within
6051                  * stack limits and initialized
6052                  */
6053                 if (!meta->map_ptr) {
6054                         /* in function declaration map_ptr must come before
6055                          * map_key, so that it's verified and known before
6056                          * we have to check map_key here. Otherwise it means
6057                          * that kernel subsystem misconfigured verifier
6058                          */
6059                         verbose(env, "invalid map_ptr to access map->key\n");
6060                         return -EACCES;
6061                 }
6062                 err = check_helper_mem_access(env, regno,
6063                                               meta->map_ptr->key_size, false,
6064                                               NULL);
6065                 break;
6066         case ARG_PTR_TO_MAP_VALUE:
6067                 if (type_may_be_null(arg_type) && register_is_null(reg))
6068                         return 0;
6069
6070                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6071                  * check [value, value + map->value_size) validity
6072                  */
6073                 if (!meta->map_ptr) {
6074                         /* kernel subsystem misconfigured verifier */
6075                         verbose(env, "invalid map_ptr to access map->value\n");
6076                         return -EACCES;
6077                 }
6078                 meta->raw_mode = arg_type & MEM_UNINIT;
6079                 err = check_helper_mem_access(env, regno,
6080                                               meta->map_ptr->value_size, false,
6081                                               meta);
6082                 break;
6083         case ARG_PTR_TO_PERCPU_BTF_ID:
6084                 if (!reg->btf_id) {
6085                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6086                         return -EACCES;
6087                 }
6088                 meta->ret_btf = reg->btf;
6089                 meta->ret_btf_id = reg->btf_id;
6090                 break;
6091         case ARG_PTR_TO_SPIN_LOCK:
6092                 if (meta->func_id == BPF_FUNC_spin_lock) {
6093                         if (process_spin_lock(env, regno, true))
6094                                 return -EACCES;
6095                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6096                         if (process_spin_lock(env, regno, false))
6097                                 return -EACCES;
6098                 } else {
6099                         verbose(env, "verifier internal error\n");
6100                         return -EFAULT;
6101                 }
6102                 break;
6103         case ARG_PTR_TO_TIMER:
6104                 if (process_timer_func(env, regno, meta))
6105                         return -EACCES;
6106                 break;
6107         case ARG_PTR_TO_FUNC:
6108                 meta->subprogno = reg->subprogno;
6109                 break;
6110         case ARG_PTR_TO_MEM:
6111                 /* The access to this pointer is only checked when we hit the
6112                  * next is_mem_size argument below.
6113                  */
6114                 meta->raw_mode = arg_type & MEM_UNINIT;
6115                 if (arg_type & MEM_FIXED_SIZE) {
6116                         err = check_helper_mem_access(env, regno,
6117                                                       fn->arg_size[arg], false,
6118                                                       meta);
6119                 }
6120                 break;
6121         case ARG_CONST_SIZE:
6122                 err = check_mem_size_reg(env, reg, regno, false, meta);
6123                 break;
6124         case ARG_CONST_SIZE_OR_ZERO:
6125                 err = check_mem_size_reg(env, reg, regno, true, meta);
6126                 break;
6127         case ARG_PTR_TO_DYNPTR:
6128                 /* We only need to check for initialized / uninitialized helper
6129                  * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6130                  * assumption is that if it is, that a helper function
6131                  * initialized the dynptr on behalf of the BPF program.
6132                  */
6133                 if (base_type(reg->type) == PTR_TO_DYNPTR)
6134                         break;
6135                 if (arg_type & MEM_UNINIT) {
6136                         if (!is_dynptr_reg_valid_uninit(env, reg)) {
6137                                 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6138                                 return -EINVAL;
6139                         }
6140
6141                         /* We only support one dynptr being uninitialized at the moment,
6142                          * which is sufficient for the helper functions we have right now.
6143                          */
6144                         if (meta->uninit_dynptr_regno) {
6145                                 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6146                                 return -EFAULT;
6147                         }
6148
6149                         meta->uninit_dynptr_regno = regno;
6150                 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6151                         verbose(env,
6152                                 "Expected an initialized dynptr as arg #%d\n",
6153                                 arg + 1);
6154                         return -EINVAL;
6155                 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6156                         const char *err_extra = "";
6157
6158                         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6159                         case DYNPTR_TYPE_LOCAL:
6160                                 err_extra = "local";
6161                                 break;
6162                         case DYNPTR_TYPE_RINGBUF:
6163                                 err_extra = "ringbuf";
6164                                 break;
6165                         default:
6166                                 err_extra = "<unknown>";
6167                                 break;
6168                         }
6169                         verbose(env,
6170                                 "Expected a dynptr of type %s as arg #%d\n",
6171                                 err_extra, arg + 1);
6172                         return -EINVAL;
6173                 }
6174                 break;
6175         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6176                 if (!tnum_is_const(reg->var_off)) {
6177                         verbose(env, "R%d is not a known constant'\n",
6178                                 regno);
6179                         return -EACCES;
6180                 }
6181                 meta->mem_size = reg->var_off.value;
6182                 err = mark_chain_precision(env, regno);
6183                 if (err)
6184                         return err;
6185                 break;
6186         case ARG_PTR_TO_INT:
6187         case ARG_PTR_TO_LONG:
6188         {
6189                 int size = int_ptr_type_to_size(arg_type);
6190
6191                 err = check_helper_mem_access(env, regno, size, false, meta);
6192                 if (err)
6193                         return err;
6194                 err = check_ptr_alignment(env, reg, 0, size, true);
6195                 break;
6196         }
6197         case ARG_PTR_TO_CONST_STR:
6198         {
6199                 struct bpf_map *map = reg->map_ptr;
6200                 int map_off;
6201                 u64 map_addr;
6202                 char *str_ptr;
6203
6204                 if (!bpf_map_is_rdonly(map)) {
6205                         verbose(env, "R%d does not point to a readonly map'\n", regno);
6206                         return -EACCES;
6207                 }
6208
6209                 if (!tnum_is_const(reg->var_off)) {
6210                         verbose(env, "R%d is not a constant address'\n", regno);
6211                         return -EACCES;
6212                 }
6213
6214                 if (!map->ops->map_direct_value_addr) {
6215                         verbose(env, "no direct value access support for this map type\n");
6216                         return -EACCES;
6217                 }
6218
6219                 err = check_map_access(env, regno, reg->off,
6220                                        map->value_size - reg->off, false,
6221                                        ACCESS_HELPER);
6222                 if (err)
6223                         return err;
6224
6225                 map_off = reg->off + reg->var_off.value;
6226                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6227                 if (err) {
6228                         verbose(env, "direct value access on string failed\n");
6229                         return err;
6230                 }
6231
6232                 str_ptr = (char *)(long)(map_addr);
6233                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6234                         verbose(env, "string is not zero-terminated\n");
6235                         return -EINVAL;
6236                 }
6237                 break;
6238         }
6239         case ARG_PTR_TO_KPTR:
6240                 if (process_kptr_func(env, regno, meta))
6241                         return -EACCES;
6242                 break;
6243         }
6244
6245         return err;
6246 }
6247
6248 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6249 {
6250         enum bpf_attach_type eatype = env->prog->expected_attach_type;
6251         enum bpf_prog_type type = resolve_prog_type(env->prog);
6252
6253         if (func_id != BPF_FUNC_map_update_elem)
6254                 return false;
6255
6256         /* It's not possible to get access to a locked struct sock in these
6257          * contexts, so updating is safe.
6258          */
6259         switch (type) {
6260         case BPF_PROG_TYPE_TRACING:
6261                 if (eatype == BPF_TRACE_ITER)
6262                         return true;
6263                 break;
6264         case BPF_PROG_TYPE_SOCKET_FILTER:
6265         case BPF_PROG_TYPE_SCHED_CLS:
6266         case BPF_PROG_TYPE_SCHED_ACT:
6267         case BPF_PROG_TYPE_XDP:
6268         case BPF_PROG_TYPE_SK_REUSEPORT:
6269         case BPF_PROG_TYPE_FLOW_DISSECTOR:
6270         case BPF_PROG_TYPE_SK_LOOKUP:
6271                 return true;
6272         default:
6273                 break;
6274         }
6275
6276         verbose(env, "cannot update sockmap in this context\n");
6277         return false;
6278 }
6279
6280 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6281 {
6282         return env->prog->jit_requested &&
6283                bpf_jit_supports_subprog_tailcalls();
6284 }
6285
6286 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6287                                         struct bpf_map *map, int func_id)
6288 {
6289         if (!map)
6290                 return 0;
6291
6292         /* We need a two way check, first is from map perspective ... */
6293         switch (map->map_type) {
6294         case BPF_MAP_TYPE_PROG_ARRAY:
6295                 if (func_id != BPF_FUNC_tail_call)
6296                         goto error;
6297                 break;
6298         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6299                 if (func_id != BPF_FUNC_perf_event_read &&
6300                     func_id != BPF_FUNC_perf_event_output &&
6301                     func_id != BPF_FUNC_skb_output &&
6302                     func_id != BPF_FUNC_perf_event_read_value &&
6303                     func_id != BPF_FUNC_xdp_output)
6304                         goto error;
6305                 break;
6306         case BPF_MAP_TYPE_RINGBUF:
6307                 if (func_id != BPF_FUNC_ringbuf_output &&
6308                     func_id != BPF_FUNC_ringbuf_reserve &&
6309                     func_id != BPF_FUNC_ringbuf_query &&
6310                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6311                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6312                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
6313                         goto error;
6314                 break;
6315         case BPF_MAP_TYPE_USER_RINGBUF:
6316                 if (func_id != BPF_FUNC_user_ringbuf_drain)
6317                         goto error;
6318                 break;
6319         case BPF_MAP_TYPE_STACK_TRACE:
6320                 if (func_id != BPF_FUNC_get_stackid)
6321                         goto error;
6322                 break;
6323         case BPF_MAP_TYPE_CGROUP_ARRAY:
6324                 if (func_id != BPF_FUNC_skb_under_cgroup &&
6325                     func_id != BPF_FUNC_current_task_under_cgroup)
6326                         goto error;
6327                 break;
6328         case BPF_MAP_TYPE_CGROUP_STORAGE:
6329         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6330                 if (func_id != BPF_FUNC_get_local_storage)
6331                         goto error;
6332                 break;
6333         case BPF_MAP_TYPE_DEVMAP:
6334         case BPF_MAP_TYPE_DEVMAP_HASH:
6335                 if (func_id != BPF_FUNC_redirect_map &&
6336                     func_id != BPF_FUNC_map_lookup_elem)
6337                         goto error;
6338                 break;
6339         /* Restrict bpf side of cpumap and xskmap, open when use-cases
6340          * appear.
6341          */
6342         case BPF_MAP_TYPE_CPUMAP:
6343                 if (func_id != BPF_FUNC_redirect_map)
6344                         goto error;
6345                 break;
6346         case BPF_MAP_TYPE_XSKMAP:
6347                 if (func_id != BPF_FUNC_redirect_map &&
6348                     func_id != BPF_FUNC_map_lookup_elem)
6349                         goto error;
6350                 break;
6351         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6352         case BPF_MAP_TYPE_HASH_OF_MAPS:
6353                 if (func_id != BPF_FUNC_map_lookup_elem)
6354                         goto error;
6355                 break;
6356         case BPF_MAP_TYPE_SOCKMAP:
6357                 if (func_id != BPF_FUNC_sk_redirect_map &&
6358                     func_id != BPF_FUNC_sock_map_update &&
6359                     func_id != BPF_FUNC_map_delete_elem &&
6360                     func_id != BPF_FUNC_msg_redirect_map &&
6361                     func_id != BPF_FUNC_sk_select_reuseport &&
6362                     func_id != BPF_FUNC_map_lookup_elem &&
6363                     !may_update_sockmap(env, func_id))
6364                         goto error;
6365                 break;
6366         case BPF_MAP_TYPE_SOCKHASH:
6367                 if (func_id != BPF_FUNC_sk_redirect_hash &&
6368                     func_id != BPF_FUNC_sock_hash_update &&
6369                     func_id != BPF_FUNC_map_delete_elem &&
6370                     func_id != BPF_FUNC_msg_redirect_hash &&
6371                     func_id != BPF_FUNC_sk_select_reuseport &&
6372                     func_id != BPF_FUNC_map_lookup_elem &&
6373                     !may_update_sockmap(env, func_id))
6374                         goto error;
6375                 break;
6376         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6377                 if (func_id != BPF_FUNC_sk_select_reuseport)
6378                         goto error;
6379                 break;
6380         case BPF_MAP_TYPE_QUEUE:
6381         case BPF_MAP_TYPE_STACK:
6382                 if (func_id != BPF_FUNC_map_peek_elem &&
6383                     func_id != BPF_FUNC_map_pop_elem &&
6384                     func_id != BPF_FUNC_map_push_elem)
6385                         goto error;
6386                 break;
6387         case BPF_MAP_TYPE_SK_STORAGE:
6388                 if (func_id != BPF_FUNC_sk_storage_get &&
6389                     func_id != BPF_FUNC_sk_storage_delete)
6390                         goto error;
6391                 break;
6392         case BPF_MAP_TYPE_INODE_STORAGE:
6393                 if (func_id != BPF_FUNC_inode_storage_get &&
6394                     func_id != BPF_FUNC_inode_storage_delete)
6395                         goto error;
6396                 break;
6397         case BPF_MAP_TYPE_TASK_STORAGE:
6398                 if (func_id != BPF_FUNC_task_storage_get &&
6399                     func_id != BPF_FUNC_task_storage_delete)
6400                         goto error;
6401                 break;
6402         case BPF_MAP_TYPE_BLOOM_FILTER:
6403                 if (func_id != BPF_FUNC_map_peek_elem &&
6404                     func_id != BPF_FUNC_map_push_elem)
6405                         goto error;
6406                 break;
6407         default:
6408                 break;
6409         }
6410
6411         /* ... and second from the function itself. */
6412         switch (func_id) {
6413         case BPF_FUNC_tail_call:
6414                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6415                         goto error;
6416                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6417                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6418                         return -EINVAL;
6419                 }
6420                 break;
6421         case BPF_FUNC_perf_event_read:
6422         case BPF_FUNC_perf_event_output:
6423         case BPF_FUNC_perf_event_read_value:
6424         case BPF_FUNC_skb_output:
6425         case BPF_FUNC_xdp_output:
6426                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6427                         goto error;
6428                 break;
6429         case BPF_FUNC_ringbuf_output:
6430         case BPF_FUNC_ringbuf_reserve:
6431         case BPF_FUNC_ringbuf_query:
6432         case BPF_FUNC_ringbuf_reserve_dynptr:
6433         case BPF_FUNC_ringbuf_submit_dynptr:
6434         case BPF_FUNC_ringbuf_discard_dynptr:
6435                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6436                         goto error;
6437                 break;
6438         case BPF_FUNC_user_ringbuf_drain:
6439                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6440                         goto error;
6441                 break;
6442         case BPF_FUNC_get_stackid:
6443                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6444                         goto error;
6445                 break;
6446         case BPF_FUNC_current_task_under_cgroup:
6447         case BPF_FUNC_skb_under_cgroup:
6448                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6449                         goto error;
6450                 break;
6451         case BPF_FUNC_redirect_map:
6452                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6453                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6454                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
6455                     map->map_type != BPF_MAP_TYPE_XSKMAP)
6456                         goto error;
6457                 break;
6458         case BPF_FUNC_sk_redirect_map:
6459         case BPF_FUNC_msg_redirect_map:
6460         case BPF_FUNC_sock_map_update:
6461                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6462                         goto error;
6463                 break;
6464         case BPF_FUNC_sk_redirect_hash:
6465         case BPF_FUNC_msg_redirect_hash:
6466         case BPF_FUNC_sock_hash_update:
6467                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6468                         goto error;
6469                 break;
6470         case BPF_FUNC_get_local_storage:
6471                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6472                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6473                         goto error;
6474                 break;
6475         case BPF_FUNC_sk_select_reuseport:
6476                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6477                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6478                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
6479                         goto error;
6480                 break;
6481         case BPF_FUNC_map_pop_elem:
6482                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6483                     map->map_type != BPF_MAP_TYPE_STACK)
6484                         goto error;
6485                 break;
6486         case BPF_FUNC_map_peek_elem:
6487         case BPF_FUNC_map_push_elem:
6488                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6489                     map->map_type != BPF_MAP_TYPE_STACK &&
6490                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6491                         goto error;
6492                 break;
6493         case BPF_FUNC_map_lookup_percpu_elem:
6494                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6495                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6496                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6497                         goto error;
6498                 break;
6499         case BPF_FUNC_sk_storage_get:
6500         case BPF_FUNC_sk_storage_delete:
6501                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6502                         goto error;
6503                 break;
6504         case BPF_FUNC_inode_storage_get:
6505         case BPF_FUNC_inode_storage_delete:
6506                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6507                         goto error;
6508                 break;
6509         case BPF_FUNC_task_storage_get:
6510         case BPF_FUNC_task_storage_delete:
6511                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6512                         goto error;
6513                 break;
6514         default:
6515                 break;
6516         }
6517
6518         return 0;
6519 error:
6520         verbose(env, "cannot pass map_type %d into func %s#%d\n",
6521                 map->map_type, func_id_name(func_id), func_id);
6522         return -EINVAL;
6523 }
6524
6525 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6526 {
6527         int count = 0;
6528
6529         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6530                 count++;
6531         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6532                 count++;
6533         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6534                 count++;
6535         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6536                 count++;
6537         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6538                 count++;
6539
6540         /* We only support one arg being in raw mode at the moment,
6541          * which is sufficient for the helper functions we have
6542          * right now.
6543          */
6544         return count <= 1;
6545 }
6546
6547 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6548 {
6549         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6550         bool has_size = fn->arg_size[arg] != 0;
6551         bool is_next_size = false;
6552
6553         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6554                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6555
6556         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6557                 return is_next_size;
6558
6559         return has_size == is_next_size || is_next_size == is_fixed;
6560 }
6561
6562 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6563 {
6564         /* bpf_xxx(..., buf, len) call will access 'len'
6565          * bytes from memory 'buf'. Both arg types need
6566          * to be paired, so make sure there's no buggy
6567          * helper function specification.
6568          */
6569         if (arg_type_is_mem_size(fn->arg1_type) ||
6570             check_args_pair_invalid(fn, 0) ||
6571             check_args_pair_invalid(fn, 1) ||
6572             check_args_pair_invalid(fn, 2) ||
6573             check_args_pair_invalid(fn, 3) ||
6574             check_args_pair_invalid(fn, 4))
6575                 return false;
6576
6577         return true;
6578 }
6579
6580 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6581 {
6582         int i;
6583
6584         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6585                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6586                         return false;
6587
6588                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6589                     /* arg_btf_id and arg_size are in a union. */
6590                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6591                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6592                         return false;
6593         }
6594
6595         return true;
6596 }
6597
6598 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6599 {
6600         return check_raw_mode_ok(fn) &&
6601                check_arg_pair_ok(fn) &&
6602                check_btf_id_ok(fn) ? 0 : -EINVAL;
6603 }
6604
6605 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6606  * are now invalid, so turn them into unknown SCALAR_VALUE.
6607  */
6608 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6609 {
6610         struct bpf_func_state *state;
6611         struct bpf_reg_state *reg;
6612
6613         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6614                 if (reg_is_pkt_pointer_any(reg))
6615                         __mark_reg_unknown(env, reg);
6616         }));
6617 }
6618
6619 enum {
6620         AT_PKT_END = -1,
6621         BEYOND_PKT_END = -2,
6622 };
6623
6624 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6625 {
6626         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6627         struct bpf_reg_state *reg = &state->regs[regn];
6628
6629         if (reg->type != PTR_TO_PACKET)
6630                 /* PTR_TO_PACKET_META is not supported yet */
6631                 return;
6632
6633         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6634          * How far beyond pkt_end it goes is unknown.
6635          * if (!range_open) it's the case of pkt >= pkt_end
6636          * if (range_open) it's the case of pkt > pkt_end
6637          * hence this pointer is at least 1 byte bigger than pkt_end
6638          */
6639         if (range_open)
6640                 reg->range = BEYOND_PKT_END;
6641         else
6642                 reg->range = AT_PKT_END;
6643 }
6644
6645 /* The pointer with the specified id has released its reference to kernel
6646  * resources. Identify all copies of the same pointer and clear the reference.
6647  */
6648 static int release_reference(struct bpf_verifier_env *env,
6649                              int ref_obj_id)
6650 {
6651         struct bpf_func_state *state;
6652         struct bpf_reg_state *reg;
6653         int err;
6654
6655         err = release_reference_state(cur_func(env), ref_obj_id);
6656         if (err)
6657                 return err;
6658
6659         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6660                 if (reg->ref_obj_id == ref_obj_id) {
6661                         if (!env->allow_ptr_leaks)
6662                                 __mark_reg_not_init(env, reg);
6663                         else
6664                                 __mark_reg_unknown(env, reg);
6665                 }
6666         }));
6667
6668         return 0;
6669 }
6670
6671 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6672                                     struct bpf_reg_state *regs)
6673 {
6674         int i;
6675
6676         /* after the call registers r0 - r5 were scratched */
6677         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6678                 mark_reg_not_init(env, regs, caller_saved[i]);
6679                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6680         }
6681 }
6682
6683 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6684                                    struct bpf_func_state *caller,
6685                                    struct bpf_func_state *callee,
6686                                    int insn_idx);
6687
6688 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6689                              int *insn_idx, int subprog,
6690                              set_callee_state_fn set_callee_state_cb)
6691 {
6692         struct bpf_verifier_state *state = env->cur_state;
6693         struct bpf_func_info_aux *func_info_aux;
6694         struct bpf_func_state *caller, *callee;
6695         int err;
6696         bool is_global = false;
6697
6698         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6699                 verbose(env, "the call stack of %d frames is too deep\n",
6700                         state->curframe + 2);
6701                 return -E2BIG;
6702         }
6703
6704         caller = state->frame[state->curframe];
6705         if (state->frame[state->curframe + 1]) {
6706                 verbose(env, "verifier bug. Frame %d already allocated\n",
6707                         state->curframe + 1);
6708                 return -EFAULT;
6709         }
6710
6711         func_info_aux = env->prog->aux->func_info_aux;
6712         if (func_info_aux)
6713                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6714         err = btf_check_subprog_call(env, subprog, caller->regs);
6715         if (err == -EFAULT)
6716                 return err;
6717         if (is_global) {
6718                 if (err) {
6719                         verbose(env, "Caller passes invalid args into func#%d\n",
6720                                 subprog);
6721                         return err;
6722                 } else {
6723                         if (env->log.level & BPF_LOG_LEVEL)
6724                                 verbose(env,
6725                                         "Func#%d is global and valid. Skipping.\n",
6726                                         subprog);
6727                         clear_caller_saved_regs(env, caller->regs);
6728
6729                         /* All global functions return a 64-bit SCALAR_VALUE */
6730                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
6731                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6732
6733                         /* continue with next insn after call */
6734                         return 0;
6735                 }
6736         }
6737
6738         if (insn->code == (BPF_JMP | BPF_CALL) &&
6739             insn->src_reg == 0 &&
6740             insn->imm == BPF_FUNC_timer_set_callback) {
6741                 struct bpf_verifier_state *async_cb;
6742
6743                 /* there is no real recursion here. timer callbacks are async */
6744                 env->subprog_info[subprog].is_async_cb = true;
6745                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6746                                          *insn_idx, subprog);
6747                 if (!async_cb)
6748                         return -EFAULT;
6749                 callee = async_cb->frame[0];
6750                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6751
6752                 /* Convert bpf_timer_set_callback() args into timer callback args */
6753                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6754                 if (err)
6755                         return err;
6756
6757                 clear_caller_saved_regs(env, caller->regs);
6758                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6759                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6760                 /* continue with next insn after call */
6761                 return 0;
6762         }
6763
6764         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6765         if (!callee)
6766                 return -ENOMEM;
6767         state->frame[state->curframe + 1] = callee;
6768
6769         /* callee cannot access r0, r6 - r9 for reading and has to write
6770          * into its own stack before reading from it.
6771          * callee can read/write into caller's stack
6772          */
6773         init_func_state(env, callee,
6774                         /* remember the callsite, it will be used by bpf_exit */
6775                         *insn_idx /* callsite */,
6776                         state->curframe + 1 /* frameno within this callchain */,
6777                         subprog /* subprog number within this prog */);
6778
6779         /* Transfer references to the callee */
6780         err = copy_reference_state(callee, caller);
6781         if (err)
6782                 goto err_out;
6783
6784         err = set_callee_state_cb(env, caller, callee, *insn_idx);
6785         if (err)
6786                 goto err_out;
6787
6788         clear_caller_saved_regs(env, caller->regs);
6789
6790         /* only increment it after check_reg_arg() finished */
6791         state->curframe++;
6792
6793         /* and go analyze first insn of the callee */
6794         *insn_idx = env->subprog_info[subprog].start - 1;
6795
6796         if (env->log.level & BPF_LOG_LEVEL) {
6797                 verbose(env, "caller:\n");
6798                 print_verifier_state(env, caller, true);
6799                 verbose(env, "callee:\n");
6800                 print_verifier_state(env, callee, true);
6801         }
6802         return 0;
6803
6804 err_out:
6805         free_func_state(callee);
6806         state->frame[state->curframe + 1] = NULL;
6807         return err;
6808 }
6809
6810 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6811                                    struct bpf_func_state *caller,
6812                                    struct bpf_func_state *callee)
6813 {
6814         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6815          *      void *callback_ctx, u64 flags);
6816          * callback_fn(struct bpf_map *map, void *key, void *value,
6817          *      void *callback_ctx);
6818          */
6819         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6820
6821         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6822         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6823         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6824
6825         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6826         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6827         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6828
6829         /* pointer to stack or null */
6830         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6831
6832         /* unused */
6833         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6834         return 0;
6835 }
6836
6837 static int set_callee_state(struct bpf_verifier_env *env,
6838                             struct bpf_func_state *caller,
6839                             struct bpf_func_state *callee, int insn_idx)
6840 {
6841         int i;
6842
6843         /* copy r1 - r5 args that callee can access.  The copy includes parent
6844          * pointers, which connects us up to the liveness chain
6845          */
6846         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6847                 callee->regs[i] = caller->regs[i];
6848         return 0;
6849 }
6850
6851 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6852                            int *insn_idx)
6853 {
6854         int subprog, target_insn;
6855
6856         target_insn = *insn_idx + insn->imm + 1;
6857         subprog = find_subprog(env, target_insn);
6858         if (subprog < 0) {
6859                 verbose(env, "verifier bug. No program starts at insn %d\n",
6860                         target_insn);
6861                 return -EFAULT;
6862         }
6863
6864         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6865 }
6866
6867 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6868                                        struct bpf_func_state *caller,
6869                                        struct bpf_func_state *callee,
6870                                        int insn_idx)
6871 {
6872         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6873         struct bpf_map *map;
6874         int err;
6875
6876         if (bpf_map_ptr_poisoned(insn_aux)) {
6877                 verbose(env, "tail_call abusing map_ptr\n");
6878                 return -EINVAL;
6879         }
6880
6881         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6882         if (!map->ops->map_set_for_each_callback_args ||
6883             !map->ops->map_for_each_callback) {
6884                 verbose(env, "callback function not allowed for map\n");
6885                 return -ENOTSUPP;
6886         }
6887
6888         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6889         if (err)
6890                 return err;
6891
6892         callee->in_callback_fn = true;
6893         callee->callback_ret_range = tnum_range(0, 1);
6894         return 0;
6895 }
6896
6897 static int set_loop_callback_state(struct bpf_verifier_env *env,
6898                                    struct bpf_func_state *caller,
6899                                    struct bpf_func_state *callee,
6900                                    int insn_idx)
6901 {
6902         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6903          *          u64 flags);
6904          * callback_fn(u32 index, void *callback_ctx);
6905          */
6906         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6907         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6908
6909         /* unused */
6910         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6911         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6912         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6913
6914         callee->in_callback_fn = true;
6915         callee->callback_ret_range = tnum_range(0, 1);
6916         return 0;
6917 }
6918
6919 static int set_timer_callback_state(struct bpf_verifier_env *env,
6920                                     struct bpf_func_state *caller,
6921                                     struct bpf_func_state *callee,
6922                                     int insn_idx)
6923 {
6924         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6925
6926         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6927          * callback_fn(struct bpf_map *map, void *key, void *value);
6928          */
6929         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6930         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6931         callee->regs[BPF_REG_1].map_ptr = map_ptr;
6932
6933         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6934         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6935         callee->regs[BPF_REG_2].map_ptr = map_ptr;
6936
6937         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6938         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6939         callee->regs[BPF_REG_3].map_ptr = map_ptr;
6940
6941         /* unused */
6942         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6943         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6944         callee->in_async_callback_fn = true;
6945         callee->callback_ret_range = tnum_range(0, 1);
6946         return 0;
6947 }
6948
6949 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6950                                        struct bpf_func_state *caller,
6951                                        struct bpf_func_state *callee,
6952                                        int insn_idx)
6953 {
6954         /* bpf_find_vma(struct task_struct *task, u64 addr,
6955          *               void *callback_fn, void *callback_ctx, u64 flags)
6956          * (callback_fn)(struct task_struct *task,
6957          *               struct vm_area_struct *vma, void *callback_ctx);
6958          */
6959         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6960
6961         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6962         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6963         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6964         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6965
6966         /* pointer to stack or null */
6967         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6968
6969         /* unused */
6970         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6971         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6972         callee->in_callback_fn = true;
6973         callee->callback_ret_range = tnum_range(0, 1);
6974         return 0;
6975 }
6976
6977 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
6978                                            struct bpf_func_state *caller,
6979                                            struct bpf_func_state *callee,
6980                                            int insn_idx)
6981 {
6982         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
6983          *                        callback_ctx, u64 flags);
6984          * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
6985          */
6986         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
6987         callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
6988         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6989         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6990
6991         /* unused */
6992         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6993         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6994         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6995
6996         callee->in_callback_fn = true;
6997         callee->callback_ret_range = tnum_range(0, 1);
6998         return 0;
6999 }
7000
7001 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7002 {
7003         struct bpf_verifier_state *state = env->cur_state;
7004         struct bpf_func_state *caller, *callee;
7005         struct bpf_reg_state *r0;
7006         int err;
7007
7008         callee = state->frame[state->curframe];
7009         r0 = &callee->regs[BPF_REG_0];
7010         if (r0->type == PTR_TO_STACK) {
7011                 /* technically it's ok to return caller's stack pointer
7012                  * (or caller's caller's pointer) back to the caller,
7013                  * since these pointers are valid. Only current stack
7014                  * pointer will be invalid as soon as function exits,
7015                  * but let's be conservative
7016                  */
7017                 verbose(env, "cannot return stack pointer to the caller\n");
7018                 return -EINVAL;
7019         }
7020
7021         caller = state->frame[state->curframe - 1];
7022         if (callee->in_callback_fn) {
7023                 /* enforce R0 return value range [0, 1]. */
7024                 struct tnum range = callee->callback_ret_range;
7025
7026                 if (r0->type != SCALAR_VALUE) {
7027                         verbose(env, "R0 not a scalar value\n");
7028                         return -EACCES;
7029                 }
7030                 if (!tnum_in(range, r0->var_off)) {
7031                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7032                         return -EINVAL;
7033                 }
7034         } else {
7035                 /* return to the caller whatever r0 had in the callee */
7036                 caller->regs[BPF_REG_0] = *r0;
7037         }
7038
7039         /* callback_fn frame should have released its own additions to parent's
7040          * reference state at this point, or check_reference_leak would
7041          * complain, hence it must be the same as the caller. There is no need
7042          * to copy it back.
7043          */
7044         if (!callee->in_callback_fn) {
7045                 /* Transfer references to the caller */
7046                 err = copy_reference_state(caller, callee);
7047                 if (err)
7048                         return err;
7049         }
7050
7051         *insn_idx = callee->callsite + 1;
7052         if (env->log.level & BPF_LOG_LEVEL) {
7053                 verbose(env, "returning from callee:\n");
7054                 print_verifier_state(env, callee, true);
7055                 verbose(env, "to caller at %d:\n", *insn_idx);
7056                 print_verifier_state(env, caller, true);
7057         }
7058         /* clear everything in the callee */
7059         free_func_state(callee);
7060         state->frame[state->curframe--] = NULL;
7061         return 0;
7062 }
7063
7064 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7065                                    int func_id,
7066                                    struct bpf_call_arg_meta *meta)
7067 {
7068         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7069
7070         if (ret_type != RET_INTEGER ||
7071             (func_id != BPF_FUNC_get_stack &&
7072              func_id != BPF_FUNC_get_task_stack &&
7073              func_id != BPF_FUNC_probe_read_str &&
7074              func_id != BPF_FUNC_probe_read_kernel_str &&
7075              func_id != BPF_FUNC_probe_read_user_str))
7076                 return;
7077
7078         ret_reg->smax_value = meta->msize_max_value;
7079         ret_reg->s32_max_value = meta->msize_max_value;
7080         ret_reg->smin_value = -MAX_ERRNO;
7081         ret_reg->s32_min_value = -MAX_ERRNO;
7082         reg_bounds_sync(ret_reg);
7083 }
7084
7085 static int
7086 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7087                 int func_id, int insn_idx)
7088 {
7089         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7090         struct bpf_map *map = meta->map_ptr;
7091
7092         if (func_id != BPF_FUNC_tail_call &&
7093             func_id != BPF_FUNC_map_lookup_elem &&
7094             func_id != BPF_FUNC_map_update_elem &&
7095             func_id != BPF_FUNC_map_delete_elem &&
7096             func_id != BPF_FUNC_map_push_elem &&
7097             func_id != BPF_FUNC_map_pop_elem &&
7098             func_id != BPF_FUNC_map_peek_elem &&
7099             func_id != BPF_FUNC_for_each_map_elem &&
7100             func_id != BPF_FUNC_redirect_map &&
7101             func_id != BPF_FUNC_map_lookup_percpu_elem)
7102                 return 0;
7103
7104         if (map == NULL) {
7105                 verbose(env, "kernel subsystem misconfigured verifier\n");
7106                 return -EINVAL;
7107         }
7108
7109         /* In case of read-only, some additional restrictions
7110          * need to be applied in order to prevent altering the
7111          * state of the map from program side.
7112          */
7113         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7114             (func_id == BPF_FUNC_map_delete_elem ||
7115              func_id == BPF_FUNC_map_update_elem ||
7116              func_id == BPF_FUNC_map_push_elem ||
7117              func_id == BPF_FUNC_map_pop_elem)) {
7118                 verbose(env, "write into map forbidden\n");
7119                 return -EACCES;
7120         }
7121
7122         if (!BPF_MAP_PTR(aux->map_ptr_state))
7123                 bpf_map_ptr_store(aux, meta->map_ptr,
7124                                   !meta->map_ptr->bypass_spec_v1);
7125         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7126                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7127                                   !meta->map_ptr->bypass_spec_v1);
7128         return 0;
7129 }
7130
7131 static int
7132 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7133                 int func_id, int insn_idx)
7134 {
7135         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7136         struct bpf_reg_state *regs = cur_regs(env), *reg;
7137         struct bpf_map *map = meta->map_ptr;
7138         u64 val, max;
7139         int err;
7140
7141         if (func_id != BPF_FUNC_tail_call)
7142                 return 0;
7143         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7144                 verbose(env, "kernel subsystem misconfigured verifier\n");
7145                 return -EINVAL;
7146         }
7147
7148         reg = &regs[BPF_REG_3];
7149         val = reg->var_off.value;
7150         max = map->max_entries;
7151
7152         if (!(register_is_const(reg) && val < max)) {
7153                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7154                 return 0;
7155         }
7156
7157         err = mark_chain_precision(env, BPF_REG_3);
7158         if (err)
7159                 return err;
7160         if (bpf_map_key_unseen(aux))
7161                 bpf_map_key_store(aux, val);
7162         else if (!bpf_map_key_poisoned(aux) &&
7163                   bpf_map_key_immediate(aux) != val)
7164                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7165         return 0;
7166 }
7167
7168 static int check_reference_leak(struct bpf_verifier_env *env)
7169 {
7170         struct bpf_func_state *state = cur_func(env);
7171         bool refs_lingering = false;
7172         int i;
7173
7174         if (state->frameno && !state->in_callback_fn)
7175                 return 0;
7176
7177         for (i = 0; i < state->acquired_refs; i++) {
7178                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7179                         continue;
7180                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7181                         state->refs[i].id, state->refs[i].insn_idx);
7182                 refs_lingering = true;
7183         }
7184         return refs_lingering ? -EINVAL : 0;
7185 }
7186
7187 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7188                                    struct bpf_reg_state *regs)
7189 {
7190         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7191         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7192         struct bpf_map *fmt_map = fmt_reg->map_ptr;
7193         int err, fmt_map_off, num_args;
7194         u64 fmt_addr;
7195         char *fmt;
7196
7197         /* data must be an array of u64 */
7198         if (data_len_reg->var_off.value % 8)
7199                 return -EINVAL;
7200         num_args = data_len_reg->var_off.value / 8;
7201
7202         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7203          * and map_direct_value_addr is set.
7204          */
7205         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7206         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7207                                                   fmt_map_off);
7208         if (err) {
7209                 verbose(env, "verifier bug\n");
7210                 return -EFAULT;
7211         }
7212         fmt = (char *)(long)fmt_addr + fmt_map_off;
7213
7214         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7215          * can focus on validating the format specifiers.
7216          */
7217         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7218         if (err < 0)
7219                 verbose(env, "Invalid format string\n");
7220
7221         return err;
7222 }
7223
7224 static int check_get_func_ip(struct bpf_verifier_env *env)
7225 {
7226         enum bpf_prog_type type = resolve_prog_type(env->prog);
7227         int func_id = BPF_FUNC_get_func_ip;
7228
7229         if (type == BPF_PROG_TYPE_TRACING) {
7230                 if (!bpf_prog_has_trampoline(env->prog)) {
7231                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7232                                 func_id_name(func_id), func_id);
7233                         return -ENOTSUPP;
7234                 }
7235                 return 0;
7236         } else if (type == BPF_PROG_TYPE_KPROBE) {
7237                 return 0;
7238         }
7239
7240         verbose(env, "func %s#%d not supported for program type %d\n",
7241                 func_id_name(func_id), func_id, type);
7242         return -ENOTSUPP;
7243 }
7244
7245 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7246 {
7247         return &env->insn_aux_data[env->insn_idx];
7248 }
7249
7250 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7251 {
7252         struct bpf_reg_state *regs = cur_regs(env);
7253         struct bpf_reg_state *reg = &regs[BPF_REG_4];
7254         bool reg_is_null = register_is_null(reg);
7255
7256         if (reg_is_null)
7257                 mark_chain_precision(env, BPF_REG_4);
7258
7259         return reg_is_null;
7260 }
7261
7262 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7263 {
7264         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7265
7266         if (!state->initialized) {
7267                 state->initialized = 1;
7268                 state->fit_for_inline = loop_flag_is_zero(env);
7269                 state->callback_subprogno = subprogno;
7270                 return;
7271         }
7272
7273         if (!state->fit_for_inline)
7274                 return;
7275
7276         state->fit_for_inline = (loop_flag_is_zero(env) &&
7277                                  state->callback_subprogno == subprogno);
7278 }
7279
7280 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7281                              int *insn_idx_p)
7282 {
7283         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7284         const struct bpf_func_proto *fn = NULL;
7285         enum bpf_return_type ret_type;
7286         enum bpf_type_flag ret_flag;
7287         struct bpf_reg_state *regs;
7288         struct bpf_call_arg_meta meta;
7289         int insn_idx = *insn_idx_p;
7290         bool changes_data;
7291         int i, err, func_id;
7292
7293         /* find function prototype */
7294         func_id = insn->imm;
7295         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7296                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7297                         func_id);
7298                 return -EINVAL;
7299         }
7300
7301         if (env->ops->get_func_proto)
7302                 fn = env->ops->get_func_proto(func_id, env->prog);
7303         if (!fn) {
7304                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7305                         func_id);
7306                 return -EINVAL;
7307         }
7308
7309         /* eBPF programs must be GPL compatible to use GPL-ed functions */
7310         if (!env->prog->gpl_compatible && fn->gpl_only) {
7311                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7312                 return -EINVAL;
7313         }
7314
7315         if (fn->allowed && !fn->allowed(env->prog)) {
7316                 verbose(env, "helper call is not allowed in probe\n");
7317                 return -EINVAL;
7318         }
7319
7320         /* With LD_ABS/IND some JITs save/restore skb from r1. */
7321         changes_data = bpf_helper_changes_pkt_data(fn->func);
7322         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7323                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7324                         func_id_name(func_id), func_id);
7325                 return -EINVAL;
7326         }
7327
7328         memset(&meta, 0, sizeof(meta));
7329         meta.pkt_access = fn->pkt_access;
7330
7331         err = check_func_proto(fn, func_id);
7332         if (err) {
7333                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7334                         func_id_name(func_id), func_id);
7335                 return err;
7336         }
7337
7338         meta.func_id = func_id;
7339         /* check args */
7340         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7341                 err = check_func_arg(env, i, &meta, fn);
7342                 if (err)
7343                         return err;
7344         }
7345
7346         err = record_func_map(env, &meta, func_id, insn_idx);
7347         if (err)
7348                 return err;
7349
7350         err = record_func_key(env, &meta, func_id, insn_idx);
7351         if (err)
7352                 return err;
7353
7354         /* Mark slots with STACK_MISC in case of raw mode, stack offset
7355          * is inferred from register state.
7356          */
7357         for (i = 0; i < meta.access_size; i++) {
7358                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7359                                        BPF_WRITE, -1, false);
7360                 if (err)
7361                         return err;
7362         }
7363
7364         regs = cur_regs(env);
7365
7366         if (meta.uninit_dynptr_regno) {
7367                 /* we write BPF_DW bits (8 bytes) at a time */
7368                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7369                         err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7370                                                i, BPF_DW, BPF_WRITE, -1, false);
7371                         if (err)
7372                                 return err;
7373                 }
7374
7375                 err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7376                                               fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7377                                               insn_idx);
7378                 if (err)
7379                         return err;
7380         }
7381
7382         if (meta.release_regno) {
7383                 err = -EINVAL;
7384                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7385                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7386                 else if (meta.ref_obj_id)
7387                         err = release_reference(env, meta.ref_obj_id);
7388                 /* meta.ref_obj_id can only be 0 if register that is meant to be
7389                  * released is NULL, which must be > R0.
7390                  */
7391                 else if (register_is_null(&regs[meta.release_regno]))
7392                         err = 0;
7393                 if (err) {
7394                         verbose(env, "func %s#%d reference has not been acquired before\n",
7395                                 func_id_name(func_id), func_id);
7396                         return err;
7397                 }
7398         }
7399
7400         switch (func_id) {
7401         case BPF_FUNC_tail_call:
7402                 err = check_reference_leak(env);
7403                 if (err) {
7404                         verbose(env, "tail_call would lead to reference leak\n");
7405                         return err;
7406                 }
7407                 break;
7408         case BPF_FUNC_get_local_storage:
7409                 /* check that flags argument in get_local_storage(map, flags) is 0,
7410                  * this is required because get_local_storage() can't return an error.
7411                  */
7412                 if (!register_is_null(&regs[BPF_REG_2])) {
7413                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7414                         return -EINVAL;
7415                 }
7416                 break;
7417         case BPF_FUNC_for_each_map_elem:
7418                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7419                                         set_map_elem_callback_state);
7420                 break;
7421         case BPF_FUNC_timer_set_callback:
7422                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7423                                         set_timer_callback_state);
7424                 break;
7425         case BPF_FUNC_find_vma:
7426                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7427                                         set_find_vma_callback_state);
7428                 break;
7429         case BPF_FUNC_snprintf:
7430                 err = check_bpf_snprintf_call(env, regs);
7431                 break;
7432         case BPF_FUNC_loop:
7433                 update_loop_inline_state(env, meta.subprogno);
7434                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7435                                         set_loop_callback_state);
7436                 break;
7437         case BPF_FUNC_dynptr_from_mem:
7438                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7439                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7440                                 reg_type_str(env, regs[BPF_REG_1].type));
7441                         return -EACCES;
7442                 }
7443                 break;
7444         case BPF_FUNC_set_retval:
7445                 if (prog_type == BPF_PROG_TYPE_LSM &&
7446                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7447                         if (!env->prog->aux->attach_func_proto->type) {
7448                                 /* Make sure programs that attach to void
7449                                  * hooks don't try to modify return value.
7450                                  */
7451                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7452                                 return -EINVAL;
7453                         }
7454                 }
7455                 break;
7456         case BPF_FUNC_dynptr_data:
7457                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7458                         if (arg_type_is_dynptr(fn->arg_type[i])) {
7459                                 struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7460
7461                                 if (meta.ref_obj_id) {
7462                                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7463                                         return -EFAULT;
7464                                 }
7465
7466                                 if (base_type(reg->type) != PTR_TO_DYNPTR)
7467                                         /* Find the id of the dynptr we're
7468                                          * tracking the reference of
7469                                          */
7470                                         meta.ref_obj_id = stack_slot_get_id(env, reg);
7471                                 break;
7472                         }
7473                 }
7474                 if (i == MAX_BPF_FUNC_REG_ARGS) {
7475                         verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7476                         return -EFAULT;
7477                 }
7478                 break;
7479         case BPF_FUNC_user_ringbuf_drain:
7480                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7481                                         set_user_ringbuf_callback_state);
7482                 break;
7483         }
7484
7485         if (err)
7486                 return err;
7487
7488         /* reset caller saved regs */
7489         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7490                 mark_reg_not_init(env, regs, caller_saved[i]);
7491                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7492         }
7493
7494         /* helper call returns 64-bit value. */
7495         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7496
7497         /* update return register (already marked as written above) */
7498         ret_type = fn->ret_type;
7499         ret_flag = type_flag(ret_type);
7500
7501         switch (base_type(ret_type)) {
7502         case RET_INTEGER:
7503                 /* sets type to SCALAR_VALUE */
7504                 mark_reg_unknown(env, regs, BPF_REG_0);
7505                 break;
7506         case RET_VOID:
7507                 regs[BPF_REG_0].type = NOT_INIT;
7508                 break;
7509         case RET_PTR_TO_MAP_VALUE:
7510                 /* There is no offset yet applied, variable or fixed */
7511                 mark_reg_known_zero(env, regs, BPF_REG_0);
7512                 /* remember map_ptr, so that check_map_access()
7513                  * can check 'value_size' boundary of memory access
7514                  * to map element returned from bpf_map_lookup_elem()
7515                  */
7516                 if (meta.map_ptr == NULL) {
7517                         verbose(env,
7518                                 "kernel subsystem misconfigured verifier\n");
7519                         return -EINVAL;
7520                 }
7521                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7522                 regs[BPF_REG_0].map_uid = meta.map_uid;
7523                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7524                 if (!type_may_be_null(ret_type) &&
7525                     map_value_has_spin_lock(meta.map_ptr)) {
7526                         regs[BPF_REG_0].id = ++env->id_gen;
7527                 }
7528                 break;
7529         case RET_PTR_TO_SOCKET:
7530                 mark_reg_known_zero(env, regs, BPF_REG_0);
7531                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7532                 break;
7533         case RET_PTR_TO_SOCK_COMMON:
7534                 mark_reg_known_zero(env, regs, BPF_REG_0);
7535                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7536                 break;
7537         case RET_PTR_TO_TCP_SOCK:
7538                 mark_reg_known_zero(env, regs, BPF_REG_0);
7539                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7540                 break;
7541         case RET_PTR_TO_ALLOC_MEM:
7542                 mark_reg_known_zero(env, regs, BPF_REG_0);
7543                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7544                 regs[BPF_REG_0].mem_size = meta.mem_size;
7545                 break;
7546         case RET_PTR_TO_MEM_OR_BTF_ID:
7547         {
7548                 const struct btf_type *t;
7549
7550                 mark_reg_known_zero(env, regs, BPF_REG_0);
7551                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7552                 if (!btf_type_is_struct(t)) {
7553                         u32 tsize;
7554                         const struct btf_type *ret;
7555                         const char *tname;
7556
7557                         /* resolve the type size of ksym. */
7558                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7559                         if (IS_ERR(ret)) {
7560                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7561                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7562                                         tname, PTR_ERR(ret));
7563                                 return -EINVAL;
7564                         }
7565                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7566                         regs[BPF_REG_0].mem_size = tsize;
7567                 } else {
7568                         /* MEM_RDONLY may be carried from ret_flag, but it
7569                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7570                          * it will confuse the check of PTR_TO_BTF_ID in
7571                          * check_mem_access().
7572                          */
7573                         ret_flag &= ~MEM_RDONLY;
7574
7575                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7576                         regs[BPF_REG_0].btf = meta.ret_btf;
7577                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7578                 }
7579                 break;
7580         }
7581         case RET_PTR_TO_BTF_ID:
7582         {
7583                 struct btf *ret_btf;
7584                 int ret_btf_id;
7585
7586                 mark_reg_known_zero(env, regs, BPF_REG_0);
7587                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7588                 if (func_id == BPF_FUNC_kptr_xchg) {
7589                         ret_btf = meta.kptr_off_desc->kptr.btf;
7590                         ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7591                 } else {
7592                         if (fn->ret_btf_id == BPF_PTR_POISON) {
7593                                 verbose(env, "verifier internal error:");
7594                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7595                                         func_id_name(func_id));
7596                                 return -EINVAL;
7597                         }
7598                         ret_btf = btf_vmlinux;
7599                         ret_btf_id = *fn->ret_btf_id;
7600                 }
7601                 if (ret_btf_id == 0) {
7602                         verbose(env, "invalid return type %u of func %s#%d\n",
7603                                 base_type(ret_type), func_id_name(func_id),
7604                                 func_id);
7605                         return -EINVAL;
7606                 }
7607                 regs[BPF_REG_0].btf = ret_btf;
7608                 regs[BPF_REG_0].btf_id = ret_btf_id;
7609                 break;
7610         }
7611         default:
7612                 verbose(env, "unknown return type %u of func %s#%d\n",
7613                         base_type(ret_type), func_id_name(func_id), func_id);
7614                 return -EINVAL;
7615         }
7616
7617         if (type_may_be_null(regs[BPF_REG_0].type))
7618                 regs[BPF_REG_0].id = ++env->id_gen;
7619
7620         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7621                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7622                         func_id_name(func_id), func_id);
7623                 return -EFAULT;
7624         }
7625
7626         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7627                 /* For release_reference() */
7628                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7629         } else if (is_acquire_function(func_id, meta.map_ptr)) {
7630                 int id = acquire_reference_state(env, insn_idx);
7631
7632                 if (id < 0)
7633                         return id;
7634                 /* For mark_ptr_or_null_reg() */
7635                 regs[BPF_REG_0].id = id;
7636                 /* For release_reference() */
7637                 regs[BPF_REG_0].ref_obj_id = id;
7638         }
7639
7640         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7641
7642         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7643         if (err)
7644                 return err;
7645
7646         if ((func_id == BPF_FUNC_get_stack ||
7647              func_id == BPF_FUNC_get_task_stack) &&
7648             !env->prog->has_callchain_buf) {
7649                 const char *err_str;
7650
7651 #ifdef CONFIG_PERF_EVENTS
7652                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7653                 err_str = "cannot get callchain buffer for func %s#%d\n";
7654 #else
7655                 err = -ENOTSUPP;
7656                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7657 #endif
7658                 if (err) {
7659                         verbose(env, err_str, func_id_name(func_id), func_id);
7660                         return err;
7661                 }
7662
7663                 env->prog->has_callchain_buf = true;
7664         }
7665
7666         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7667                 env->prog->call_get_stack = true;
7668
7669         if (func_id == BPF_FUNC_get_func_ip) {
7670                 if (check_get_func_ip(env))
7671                         return -ENOTSUPP;
7672                 env->prog->call_get_func_ip = true;
7673         }
7674
7675         if (changes_data)
7676                 clear_all_pkt_pointers(env);
7677         return 0;
7678 }
7679
7680 /* mark_btf_func_reg_size() is used when the reg size is determined by
7681  * the BTF func_proto's return value size and argument.
7682  */
7683 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7684                                    size_t reg_size)
7685 {
7686         struct bpf_reg_state *reg = &cur_regs(env)[regno];
7687
7688         if (regno == BPF_REG_0) {
7689                 /* Function return value */
7690                 reg->live |= REG_LIVE_WRITTEN;
7691                 reg->subreg_def = reg_size == sizeof(u64) ?
7692                         DEF_NOT_SUBREG : env->insn_idx + 1;
7693         } else {
7694                 /* Function argument */
7695                 if (reg_size == sizeof(u64)) {
7696                         mark_insn_zext(env, reg);
7697                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7698                 } else {
7699                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7700                 }
7701         }
7702 }
7703
7704 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7705                             int *insn_idx_p)
7706 {
7707         const struct btf_type *t, *func, *func_proto, *ptr_type;
7708         struct bpf_reg_state *regs = cur_regs(env);
7709         struct bpf_kfunc_arg_meta meta = { 0 };
7710         const char *func_name, *ptr_type_name;
7711         u32 i, nargs, func_id, ptr_type_id;
7712         int err, insn_idx = *insn_idx_p;
7713         const struct btf_param *args;
7714         struct btf *desc_btf;
7715         u32 *kfunc_flags;
7716         bool acq;
7717
7718         /* skip for now, but return error when we find this in fixup_kfunc_call */
7719         if (!insn->imm)
7720                 return 0;
7721
7722         desc_btf = find_kfunc_desc_btf(env, insn->off);
7723         if (IS_ERR(desc_btf))
7724                 return PTR_ERR(desc_btf);
7725
7726         func_id = insn->imm;
7727         func = btf_type_by_id(desc_btf, func_id);
7728         func_name = btf_name_by_offset(desc_btf, func->name_off);
7729         func_proto = btf_type_by_id(desc_btf, func->type);
7730
7731         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7732         if (!kfunc_flags) {
7733                 verbose(env, "calling kernel function %s is not allowed\n",
7734                         func_name);
7735                 return -EACCES;
7736         }
7737         if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7738                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7739                 return -EACCES;
7740         }
7741
7742         acq = *kfunc_flags & KF_ACQUIRE;
7743
7744         meta.flags = *kfunc_flags;
7745
7746         /* Check the arguments */
7747         err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7748         if (err < 0)
7749                 return err;
7750         /* In case of release function, we get register number of refcounted
7751          * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7752          */
7753         if (err) {
7754                 err = release_reference(env, regs[err].ref_obj_id);
7755                 if (err) {
7756                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7757                                 func_name, func_id);
7758                         return err;
7759                 }
7760         }
7761
7762         for (i = 0; i < CALLER_SAVED_REGS; i++)
7763                 mark_reg_not_init(env, regs, caller_saved[i]);
7764
7765         /* Check return type */
7766         t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7767
7768         if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7769                 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7770                 return -EINVAL;
7771         }
7772
7773         if (btf_type_is_scalar(t)) {
7774                 mark_reg_unknown(env, regs, BPF_REG_0);
7775                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7776         } else if (btf_type_is_ptr(t)) {
7777                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7778                                                    &ptr_type_id);
7779                 if (!btf_type_is_struct(ptr_type)) {
7780                         if (!meta.r0_size) {
7781                                 ptr_type_name = btf_name_by_offset(desc_btf,
7782                                                                    ptr_type->name_off);
7783                                 verbose(env,
7784                                         "kernel function %s returns pointer type %s %s is not supported\n",
7785                                         func_name,
7786                                         btf_type_str(ptr_type),
7787                                         ptr_type_name);
7788                                 return -EINVAL;
7789                         }
7790
7791                         mark_reg_known_zero(env, regs, BPF_REG_0);
7792                         regs[BPF_REG_0].type = PTR_TO_MEM;
7793                         regs[BPF_REG_0].mem_size = meta.r0_size;
7794
7795                         if (meta.r0_rdonly)
7796                                 regs[BPF_REG_0].type |= MEM_RDONLY;
7797
7798                         /* Ensures we don't access the memory after a release_reference() */
7799                         if (meta.ref_obj_id)
7800                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7801                 } else {
7802                         mark_reg_known_zero(env, regs, BPF_REG_0);
7803                         regs[BPF_REG_0].btf = desc_btf;
7804                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7805                         regs[BPF_REG_0].btf_id = ptr_type_id;
7806                 }
7807                 if (*kfunc_flags & KF_RET_NULL) {
7808                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7809                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7810                         regs[BPF_REG_0].id = ++env->id_gen;
7811                 }
7812                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7813                 if (acq) {
7814                         int id = acquire_reference_state(env, insn_idx);
7815
7816                         if (id < 0)
7817                                 return id;
7818                         regs[BPF_REG_0].id = id;
7819                         regs[BPF_REG_0].ref_obj_id = id;
7820                 }
7821         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7822
7823         nargs = btf_type_vlen(func_proto);
7824         args = (const struct btf_param *)(func_proto + 1);
7825         for (i = 0; i < nargs; i++) {
7826                 u32 regno = i + 1;
7827
7828                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7829                 if (btf_type_is_ptr(t))
7830                         mark_btf_func_reg_size(env, regno, sizeof(void *));
7831                 else
7832                         /* scalar. ensured by btf_check_kfunc_arg_match() */
7833                         mark_btf_func_reg_size(env, regno, t->size);
7834         }
7835
7836         return 0;
7837 }
7838
7839 static bool signed_add_overflows(s64 a, s64 b)
7840 {
7841         /* Do the add in u64, where overflow is well-defined */
7842         s64 res = (s64)((u64)a + (u64)b);
7843
7844         if (b < 0)
7845                 return res > a;
7846         return res < a;
7847 }
7848
7849 static bool signed_add32_overflows(s32 a, s32 b)
7850 {
7851         /* Do the add in u32, where overflow is well-defined */
7852         s32 res = (s32)((u32)a + (u32)b);
7853
7854         if (b < 0)
7855                 return res > a;
7856         return res < a;
7857 }
7858
7859 static bool signed_sub_overflows(s64 a, s64 b)
7860 {
7861         /* Do the sub in u64, where overflow is well-defined */
7862         s64 res = (s64)((u64)a - (u64)b);
7863
7864         if (b < 0)
7865                 return res < a;
7866         return res > a;
7867 }
7868
7869 static bool signed_sub32_overflows(s32 a, s32 b)
7870 {
7871         /* Do the sub in u32, where overflow is well-defined */
7872         s32 res = (s32)((u32)a - (u32)b);
7873
7874         if (b < 0)
7875                 return res < a;
7876         return res > a;
7877 }
7878
7879 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7880                                   const struct bpf_reg_state *reg,
7881                                   enum bpf_reg_type type)
7882 {
7883         bool known = tnum_is_const(reg->var_off);
7884         s64 val = reg->var_off.value;
7885         s64 smin = reg->smin_value;
7886
7887         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7888                 verbose(env, "math between %s pointer and %lld is not allowed\n",
7889                         reg_type_str(env, type), val);
7890                 return false;
7891         }
7892
7893         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7894                 verbose(env, "%s pointer offset %d is not allowed\n",
7895                         reg_type_str(env, type), reg->off);
7896                 return false;
7897         }
7898
7899         if (smin == S64_MIN) {
7900                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7901                         reg_type_str(env, type));
7902                 return false;
7903         }
7904
7905         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7906                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7907                         smin, reg_type_str(env, type));
7908                 return false;
7909         }
7910
7911         return true;
7912 }
7913
7914 enum {
7915         REASON_BOUNDS   = -1,
7916         REASON_TYPE     = -2,
7917         REASON_PATHS    = -3,
7918         REASON_LIMIT    = -4,
7919         REASON_STACK    = -5,
7920 };
7921
7922 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7923                               u32 *alu_limit, bool mask_to_left)
7924 {
7925         u32 max = 0, ptr_limit = 0;
7926
7927         switch (ptr_reg->type) {
7928         case PTR_TO_STACK:
7929                 /* Offset 0 is out-of-bounds, but acceptable start for the
7930                  * left direction, see BPF_REG_FP. Also, unknown scalar
7931                  * offset where we would need to deal with min/max bounds is
7932                  * currently prohibited for unprivileged.
7933                  */
7934                 max = MAX_BPF_STACK + mask_to_left;
7935                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7936                 break;
7937         case PTR_TO_MAP_VALUE:
7938                 max = ptr_reg->map_ptr->value_size;
7939                 ptr_limit = (mask_to_left ?
7940                              ptr_reg->smin_value :
7941                              ptr_reg->umax_value) + ptr_reg->off;
7942                 break;
7943         default:
7944                 return REASON_TYPE;
7945         }
7946
7947         if (ptr_limit >= max)
7948                 return REASON_LIMIT;
7949         *alu_limit = ptr_limit;
7950         return 0;
7951 }
7952
7953 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7954                                     const struct bpf_insn *insn)
7955 {
7956         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7957 }
7958
7959 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7960                                        u32 alu_state, u32 alu_limit)
7961 {
7962         /* If we arrived here from different branches with different
7963          * state or limits to sanitize, then this won't work.
7964          */
7965         if (aux->alu_state &&
7966             (aux->alu_state != alu_state ||
7967              aux->alu_limit != alu_limit))
7968                 return REASON_PATHS;
7969
7970         /* Corresponding fixup done in do_misc_fixups(). */
7971         aux->alu_state = alu_state;
7972         aux->alu_limit = alu_limit;
7973         return 0;
7974 }
7975
7976 static int sanitize_val_alu(struct bpf_verifier_env *env,
7977                             struct bpf_insn *insn)
7978 {
7979         struct bpf_insn_aux_data *aux = cur_aux(env);
7980
7981         if (can_skip_alu_sanitation(env, insn))
7982                 return 0;
7983
7984         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7985 }
7986
7987 static bool sanitize_needed(u8 opcode)
7988 {
7989         return opcode == BPF_ADD || opcode == BPF_SUB;
7990 }
7991
7992 struct bpf_sanitize_info {
7993         struct bpf_insn_aux_data aux;
7994         bool mask_to_left;
7995 };
7996
7997 static struct bpf_verifier_state *
7998 sanitize_speculative_path(struct bpf_verifier_env *env,
7999                           const struct bpf_insn *insn,
8000                           u32 next_idx, u32 curr_idx)
8001 {
8002         struct bpf_verifier_state *branch;
8003         struct bpf_reg_state *regs;
8004
8005         branch = push_stack(env, next_idx, curr_idx, true);
8006         if (branch && insn) {
8007                 regs = branch->frame[branch->curframe]->regs;
8008                 if (BPF_SRC(insn->code) == BPF_K) {
8009                         mark_reg_unknown(env, regs, insn->dst_reg);
8010                 } else if (BPF_SRC(insn->code) == BPF_X) {
8011                         mark_reg_unknown(env, regs, insn->dst_reg);
8012                         mark_reg_unknown(env, regs, insn->src_reg);
8013                 }
8014         }
8015         return branch;
8016 }
8017
8018 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8019                             struct bpf_insn *insn,
8020                             const struct bpf_reg_state *ptr_reg,
8021                             const struct bpf_reg_state *off_reg,
8022                             struct bpf_reg_state *dst_reg,
8023                             struct bpf_sanitize_info *info,
8024                             const bool commit_window)
8025 {
8026         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8027         struct bpf_verifier_state *vstate = env->cur_state;
8028         bool off_is_imm = tnum_is_const(off_reg->var_off);
8029         bool off_is_neg = off_reg->smin_value < 0;
8030         bool ptr_is_dst_reg = ptr_reg == dst_reg;
8031         u8 opcode = BPF_OP(insn->code);
8032         u32 alu_state, alu_limit;
8033         struct bpf_reg_state tmp;
8034         bool ret;
8035         int err;
8036
8037         if (can_skip_alu_sanitation(env, insn))
8038                 return 0;
8039
8040         /* We already marked aux for masking from non-speculative
8041          * paths, thus we got here in the first place. We only care
8042          * to explore bad access from here.
8043          */
8044         if (vstate->speculative)
8045                 goto do_sim;
8046
8047         if (!commit_window) {
8048                 if (!tnum_is_const(off_reg->var_off) &&
8049                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8050                         return REASON_BOUNDS;
8051
8052                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
8053                                      (opcode == BPF_SUB && !off_is_neg);
8054         }
8055
8056         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8057         if (err < 0)
8058                 return err;
8059
8060         if (commit_window) {
8061                 /* In commit phase we narrow the masking window based on
8062                  * the observed pointer move after the simulated operation.
8063                  */
8064                 alu_state = info->aux.alu_state;
8065                 alu_limit = abs(info->aux.alu_limit - alu_limit);
8066         } else {
8067                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8068                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8069                 alu_state |= ptr_is_dst_reg ?
8070                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8071
8072                 /* Limit pruning on unknown scalars to enable deep search for
8073                  * potential masking differences from other program paths.
8074                  */
8075                 if (!off_is_imm)
8076                         env->explore_alu_limits = true;
8077         }
8078
8079         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8080         if (err < 0)
8081                 return err;
8082 do_sim:
8083         /* If we're in commit phase, we're done here given we already
8084          * pushed the truncated dst_reg into the speculative verification
8085          * stack.
8086          *
8087          * Also, when register is a known constant, we rewrite register-based
8088          * operation to immediate-based, and thus do not need masking (and as
8089          * a consequence, do not need to simulate the zero-truncation either).
8090          */
8091         if (commit_window || off_is_imm)
8092                 return 0;
8093
8094         /* Simulate and find potential out-of-bounds access under
8095          * speculative execution from truncation as a result of
8096          * masking when off was not within expected range. If off
8097          * sits in dst, then we temporarily need to move ptr there
8098          * to simulate dst (== 0) +/-= ptr. Needed, for example,
8099          * for cases where we use K-based arithmetic in one direction
8100          * and truncated reg-based in the other in order to explore
8101          * bad access.
8102          */
8103         if (!ptr_is_dst_reg) {
8104                 tmp = *dst_reg;
8105                 copy_register_state(dst_reg, ptr_reg);
8106         }
8107         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8108                                         env->insn_idx);
8109         if (!ptr_is_dst_reg && ret)
8110                 *dst_reg = tmp;
8111         return !ret ? REASON_STACK : 0;
8112 }
8113
8114 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8115 {
8116         struct bpf_verifier_state *vstate = env->cur_state;
8117
8118         /* If we simulate paths under speculation, we don't update the
8119          * insn as 'seen' such that when we verify unreachable paths in
8120          * the non-speculative domain, sanitize_dead_code() can still
8121          * rewrite/sanitize them.
8122          */
8123         if (!vstate->speculative)
8124                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8125 }
8126
8127 static int sanitize_err(struct bpf_verifier_env *env,
8128                         const struct bpf_insn *insn, int reason,
8129                         const struct bpf_reg_state *off_reg,
8130                         const struct bpf_reg_state *dst_reg)
8131 {
8132         static const char *err = "pointer arithmetic with it prohibited for !root";
8133         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8134         u32 dst = insn->dst_reg, src = insn->src_reg;
8135
8136         switch (reason) {
8137         case REASON_BOUNDS:
8138                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8139                         off_reg == dst_reg ? dst : src, err);
8140                 break;
8141         case REASON_TYPE:
8142                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8143                         off_reg == dst_reg ? src : dst, err);
8144                 break;
8145         case REASON_PATHS:
8146                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8147                         dst, op, err);
8148                 break;
8149         case REASON_LIMIT:
8150                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8151                         dst, op, err);
8152                 break;
8153         case REASON_STACK:
8154                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8155                         dst, err);
8156                 break;
8157         default:
8158                 verbose(env, "verifier internal error: unknown reason (%d)\n",
8159                         reason);
8160                 break;
8161         }
8162
8163         return -EACCES;
8164 }
8165
8166 /* check that stack access falls within stack limits and that 'reg' doesn't
8167  * have a variable offset.
8168  *
8169  * Variable offset is prohibited for unprivileged mode for simplicity since it
8170  * requires corresponding support in Spectre masking for stack ALU.  See also
8171  * retrieve_ptr_limit().
8172  *
8173  *
8174  * 'off' includes 'reg->off'.
8175  */
8176 static int check_stack_access_for_ptr_arithmetic(
8177                                 struct bpf_verifier_env *env,
8178                                 int regno,
8179                                 const struct bpf_reg_state *reg,
8180                                 int off)
8181 {
8182         if (!tnum_is_const(reg->var_off)) {
8183                 char tn_buf[48];
8184
8185                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8186                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8187                         regno, tn_buf, off);
8188                 return -EACCES;
8189         }
8190
8191         if (off >= 0 || off < -MAX_BPF_STACK) {
8192                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8193                         "prohibited for !root; off=%d\n", regno, off);
8194                 return -EACCES;
8195         }
8196
8197         return 0;
8198 }
8199
8200 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8201                                  const struct bpf_insn *insn,
8202                                  const struct bpf_reg_state *dst_reg)
8203 {
8204         u32 dst = insn->dst_reg;
8205
8206         /* For unprivileged we require that resulting offset must be in bounds
8207          * in order to be able to sanitize access later on.
8208          */
8209         if (env->bypass_spec_v1)
8210                 return 0;
8211
8212         switch (dst_reg->type) {
8213         case PTR_TO_STACK:
8214                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8215                                         dst_reg->off + dst_reg->var_off.value))
8216                         return -EACCES;
8217                 break;
8218         case PTR_TO_MAP_VALUE:
8219                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8220                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8221                                 "prohibited for !root\n", dst);
8222                         return -EACCES;
8223                 }
8224                 break;
8225         default:
8226                 break;
8227         }
8228
8229         return 0;
8230 }
8231
8232 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8233  * Caller should also handle BPF_MOV case separately.
8234  * If we return -EACCES, caller may want to try again treating pointer as a
8235  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8236  */
8237 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8238                                    struct bpf_insn *insn,
8239                                    const struct bpf_reg_state *ptr_reg,
8240                                    const struct bpf_reg_state *off_reg)
8241 {
8242         struct bpf_verifier_state *vstate = env->cur_state;
8243         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8244         struct bpf_reg_state *regs = state->regs, *dst_reg;
8245         bool known = tnum_is_const(off_reg->var_off);
8246         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8247             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8248         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8249             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8250         struct bpf_sanitize_info info = {};
8251         u8 opcode = BPF_OP(insn->code);
8252         u32 dst = insn->dst_reg;
8253         int ret;
8254
8255         dst_reg = &regs[dst];
8256
8257         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8258             smin_val > smax_val || umin_val > umax_val) {
8259                 /* Taint dst register if offset had invalid bounds derived from
8260                  * e.g. dead branches.
8261                  */
8262                 __mark_reg_unknown(env, dst_reg);
8263                 return 0;
8264         }
8265
8266         if (BPF_CLASS(insn->code) != BPF_ALU64) {
8267                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8268                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8269                         __mark_reg_unknown(env, dst_reg);
8270                         return 0;
8271                 }
8272
8273                 verbose(env,
8274                         "R%d 32-bit pointer arithmetic prohibited\n",
8275                         dst);
8276                 return -EACCES;
8277         }
8278
8279         if (ptr_reg->type & PTR_MAYBE_NULL) {
8280                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8281                         dst, reg_type_str(env, ptr_reg->type));
8282                 return -EACCES;
8283         }
8284
8285         switch (base_type(ptr_reg->type)) {
8286         case CONST_PTR_TO_MAP:
8287                 /* smin_val represents the known value */
8288                 if (known && smin_val == 0 && opcode == BPF_ADD)
8289                         break;
8290                 fallthrough;
8291         case PTR_TO_PACKET_END:
8292         case PTR_TO_SOCKET:
8293         case PTR_TO_SOCK_COMMON:
8294         case PTR_TO_TCP_SOCK:
8295         case PTR_TO_XDP_SOCK:
8296                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8297                         dst, reg_type_str(env, ptr_reg->type));
8298                 return -EACCES;
8299         default:
8300                 break;
8301         }
8302
8303         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8304          * The id may be overwritten later if we create a new variable offset.
8305          */
8306         dst_reg->type = ptr_reg->type;
8307         dst_reg->id = ptr_reg->id;
8308
8309         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8310             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8311                 return -EINVAL;
8312
8313         /* pointer types do not carry 32-bit bounds at the moment. */
8314         __mark_reg32_unbounded(dst_reg);
8315
8316         if (sanitize_needed(opcode)) {
8317                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8318                                        &info, false);
8319                 if (ret < 0)
8320                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8321         }
8322
8323         switch (opcode) {
8324         case BPF_ADD:
8325                 /* We can take a fixed offset as long as it doesn't overflow
8326                  * the s32 'off' field
8327                  */
8328                 if (known && (ptr_reg->off + smin_val ==
8329                               (s64)(s32)(ptr_reg->off + smin_val))) {
8330                         /* pointer += K.  Accumulate it into fixed offset */
8331                         dst_reg->smin_value = smin_ptr;
8332                         dst_reg->smax_value = smax_ptr;
8333                         dst_reg->umin_value = umin_ptr;
8334                         dst_reg->umax_value = umax_ptr;
8335                         dst_reg->var_off = ptr_reg->var_off;
8336                         dst_reg->off = ptr_reg->off + smin_val;
8337                         dst_reg->raw = ptr_reg->raw;
8338                         break;
8339                 }
8340                 /* A new variable offset is created.  Note that off_reg->off
8341                  * == 0, since it's a scalar.
8342                  * dst_reg gets the pointer type and since some positive
8343                  * integer value was added to the pointer, give it a new 'id'
8344                  * if it's a PTR_TO_PACKET.
8345                  * this creates a new 'base' pointer, off_reg (variable) gets
8346                  * added into the variable offset, and we copy the fixed offset
8347                  * from ptr_reg.
8348                  */
8349                 if (signed_add_overflows(smin_ptr, smin_val) ||
8350                     signed_add_overflows(smax_ptr, smax_val)) {
8351                         dst_reg->smin_value = S64_MIN;
8352                         dst_reg->smax_value = S64_MAX;
8353                 } else {
8354                         dst_reg->smin_value = smin_ptr + smin_val;
8355                         dst_reg->smax_value = smax_ptr + smax_val;
8356                 }
8357                 if (umin_ptr + umin_val < umin_ptr ||
8358                     umax_ptr + umax_val < umax_ptr) {
8359                         dst_reg->umin_value = 0;
8360                         dst_reg->umax_value = U64_MAX;
8361                 } else {
8362                         dst_reg->umin_value = umin_ptr + umin_val;
8363                         dst_reg->umax_value = umax_ptr + umax_val;
8364                 }
8365                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8366                 dst_reg->off = ptr_reg->off;
8367                 dst_reg->raw = ptr_reg->raw;
8368                 if (reg_is_pkt_pointer(ptr_reg)) {
8369                         dst_reg->id = ++env->id_gen;
8370                         /* something was added to pkt_ptr, set range to zero */
8371                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8372                 }
8373                 break;
8374         case BPF_SUB:
8375                 if (dst_reg == off_reg) {
8376                         /* scalar -= pointer.  Creates an unknown scalar */
8377                         verbose(env, "R%d tried to subtract pointer from scalar\n",
8378                                 dst);
8379                         return -EACCES;
8380                 }
8381                 /* We don't allow subtraction from FP, because (according to
8382                  * test_verifier.c test "invalid fp arithmetic", JITs might not
8383                  * be able to deal with it.
8384                  */
8385                 if (ptr_reg->type == PTR_TO_STACK) {
8386                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
8387                                 dst);
8388                         return -EACCES;
8389                 }
8390                 if (known && (ptr_reg->off - smin_val ==
8391                               (s64)(s32)(ptr_reg->off - smin_val))) {
8392                         /* pointer -= K.  Subtract it from fixed offset */
8393                         dst_reg->smin_value = smin_ptr;
8394                         dst_reg->smax_value = smax_ptr;
8395                         dst_reg->umin_value = umin_ptr;
8396                         dst_reg->umax_value = umax_ptr;
8397                         dst_reg->var_off = ptr_reg->var_off;
8398                         dst_reg->id = ptr_reg->id;
8399                         dst_reg->off = ptr_reg->off - smin_val;
8400                         dst_reg->raw = ptr_reg->raw;
8401                         break;
8402                 }
8403                 /* A new variable offset is created.  If the subtrahend is known
8404                  * nonnegative, then any reg->range we had before is still good.
8405                  */
8406                 if (signed_sub_overflows(smin_ptr, smax_val) ||
8407                     signed_sub_overflows(smax_ptr, smin_val)) {
8408                         /* Overflow possible, we know nothing */
8409                         dst_reg->smin_value = S64_MIN;
8410                         dst_reg->smax_value = S64_MAX;
8411                 } else {
8412                         dst_reg->smin_value = smin_ptr - smax_val;
8413                         dst_reg->smax_value = smax_ptr - smin_val;
8414                 }
8415                 if (umin_ptr < umax_val) {
8416                         /* Overflow possible, we know nothing */
8417                         dst_reg->umin_value = 0;
8418                         dst_reg->umax_value = U64_MAX;
8419                 } else {
8420                         /* Cannot overflow (as long as bounds are consistent) */
8421                         dst_reg->umin_value = umin_ptr - umax_val;
8422                         dst_reg->umax_value = umax_ptr - umin_val;
8423                 }
8424                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8425                 dst_reg->off = ptr_reg->off;
8426                 dst_reg->raw = ptr_reg->raw;
8427                 if (reg_is_pkt_pointer(ptr_reg)) {
8428                         dst_reg->id = ++env->id_gen;
8429                         /* something was added to pkt_ptr, set range to zero */
8430                         if (smin_val < 0)
8431                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8432                 }
8433                 break;
8434         case BPF_AND:
8435         case BPF_OR:
8436         case BPF_XOR:
8437                 /* bitwise ops on pointers are troublesome, prohibit. */
8438                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8439                         dst, bpf_alu_string[opcode >> 4]);
8440                 return -EACCES;
8441         default:
8442                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8443                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8444                         dst, bpf_alu_string[opcode >> 4]);
8445                 return -EACCES;
8446         }
8447
8448         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8449                 return -EINVAL;
8450         reg_bounds_sync(dst_reg);
8451         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8452                 return -EACCES;
8453         if (sanitize_needed(opcode)) {
8454                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8455                                        &info, true);
8456                 if (ret < 0)
8457                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8458         }
8459
8460         return 0;
8461 }
8462
8463 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8464                                  struct bpf_reg_state *src_reg)
8465 {
8466         s32 smin_val = src_reg->s32_min_value;
8467         s32 smax_val = src_reg->s32_max_value;
8468         u32 umin_val = src_reg->u32_min_value;
8469         u32 umax_val = src_reg->u32_max_value;
8470
8471         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8472             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8473                 dst_reg->s32_min_value = S32_MIN;
8474                 dst_reg->s32_max_value = S32_MAX;
8475         } else {
8476                 dst_reg->s32_min_value += smin_val;
8477                 dst_reg->s32_max_value += smax_val;
8478         }
8479         if (dst_reg->u32_min_value + umin_val < umin_val ||
8480             dst_reg->u32_max_value + umax_val < umax_val) {
8481                 dst_reg->u32_min_value = 0;
8482                 dst_reg->u32_max_value = U32_MAX;
8483         } else {
8484                 dst_reg->u32_min_value += umin_val;
8485                 dst_reg->u32_max_value += umax_val;
8486         }
8487 }
8488
8489 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8490                                struct bpf_reg_state *src_reg)
8491 {
8492         s64 smin_val = src_reg->smin_value;
8493         s64 smax_val = src_reg->smax_value;
8494         u64 umin_val = src_reg->umin_value;
8495         u64 umax_val = src_reg->umax_value;
8496
8497         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8498             signed_add_overflows(dst_reg->smax_value, smax_val)) {
8499                 dst_reg->smin_value = S64_MIN;
8500                 dst_reg->smax_value = S64_MAX;
8501         } else {
8502                 dst_reg->smin_value += smin_val;
8503                 dst_reg->smax_value += smax_val;
8504         }
8505         if (dst_reg->umin_value + umin_val < umin_val ||
8506             dst_reg->umax_value + umax_val < umax_val) {
8507                 dst_reg->umin_value = 0;
8508                 dst_reg->umax_value = U64_MAX;
8509         } else {
8510                 dst_reg->umin_value += umin_val;
8511                 dst_reg->umax_value += umax_val;
8512         }
8513 }
8514
8515 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8516                                  struct bpf_reg_state *src_reg)
8517 {
8518         s32 smin_val = src_reg->s32_min_value;
8519         s32 smax_val = src_reg->s32_max_value;
8520         u32 umin_val = src_reg->u32_min_value;
8521         u32 umax_val = src_reg->u32_max_value;
8522
8523         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8524             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8525                 /* Overflow possible, we know nothing */
8526                 dst_reg->s32_min_value = S32_MIN;
8527                 dst_reg->s32_max_value = S32_MAX;
8528         } else {
8529                 dst_reg->s32_min_value -= smax_val;
8530                 dst_reg->s32_max_value -= smin_val;
8531         }
8532         if (dst_reg->u32_min_value < umax_val) {
8533                 /* Overflow possible, we know nothing */
8534                 dst_reg->u32_min_value = 0;
8535                 dst_reg->u32_max_value = U32_MAX;
8536         } else {
8537                 /* Cannot overflow (as long as bounds are consistent) */
8538                 dst_reg->u32_min_value -= umax_val;
8539                 dst_reg->u32_max_value -= umin_val;
8540         }
8541 }
8542
8543 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8544                                struct bpf_reg_state *src_reg)
8545 {
8546         s64 smin_val = src_reg->smin_value;
8547         s64 smax_val = src_reg->smax_value;
8548         u64 umin_val = src_reg->umin_value;
8549         u64 umax_val = src_reg->umax_value;
8550
8551         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8552             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8553                 /* Overflow possible, we know nothing */
8554                 dst_reg->smin_value = S64_MIN;
8555                 dst_reg->smax_value = S64_MAX;
8556         } else {
8557                 dst_reg->smin_value -= smax_val;
8558                 dst_reg->smax_value -= smin_val;
8559         }
8560         if (dst_reg->umin_value < umax_val) {
8561                 /* Overflow possible, we know nothing */
8562                 dst_reg->umin_value = 0;
8563                 dst_reg->umax_value = U64_MAX;
8564         } else {
8565                 /* Cannot overflow (as long as bounds are consistent) */
8566                 dst_reg->umin_value -= umax_val;
8567                 dst_reg->umax_value -= umin_val;
8568         }
8569 }
8570
8571 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8572                                  struct bpf_reg_state *src_reg)
8573 {
8574         s32 smin_val = src_reg->s32_min_value;
8575         u32 umin_val = src_reg->u32_min_value;
8576         u32 umax_val = src_reg->u32_max_value;
8577
8578         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8579                 /* Ain't nobody got time to multiply that sign */
8580                 __mark_reg32_unbounded(dst_reg);
8581                 return;
8582         }
8583         /* Both values are positive, so we can work with unsigned and
8584          * copy the result to signed (unless it exceeds S32_MAX).
8585          */
8586         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8587                 /* Potential overflow, we know nothing */
8588                 __mark_reg32_unbounded(dst_reg);
8589                 return;
8590         }
8591         dst_reg->u32_min_value *= umin_val;
8592         dst_reg->u32_max_value *= umax_val;
8593         if (dst_reg->u32_max_value > S32_MAX) {
8594                 /* Overflow possible, we know nothing */
8595                 dst_reg->s32_min_value = S32_MIN;
8596                 dst_reg->s32_max_value = S32_MAX;
8597         } else {
8598                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8599                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8600         }
8601 }
8602
8603 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8604                                struct bpf_reg_state *src_reg)
8605 {
8606         s64 smin_val = src_reg->smin_value;
8607         u64 umin_val = src_reg->umin_value;
8608         u64 umax_val = src_reg->umax_value;
8609
8610         if (smin_val < 0 || dst_reg->smin_value < 0) {
8611                 /* Ain't nobody got time to multiply that sign */
8612                 __mark_reg64_unbounded(dst_reg);
8613                 return;
8614         }
8615         /* Both values are positive, so we can work with unsigned and
8616          * copy the result to signed (unless it exceeds S64_MAX).
8617          */
8618         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8619                 /* Potential overflow, we know nothing */
8620                 __mark_reg64_unbounded(dst_reg);
8621                 return;
8622         }
8623         dst_reg->umin_value *= umin_val;
8624         dst_reg->umax_value *= umax_val;
8625         if (dst_reg->umax_value > S64_MAX) {
8626                 /* Overflow possible, we know nothing */
8627                 dst_reg->smin_value = S64_MIN;
8628                 dst_reg->smax_value = S64_MAX;
8629         } else {
8630                 dst_reg->smin_value = dst_reg->umin_value;
8631                 dst_reg->smax_value = dst_reg->umax_value;
8632         }
8633 }
8634
8635 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8636                                  struct bpf_reg_state *src_reg)
8637 {
8638         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8639         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8640         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8641         s32 smin_val = src_reg->s32_min_value;
8642         u32 umax_val = src_reg->u32_max_value;
8643
8644         if (src_known && dst_known) {
8645                 __mark_reg32_known(dst_reg, var32_off.value);
8646                 return;
8647         }
8648
8649         /* We get our minimum from the var_off, since that's inherently
8650          * bitwise.  Our maximum is the minimum of the operands' maxima.
8651          */
8652         dst_reg->u32_min_value = var32_off.value;
8653         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8654         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8655                 /* Lose signed bounds when ANDing negative numbers,
8656                  * ain't nobody got time for that.
8657                  */
8658                 dst_reg->s32_min_value = S32_MIN;
8659                 dst_reg->s32_max_value = S32_MAX;
8660         } else {
8661                 /* ANDing two positives gives a positive, so safe to
8662                  * cast result into s64.
8663                  */
8664                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8665                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8666         }
8667 }
8668
8669 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8670                                struct bpf_reg_state *src_reg)
8671 {
8672         bool src_known = tnum_is_const(src_reg->var_off);
8673         bool dst_known = tnum_is_const(dst_reg->var_off);
8674         s64 smin_val = src_reg->smin_value;
8675         u64 umax_val = src_reg->umax_value;
8676
8677         if (src_known && dst_known) {
8678                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8679                 return;
8680         }
8681
8682         /* We get our minimum from the var_off, since that's inherently
8683          * bitwise.  Our maximum is the minimum of the operands' maxima.
8684          */
8685         dst_reg->umin_value = dst_reg->var_off.value;
8686         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8687         if (dst_reg->smin_value < 0 || smin_val < 0) {
8688                 /* Lose signed bounds when ANDing negative numbers,
8689                  * ain't nobody got time for that.
8690                  */
8691                 dst_reg->smin_value = S64_MIN;
8692                 dst_reg->smax_value = S64_MAX;
8693         } else {
8694                 /* ANDing two positives gives a positive, so safe to
8695                  * cast result into s64.
8696                  */
8697                 dst_reg->smin_value = dst_reg->umin_value;
8698                 dst_reg->smax_value = dst_reg->umax_value;
8699         }
8700         /* We may learn something more from the var_off */
8701         __update_reg_bounds(dst_reg);
8702 }
8703
8704 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8705                                 struct bpf_reg_state *src_reg)
8706 {
8707         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8708         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8709         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8710         s32 smin_val = src_reg->s32_min_value;
8711         u32 umin_val = src_reg->u32_min_value;
8712
8713         if (src_known && dst_known) {
8714                 __mark_reg32_known(dst_reg, var32_off.value);
8715                 return;
8716         }
8717
8718         /* We get our maximum from the var_off, and our minimum is the
8719          * maximum of the operands' minima
8720          */
8721         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8722         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8723         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8724                 /* Lose signed bounds when ORing negative numbers,
8725                  * ain't nobody got time for that.
8726                  */
8727                 dst_reg->s32_min_value = S32_MIN;
8728                 dst_reg->s32_max_value = S32_MAX;
8729         } else {
8730                 /* ORing two positives gives a positive, so safe to
8731                  * cast result into s64.
8732                  */
8733                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8734                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8735         }
8736 }
8737
8738 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8739                               struct bpf_reg_state *src_reg)
8740 {
8741         bool src_known = tnum_is_const(src_reg->var_off);
8742         bool dst_known = tnum_is_const(dst_reg->var_off);
8743         s64 smin_val = src_reg->smin_value;
8744         u64 umin_val = src_reg->umin_value;
8745
8746         if (src_known && dst_known) {
8747                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8748                 return;
8749         }
8750
8751         /* We get our maximum from the var_off, and our minimum is the
8752          * maximum of the operands' minima
8753          */
8754         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8755         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8756         if (dst_reg->smin_value < 0 || smin_val < 0) {
8757                 /* Lose signed bounds when ORing negative numbers,
8758                  * ain't nobody got time for that.
8759                  */
8760                 dst_reg->smin_value = S64_MIN;
8761                 dst_reg->smax_value = S64_MAX;
8762         } else {
8763                 /* ORing two positives gives a positive, so safe to
8764                  * cast result into s64.
8765                  */
8766                 dst_reg->smin_value = dst_reg->umin_value;
8767                 dst_reg->smax_value = dst_reg->umax_value;
8768         }
8769         /* We may learn something more from the var_off */
8770         __update_reg_bounds(dst_reg);
8771 }
8772
8773 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8774                                  struct bpf_reg_state *src_reg)
8775 {
8776         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8777         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8778         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8779         s32 smin_val = src_reg->s32_min_value;
8780
8781         if (src_known && dst_known) {
8782                 __mark_reg32_known(dst_reg, var32_off.value);
8783                 return;
8784         }
8785
8786         /* We get both minimum and maximum from the var32_off. */
8787         dst_reg->u32_min_value = var32_off.value;
8788         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8789
8790         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8791                 /* XORing two positive sign numbers gives a positive,
8792                  * so safe to cast u32 result into s32.
8793                  */
8794                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8795                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8796         } else {
8797                 dst_reg->s32_min_value = S32_MIN;
8798                 dst_reg->s32_max_value = S32_MAX;
8799         }
8800 }
8801
8802 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8803                                struct bpf_reg_state *src_reg)
8804 {
8805         bool src_known = tnum_is_const(src_reg->var_off);
8806         bool dst_known = tnum_is_const(dst_reg->var_off);
8807         s64 smin_val = src_reg->smin_value;
8808
8809         if (src_known && dst_known) {
8810                 /* dst_reg->var_off.value has been updated earlier */
8811                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8812                 return;
8813         }
8814
8815         /* We get both minimum and maximum from the var_off. */
8816         dst_reg->umin_value = dst_reg->var_off.value;
8817         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8818
8819         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8820                 /* XORing two positive sign numbers gives a positive,
8821                  * so safe to cast u64 result into s64.
8822                  */
8823                 dst_reg->smin_value = dst_reg->umin_value;
8824                 dst_reg->smax_value = dst_reg->umax_value;
8825         } else {
8826                 dst_reg->smin_value = S64_MIN;
8827                 dst_reg->smax_value = S64_MAX;
8828         }
8829
8830         __update_reg_bounds(dst_reg);
8831 }
8832
8833 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8834                                    u64 umin_val, u64 umax_val)
8835 {
8836         /* We lose all sign bit information (except what we can pick
8837          * up from var_off)
8838          */
8839         dst_reg->s32_min_value = S32_MIN;
8840         dst_reg->s32_max_value = S32_MAX;
8841         /* If we might shift our top bit out, then we know nothing */
8842         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8843                 dst_reg->u32_min_value = 0;
8844                 dst_reg->u32_max_value = U32_MAX;
8845         } else {
8846                 dst_reg->u32_min_value <<= umin_val;
8847                 dst_reg->u32_max_value <<= umax_val;
8848         }
8849 }
8850
8851 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8852                                  struct bpf_reg_state *src_reg)
8853 {
8854         u32 umax_val = src_reg->u32_max_value;
8855         u32 umin_val = src_reg->u32_min_value;
8856         /* u32 alu operation will zext upper bits */
8857         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8858
8859         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8860         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8861         /* Not required but being careful mark reg64 bounds as unknown so
8862          * that we are forced to pick them up from tnum and zext later and
8863          * if some path skips this step we are still safe.
8864          */
8865         __mark_reg64_unbounded(dst_reg);
8866         __update_reg32_bounds(dst_reg);
8867 }
8868
8869 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8870                                    u64 umin_val, u64 umax_val)
8871 {
8872         /* Special case <<32 because it is a common compiler pattern to sign
8873          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8874          * positive we know this shift will also be positive so we can track
8875          * bounds correctly. Otherwise we lose all sign bit information except
8876          * what we can pick up from var_off. Perhaps we can generalize this
8877          * later to shifts of any length.
8878          */
8879         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8880                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8881         else
8882                 dst_reg->smax_value = S64_MAX;
8883
8884         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8885                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8886         else
8887                 dst_reg->smin_value = S64_MIN;
8888
8889         /* If we might shift our top bit out, then we know nothing */
8890         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8891                 dst_reg->umin_value = 0;
8892                 dst_reg->umax_value = U64_MAX;
8893         } else {
8894                 dst_reg->umin_value <<= umin_val;
8895                 dst_reg->umax_value <<= umax_val;
8896         }
8897 }
8898
8899 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8900                                struct bpf_reg_state *src_reg)
8901 {
8902         u64 umax_val = src_reg->umax_value;
8903         u64 umin_val = src_reg->umin_value;
8904
8905         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8906         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8907         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8908
8909         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8910         /* We may learn something more from the var_off */
8911         __update_reg_bounds(dst_reg);
8912 }
8913
8914 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8915                                  struct bpf_reg_state *src_reg)
8916 {
8917         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8918         u32 umax_val = src_reg->u32_max_value;
8919         u32 umin_val = src_reg->u32_min_value;
8920
8921         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8922          * be negative, then either:
8923          * 1) src_reg might be zero, so the sign bit of the result is
8924          *    unknown, so we lose our signed bounds
8925          * 2) it's known negative, thus the unsigned bounds capture the
8926          *    signed bounds
8927          * 3) the signed bounds cross zero, so they tell us nothing
8928          *    about the result
8929          * If the value in dst_reg is known nonnegative, then again the
8930          * unsigned bounds capture the signed bounds.
8931          * Thus, in all cases it suffices to blow away our signed bounds
8932          * and rely on inferring new ones from the unsigned bounds and
8933          * var_off of the result.
8934          */
8935         dst_reg->s32_min_value = S32_MIN;
8936         dst_reg->s32_max_value = S32_MAX;
8937
8938         dst_reg->var_off = tnum_rshift(subreg, umin_val);
8939         dst_reg->u32_min_value >>= umax_val;
8940         dst_reg->u32_max_value >>= umin_val;
8941
8942         __mark_reg64_unbounded(dst_reg);
8943         __update_reg32_bounds(dst_reg);
8944 }
8945
8946 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8947                                struct bpf_reg_state *src_reg)
8948 {
8949         u64 umax_val = src_reg->umax_value;
8950         u64 umin_val = src_reg->umin_value;
8951
8952         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8953          * be negative, then either:
8954          * 1) src_reg might be zero, so the sign bit of the result is
8955          *    unknown, so we lose our signed bounds
8956          * 2) it's known negative, thus the unsigned bounds capture the
8957          *    signed bounds
8958          * 3) the signed bounds cross zero, so they tell us nothing
8959          *    about the result
8960          * If the value in dst_reg is known nonnegative, then again the
8961          * unsigned bounds capture the signed bounds.
8962          * Thus, in all cases it suffices to blow away our signed bounds
8963          * and rely on inferring new ones from the unsigned bounds and
8964          * var_off of the result.
8965          */
8966         dst_reg->smin_value = S64_MIN;
8967         dst_reg->smax_value = S64_MAX;
8968         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8969         dst_reg->umin_value >>= umax_val;
8970         dst_reg->umax_value >>= umin_val;
8971
8972         /* Its not easy to operate on alu32 bounds here because it depends
8973          * on bits being shifted in. Take easy way out and mark unbounded
8974          * so we can recalculate later from tnum.
8975          */
8976         __mark_reg32_unbounded(dst_reg);
8977         __update_reg_bounds(dst_reg);
8978 }
8979
8980 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8981                                   struct bpf_reg_state *src_reg)
8982 {
8983         u64 umin_val = src_reg->u32_min_value;
8984
8985         /* Upon reaching here, src_known is true and
8986          * umax_val is equal to umin_val.
8987          */
8988         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8989         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8990
8991         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8992
8993         /* blow away the dst_reg umin_value/umax_value and rely on
8994          * dst_reg var_off to refine the result.
8995          */
8996         dst_reg->u32_min_value = 0;
8997         dst_reg->u32_max_value = U32_MAX;
8998
8999         __mark_reg64_unbounded(dst_reg);
9000         __update_reg32_bounds(dst_reg);
9001 }
9002
9003 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
9004                                 struct bpf_reg_state *src_reg)
9005 {
9006         u64 umin_val = src_reg->umin_value;
9007
9008         /* Upon reaching here, src_known is true and umax_val is equal
9009          * to umin_val.
9010          */
9011         dst_reg->smin_value >>= umin_val;
9012         dst_reg->smax_value >>= umin_val;
9013
9014         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
9015
9016         /* blow away the dst_reg umin_value/umax_value and rely on
9017          * dst_reg var_off to refine the result.
9018          */
9019         dst_reg->umin_value = 0;
9020         dst_reg->umax_value = U64_MAX;
9021
9022         /* Its not easy to operate on alu32 bounds here because it depends
9023          * on bits being shifted in from upper 32-bits. Take easy way out
9024          * and mark unbounded so we can recalculate later from tnum.
9025          */
9026         __mark_reg32_unbounded(dst_reg);
9027         __update_reg_bounds(dst_reg);
9028 }
9029
9030 /* WARNING: This function does calculations on 64-bit values, but the actual
9031  * execution may occur on 32-bit values. Therefore, things like bitshifts
9032  * need extra checks in the 32-bit case.
9033  */
9034 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9035                                       struct bpf_insn *insn,
9036                                       struct bpf_reg_state *dst_reg,
9037                                       struct bpf_reg_state src_reg)
9038 {
9039         struct bpf_reg_state *regs = cur_regs(env);
9040         u8 opcode = BPF_OP(insn->code);
9041         bool src_known;
9042         s64 smin_val, smax_val;
9043         u64 umin_val, umax_val;
9044         s32 s32_min_val, s32_max_val;
9045         u32 u32_min_val, u32_max_val;
9046         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9047         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9048         int ret;
9049
9050         smin_val = src_reg.smin_value;
9051         smax_val = src_reg.smax_value;
9052         umin_val = src_reg.umin_value;
9053         umax_val = src_reg.umax_value;
9054
9055         s32_min_val = src_reg.s32_min_value;
9056         s32_max_val = src_reg.s32_max_value;
9057         u32_min_val = src_reg.u32_min_value;
9058         u32_max_val = src_reg.u32_max_value;
9059
9060         if (alu32) {
9061                 src_known = tnum_subreg_is_const(src_reg.var_off);
9062                 if ((src_known &&
9063                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9064                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9065                         /* Taint dst register if offset had invalid bounds
9066                          * derived from e.g. dead branches.
9067                          */
9068                         __mark_reg_unknown(env, dst_reg);
9069                         return 0;
9070                 }
9071         } else {
9072                 src_known = tnum_is_const(src_reg.var_off);
9073                 if ((src_known &&
9074                      (smin_val != smax_val || umin_val != umax_val)) ||
9075                     smin_val > smax_val || umin_val > umax_val) {
9076                         /* Taint dst register if offset had invalid bounds
9077                          * derived from e.g. dead branches.
9078                          */
9079                         __mark_reg_unknown(env, dst_reg);
9080                         return 0;
9081                 }
9082         }
9083
9084         if (!src_known &&
9085             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9086                 __mark_reg_unknown(env, dst_reg);
9087                 return 0;
9088         }
9089
9090         if (sanitize_needed(opcode)) {
9091                 ret = sanitize_val_alu(env, insn);
9092                 if (ret < 0)
9093                         return sanitize_err(env, insn, ret, NULL, NULL);
9094         }
9095
9096         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9097          * There are two classes of instructions: The first class we track both
9098          * alu32 and alu64 sign/unsigned bounds independently this provides the
9099          * greatest amount of precision when alu operations are mixed with jmp32
9100          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9101          * and BPF_OR. This is possible because these ops have fairly easy to
9102          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9103          * See alu32 verifier tests for examples. The second class of
9104          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9105          * with regards to tracking sign/unsigned bounds because the bits may
9106          * cross subreg boundaries in the alu64 case. When this happens we mark
9107          * the reg unbounded in the subreg bound space and use the resulting
9108          * tnum to calculate an approximation of the sign/unsigned bounds.
9109          */
9110         switch (opcode) {
9111         case BPF_ADD:
9112                 scalar32_min_max_add(dst_reg, &src_reg);
9113                 scalar_min_max_add(dst_reg, &src_reg);
9114                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9115                 break;
9116         case BPF_SUB:
9117                 scalar32_min_max_sub(dst_reg, &src_reg);
9118                 scalar_min_max_sub(dst_reg, &src_reg);
9119                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9120                 break;
9121         case BPF_MUL:
9122                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9123                 scalar32_min_max_mul(dst_reg, &src_reg);
9124                 scalar_min_max_mul(dst_reg, &src_reg);
9125                 break;
9126         case BPF_AND:
9127                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9128                 scalar32_min_max_and(dst_reg, &src_reg);
9129                 scalar_min_max_and(dst_reg, &src_reg);
9130                 break;
9131         case BPF_OR:
9132                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9133                 scalar32_min_max_or(dst_reg, &src_reg);
9134                 scalar_min_max_or(dst_reg, &src_reg);
9135                 break;
9136         case BPF_XOR:
9137                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9138                 scalar32_min_max_xor(dst_reg, &src_reg);
9139                 scalar_min_max_xor(dst_reg, &src_reg);
9140                 break;
9141         case BPF_LSH:
9142                 if (umax_val >= insn_bitness) {
9143                         /* Shifts greater than 31 or 63 are undefined.
9144                          * This includes shifts by a negative number.
9145                          */
9146                         mark_reg_unknown(env, regs, insn->dst_reg);
9147                         break;
9148                 }
9149                 if (alu32)
9150                         scalar32_min_max_lsh(dst_reg, &src_reg);
9151                 else
9152                         scalar_min_max_lsh(dst_reg, &src_reg);
9153                 break;
9154         case BPF_RSH:
9155                 if (umax_val >= insn_bitness) {
9156                         /* Shifts greater than 31 or 63 are undefined.
9157                          * This includes shifts by a negative number.
9158                          */
9159                         mark_reg_unknown(env, regs, insn->dst_reg);
9160                         break;
9161                 }
9162                 if (alu32)
9163                         scalar32_min_max_rsh(dst_reg, &src_reg);
9164                 else
9165                         scalar_min_max_rsh(dst_reg, &src_reg);
9166                 break;
9167         case BPF_ARSH:
9168                 if (umax_val >= insn_bitness) {
9169                         /* Shifts greater than 31 or 63 are undefined.
9170                          * This includes shifts by a negative number.
9171                          */
9172                         mark_reg_unknown(env, regs, insn->dst_reg);
9173                         break;
9174                 }
9175                 if (alu32)
9176                         scalar32_min_max_arsh(dst_reg, &src_reg);
9177                 else
9178                         scalar_min_max_arsh(dst_reg, &src_reg);
9179                 break;
9180         default:
9181                 mark_reg_unknown(env, regs, insn->dst_reg);
9182                 break;
9183         }
9184
9185         /* ALU32 ops are zero extended into 64bit register */
9186         if (alu32)
9187                 zext_32_to_64(dst_reg);
9188         reg_bounds_sync(dst_reg);
9189         return 0;
9190 }
9191
9192 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9193  * and var_off.
9194  */
9195 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9196                                    struct bpf_insn *insn)
9197 {
9198         struct bpf_verifier_state *vstate = env->cur_state;
9199         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9200         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9201         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9202         u8 opcode = BPF_OP(insn->code);
9203         int err;
9204
9205         dst_reg = &regs[insn->dst_reg];
9206         src_reg = NULL;
9207         if (dst_reg->type != SCALAR_VALUE)
9208                 ptr_reg = dst_reg;
9209         else
9210                 /* Make sure ID is cleared otherwise dst_reg min/max could be
9211                  * incorrectly propagated into other registers by find_equal_scalars()
9212                  */
9213                 dst_reg->id = 0;
9214         if (BPF_SRC(insn->code) == BPF_X) {
9215                 src_reg = &regs[insn->src_reg];
9216                 if (src_reg->type != SCALAR_VALUE) {
9217                         if (dst_reg->type != SCALAR_VALUE) {
9218                                 /* Combining two pointers by any ALU op yields
9219                                  * an arbitrary scalar. Disallow all math except
9220                                  * pointer subtraction
9221                                  */
9222                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9223                                         mark_reg_unknown(env, regs, insn->dst_reg);
9224                                         return 0;
9225                                 }
9226                                 verbose(env, "R%d pointer %s pointer prohibited\n",
9227                                         insn->dst_reg,
9228                                         bpf_alu_string[opcode >> 4]);
9229                                 return -EACCES;
9230                         } else {
9231                                 /* scalar += pointer
9232                                  * This is legal, but we have to reverse our
9233                                  * src/dest handling in computing the range
9234                                  */
9235                                 err = mark_chain_precision(env, insn->dst_reg);
9236                                 if (err)
9237                                         return err;
9238                                 return adjust_ptr_min_max_vals(env, insn,
9239                                                                src_reg, dst_reg);
9240                         }
9241                 } else if (ptr_reg) {
9242                         /* pointer += scalar */
9243                         err = mark_chain_precision(env, insn->src_reg);
9244                         if (err)
9245                                 return err;
9246                         return adjust_ptr_min_max_vals(env, insn,
9247                                                        dst_reg, src_reg);
9248                 } else if (dst_reg->precise) {
9249                         /* if dst_reg is precise, src_reg should be precise as well */
9250                         err = mark_chain_precision(env, insn->src_reg);
9251                         if (err)
9252                                 return err;
9253                 }
9254         } else {
9255                 /* Pretend the src is a reg with a known value, since we only
9256                  * need to be able to read from this state.
9257                  */
9258                 off_reg.type = SCALAR_VALUE;
9259                 __mark_reg_known(&off_reg, insn->imm);
9260                 src_reg = &off_reg;
9261                 if (ptr_reg) /* pointer += K */
9262                         return adjust_ptr_min_max_vals(env, insn,
9263                                                        ptr_reg, src_reg);
9264         }
9265
9266         /* Got here implies adding two SCALAR_VALUEs */
9267         if (WARN_ON_ONCE(ptr_reg)) {
9268                 print_verifier_state(env, state, true);
9269                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9270                 return -EINVAL;
9271         }
9272         if (WARN_ON(!src_reg)) {
9273                 print_verifier_state(env, state, true);
9274                 verbose(env, "verifier internal error: no src_reg\n");
9275                 return -EINVAL;
9276         }
9277         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9278 }
9279
9280 /* check validity of 32-bit and 64-bit arithmetic operations */
9281 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9282 {
9283         struct bpf_reg_state *regs = cur_regs(env);
9284         u8 opcode = BPF_OP(insn->code);
9285         int err;
9286
9287         if (opcode == BPF_END || opcode == BPF_NEG) {
9288                 if (opcode == BPF_NEG) {
9289                         if (BPF_SRC(insn->code) != BPF_K ||
9290                             insn->src_reg != BPF_REG_0 ||
9291                             insn->off != 0 || insn->imm != 0) {
9292                                 verbose(env, "BPF_NEG uses reserved fields\n");
9293                                 return -EINVAL;
9294                         }
9295                 } else {
9296                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9297                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9298                             BPF_CLASS(insn->code) == BPF_ALU64) {
9299                                 verbose(env, "BPF_END uses reserved fields\n");
9300                                 return -EINVAL;
9301                         }
9302                 }
9303
9304                 /* check src operand */
9305                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9306                 if (err)
9307                         return err;
9308
9309                 if (is_pointer_value(env, insn->dst_reg)) {
9310                         verbose(env, "R%d pointer arithmetic prohibited\n",
9311                                 insn->dst_reg);
9312                         return -EACCES;
9313                 }
9314
9315                 /* check dest operand */
9316                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9317                 if (err)
9318                         return err;
9319
9320         } else if (opcode == BPF_MOV) {
9321
9322                 if (BPF_SRC(insn->code) == BPF_X) {
9323                         if (insn->imm != 0 || insn->off != 0) {
9324                                 verbose(env, "BPF_MOV uses reserved fields\n");
9325                                 return -EINVAL;
9326                         }
9327
9328                         /* check src operand */
9329                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9330                         if (err)
9331                                 return err;
9332                 } else {
9333                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9334                                 verbose(env, "BPF_MOV uses reserved fields\n");
9335                                 return -EINVAL;
9336                         }
9337                 }
9338
9339                 /* check dest operand, mark as required later */
9340                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9341                 if (err)
9342                         return err;
9343
9344                 if (BPF_SRC(insn->code) == BPF_X) {
9345                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
9346                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9347
9348                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9349                                 /* case: R1 = R2
9350                                  * copy register state to dest reg
9351                                  */
9352                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9353                                         /* Assign src and dst registers the same ID
9354                                          * that will be used by find_equal_scalars()
9355                                          * to propagate min/max range.
9356                                          */
9357                                         src_reg->id = ++env->id_gen;
9358                                 copy_register_state(dst_reg, src_reg);
9359                                 dst_reg->live |= REG_LIVE_WRITTEN;
9360                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
9361                         } else {
9362                                 /* R1 = (u32) R2 */
9363                                 if (is_pointer_value(env, insn->src_reg)) {
9364                                         verbose(env,
9365                                                 "R%d partial copy of pointer\n",
9366                                                 insn->src_reg);
9367                                         return -EACCES;
9368                                 } else if (src_reg->type == SCALAR_VALUE) {
9369                                         copy_register_state(dst_reg, src_reg);
9370                                         /* Make sure ID is cleared otherwise
9371                                          * dst_reg min/max could be incorrectly
9372                                          * propagated into src_reg by find_equal_scalars()
9373                                          */
9374                                         dst_reg->id = 0;
9375                                         dst_reg->live |= REG_LIVE_WRITTEN;
9376                                         dst_reg->subreg_def = env->insn_idx + 1;
9377                                 } else {
9378                                         mark_reg_unknown(env, regs,
9379                                                          insn->dst_reg);
9380                                 }
9381                                 zext_32_to_64(dst_reg);
9382                                 reg_bounds_sync(dst_reg);
9383                         }
9384                 } else {
9385                         /* case: R = imm
9386                          * remember the value we stored into this reg
9387                          */
9388                         /* clear any state __mark_reg_known doesn't set */
9389                         mark_reg_unknown(env, regs, insn->dst_reg);
9390                         regs[insn->dst_reg].type = SCALAR_VALUE;
9391                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9392                                 __mark_reg_known(regs + insn->dst_reg,
9393                                                  insn->imm);
9394                         } else {
9395                                 __mark_reg_known(regs + insn->dst_reg,
9396                                                  (u32)insn->imm);
9397                         }
9398                 }
9399
9400         } else if (opcode > BPF_END) {
9401                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9402                 return -EINVAL;
9403
9404         } else {        /* all other ALU ops: and, sub, xor, add, ... */
9405
9406                 if (BPF_SRC(insn->code) == BPF_X) {
9407                         if (insn->imm != 0 || insn->off != 0) {
9408                                 verbose(env, "BPF_ALU uses reserved fields\n");
9409                                 return -EINVAL;
9410                         }
9411                         /* check src1 operand */
9412                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9413                         if (err)
9414                                 return err;
9415                 } else {
9416                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9417                                 verbose(env, "BPF_ALU uses reserved fields\n");
9418                                 return -EINVAL;
9419                         }
9420                 }
9421
9422                 /* check src2 operand */
9423                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9424                 if (err)
9425                         return err;
9426
9427                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9428                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9429                         verbose(env, "div by zero\n");
9430                         return -EINVAL;
9431                 }
9432
9433                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9434                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9435                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9436
9437                         if (insn->imm < 0 || insn->imm >= size) {
9438                                 verbose(env, "invalid shift %d\n", insn->imm);
9439                                 return -EINVAL;
9440                         }
9441                 }
9442
9443                 /* check dest operand */
9444                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9445                 if (err)
9446                         return err;
9447
9448                 return adjust_reg_min_max_vals(env, insn);
9449         }
9450
9451         return 0;
9452 }
9453
9454 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9455                                    struct bpf_reg_state *dst_reg,
9456                                    enum bpf_reg_type type,
9457                                    bool range_right_open)
9458 {
9459         struct bpf_func_state *state;
9460         struct bpf_reg_state *reg;
9461         int new_range;
9462
9463         if (dst_reg->off < 0 ||
9464             (dst_reg->off == 0 && range_right_open))
9465                 /* This doesn't give us any range */
9466                 return;
9467
9468         if (dst_reg->umax_value > MAX_PACKET_OFF ||
9469             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9470                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
9471                  * than pkt_end, but that's because it's also less than pkt.
9472                  */
9473                 return;
9474
9475         new_range = dst_reg->off;
9476         if (range_right_open)
9477                 new_range++;
9478
9479         /* Examples for register markings:
9480          *
9481          * pkt_data in dst register:
9482          *
9483          *   r2 = r3;
9484          *   r2 += 8;
9485          *   if (r2 > pkt_end) goto <handle exception>
9486          *   <access okay>
9487          *
9488          *   r2 = r3;
9489          *   r2 += 8;
9490          *   if (r2 < pkt_end) goto <access okay>
9491          *   <handle exception>
9492          *
9493          *   Where:
9494          *     r2 == dst_reg, pkt_end == src_reg
9495          *     r2=pkt(id=n,off=8,r=0)
9496          *     r3=pkt(id=n,off=0,r=0)
9497          *
9498          * pkt_data in src register:
9499          *
9500          *   r2 = r3;
9501          *   r2 += 8;
9502          *   if (pkt_end >= r2) goto <access okay>
9503          *   <handle exception>
9504          *
9505          *   r2 = r3;
9506          *   r2 += 8;
9507          *   if (pkt_end <= r2) goto <handle exception>
9508          *   <access okay>
9509          *
9510          *   Where:
9511          *     pkt_end == dst_reg, r2 == src_reg
9512          *     r2=pkt(id=n,off=8,r=0)
9513          *     r3=pkt(id=n,off=0,r=0)
9514          *
9515          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9516          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9517          * and [r3, r3 + 8-1) respectively is safe to access depending on
9518          * the check.
9519          */
9520
9521         /* If our ids match, then we must have the same max_value.  And we
9522          * don't care about the other reg's fixed offset, since if it's too big
9523          * the range won't allow anything.
9524          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9525          */
9526         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9527                 if (reg->type == type && reg->id == dst_reg->id)
9528                         /* keep the maximum range already checked */
9529                         reg->range = max(reg->range, new_range);
9530         }));
9531 }
9532
9533 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9534 {
9535         struct tnum subreg = tnum_subreg(reg->var_off);
9536         s32 sval = (s32)val;
9537
9538         switch (opcode) {
9539         case BPF_JEQ:
9540                 if (tnum_is_const(subreg))
9541                         return !!tnum_equals_const(subreg, val);
9542                 break;
9543         case BPF_JNE:
9544                 if (tnum_is_const(subreg))
9545                         return !tnum_equals_const(subreg, val);
9546                 break;
9547         case BPF_JSET:
9548                 if ((~subreg.mask & subreg.value) & val)
9549                         return 1;
9550                 if (!((subreg.mask | subreg.value) & val))
9551                         return 0;
9552                 break;
9553         case BPF_JGT:
9554                 if (reg->u32_min_value > val)
9555                         return 1;
9556                 else if (reg->u32_max_value <= val)
9557                         return 0;
9558                 break;
9559         case BPF_JSGT:
9560                 if (reg->s32_min_value > sval)
9561                         return 1;
9562                 else if (reg->s32_max_value <= sval)
9563                         return 0;
9564                 break;
9565         case BPF_JLT:
9566                 if (reg->u32_max_value < val)
9567                         return 1;
9568                 else if (reg->u32_min_value >= val)
9569                         return 0;
9570                 break;
9571         case BPF_JSLT:
9572                 if (reg->s32_max_value < sval)
9573                         return 1;
9574                 else if (reg->s32_min_value >= sval)
9575                         return 0;
9576                 break;
9577         case BPF_JGE:
9578                 if (reg->u32_min_value >= val)
9579                         return 1;
9580                 else if (reg->u32_max_value < val)
9581                         return 0;
9582                 break;
9583         case BPF_JSGE:
9584                 if (reg->s32_min_value >= sval)
9585                         return 1;
9586                 else if (reg->s32_max_value < sval)
9587                         return 0;
9588                 break;
9589         case BPF_JLE:
9590                 if (reg->u32_max_value <= val)
9591                         return 1;
9592                 else if (reg->u32_min_value > val)
9593                         return 0;
9594                 break;
9595         case BPF_JSLE:
9596                 if (reg->s32_max_value <= sval)
9597                         return 1;
9598                 else if (reg->s32_min_value > sval)
9599                         return 0;
9600                 break;
9601         }
9602
9603         return -1;
9604 }
9605
9606
9607 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9608 {
9609         s64 sval = (s64)val;
9610
9611         switch (opcode) {
9612         case BPF_JEQ:
9613                 if (tnum_is_const(reg->var_off))
9614                         return !!tnum_equals_const(reg->var_off, val);
9615                 break;
9616         case BPF_JNE:
9617                 if (tnum_is_const(reg->var_off))
9618                         return !tnum_equals_const(reg->var_off, val);
9619                 break;
9620         case BPF_JSET:
9621                 if ((~reg->var_off.mask & reg->var_off.value) & val)
9622                         return 1;
9623                 if (!((reg->var_off.mask | reg->var_off.value) & val))
9624                         return 0;
9625                 break;
9626         case BPF_JGT:
9627                 if (reg->umin_value > val)
9628                         return 1;
9629                 else if (reg->umax_value <= val)
9630                         return 0;
9631                 break;
9632         case BPF_JSGT:
9633                 if (reg->smin_value > sval)
9634                         return 1;
9635                 else if (reg->smax_value <= sval)
9636                         return 0;
9637                 break;
9638         case BPF_JLT:
9639                 if (reg->umax_value < val)
9640                         return 1;
9641                 else if (reg->umin_value >= val)
9642                         return 0;
9643                 break;
9644         case BPF_JSLT:
9645                 if (reg->smax_value < sval)
9646                         return 1;
9647                 else if (reg->smin_value >= sval)
9648                         return 0;
9649                 break;
9650         case BPF_JGE:
9651                 if (reg->umin_value >= val)
9652                         return 1;
9653                 else if (reg->umax_value < val)
9654                         return 0;
9655                 break;
9656         case BPF_JSGE:
9657                 if (reg->smin_value >= sval)
9658                         return 1;
9659                 else if (reg->smax_value < sval)
9660                         return 0;
9661                 break;
9662         case BPF_JLE:
9663                 if (reg->umax_value <= val)
9664                         return 1;
9665                 else if (reg->umin_value > val)
9666                         return 0;
9667                 break;
9668         case BPF_JSLE:
9669                 if (reg->smax_value <= sval)
9670                         return 1;
9671                 else if (reg->smin_value > sval)
9672                         return 0;
9673                 break;
9674         }
9675
9676         return -1;
9677 }
9678
9679 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9680  * and return:
9681  *  1 - branch will be taken and "goto target" will be executed
9682  *  0 - branch will not be taken and fall-through to next insn
9683  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9684  *      range [0,10]
9685  */
9686 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9687                            bool is_jmp32)
9688 {
9689         if (__is_pointer_value(false, reg)) {
9690                 if (!reg_type_not_null(reg->type))
9691                         return -1;
9692
9693                 /* If pointer is valid tests against zero will fail so we can
9694                  * use this to direct branch taken.
9695                  */
9696                 if (val != 0)
9697                         return -1;
9698
9699                 switch (opcode) {
9700                 case BPF_JEQ:
9701                         return 0;
9702                 case BPF_JNE:
9703                         return 1;
9704                 default:
9705                         return -1;
9706                 }
9707         }
9708
9709         if (is_jmp32)
9710                 return is_branch32_taken(reg, val, opcode);
9711         return is_branch64_taken(reg, val, opcode);
9712 }
9713
9714 static int flip_opcode(u32 opcode)
9715 {
9716         /* How can we transform "a <op> b" into "b <op> a"? */
9717         static const u8 opcode_flip[16] = {
9718                 /* these stay the same */
9719                 [BPF_JEQ  >> 4] = BPF_JEQ,
9720                 [BPF_JNE  >> 4] = BPF_JNE,
9721                 [BPF_JSET >> 4] = BPF_JSET,
9722                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9723                 [BPF_JGE  >> 4] = BPF_JLE,
9724                 [BPF_JGT  >> 4] = BPF_JLT,
9725                 [BPF_JLE  >> 4] = BPF_JGE,
9726                 [BPF_JLT  >> 4] = BPF_JGT,
9727                 [BPF_JSGE >> 4] = BPF_JSLE,
9728                 [BPF_JSGT >> 4] = BPF_JSLT,
9729                 [BPF_JSLE >> 4] = BPF_JSGE,
9730                 [BPF_JSLT >> 4] = BPF_JSGT
9731         };
9732         return opcode_flip[opcode >> 4];
9733 }
9734
9735 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9736                                    struct bpf_reg_state *src_reg,
9737                                    u8 opcode)
9738 {
9739         struct bpf_reg_state *pkt;
9740
9741         if (src_reg->type == PTR_TO_PACKET_END) {
9742                 pkt = dst_reg;
9743         } else if (dst_reg->type == PTR_TO_PACKET_END) {
9744                 pkt = src_reg;
9745                 opcode = flip_opcode(opcode);
9746         } else {
9747                 return -1;
9748         }
9749
9750         if (pkt->range >= 0)
9751                 return -1;
9752
9753         switch (opcode) {
9754         case BPF_JLE:
9755                 /* pkt <= pkt_end */
9756                 fallthrough;
9757         case BPF_JGT:
9758                 /* pkt > pkt_end */
9759                 if (pkt->range == BEYOND_PKT_END)
9760                         /* pkt has at last one extra byte beyond pkt_end */
9761                         return opcode == BPF_JGT;
9762                 break;
9763         case BPF_JLT:
9764                 /* pkt < pkt_end */
9765                 fallthrough;
9766         case BPF_JGE:
9767                 /* pkt >= pkt_end */
9768                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9769                         return opcode == BPF_JGE;
9770                 break;
9771         }
9772         return -1;
9773 }
9774
9775 /* Adjusts the register min/max values in the case that the dst_reg is the
9776  * variable register that we are working on, and src_reg is a constant or we're
9777  * simply doing a BPF_K check.
9778  * In JEQ/JNE cases we also adjust the var_off values.
9779  */
9780 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9781                             struct bpf_reg_state *false_reg,
9782                             u64 val, u32 val32,
9783                             u8 opcode, bool is_jmp32)
9784 {
9785         struct tnum false_32off = tnum_subreg(false_reg->var_off);
9786         struct tnum false_64off = false_reg->var_off;
9787         struct tnum true_32off = tnum_subreg(true_reg->var_off);
9788         struct tnum true_64off = true_reg->var_off;
9789         s64 sval = (s64)val;
9790         s32 sval32 = (s32)val32;
9791
9792         /* If the dst_reg is a pointer, we can't learn anything about its
9793          * variable offset from the compare (unless src_reg were a pointer into
9794          * the same object, but we don't bother with that.
9795          * Since false_reg and true_reg have the same type by construction, we
9796          * only need to check one of them for pointerness.
9797          */
9798         if (__is_pointer_value(false, false_reg))
9799                 return;
9800
9801         switch (opcode) {
9802         /* JEQ/JNE comparison doesn't change the register equivalence.
9803          *
9804          * r1 = r2;
9805          * if (r1 == 42) goto label;
9806          * ...
9807          * label: // here both r1 and r2 are known to be 42.
9808          *
9809          * Hence when marking register as known preserve it's ID.
9810          */
9811         case BPF_JEQ:
9812                 if (is_jmp32) {
9813                         __mark_reg32_known(true_reg, val32);
9814                         true_32off = tnum_subreg(true_reg->var_off);
9815                 } else {
9816                         ___mark_reg_known(true_reg, val);
9817                         true_64off = true_reg->var_off;
9818                 }
9819                 break;
9820         case BPF_JNE:
9821                 if (is_jmp32) {
9822                         __mark_reg32_known(false_reg, val32);
9823                         false_32off = tnum_subreg(false_reg->var_off);
9824                 } else {
9825                         ___mark_reg_known(false_reg, val);
9826                         false_64off = false_reg->var_off;
9827                 }
9828                 break;
9829         case BPF_JSET:
9830                 if (is_jmp32) {
9831                         false_32off = tnum_and(false_32off, tnum_const(~val32));
9832                         if (is_power_of_2(val32))
9833                                 true_32off = tnum_or(true_32off,
9834                                                      tnum_const(val32));
9835                 } else {
9836                         false_64off = tnum_and(false_64off, tnum_const(~val));
9837                         if (is_power_of_2(val))
9838                                 true_64off = tnum_or(true_64off,
9839                                                      tnum_const(val));
9840                 }
9841                 break;
9842         case BPF_JGE:
9843         case BPF_JGT:
9844         {
9845                 if (is_jmp32) {
9846                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9847                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9848
9849                         false_reg->u32_max_value = min(false_reg->u32_max_value,
9850                                                        false_umax);
9851                         true_reg->u32_min_value = max(true_reg->u32_min_value,
9852                                                       true_umin);
9853                 } else {
9854                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9855                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9856
9857                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
9858                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
9859                 }
9860                 break;
9861         }
9862         case BPF_JSGE:
9863         case BPF_JSGT:
9864         {
9865                 if (is_jmp32) {
9866                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9867                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9868
9869                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9870                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9871                 } else {
9872                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9873                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9874
9875                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
9876                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
9877                 }
9878                 break;
9879         }
9880         case BPF_JLE:
9881         case BPF_JLT:
9882         {
9883                 if (is_jmp32) {
9884                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9885                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9886
9887                         false_reg->u32_min_value = max(false_reg->u32_min_value,
9888                                                        false_umin);
9889                         true_reg->u32_max_value = min(true_reg->u32_max_value,
9890                                                       true_umax);
9891                 } else {
9892                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9893                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9894
9895                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
9896                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
9897                 }
9898                 break;
9899         }
9900         case BPF_JSLE:
9901         case BPF_JSLT:
9902         {
9903                 if (is_jmp32) {
9904                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9905                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9906
9907                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9908                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9909                 } else {
9910                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9911                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9912
9913                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
9914                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
9915                 }
9916                 break;
9917         }
9918         default:
9919                 return;
9920         }
9921
9922         if (is_jmp32) {
9923                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9924                                              tnum_subreg(false_32off));
9925                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9926                                             tnum_subreg(true_32off));
9927                 __reg_combine_32_into_64(false_reg);
9928                 __reg_combine_32_into_64(true_reg);
9929         } else {
9930                 false_reg->var_off = false_64off;
9931                 true_reg->var_off = true_64off;
9932                 __reg_combine_64_into_32(false_reg);
9933                 __reg_combine_64_into_32(true_reg);
9934         }
9935 }
9936
9937 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9938  * the variable reg.
9939  */
9940 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9941                                 struct bpf_reg_state *false_reg,
9942                                 u64 val, u32 val32,
9943                                 u8 opcode, bool is_jmp32)
9944 {
9945         opcode = flip_opcode(opcode);
9946         /* This uses zero as "not present in table"; luckily the zero opcode,
9947          * BPF_JA, can't get here.
9948          */
9949         if (opcode)
9950                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9951 }
9952
9953 /* Regs are known to be equal, so intersect their min/max/var_off */
9954 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9955                                   struct bpf_reg_state *dst_reg)
9956 {
9957         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9958                                                         dst_reg->umin_value);
9959         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9960                                                         dst_reg->umax_value);
9961         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9962                                                         dst_reg->smin_value);
9963         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9964                                                         dst_reg->smax_value);
9965         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9966                                                              dst_reg->var_off);
9967         reg_bounds_sync(src_reg);
9968         reg_bounds_sync(dst_reg);
9969 }
9970
9971 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9972                                 struct bpf_reg_state *true_dst,
9973                                 struct bpf_reg_state *false_src,
9974                                 struct bpf_reg_state *false_dst,
9975                                 u8 opcode)
9976 {
9977         switch (opcode) {
9978         case BPF_JEQ:
9979                 __reg_combine_min_max(true_src, true_dst);
9980                 break;
9981         case BPF_JNE:
9982                 __reg_combine_min_max(false_src, false_dst);
9983                 break;
9984         }
9985 }
9986
9987 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9988                                  struct bpf_reg_state *reg, u32 id,
9989                                  bool is_null)
9990 {
9991         if (type_may_be_null(reg->type) && reg->id == id &&
9992             !WARN_ON_ONCE(!reg->id)) {
9993                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9994                                  !tnum_equals_const(reg->var_off, 0) ||
9995                                  reg->off)) {
9996                         /* Old offset (both fixed and variable parts) should
9997                          * have been known-zero, because we don't allow pointer
9998                          * arithmetic on pointers that might be NULL. If we
9999                          * see this happening, don't convert the register.
10000                          */
10001                         return;
10002                 }
10003                 if (is_null) {
10004                         reg->type = SCALAR_VALUE;
10005                         /* We don't need id and ref_obj_id from this point
10006                          * onwards anymore, thus we should better reset it,
10007                          * so that state pruning has chances to take effect.
10008                          */
10009                         reg->id = 0;
10010                         reg->ref_obj_id = 0;
10011
10012                         return;
10013                 }
10014
10015                 mark_ptr_not_null_reg(reg);
10016
10017                 if (!reg_may_point_to_spin_lock(reg)) {
10018                         /* For not-NULL ptr, reg->ref_obj_id will be reset
10019                          * in release_reference().
10020                          *
10021                          * reg->id is still used by spin_lock ptr. Other
10022                          * than spin_lock ptr type, reg->id can be reset.
10023                          */
10024                         reg->id = 0;
10025                 }
10026         }
10027 }
10028
10029 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10030  * be folded together at some point.
10031  */
10032 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10033                                   bool is_null)
10034 {
10035         struct bpf_func_state *state = vstate->frame[vstate->curframe];
10036         struct bpf_reg_state *regs = state->regs, *reg;
10037         u32 ref_obj_id = regs[regno].ref_obj_id;
10038         u32 id = regs[regno].id;
10039
10040         if (ref_obj_id && ref_obj_id == id && is_null)
10041                 /* regs[regno] is in the " == NULL" branch.
10042                  * No one could have freed the reference state before
10043                  * doing the NULL check.
10044                  */
10045                 WARN_ON_ONCE(release_reference_state(state, id));
10046
10047         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10048                 mark_ptr_or_null_reg(state, reg, id, is_null);
10049         }));
10050 }
10051
10052 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10053                                    struct bpf_reg_state *dst_reg,
10054                                    struct bpf_reg_state *src_reg,
10055                                    struct bpf_verifier_state *this_branch,
10056                                    struct bpf_verifier_state *other_branch)
10057 {
10058         if (BPF_SRC(insn->code) != BPF_X)
10059                 return false;
10060
10061         /* Pointers are always 64-bit. */
10062         if (BPF_CLASS(insn->code) == BPF_JMP32)
10063                 return false;
10064
10065         switch (BPF_OP(insn->code)) {
10066         case BPF_JGT:
10067                 if ((dst_reg->type == PTR_TO_PACKET &&
10068                      src_reg->type == PTR_TO_PACKET_END) ||
10069                     (dst_reg->type == PTR_TO_PACKET_META &&
10070                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10071                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10072                         find_good_pkt_pointers(this_branch, dst_reg,
10073                                                dst_reg->type, false);
10074                         mark_pkt_end(other_branch, insn->dst_reg, true);
10075                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10076                             src_reg->type == PTR_TO_PACKET) ||
10077                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10078                             src_reg->type == PTR_TO_PACKET_META)) {
10079                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10080                         find_good_pkt_pointers(other_branch, src_reg,
10081                                                src_reg->type, true);
10082                         mark_pkt_end(this_branch, insn->src_reg, false);
10083                 } else {
10084                         return false;
10085                 }
10086                 break;
10087         case BPF_JLT:
10088                 if ((dst_reg->type == PTR_TO_PACKET &&
10089                      src_reg->type == PTR_TO_PACKET_END) ||
10090                     (dst_reg->type == PTR_TO_PACKET_META &&
10091                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10092                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10093                         find_good_pkt_pointers(other_branch, dst_reg,
10094                                                dst_reg->type, true);
10095                         mark_pkt_end(this_branch, insn->dst_reg, false);
10096                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10097                             src_reg->type == PTR_TO_PACKET) ||
10098                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10099                             src_reg->type == PTR_TO_PACKET_META)) {
10100                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10101                         find_good_pkt_pointers(this_branch, src_reg,
10102                                                src_reg->type, false);
10103                         mark_pkt_end(other_branch, insn->src_reg, true);
10104                 } else {
10105                         return false;
10106                 }
10107                 break;
10108         case BPF_JGE:
10109                 if ((dst_reg->type == PTR_TO_PACKET &&
10110                      src_reg->type == PTR_TO_PACKET_END) ||
10111                     (dst_reg->type == PTR_TO_PACKET_META &&
10112                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10113                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10114                         find_good_pkt_pointers(this_branch, dst_reg,
10115                                                dst_reg->type, true);
10116                         mark_pkt_end(other_branch, insn->dst_reg, false);
10117                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10118                             src_reg->type == PTR_TO_PACKET) ||
10119                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10120                             src_reg->type == PTR_TO_PACKET_META)) {
10121                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10122                         find_good_pkt_pointers(other_branch, src_reg,
10123                                                src_reg->type, false);
10124                         mark_pkt_end(this_branch, insn->src_reg, true);
10125                 } else {
10126                         return false;
10127                 }
10128                 break;
10129         case BPF_JLE:
10130                 if ((dst_reg->type == PTR_TO_PACKET &&
10131                      src_reg->type == PTR_TO_PACKET_END) ||
10132                     (dst_reg->type == PTR_TO_PACKET_META &&
10133                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10134                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10135                         find_good_pkt_pointers(other_branch, dst_reg,
10136                                                dst_reg->type, false);
10137                         mark_pkt_end(this_branch, insn->dst_reg, true);
10138                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10139                             src_reg->type == PTR_TO_PACKET) ||
10140                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10141                             src_reg->type == PTR_TO_PACKET_META)) {
10142                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10143                         find_good_pkt_pointers(this_branch, src_reg,
10144                                                src_reg->type, true);
10145                         mark_pkt_end(other_branch, insn->src_reg, false);
10146                 } else {
10147                         return false;
10148                 }
10149                 break;
10150         default:
10151                 return false;
10152         }
10153
10154         return true;
10155 }
10156
10157 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10158                                struct bpf_reg_state *known_reg)
10159 {
10160         struct bpf_func_state *state;
10161         struct bpf_reg_state *reg;
10162
10163         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10164                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10165                         copy_register_state(reg, known_reg);
10166         }));
10167 }
10168
10169 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10170                              struct bpf_insn *insn, int *insn_idx)
10171 {
10172         struct bpf_verifier_state *this_branch = env->cur_state;
10173         struct bpf_verifier_state *other_branch;
10174         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10175         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10176         u8 opcode = BPF_OP(insn->code);
10177         bool is_jmp32;
10178         int pred = -1;
10179         int err;
10180
10181         /* Only conditional jumps are expected to reach here. */
10182         if (opcode == BPF_JA || opcode > BPF_JSLE) {
10183                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10184                 return -EINVAL;
10185         }
10186
10187         if (BPF_SRC(insn->code) == BPF_X) {
10188                 if (insn->imm != 0) {
10189                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10190                         return -EINVAL;
10191                 }
10192
10193                 /* check src1 operand */
10194                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10195                 if (err)
10196                         return err;
10197
10198                 if (is_pointer_value(env, insn->src_reg)) {
10199                         verbose(env, "R%d pointer comparison prohibited\n",
10200                                 insn->src_reg);
10201                         return -EACCES;
10202                 }
10203                 src_reg = &regs[insn->src_reg];
10204         } else {
10205                 if (insn->src_reg != BPF_REG_0) {
10206                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10207                         return -EINVAL;
10208                 }
10209         }
10210
10211         /* check src2 operand */
10212         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10213         if (err)
10214                 return err;
10215
10216         dst_reg = &regs[insn->dst_reg];
10217         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10218
10219         if (BPF_SRC(insn->code) == BPF_K) {
10220                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10221         } else if (src_reg->type == SCALAR_VALUE &&
10222                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10223                 pred = is_branch_taken(dst_reg,
10224                                        tnum_subreg(src_reg->var_off).value,
10225                                        opcode,
10226                                        is_jmp32);
10227         } else if (src_reg->type == SCALAR_VALUE &&
10228                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10229                 pred = is_branch_taken(dst_reg,
10230                                        src_reg->var_off.value,
10231                                        opcode,
10232                                        is_jmp32);
10233         } else if (reg_is_pkt_pointer_any(dst_reg) &&
10234                    reg_is_pkt_pointer_any(src_reg) &&
10235                    !is_jmp32) {
10236                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10237         }
10238
10239         if (pred >= 0) {
10240                 /* If we get here with a dst_reg pointer type it is because
10241                  * above is_branch_taken() special cased the 0 comparison.
10242                  */
10243                 if (!__is_pointer_value(false, dst_reg))
10244                         err = mark_chain_precision(env, insn->dst_reg);
10245                 if (BPF_SRC(insn->code) == BPF_X && !err &&
10246                     !__is_pointer_value(false, src_reg))
10247                         err = mark_chain_precision(env, insn->src_reg);
10248                 if (err)
10249                         return err;
10250         }
10251
10252         if (pred == 1) {
10253                 /* Only follow the goto, ignore fall-through. If needed, push
10254                  * the fall-through branch for simulation under speculative
10255                  * execution.
10256                  */
10257                 if (!env->bypass_spec_v1 &&
10258                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
10259                                                *insn_idx))
10260                         return -EFAULT;
10261                 *insn_idx += insn->off;
10262                 return 0;
10263         } else if (pred == 0) {
10264                 /* Only follow the fall-through branch, since that's where the
10265                  * program will go. If needed, push the goto branch for
10266                  * simulation under speculative execution.
10267                  */
10268                 if (!env->bypass_spec_v1 &&
10269                     !sanitize_speculative_path(env, insn,
10270                                                *insn_idx + insn->off + 1,
10271                                                *insn_idx))
10272                         return -EFAULT;
10273                 return 0;
10274         }
10275
10276         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10277                                   false);
10278         if (!other_branch)
10279                 return -EFAULT;
10280         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10281
10282         /* detect if we are comparing against a constant value so we can adjust
10283          * our min/max values for our dst register.
10284          * this is only legit if both are scalars (or pointers to the same
10285          * object, I suppose, but we don't support that right now), because
10286          * otherwise the different base pointers mean the offsets aren't
10287          * comparable.
10288          */
10289         if (BPF_SRC(insn->code) == BPF_X) {
10290                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10291
10292                 if (dst_reg->type == SCALAR_VALUE &&
10293                     src_reg->type == SCALAR_VALUE) {
10294                         if (tnum_is_const(src_reg->var_off) ||
10295                             (is_jmp32 &&
10296                              tnum_is_const(tnum_subreg(src_reg->var_off))))
10297                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10298                                                 dst_reg,
10299                                                 src_reg->var_off.value,
10300                                                 tnum_subreg(src_reg->var_off).value,
10301                                                 opcode, is_jmp32);
10302                         else if (tnum_is_const(dst_reg->var_off) ||
10303                                  (is_jmp32 &&
10304                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
10305                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10306                                                     src_reg,
10307                                                     dst_reg->var_off.value,
10308                                                     tnum_subreg(dst_reg->var_off).value,
10309                                                     opcode, is_jmp32);
10310                         else if (!is_jmp32 &&
10311                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
10312                                 /* Comparing for equality, we can combine knowledge */
10313                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10314                                                     &other_branch_regs[insn->dst_reg],
10315                                                     src_reg, dst_reg, opcode);
10316                         if (src_reg->id &&
10317                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10318                                 find_equal_scalars(this_branch, src_reg);
10319                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10320                         }
10321
10322                 }
10323         } else if (dst_reg->type == SCALAR_VALUE) {
10324                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10325                                         dst_reg, insn->imm, (u32)insn->imm,
10326                                         opcode, is_jmp32);
10327         }
10328
10329         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10330             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10331                 find_equal_scalars(this_branch, dst_reg);
10332                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10333         }
10334
10335         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10336          * NOTE: these optimizations below are related with pointer comparison
10337          *       which will never be JMP32.
10338          */
10339         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10340             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10341             type_may_be_null(dst_reg->type)) {
10342                 /* Mark all identical registers in each branch as either
10343                  * safe or unknown depending R == 0 or R != 0 conditional.
10344                  */
10345                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10346                                       opcode == BPF_JNE);
10347                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10348                                       opcode == BPF_JEQ);
10349         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10350                                            this_branch, other_branch) &&
10351                    is_pointer_value(env, insn->dst_reg)) {
10352                 verbose(env, "R%d pointer comparison prohibited\n",
10353                         insn->dst_reg);
10354                 return -EACCES;
10355         }
10356         if (env->log.level & BPF_LOG_LEVEL)
10357                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10358         return 0;
10359 }
10360
10361 /* verify BPF_LD_IMM64 instruction */
10362 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10363 {
10364         struct bpf_insn_aux_data *aux = cur_aux(env);
10365         struct bpf_reg_state *regs = cur_regs(env);
10366         struct bpf_reg_state *dst_reg;
10367         struct bpf_map *map;
10368         int err;
10369
10370         if (BPF_SIZE(insn->code) != BPF_DW) {
10371                 verbose(env, "invalid BPF_LD_IMM insn\n");
10372                 return -EINVAL;
10373         }
10374         if (insn->off != 0) {
10375                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10376                 return -EINVAL;
10377         }
10378
10379         err = check_reg_arg(env, insn->dst_reg, DST_OP);
10380         if (err)
10381                 return err;
10382
10383         dst_reg = &regs[insn->dst_reg];
10384         if (insn->src_reg == 0) {
10385                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10386
10387                 dst_reg->type = SCALAR_VALUE;
10388                 __mark_reg_known(&regs[insn->dst_reg], imm);
10389                 return 0;
10390         }
10391
10392         /* All special src_reg cases are listed below. From this point onwards
10393          * we either succeed and assign a corresponding dst_reg->type after
10394          * zeroing the offset, or fail and reject the program.
10395          */
10396         mark_reg_known_zero(env, regs, insn->dst_reg);
10397
10398         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10399                 dst_reg->type = aux->btf_var.reg_type;
10400                 switch (base_type(dst_reg->type)) {
10401                 case PTR_TO_MEM:
10402                         dst_reg->mem_size = aux->btf_var.mem_size;
10403                         break;
10404                 case PTR_TO_BTF_ID:
10405                         dst_reg->btf = aux->btf_var.btf;
10406                         dst_reg->btf_id = aux->btf_var.btf_id;
10407                         break;
10408                 default:
10409                         verbose(env, "bpf verifier is misconfigured\n");
10410                         return -EFAULT;
10411                 }
10412                 return 0;
10413         }
10414
10415         if (insn->src_reg == BPF_PSEUDO_FUNC) {
10416                 struct bpf_prog_aux *aux = env->prog->aux;
10417                 u32 subprogno = find_subprog(env,
10418                                              env->insn_idx + insn->imm + 1);
10419
10420                 if (!aux->func_info) {
10421                         verbose(env, "missing btf func_info\n");
10422                         return -EINVAL;
10423                 }
10424                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10425                         verbose(env, "callback function not static\n");
10426                         return -EINVAL;
10427                 }
10428
10429                 dst_reg->type = PTR_TO_FUNC;
10430                 dst_reg->subprogno = subprogno;
10431                 return 0;
10432         }
10433
10434         map = env->used_maps[aux->map_index];
10435         dst_reg->map_ptr = map;
10436
10437         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10438             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10439                 dst_reg->type = PTR_TO_MAP_VALUE;
10440                 dst_reg->off = aux->map_off;
10441                 if (map_value_has_spin_lock(map))
10442                         dst_reg->id = ++env->id_gen;
10443         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10444                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10445                 dst_reg->type = CONST_PTR_TO_MAP;
10446         } else {
10447                 verbose(env, "bpf verifier is misconfigured\n");
10448                 return -EINVAL;
10449         }
10450
10451         return 0;
10452 }
10453
10454 static bool may_access_skb(enum bpf_prog_type type)
10455 {
10456         switch (type) {
10457         case BPF_PROG_TYPE_SOCKET_FILTER:
10458         case BPF_PROG_TYPE_SCHED_CLS:
10459         case BPF_PROG_TYPE_SCHED_ACT:
10460                 return true;
10461         default:
10462                 return false;
10463         }
10464 }
10465
10466 /* verify safety of LD_ABS|LD_IND instructions:
10467  * - they can only appear in the programs where ctx == skb
10468  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10469  *   preserve R6-R9, and store return value into R0
10470  *
10471  * Implicit input:
10472  *   ctx == skb == R6 == CTX
10473  *
10474  * Explicit input:
10475  *   SRC == any register
10476  *   IMM == 32-bit immediate
10477  *
10478  * Output:
10479  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10480  */
10481 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10482 {
10483         struct bpf_reg_state *regs = cur_regs(env);
10484         static const int ctx_reg = BPF_REG_6;
10485         u8 mode = BPF_MODE(insn->code);
10486         int i, err;
10487
10488         if (!may_access_skb(resolve_prog_type(env->prog))) {
10489                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10490                 return -EINVAL;
10491         }
10492
10493         if (!env->ops->gen_ld_abs) {
10494                 verbose(env, "bpf verifier is misconfigured\n");
10495                 return -EINVAL;
10496         }
10497
10498         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10499             BPF_SIZE(insn->code) == BPF_DW ||
10500             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10501                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10502                 return -EINVAL;
10503         }
10504
10505         /* check whether implicit source operand (register R6) is readable */
10506         err = check_reg_arg(env, ctx_reg, SRC_OP);
10507         if (err)
10508                 return err;
10509
10510         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10511          * gen_ld_abs() may terminate the program at runtime, leading to
10512          * reference leak.
10513          */
10514         err = check_reference_leak(env);
10515         if (err) {
10516                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10517                 return err;
10518         }
10519
10520         if (env->cur_state->active_spin_lock) {
10521                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10522                 return -EINVAL;
10523         }
10524
10525         if (regs[ctx_reg].type != PTR_TO_CTX) {
10526                 verbose(env,
10527                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10528                 return -EINVAL;
10529         }
10530
10531         if (mode == BPF_IND) {
10532                 /* check explicit source operand */
10533                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10534                 if (err)
10535                         return err;
10536         }
10537
10538         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10539         if (err < 0)
10540                 return err;
10541
10542         /* reset caller saved regs to unreadable */
10543         for (i = 0; i < CALLER_SAVED_REGS; i++) {
10544                 mark_reg_not_init(env, regs, caller_saved[i]);
10545                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10546         }
10547
10548         /* mark destination R0 register as readable, since it contains
10549          * the value fetched from the packet.
10550          * Already marked as written above.
10551          */
10552         mark_reg_unknown(env, regs, BPF_REG_0);
10553         /* ld_abs load up to 32-bit skb data. */
10554         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10555         return 0;
10556 }
10557
10558 static int check_return_code(struct bpf_verifier_env *env)
10559 {
10560         struct tnum enforce_attach_type_range = tnum_unknown;
10561         const struct bpf_prog *prog = env->prog;
10562         struct bpf_reg_state *reg;
10563         struct tnum range = tnum_range(0, 1);
10564         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10565         int err;
10566         struct bpf_func_state *frame = env->cur_state->frame[0];
10567         const bool is_subprog = frame->subprogno;
10568
10569         /* LSM and struct_ops func-ptr's return type could be "void" */
10570         if (!is_subprog) {
10571                 switch (prog_type) {
10572                 case BPF_PROG_TYPE_LSM:
10573                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
10574                                 /* See below, can be 0 or 0-1 depending on hook. */
10575                                 break;
10576                         fallthrough;
10577                 case BPF_PROG_TYPE_STRUCT_OPS:
10578                         if (!prog->aux->attach_func_proto->type)
10579                                 return 0;
10580                         break;
10581                 default:
10582                         break;
10583                 }
10584         }
10585
10586         /* eBPF calling convention is such that R0 is used
10587          * to return the value from eBPF program.
10588          * Make sure that it's readable at this time
10589          * of bpf_exit, which means that program wrote
10590          * something into it earlier
10591          */
10592         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10593         if (err)
10594                 return err;
10595
10596         if (is_pointer_value(env, BPF_REG_0)) {
10597                 verbose(env, "R0 leaks addr as return value\n");
10598                 return -EACCES;
10599         }
10600
10601         reg = cur_regs(env) + BPF_REG_0;
10602
10603         if (frame->in_async_callback_fn) {
10604                 /* enforce return zero from async callbacks like timer */
10605                 if (reg->type != SCALAR_VALUE) {
10606                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10607                                 reg_type_str(env, reg->type));
10608                         return -EINVAL;
10609                 }
10610
10611                 if (!tnum_in(tnum_const(0), reg->var_off)) {
10612                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10613                         return -EINVAL;
10614                 }
10615                 return 0;
10616         }
10617
10618         if (is_subprog) {
10619                 if (reg->type != SCALAR_VALUE) {
10620                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10621                                 reg_type_str(env, reg->type));
10622                         return -EINVAL;
10623                 }
10624                 return 0;
10625         }
10626
10627         switch (prog_type) {
10628         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10629                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10630                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10631                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10632                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10633                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10634                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10635                         range = tnum_range(1, 1);
10636                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10637                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10638                         range = tnum_range(0, 3);
10639                 break;
10640         case BPF_PROG_TYPE_CGROUP_SKB:
10641                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10642                         range = tnum_range(0, 3);
10643                         enforce_attach_type_range = tnum_range(2, 3);
10644                 }
10645                 break;
10646         case BPF_PROG_TYPE_CGROUP_SOCK:
10647         case BPF_PROG_TYPE_SOCK_OPS:
10648         case BPF_PROG_TYPE_CGROUP_DEVICE:
10649         case BPF_PROG_TYPE_CGROUP_SYSCTL:
10650         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10651                 break;
10652         case BPF_PROG_TYPE_RAW_TRACEPOINT:
10653                 if (!env->prog->aux->attach_btf_id)
10654                         return 0;
10655                 range = tnum_const(0);
10656                 break;
10657         case BPF_PROG_TYPE_TRACING:
10658                 switch (env->prog->expected_attach_type) {
10659                 case BPF_TRACE_FENTRY:
10660                 case BPF_TRACE_FEXIT:
10661                         range = tnum_const(0);
10662                         break;
10663                 case BPF_TRACE_RAW_TP:
10664                 case BPF_MODIFY_RETURN:
10665                         return 0;
10666                 case BPF_TRACE_ITER:
10667                         break;
10668                 default:
10669                         return -ENOTSUPP;
10670                 }
10671                 break;
10672         case BPF_PROG_TYPE_SK_LOOKUP:
10673                 range = tnum_range(SK_DROP, SK_PASS);
10674                 break;
10675
10676         case BPF_PROG_TYPE_LSM:
10677                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10678                         /* Regular BPF_PROG_TYPE_LSM programs can return
10679                          * any value.
10680                          */
10681                         return 0;
10682                 }
10683                 if (!env->prog->aux->attach_func_proto->type) {
10684                         /* Make sure programs that attach to void
10685                          * hooks don't try to modify return value.
10686                          */
10687                         range = tnum_range(1, 1);
10688                 }
10689                 break;
10690
10691         case BPF_PROG_TYPE_EXT:
10692                 /* freplace program can return anything as its return value
10693                  * depends on the to-be-replaced kernel func or bpf program.
10694                  */
10695         default:
10696                 return 0;
10697         }
10698
10699         if (reg->type != SCALAR_VALUE) {
10700                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10701                         reg_type_str(env, reg->type));
10702                 return -EINVAL;
10703         }
10704
10705         if (!tnum_in(range, reg->var_off)) {
10706                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10707                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10708                     prog_type == BPF_PROG_TYPE_LSM &&
10709                     !prog->aux->attach_func_proto->type)
10710                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10711                 return -EINVAL;
10712         }
10713
10714         if (!tnum_is_unknown(enforce_attach_type_range) &&
10715             tnum_in(enforce_attach_type_range, reg->var_off))
10716                 env->prog->enforce_expected_attach_type = 1;
10717         return 0;
10718 }
10719
10720 /* non-recursive DFS pseudo code
10721  * 1  procedure DFS-iterative(G,v):
10722  * 2      label v as discovered
10723  * 3      let S be a stack
10724  * 4      S.push(v)
10725  * 5      while S is not empty
10726  * 6            t <- S.pop()
10727  * 7            if t is what we're looking for:
10728  * 8                return t
10729  * 9            for all edges e in G.adjacentEdges(t) do
10730  * 10               if edge e is already labelled
10731  * 11                   continue with the next edge
10732  * 12               w <- G.adjacentVertex(t,e)
10733  * 13               if vertex w is not discovered and not explored
10734  * 14                   label e as tree-edge
10735  * 15                   label w as discovered
10736  * 16                   S.push(w)
10737  * 17                   continue at 5
10738  * 18               else if vertex w is discovered
10739  * 19                   label e as back-edge
10740  * 20               else
10741  * 21                   // vertex w is explored
10742  * 22                   label e as forward- or cross-edge
10743  * 23           label t as explored
10744  * 24           S.pop()
10745  *
10746  * convention:
10747  * 0x10 - discovered
10748  * 0x11 - discovered and fall-through edge labelled
10749  * 0x12 - discovered and fall-through and branch edges labelled
10750  * 0x20 - explored
10751  */
10752
10753 enum {
10754         DISCOVERED = 0x10,
10755         EXPLORED = 0x20,
10756         FALLTHROUGH = 1,
10757         BRANCH = 2,
10758 };
10759
10760 static u32 state_htab_size(struct bpf_verifier_env *env)
10761 {
10762         return env->prog->len;
10763 }
10764
10765 static struct bpf_verifier_state_list **explored_state(
10766                                         struct bpf_verifier_env *env,
10767                                         int idx)
10768 {
10769         struct bpf_verifier_state *cur = env->cur_state;
10770         struct bpf_func_state *state = cur->frame[cur->curframe];
10771
10772         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10773 }
10774
10775 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10776 {
10777         env->insn_aux_data[idx].prune_point = true;
10778 }
10779
10780 enum {
10781         DONE_EXPLORING = 0,
10782         KEEP_EXPLORING = 1,
10783 };
10784
10785 /* t, w, e - match pseudo-code above:
10786  * t - index of current instruction
10787  * w - next instruction
10788  * e - edge
10789  */
10790 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10791                      bool loop_ok)
10792 {
10793         int *insn_stack = env->cfg.insn_stack;
10794         int *insn_state = env->cfg.insn_state;
10795
10796         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10797                 return DONE_EXPLORING;
10798
10799         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10800                 return DONE_EXPLORING;
10801
10802         if (w < 0 || w >= env->prog->len) {
10803                 verbose_linfo(env, t, "%d: ", t);
10804                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10805                 return -EINVAL;
10806         }
10807
10808         if (e == BRANCH)
10809                 /* mark branch target for state pruning */
10810                 init_explored_state(env, w);
10811
10812         if (insn_state[w] == 0) {
10813                 /* tree-edge */
10814                 insn_state[t] = DISCOVERED | e;
10815                 insn_state[w] = DISCOVERED;
10816                 if (env->cfg.cur_stack >= env->prog->len)
10817                         return -E2BIG;
10818                 insn_stack[env->cfg.cur_stack++] = w;
10819                 return KEEP_EXPLORING;
10820         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10821                 if (loop_ok && env->bpf_capable)
10822                         return DONE_EXPLORING;
10823                 verbose_linfo(env, t, "%d: ", t);
10824                 verbose_linfo(env, w, "%d: ", w);
10825                 verbose(env, "back-edge from insn %d to %d\n", t, w);
10826                 return -EINVAL;
10827         } else if (insn_state[w] == EXPLORED) {
10828                 /* forward- or cross-edge */
10829                 insn_state[t] = DISCOVERED | e;
10830         } else {
10831                 verbose(env, "insn state internal bug\n");
10832                 return -EFAULT;
10833         }
10834         return DONE_EXPLORING;
10835 }
10836
10837 static int visit_func_call_insn(int t, int insn_cnt,
10838                                 struct bpf_insn *insns,
10839                                 struct bpf_verifier_env *env,
10840                                 bool visit_callee)
10841 {
10842         int ret;
10843
10844         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10845         if (ret)
10846                 return ret;
10847
10848         if (t + 1 < insn_cnt)
10849                 init_explored_state(env, t + 1);
10850         if (visit_callee) {
10851                 init_explored_state(env, t);
10852                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10853                                 /* It's ok to allow recursion from CFG point of
10854                                  * view. __check_func_call() will do the actual
10855                                  * check.
10856                                  */
10857                                 bpf_pseudo_func(insns + t));
10858         }
10859         return ret;
10860 }
10861
10862 /* Visits the instruction at index t and returns one of the following:
10863  *  < 0 - an error occurred
10864  *  DONE_EXPLORING - the instruction was fully explored
10865  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10866  */
10867 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10868 {
10869         struct bpf_insn *insns = env->prog->insnsi;
10870         int ret;
10871
10872         if (bpf_pseudo_func(insns + t))
10873                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10874
10875         /* All non-branch instructions have a single fall-through edge. */
10876         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10877             BPF_CLASS(insns[t].code) != BPF_JMP32)
10878                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10879
10880         switch (BPF_OP(insns[t].code)) {
10881         case BPF_EXIT:
10882                 return DONE_EXPLORING;
10883
10884         case BPF_CALL:
10885                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10886                         /* Mark this call insn to trigger is_state_visited() check
10887                          * before call itself is processed by __check_func_call().
10888                          * Otherwise new async state will be pushed for further
10889                          * exploration.
10890                          */
10891                         init_explored_state(env, t);
10892                 return visit_func_call_insn(t, insn_cnt, insns, env,
10893                                             insns[t].src_reg == BPF_PSEUDO_CALL);
10894
10895         case BPF_JA:
10896                 if (BPF_SRC(insns[t].code) != BPF_K)
10897                         return -EINVAL;
10898
10899                 /* unconditional jump with single edge */
10900                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10901                                 true);
10902                 if (ret)
10903                         return ret;
10904
10905                 /* unconditional jmp is not a good pruning point,
10906                  * but it's marked, since backtracking needs
10907                  * to record jmp history in is_state_visited().
10908                  */
10909                 init_explored_state(env, t + insns[t].off + 1);
10910                 /* tell verifier to check for equivalent states
10911                  * after every call and jump
10912                  */
10913                 if (t + 1 < insn_cnt)
10914                         init_explored_state(env, t + 1);
10915
10916                 return ret;
10917
10918         default:
10919                 /* conditional jump with two edges */
10920                 init_explored_state(env, t);
10921                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10922                 if (ret)
10923                         return ret;
10924
10925                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10926         }
10927 }
10928
10929 /* non-recursive depth-first-search to detect loops in BPF program
10930  * loop == back-edge in directed graph
10931  */
10932 static int check_cfg(struct bpf_verifier_env *env)
10933 {
10934         int insn_cnt = env->prog->len;
10935         int *insn_stack, *insn_state;
10936         int ret = 0;
10937         int i;
10938
10939         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10940         if (!insn_state)
10941                 return -ENOMEM;
10942
10943         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10944         if (!insn_stack) {
10945                 kvfree(insn_state);
10946                 return -ENOMEM;
10947         }
10948
10949         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10950         insn_stack[0] = 0; /* 0 is the first instruction */
10951         env->cfg.cur_stack = 1;
10952
10953         while (env->cfg.cur_stack > 0) {
10954                 int t = insn_stack[env->cfg.cur_stack - 1];
10955
10956                 ret = visit_insn(t, insn_cnt, env);
10957                 switch (ret) {
10958                 case DONE_EXPLORING:
10959                         insn_state[t] = EXPLORED;
10960                         env->cfg.cur_stack--;
10961                         break;
10962                 case KEEP_EXPLORING:
10963                         break;
10964                 default:
10965                         if (ret > 0) {
10966                                 verbose(env, "visit_insn internal bug\n");
10967                                 ret = -EFAULT;
10968                         }
10969                         goto err_free;
10970                 }
10971         }
10972
10973         if (env->cfg.cur_stack < 0) {
10974                 verbose(env, "pop stack internal bug\n");
10975                 ret = -EFAULT;
10976                 goto err_free;
10977         }
10978
10979         for (i = 0; i < insn_cnt; i++) {
10980                 if (insn_state[i] != EXPLORED) {
10981                         verbose(env, "unreachable insn %d\n", i);
10982                         ret = -EINVAL;
10983                         goto err_free;
10984                 }
10985         }
10986         ret = 0; /* cfg looks good */
10987
10988 err_free:
10989         kvfree(insn_state);
10990         kvfree(insn_stack);
10991         env->cfg.insn_state = env->cfg.insn_stack = NULL;
10992         return ret;
10993 }
10994
10995 static int check_abnormal_return(struct bpf_verifier_env *env)
10996 {
10997         int i;
10998
10999         for (i = 1; i < env->subprog_cnt; i++) {
11000                 if (env->subprog_info[i].has_ld_abs) {
11001                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
11002                         return -EINVAL;
11003                 }
11004                 if (env->subprog_info[i].has_tail_call) {
11005                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
11006                         return -EINVAL;
11007                 }
11008         }
11009         return 0;
11010 }
11011
11012 /* The minimum supported BTF func info size */
11013 #define MIN_BPF_FUNCINFO_SIZE   8
11014 #define MAX_FUNCINFO_REC_SIZE   252
11015
11016 static int check_btf_func(struct bpf_verifier_env *env,
11017                           const union bpf_attr *attr,
11018                           bpfptr_t uattr)
11019 {
11020         const struct btf_type *type, *func_proto, *ret_type;
11021         u32 i, nfuncs, urec_size, min_size;
11022         u32 krec_size = sizeof(struct bpf_func_info);
11023         struct bpf_func_info *krecord;
11024         struct bpf_func_info_aux *info_aux = NULL;
11025         struct bpf_prog *prog;
11026         const struct btf *btf;
11027         bpfptr_t urecord;
11028         u32 prev_offset = 0;
11029         bool scalar_return;
11030         int ret = -ENOMEM;
11031
11032         nfuncs = attr->func_info_cnt;
11033         if (!nfuncs) {
11034                 if (check_abnormal_return(env))
11035                         return -EINVAL;
11036                 return 0;
11037         }
11038
11039         if (nfuncs != env->subprog_cnt) {
11040                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11041                 return -EINVAL;
11042         }
11043
11044         urec_size = attr->func_info_rec_size;
11045         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11046             urec_size > MAX_FUNCINFO_REC_SIZE ||
11047             urec_size % sizeof(u32)) {
11048                 verbose(env, "invalid func info rec size %u\n", urec_size);
11049                 return -EINVAL;
11050         }
11051
11052         prog = env->prog;
11053         btf = prog->aux->btf;
11054
11055         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11056         min_size = min_t(u32, krec_size, urec_size);
11057
11058         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11059         if (!krecord)
11060                 return -ENOMEM;
11061         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11062         if (!info_aux)
11063                 goto err_free;
11064
11065         for (i = 0; i < nfuncs; i++) {
11066                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11067                 if (ret) {
11068                         if (ret == -E2BIG) {
11069                                 verbose(env, "nonzero tailing record in func info");
11070                                 /* set the size kernel expects so loader can zero
11071                                  * out the rest of the record.
11072                                  */
11073                                 if (copy_to_bpfptr_offset(uattr,
11074                                                           offsetof(union bpf_attr, func_info_rec_size),
11075                                                           &min_size, sizeof(min_size)))
11076                                         ret = -EFAULT;
11077                         }
11078                         goto err_free;
11079                 }
11080
11081                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11082                         ret = -EFAULT;
11083                         goto err_free;
11084                 }
11085
11086                 /* check insn_off */
11087                 ret = -EINVAL;
11088                 if (i == 0) {
11089                         if (krecord[i].insn_off) {
11090                                 verbose(env,
11091                                         "nonzero insn_off %u for the first func info record",
11092                                         krecord[i].insn_off);
11093                                 goto err_free;
11094                         }
11095                 } else if (krecord[i].insn_off <= prev_offset) {
11096                         verbose(env,
11097                                 "same or smaller insn offset (%u) than previous func info record (%u)",
11098                                 krecord[i].insn_off, prev_offset);
11099                         goto err_free;
11100                 }
11101
11102                 if (env->subprog_info[i].start != krecord[i].insn_off) {
11103                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11104                         goto err_free;
11105                 }
11106
11107                 /* check type_id */
11108                 type = btf_type_by_id(btf, krecord[i].type_id);
11109                 if (!type || !btf_type_is_func(type)) {
11110                         verbose(env, "invalid type id %d in func info",
11111                                 krecord[i].type_id);
11112                         goto err_free;
11113                 }
11114                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11115
11116                 func_proto = btf_type_by_id(btf, type->type);
11117                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11118                         /* btf_func_check() already verified it during BTF load */
11119                         goto err_free;
11120                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11121                 scalar_return =
11122                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11123                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11124                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11125                         goto err_free;
11126                 }
11127                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11128                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11129                         goto err_free;
11130                 }
11131
11132                 prev_offset = krecord[i].insn_off;
11133                 bpfptr_add(&urecord, urec_size);
11134         }
11135
11136         prog->aux->func_info = krecord;
11137         prog->aux->func_info_cnt = nfuncs;
11138         prog->aux->func_info_aux = info_aux;
11139         return 0;
11140
11141 err_free:
11142         kvfree(krecord);
11143         kfree(info_aux);
11144         return ret;
11145 }
11146
11147 static void adjust_btf_func(struct bpf_verifier_env *env)
11148 {
11149         struct bpf_prog_aux *aux = env->prog->aux;
11150         int i;
11151
11152         if (!aux->func_info)
11153                 return;
11154
11155         for (i = 0; i < env->subprog_cnt; i++)
11156                 aux->func_info[i].insn_off = env->subprog_info[i].start;
11157 }
11158
11159 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
11160 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
11161
11162 static int check_btf_line(struct bpf_verifier_env *env,
11163                           const union bpf_attr *attr,
11164                           bpfptr_t uattr)
11165 {
11166         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11167         struct bpf_subprog_info *sub;
11168         struct bpf_line_info *linfo;
11169         struct bpf_prog *prog;
11170         const struct btf *btf;
11171         bpfptr_t ulinfo;
11172         int err;
11173
11174         nr_linfo = attr->line_info_cnt;
11175         if (!nr_linfo)
11176                 return 0;
11177         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11178                 return -EINVAL;
11179
11180         rec_size = attr->line_info_rec_size;
11181         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11182             rec_size > MAX_LINEINFO_REC_SIZE ||
11183             rec_size & (sizeof(u32) - 1))
11184                 return -EINVAL;
11185
11186         /* Need to zero it in case the userspace may
11187          * pass in a smaller bpf_line_info object.
11188          */
11189         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11190                          GFP_KERNEL | __GFP_NOWARN);
11191         if (!linfo)
11192                 return -ENOMEM;
11193
11194         prog = env->prog;
11195         btf = prog->aux->btf;
11196
11197         s = 0;
11198         sub = env->subprog_info;
11199         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11200         expected_size = sizeof(struct bpf_line_info);
11201         ncopy = min_t(u32, expected_size, rec_size);
11202         for (i = 0; i < nr_linfo; i++) {
11203                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11204                 if (err) {
11205                         if (err == -E2BIG) {
11206                                 verbose(env, "nonzero tailing record in line_info");
11207                                 if (copy_to_bpfptr_offset(uattr,
11208                                                           offsetof(union bpf_attr, line_info_rec_size),
11209                                                           &expected_size, sizeof(expected_size)))
11210                                         err = -EFAULT;
11211                         }
11212                         goto err_free;
11213                 }
11214
11215                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11216                         err = -EFAULT;
11217                         goto err_free;
11218                 }
11219
11220                 /*
11221                  * Check insn_off to ensure
11222                  * 1) strictly increasing AND
11223                  * 2) bounded by prog->len
11224                  *
11225                  * The linfo[0].insn_off == 0 check logically falls into
11226                  * the later "missing bpf_line_info for func..." case
11227                  * because the first linfo[0].insn_off must be the
11228                  * first sub also and the first sub must have
11229                  * subprog_info[0].start == 0.
11230                  */
11231                 if ((i && linfo[i].insn_off <= prev_offset) ||
11232                     linfo[i].insn_off >= prog->len) {
11233                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11234                                 i, linfo[i].insn_off, prev_offset,
11235                                 prog->len);
11236                         err = -EINVAL;
11237                         goto err_free;
11238                 }
11239
11240                 if (!prog->insnsi[linfo[i].insn_off].code) {
11241                         verbose(env,
11242                                 "Invalid insn code at line_info[%u].insn_off\n",
11243                                 i);
11244                         err = -EINVAL;
11245                         goto err_free;
11246                 }
11247
11248                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11249                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11250                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11251                         err = -EINVAL;
11252                         goto err_free;
11253                 }
11254
11255                 if (s != env->subprog_cnt) {
11256                         if (linfo[i].insn_off == sub[s].start) {
11257                                 sub[s].linfo_idx = i;
11258                                 s++;
11259                         } else if (sub[s].start < linfo[i].insn_off) {
11260                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
11261                                 err = -EINVAL;
11262                                 goto err_free;
11263                         }
11264                 }
11265
11266                 prev_offset = linfo[i].insn_off;
11267                 bpfptr_add(&ulinfo, rec_size);
11268         }
11269
11270         if (s != env->subprog_cnt) {
11271                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11272                         env->subprog_cnt - s, s);
11273                 err = -EINVAL;
11274                 goto err_free;
11275         }
11276
11277         prog->aux->linfo = linfo;
11278         prog->aux->nr_linfo = nr_linfo;
11279
11280         return 0;
11281
11282 err_free:
11283         kvfree(linfo);
11284         return err;
11285 }
11286
11287 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
11288 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
11289
11290 static int check_core_relo(struct bpf_verifier_env *env,
11291                            const union bpf_attr *attr,
11292                            bpfptr_t uattr)
11293 {
11294         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11295         struct bpf_core_relo core_relo = {};
11296         struct bpf_prog *prog = env->prog;
11297         const struct btf *btf = prog->aux->btf;
11298         struct bpf_core_ctx ctx = {
11299                 .log = &env->log,
11300                 .btf = btf,
11301         };
11302         bpfptr_t u_core_relo;
11303         int err;
11304
11305         nr_core_relo = attr->core_relo_cnt;
11306         if (!nr_core_relo)
11307                 return 0;
11308         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11309                 return -EINVAL;
11310
11311         rec_size = attr->core_relo_rec_size;
11312         if (rec_size < MIN_CORE_RELO_SIZE ||
11313             rec_size > MAX_CORE_RELO_SIZE ||
11314             rec_size % sizeof(u32))
11315                 return -EINVAL;
11316
11317         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11318         expected_size = sizeof(struct bpf_core_relo);
11319         ncopy = min_t(u32, expected_size, rec_size);
11320
11321         /* Unlike func_info and line_info, copy and apply each CO-RE
11322          * relocation record one at a time.
11323          */
11324         for (i = 0; i < nr_core_relo; i++) {
11325                 /* future proofing when sizeof(bpf_core_relo) changes */
11326                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11327                 if (err) {
11328                         if (err == -E2BIG) {
11329                                 verbose(env, "nonzero tailing record in core_relo");
11330                                 if (copy_to_bpfptr_offset(uattr,
11331                                                           offsetof(union bpf_attr, core_relo_rec_size),
11332                                                           &expected_size, sizeof(expected_size)))
11333                                         err = -EFAULT;
11334                         }
11335                         break;
11336                 }
11337
11338                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11339                         err = -EFAULT;
11340                         break;
11341                 }
11342
11343                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11344                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11345                                 i, core_relo.insn_off, prog->len);
11346                         err = -EINVAL;
11347                         break;
11348                 }
11349
11350                 err = bpf_core_apply(&ctx, &core_relo, i,
11351                                      &prog->insnsi[core_relo.insn_off / 8]);
11352                 if (err)
11353                         break;
11354                 bpfptr_add(&u_core_relo, rec_size);
11355         }
11356         return err;
11357 }
11358
11359 static int check_btf_info(struct bpf_verifier_env *env,
11360                           const union bpf_attr *attr,
11361                           bpfptr_t uattr)
11362 {
11363         struct btf *btf;
11364         int err;
11365
11366         if (!attr->func_info_cnt && !attr->line_info_cnt) {
11367                 if (check_abnormal_return(env))
11368                         return -EINVAL;
11369                 return 0;
11370         }
11371
11372         btf = btf_get_by_fd(attr->prog_btf_fd);
11373         if (IS_ERR(btf))
11374                 return PTR_ERR(btf);
11375         if (btf_is_kernel(btf)) {
11376                 btf_put(btf);
11377                 return -EACCES;
11378         }
11379         env->prog->aux->btf = btf;
11380
11381         err = check_btf_func(env, attr, uattr);
11382         if (err)
11383                 return err;
11384
11385         err = check_btf_line(env, attr, uattr);
11386         if (err)
11387                 return err;
11388
11389         err = check_core_relo(env, attr, uattr);
11390         if (err)
11391                 return err;
11392
11393         return 0;
11394 }
11395
11396 /* check %cur's range satisfies %old's */
11397 static bool range_within(struct bpf_reg_state *old,
11398                          struct bpf_reg_state *cur)
11399 {
11400         return old->umin_value <= cur->umin_value &&
11401                old->umax_value >= cur->umax_value &&
11402                old->smin_value <= cur->smin_value &&
11403                old->smax_value >= cur->smax_value &&
11404                old->u32_min_value <= cur->u32_min_value &&
11405                old->u32_max_value >= cur->u32_max_value &&
11406                old->s32_min_value <= cur->s32_min_value &&
11407                old->s32_max_value >= cur->s32_max_value;
11408 }
11409
11410 /* If in the old state two registers had the same id, then they need to have
11411  * the same id in the new state as well.  But that id could be different from
11412  * the old state, so we need to track the mapping from old to new ids.
11413  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11414  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11415  * regs with a different old id could still have new id 9, we don't care about
11416  * that.
11417  * So we look through our idmap to see if this old id has been seen before.  If
11418  * so, we require the new id to match; otherwise, we add the id pair to the map.
11419  */
11420 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11421 {
11422         unsigned int i;
11423
11424         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11425                 if (!idmap[i].old) {
11426                         /* Reached an empty slot; haven't seen this id before */
11427                         idmap[i].old = old_id;
11428                         idmap[i].cur = cur_id;
11429                         return true;
11430                 }
11431                 if (idmap[i].old == old_id)
11432                         return idmap[i].cur == cur_id;
11433         }
11434         /* We ran out of idmap slots, which should be impossible */
11435         WARN_ON_ONCE(1);
11436         return false;
11437 }
11438
11439 static void clean_func_state(struct bpf_verifier_env *env,
11440                              struct bpf_func_state *st)
11441 {
11442         enum bpf_reg_liveness live;
11443         int i, j;
11444
11445         for (i = 0; i < BPF_REG_FP; i++) {
11446                 live = st->regs[i].live;
11447                 /* liveness must not touch this register anymore */
11448                 st->regs[i].live |= REG_LIVE_DONE;
11449                 if (!(live & REG_LIVE_READ))
11450                         /* since the register is unused, clear its state
11451                          * to make further comparison simpler
11452                          */
11453                         __mark_reg_not_init(env, &st->regs[i]);
11454         }
11455
11456         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11457                 live = st->stack[i].spilled_ptr.live;
11458                 /* liveness must not touch this stack slot anymore */
11459                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11460                 if (!(live & REG_LIVE_READ)) {
11461                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11462                         for (j = 0; j < BPF_REG_SIZE; j++)
11463                                 st->stack[i].slot_type[j] = STACK_INVALID;
11464                 }
11465         }
11466 }
11467
11468 static void clean_verifier_state(struct bpf_verifier_env *env,
11469                                  struct bpf_verifier_state *st)
11470 {
11471         int i;
11472
11473         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11474                 /* all regs in this state in all frames were already marked */
11475                 return;
11476
11477         for (i = 0; i <= st->curframe; i++)
11478                 clean_func_state(env, st->frame[i]);
11479 }
11480
11481 /* the parentage chains form a tree.
11482  * the verifier states are added to state lists at given insn and
11483  * pushed into state stack for future exploration.
11484  * when the verifier reaches bpf_exit insn some of the verifer states
11485  * stored in the state lists have their final liveness state already,
11486  * but a lot of states will get revised from liveness point of view when
11487  * the verifier explores other branches.
11488  * Example:
11489  * 1: r0 = 1
11490  * 2: if r1 == 100 goto pc+1
11491  * 3: r0 = 2
11492  * 4: exit
11493  * when the verifier reaches exit insn the register r0 in the state list of
11494  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11495  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11496  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11497  *
11498  * Since the verifier pushes the branch states as it sees them while exploring
11499  * the program the condition of walking the branch instruction for the second
11500  * time means that all states below this branch were already explored and
11501  * their final liveness marks are already propagated.
11502  * Hence when the verifier completes the search of state list in is_state_visited()
11503  * we can call this clean_live_states() function to mark all liveness states
11504  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11505  * will not be used.
11506  * This function also clears the registers and stack for states that !READ
11507  * to simplify state merging.
11508  *
11509  * Important note here that walking the same branch instruction in the callee
11510  * doesn't meant that the states are DONE. The verifier has to compare
11511  * the callsites
11512  */
11513 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11514                               struct bpf_verifier_state *cur)
11515 {
11516         struct bpf_verifier_state_list *sl;
11517         int i;
11518
11519         sl = *explored_state(env, insn);
11520         while (sl) {
11521                 if (sl->state.branches)
11522                         goto next;
11523                 if (sl->state.insn_idx != insn ||
11524                     sl->state.curframe != cur->curframe)
11525                         goto next;
11526                 for (i = 0; i <= cur->curframe; i++)
11527                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11528                                 goto next;
11529                 clean_verifier_state(env, &sl->state);
11530 next:
11531                 sl = sl->next;
11532         }
11533 }
11534
11535 /* Returns true if (rold safe implies rcur safe) */
11536 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11537                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11538 {
11539         bool equal;
11540
11541         if (!(rold->live & REG_LIVE_READ))
11542                 /* explored state didn't use this */
11543                 return true;
11544
11545         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11546
11547         if (rold->type == PTR_TO_STACK)
11548                 /* two stack pointers are equal only if they're pointing to
11549                  * the same stack frame, since fp-8 in foo != fp-8 in bar
11550                  */
11551                 return equal && rold->frameno == rcur->frameno;
11552
11553         if (equal)
11554                 return true;
11555
11556         if (rold->type == NOT_INIT)
11557                 /* explored state can't have used this */
11558                 return true;
11559         if (rcur->type == NOT_INIT)
11560                 return false;
11561         switch (base_type(rold->type)) {
11562         case SCALAR_VALUE:
11563                 if (env->explore_alu_limits)
11564                         return false;
11565                 if (rcur->type == SCALAR_VALUE) {
11566                         if (!rold->precise && !rcur->precise)
11567                                 return true;
11568                         /* new val must satisfy old val knowledge */
11569                         return range_within(rold, rcur) &&
11570                                tnum_in(rold->var_off, rcur->var_off);
11571                 } else {
11572                         /* We're trying to use a pointer in place of a scalar.
11573                          * Even if the scalar was unbounded, this could lead to
11574                          * pointer leaks because scalars are allowed to leak
11575                          * while pointers are not. We could make this safe in
11576                          * special cases if root is calling us, but it's
11577                          * probably not worth the hassle.
11578                          */
11579                         return false;
11580                 }
11581         case PTR_TO_MAP_KEY:
11582         case PTR_TO_MAP_VALUE:
11583                 /* a PTR_TO_MAP_VALUE could be safe to use as a
11584                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11585                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11586                  * checked, doing so could have affected others with the same
11587                  * id, and we can't check for that because we lost the id when
11588                  * we converted to a PTR_TO_MAP_VALUE.
11589                  */
11590                 if (type_may_be_null(rold->type)) {
11591                         if (!type_may_be_null(rcur->type))
11592                                 return false;
11593                         if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11594                                 return false;
11595                         /* Check our ids match any regs they're supposed to */
11596                         return check_ids(rold->id, rcur->id, idmap);
11597                 }
11598
11599                 /* If the new min/max/var_off satisfy the old ones and
11600                  * everything else matches, we are OK.
11601                  * 'id' is not compared, since it's only used for maps with
11602                  * bpf_spin_lock inside map element and in such cases if
11603                  * the rest of the prog is valid for one map element then
11604                  * it's valid for all map elements regardless of the key
11605                  * used in bpf_map_lookup()
11606                  */
11607                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11608                        range_within(rold, rcur) &&
11609                        tnum_in(rold->var_off, rcur->var_off);
11610         case PTR_TO_PACKET_META:
11611         case PTR_TO_PACKET:
11612                 if (rcur->type != rold->type)
11613                         return false;
11614                 /* We must have at least as much range as the old ptr
11615                  * did, so that any accesses which were safe before are
11616                  * still safe.  This is true even if old range < old off,
11617                  * since someone could have accessed through (ptr - k), or
11618                  * even done ptr -= k in a register, to get a safe access.
11619                  */
11620                 if (rold->range > rcur->range)
11621                         return false;
11622                 /* If the offsets don't match, we can't trust our alignment;
11623                  * nor can we be sure that we won't fall out of range.
11624                  */
11625                 if (rold->off != rcur->off)
11626                         return false;
11627                 /* id relations must be preserved */
11628                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11629                         return false;
11630                 /* new val must satisfy old val knowledge */
11631                 return range_within(rold, rcur) &&
11632                        tnum_in(rold->var_off, rcur->var_off);
11633         case PTR_TO_CTX:
11634         case CONST_PTR_TO_MAP:
11635         case PTR_TO_PACKET_END:
11636         case PTR_TO_FLOW_KEYS:
11637         case PTR_TO_SOCKET:
11638         case PTR_TO_SOCK_COMMON:
11639         case PTR_TO_TCP_SOCK:
11640         case PTR_TO_XDP_SOCK:
11641                 /* Only valid matches are exact, which memcmp() above
11642                  * would have accepted
11643                  */
11644         default:
11645                 /* Don't know what's going on, just say it's not safe */
11646                 return false;
11647         }
11648
11649         /* Shouldn't get here; if we do, say it's not safe */
11650         WARN_ON_ONCE(1);
11651         return false;
11652 }
11653
11654 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11655                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11656 {
11657         int i, spi;
11658
11659         /* walk slots of the explored stack and ignore any additional
11660          * slots in the current stack, since explored(safe) state
11661          * didn't use them
11662          */
11663         for (i = 0; i < old->allocated_stack; i++) {
11664                 spi = i / BPF_REG_SIZE;
11665
11666                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11667                         i += BPF_REG_SIZE - 1;
11668                         /* explored state didn't use this */
11669                         continue;
11670                 }
11671
11672                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11673                         continue;
11674
11675                 /* explored stack has more populated slots than current stack
11676                  * and these slots were used
11677                  */
11678                 if (i >= cur->allocated_stack)
11679                         return false;
11680
11681                 /* if old state was safe with misc data in the stack
11682                  * it will be safe with zero-initialized stack.
11683                  * The opposite is not true
11684                  */
11685                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11686                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11687                         continue;
11688                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11689                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11690                         /* Ex: old explored (safe) state has STACK_SPILL in
11691                          * this stack slot, but current has STACK_MISC ->
11692                          * this verifier states are not equivalent,
11693                          * return false to continue verification of this path
11694                          */
11695                         return false;
11696                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11697                         continue;
11698                 if (!is_spilled_reg(&old->stack[spi]))
11699                         continue;
11700                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11701                              &cur->stack[spi].spilled_ptr, idmap))
11702                         /* when explored and current stack slot are both storing
11703                          * spilled registers, check that stored pointers types
11704                          * are the same as well.
11705                          * Ex: explored safe path could have stored
11706                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11707                          * but current path has stored:
11708                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11709                          * such verifier states are not equivalent.
11710                          * return false to continue verification of this path
11711                          */
11712                         return false;
11713         }
11714         return true;
11715 }
11716
11717 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11718 {
11719         if (old->acquired_refs != cur->acquired_refs)
11720                 return false;
11721         return !memcmp(old->refs, cur->refs,
11722                        sizeof(*old->refs) * old->acquired_refs);
11723 }
11724
11725 /* compare two verifier states
11726  *
11727  * all states stored in state_list are known to be valid, since
11728  * verifier reached 'bpf_exit' instruction through them
11729  *
11730  * this function is called when verifier exploring different branches of
11731  * execution popped from the state stack. If it sees an old state that has
11732  * more strict register state and more strict stack state then this execution
11733  * branch doesn't need to be explored further, since verifier already
11734  * concluded that more strict state leads to valid finish.
11735  *
11736  * Therefore two states are equivalent if register state is more conservative
11737  * and explored stack state is more conservative than the current one.
11738  * Example:
11739  *       explored                   current
11740  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11741  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11742  *
11743  * In other words if current stack state (one being explored) has more
11744  * valid slots than old one that already passed validation, it means
11745  * the verifier can stop exploring and conclude that current state is valid too
11746  *
11747  * Similarly with registers. If explored state has register type as invalid
11748  * whereas register type in current state is meaningful, it means that
11749  * the current state will reach 'bpf_exit' instruction safely
11750  */
11751 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11752                               struct bpf_func_state *cur)
11753 {
11754         int i;
11755
11756         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11757         for (i = 0; i < MAX_BPF_REG; i++)
11758                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11759                              env->idmap_scratch))
11760                         return false;
11761
11762         if (!stacksafe(env, old, cur, env->idmap_scratch))
11763                 return false;
11764
11765         if (!refsafe(old, cur))
11766                 return false;
11767
11768         return true;
11769 }
11770
11771 static bool states_equal(struct bpf_verifier_env *env,
11772                          struct bpf_verifier_state *old,
11773                          struct bpf_verifier_state *cur)
11774 {
11775         int i;
11776
11777         if (old->curframe != cur->curframe)
11778                 return false;
11779
11780         /* Verification state from speculative execution simulation
11781          * must never prune a non-speculative execution one.
11782          */
11783         if (old->speculative && !cur->speculative)
11784                 return false;
11785
11786         if (old->active_spin_lock != cur->active_spin_lock)
11787                 return false;
11788
11789         /* for states to be equal callsites have to be the same
11790          * and all frame states need to be equivalent
11791          */
11792         for (i = 0; i <= old->curframe; i++) {
11793                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11794                         return false;
11795                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11796                         return false;
11797         }
11798         return true;
11799 }
11800
11801 /* Return 0 if no propagation happened. Return negative error code if error
11802  * happened. Otherwise, return the propagated bit.
11803  */
11804 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11805                                   struct bpf_reg_state *reg,
11806                                   struct bpf_reg_state *parent_reg)
11807 {
11808         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11809         u8 flag = reg->live & REG_LIVE_READ;
11810         int err;
11811
11812         /* When comes here, read flags of PARENT_REG or REG could be any of
11813          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11814          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11815          */
11816         if (parent_flag == REG_LIVE_READ64 ||
11817             /* Or if there is no read flag from REG. */
11818             !flag ||
11819             /* Or if the read flag from REG is the same as PARENT_REG. */
11820             parent_flag == flag)
11821                 return 0;
11822
11823         err = mark_reg_read(env, reg, parent_reg, flag);
11824         if (err)
11825                 return err;
11826
11827         return flag;
11828 }
11829
11830 /* A write screens off any subsequent reads; but write marks come from the
11831  * straight-line code between a state and its parent.  When we arrive at an
11832  * equivalent state (jump target or such) we didn't arrive by the straight-line
11833  * code, so read marks in the state must propagate to the parent regardless
11834  * of the state's write marks. That's what 'parent == state->parent' comparison
11835  * in mark_reg_read() is for.
11836  */
11837 static int propagate_liveness(struct bpf_verifier_env *env,
11838                               const struct bpf_verifier_state *vstate,
11839                               struct bpf_verifier_state *vparent)
11840 {
11841         struct bpf_reg_state *state_reg, *parent_reg;
11842         struct bpf_func_state *state, *parent;
11843         int i, frame, err = 0;
11844
11845         if (vparent->curframe != vstate->curframe) {
11846                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11847                      vparent->curframe, vstate->curframe);
11848                 return -EFAULT;
11849         }
11850         /* Propagate read liveness of registers... */
11851         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11852         for (frame = 0; frame <= vstate->curframe; frame++) {
11853                 parent = vparent->frame[frame];
11854                 state = vstate->frame[frame];
11855                 parent_reg = parent->regs;
11856                 state_reg = state->regs;
11857                 /* We don't need to worry about FP liveness, it's read-only */
11858                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11859                         err = propagate_liveness_reg(env, &state_reg[i],
11860                                                      &parent_reg[i]);
11861                         if (err < 0)
11862                                 return err;
11863                         if (err == REG_LIVE_READ64)
11864                                 mark_insn_zext(env, &parent_reg[i]);
11865                 }
11866
11867                 /* Propagate stack slots. */
11868                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11869                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11870                         parent_reg = &parent->stack[i].spilled_ptr;
11871                         state_reg = &state->stack[i].spilled_ptr;
11872                         err = propagate_liveness_reg(env, state_reg,
11873                                                      parent_reg);
11874                         if (err < 0)
11875                                 return err;
11876                 }
11877         }
11878         return 0;
11879 }
11880
11881 /* find precise scalars in the previous equivalent state and
11882  * propagate them into the current state
11883  */
11884 static int propagate_precision(struct bpf_verifier_env *env,
11885                                const struct bpf_verifier_state *old)
11886 {
11887         struct bpf_reg_state *state_reg;
11888         struct bpf_func_state *state;
11889         int i, err = 0, fr;
11890
11891         for (fr = old->curframe; fr >= 0; fr--) {
11892                 state = old->frame[fr];
11893                 state_reg = state->regs;
11894                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11895                         if (state_reg->type != SCALAR_VALUE ||
11896                             !state_reg->precise)
11897                                 continue;
11898                         if (env->log.level & BPF_LOG_LEVEL2)
11899                                 verbose(env, "frame %d: propagating r%d\n", i, fr);
11900                         err = mark_chain_precision_frame(env, fr, i);
11901                         if (err < 0)
11902                                 return err;
11903                 }
11904
11905                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11906                         if (!is_spilled_reg(&state->stack[i]))
11907                                 continue;
11908                         state_reg = &state->stack[i].spilled_ptr;
11909                         if (state_reg->type != SCALAR_VALUE ||
11910                             !state_reg->precise)
11911                                 continue;
11912                         if (env->log.level & BPF_LOG_LEVEL2)
11913                                 verbose(env, "frame %d: propagating fp%d\n",
11914                                         (-i - 1) * BPF_REG_SIZE, fr);
11915                         err = mark_chain_precision_stack_frame(env, fr, i);
11916                         if (err < 0)
11917                                 return err;
11918                 }
11919         }
11920         return 0;
11921 }
11922
11923 static bool states_maybe_looping(struct bpf_verifier_state *old,
11924                                  struct bpf_verifier_state *cur)
11925 {
11926         struct bpf_func_state *fold, *fcur;
11927         int i, fr = cur->curframe;
11928
11929         if (old->curframe != fr)
11930                 return false;
11931
11932         fold = old->frame[fr];
11933         fcur = cur->frame[fr];
11934         for (i = 0; i < MAX_BPF_REG; i++)
11935                 if (memcmp(&fold->regs[i], &fcur->regs[i],
11936                            offsetof(struct bpf_reg_state, parent)))
11937                         return false;
11938         return true;
11939 }
11940
11941
11942 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11943 {
11944         struct bpf_verifier_state_list *new_sl;
11945         struct bpf_verifier_state_list *sl, **pprev;
11946         struct bpf_verifier_state *cur = env->cur_state, *new;
11947         int i, j, err, states_cnt = 0;
11948         bool add_new_state = env->test_state_freq ? true : false;
11949
11950         cur->last_insn_idx = env->prev_insn_idx;
11951         if (!env->insn_aux_data[insn_idx].prune_point)
11952                 /* this 'insn_idx' instruction wasn't marked, so we will not
11953                  * be doing state search here
11954                  */
11955                 return 0;
11956
11957         /* bpf progs typically have pruning point every 4 instructions
11958          * http://vger.kernel.org/bpfconf2019.html#session-1
11959          * Do not add new state for future pruning if the verifier hasn't seen
11960          * at least 2 jumps and at least 8 instructions.
11961          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11962          * In tests that amounts to up to 50% reduction into total verifier
11963          * memory consumption and 20% verifier time speedup.
11964          */
11965         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11966             env->insn_processed - env->prev_insn_processed >= 8)
11967                 add_new_state = true;
11968
11969         pprev = explored_state(env, insn_idx);
11970         sl = *pprev;
11971
11972         clean_live_states(env, insn_idx, cur);
11973
11974         while (sl) {
11975                 states_cnt++;
11976                 if (sl->state.insn_idx != insn_idx)
11977                         goto next;
11978
11979                 if (sl->state.branches) {
11980                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11981
11982                         if (frame->in_async_callback_fn &&
11983                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11984                                 /* Different async_entry_cnt means that the verifier is
11985                                  * processing another entry into async callback.
11986                                  * Seeing the same state is not an indication of infinite
11987                                  * loop or infinite recursion.
11988                                  * But finding the same state doesn't mean that it's safe
11989                                  * to stop processing the current state. The previous state
11990                                  * hasn't yet reached bpf_exit, since state.branches > 0.
11991                                  * Checking in_async_callback_fn alone is not enough either.
11992                                  * Since the verifier still needs to catch infinite loops
11993                                  * inside async callbacks.
11994                                  */
11995                         } else if (states_maybe_looping(&sl->state, cur) &&
11996                                    states_equal(env, &sl->state, cur)) {
11997                                 verbose_linfo(env, insn_idx, "; ");
11998                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11999                                 return -EINVAL;
12000                         }
12001                         /* if the verifier is processing a loop, avoid adding new state
12002                          * too often, since different loop iterations have distinct
12003                          * states and may not help future pruning.
12004                          * This threshold shouldn't be too low to make sure that
12005                          * a loop with large bound will be rejected quickly.
12006                          * The most abusive loop will be:
12007                          * r1 += 1
12008                          * if r1 < 1000000 goto pc-2
12009                          * 1M insn_procssed limit / 100 == 10k peak states.
12010                          * This threshold shouldn't be too high either, since states
12011                          * at the end of the loop are likely to be useful in pruning.
12012                          */
12013                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
12014                             env->insn_processed - env->prev_insn_processed < 100)
12015                                 add_new_state = false;
12016                         goto miss;
12017                 }
12018                 if (states_equal(env, &sl->state, cur)) {
12019                         sl->hit_cnt++;
12020                         /* reached equivalent register/stack state,
12021                          * prune the search.
12022                          * Registers read by the continuation are read by us.
12023                          * If we have any write marks in env->cur_state, they
12024                          * will prevent corresponding reads in the continuation
12025                          * from reaching our parent (an explored_state).  Our
12026                          * own state will get the read marks recorded, but
12027                          * they'll be immediately forgotten as we're pruning
12028                          * this state and will pop a new one.
12029                          */
12030                         err = propagate_liveness(env, &sl->state, cur);
12031
12032                         /* if previous state reached the exit with precision and
12033                          * current state is equivalent to it (except precsion marks)
12034                          * the precision needs to be propagated back in
12035                          * the current state.
12036                          */
12037                         err = err ? : push_jmp_history(env, cur);
12038                         err = err ? : propagate_precision(env, &sl->state);
12039                         if (err)
12040                                 return err;
12041                         return 1;
12042                 }
12043 miss:
12044                 /* when new state is not going to be added do not increase miss count.
12045                  * Otherwise several loop iterations will remove the state
12046                  * recorded earlier. The goal of these heuristics is to have
12047                  * states from some iterations of the loop (some in the beginning
12048                  * and some at the end) to help pruning.
12049                  */
12050                 if (add_new_state)
12051                         sl->miss_cnt++;
12052                 /* heuristic to determine whether this state is beneficial
12053                  * to keep checking from state equivalence point of view.
12054                  * Higher numbers increase max_states_per_insn and verification time,
12055                  * but do not meaningfully decrease insn_processed.
12056                  */
12057                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12058                         /* the state is unlikely to be useful. Remove it to
12059                          * speed up verification
12060                          */
12061                         *pprev = sl->next;
12062                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12063                                 u32 br = sl->state.branches;
12064
12065                                 WARN_ONCE(br,
12066                                           "BUG live_done but branches_to_explore %d\n",
12067                                           br);
12068                                 free_verifier_state(&sl->state, false);
12069                                 kfree(sl);
12070                                 env->peak_states--;
12071                         } else {
12072                                 /* cannot free this state, since parentage chain may
12073                                  * walk it later. Add it for free_list instead to
12074                                  * be freed at the end of verification
12075                                  */
12076                                 sl->next = env->free_list;
12077                                 env->free_list = sl;
12078                         }
12079                         sl = *pprev;
12080                         continue;
12081                 }
12082 next:
12083                 pprev = &sl->next;
12084                 sl = *pprev;
12085         }
12086
12087         if (env->max_states_per_insn < states_cnt)
12088                 env->max_states_per_insn = states_cnt;
12089
12090         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12091                 return push_jmp_history(env, cur);
12092
12093         if (!add_new_state)
12094                 return push_jmp_history(env, cur);
12095
12096         /* There were no equivalent states, remember the current one.
12097          * Technically the current state is not proven to be safe yet,
12098          * but it will either reach outer most bpf_exit (which means it's safe)
12099          * or it will be rejected. When there are no loops the verifier won't be
12100          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12101          * again on the way to bpf_exit.
12102          * When looping the sl->state.branches will be > 0 and this state
12103          * will not be considered for equivalence until branches == 0.
12104          */
12105         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12106         if (!new_sl)
12107                 return -ENOMEM;
12108         env->total_states++;
12109         env->peak_states++;
12110         env->prev_jmps_processed = env->jmps_processed;
12111         env->prev_insn_processed = env->insn_processed;
12112
12113         /* add new state to the head of linked list */
12114         new = &new_sl->state;
12115         err = copy_verifier_state(new, cur);
12116         if (err) {
12117                 free_verifier_state(new, false);
12118                 kfree(new_sl);
12119                 return err;
12120         }
12121         new->insn_idx = insn_idx;
12122         WARN_ONCE(new->branches != 1,
12123                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12124
12125         cur->parent = new;
12126         cur->first_insn_idx = insn_idx;
12127         clear_jmp_history(cur);
12128         new_sl->next = *explored_state(env, insn_idx);
12129         *explored_state(env, insn_idx) = new_sl;
12130         /* connect new state to parentage chain. Current frame needs all
12131          * registers connected. Only r6 - r9 of the callers are alive (pushed
12132          * to the stack implicitly by JITs) so in callers' frames connect just
12133          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12134          * the state of the call instruction (with WRITTEN set), and r0 comes
12135          * from callee with its full parentage chain, anyway.
12136          */
12137         /* clear write marks in current state: the writes we did are not writes
12138          * our child did, so they don't screen off its reads from us.
12139          * (There are no read marks in current state, because reads always mark
12140          * their parent and current state never has children yet.  Only
12141          * explored_states can get read marks.)
12142          */
12143         for (j = 0; j <= cur->curframe; j++) {
12144                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12145                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12146                 for (i = 0; i < BPF_REG_FP; i++)
12147                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12148         }
12149
12150         /* all stack frames are accessible from callee, clear them all */
12151         for (j = 0; j <= cur->curframe; j++) {
12152                 struct bpf_func_state *frame = cur->frame[j];
12153                 struct bpf_func_state *newframe = new->frame[j];
12154
12155                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12156                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12157                         frame->stack[i].spilled_ptr.parent =
12158                                                 &newframe->stack[i].spilled_ptr;
12159                 }
12160         }
12161         return 0;
12162 }
12163
12164 /* Return true if it's OK to have the same insn return a different type. */
12165 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12166 {
12167         switch (base_type(type)) {
12168         case PTR_TO_CTX:
12169         case PTR_TO_SOCKET:
12170         case PTR_TO_SOCK_COMMON:
12171         case PTR_TO_TCP_SOCK:
12172         case PTR_TO_XDP_SOCK:
12173         case PTR_TO_BTF_ID:
12174                 return false;
12175         default:
12176                 return true;
12177         }
12178 }
12179
12180 /* If an instruction was previously used with particular pointer types, then we
12181  * need to be careful to avoid cases such as the below, where it may be ok
12182  * for one branch accessing the pointer, but not ok for the other branch:
12183  *
12184  * R1 = sock_ptr
12185  * goto X;
12186  * ...
12187  * R1 = some_other_valid_ptr;
12188  * goto X;
12189  * ...
12190  * R2 = *(u32 *)(R1 + 0);
12191  */
12192 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12193 {
12194         return src != prev && (!reg_type_mismatch_ok(src) ||
12195                                !reg_type_mismatch_ok(prev));
12196 }
12197
12198 static int do_check(struct bpf_verifier_env *env)
12199 {
12200         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12201         struct bpf_verifier_state *state = env->cur_state;
12202         struct bpf_insn *insns = env->prog->insnsi;
12203         struct bpf_reg_state *regs;
12204         int insn_cnt = env->prog->len;
12205         bool do_print_state = false;
12206         int prev_insn_idx = -1;
12207
12208         for (;;) {
12209                 struct bpf_insn *insn;
12210                 u8 class;
12211                 int err;
12212
12213                 env->prev_insn_idx = prev_insn_idx;
12214                 if (env->insn_idx >= insn_cnt) {
12215                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
12216                                 env->insn_idx, insn_cnt);
12217                         return -EFAULT;
12218                 }
12219
12220                 insn = &insns[env->insn_idx];
12221                 class = BPF_CLASS(insn->code);
12222
12223                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12224                         verbose(env,
12225                                 "BPF program is too large. Processed %d insn\n",
12226                                 env->insn_processed);
12227                         return -E2BIG;
12228                 }
12229
12230                 err = is_state_visited(env, env->insn_idx);
12231                 if (err < 0)
12232                         return err;
12233                 if (err == 1) {
12234                         /* found equivalent state, can prune the search */
12235                         if (env->log.level & BPF_LOG_LEVEL) {
12236                                 if (do_print_state)
12237                                         verbose(env, "\nfrom %d to %d%s: safe\n",
12238                                                 env->prev_insn_idx, env->insn_idx,
12239                                                 env->cur_state->speculative ?
12240                                                 " (speculative execution)" : "");
12241                                 else
12242                                         verbose(env, "%d: safe\n", env->insn_idx);
12243                         }
12244                         goto process_bpf_exit;
12245                 }
12246
12247                 if (signal_pending(current))
12248                         return -EAGAIN;
12249
12250                 if (need_resched())
12251                         cond_resched();
12252
12253                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12254                         verbose(env, "\nfrom %d to %d%s:",
12255                                 env->prev_insn_idx, env->insn_idx,
12256                                 env->cur_state->speculative ?
12257                                 " (speculative execution)" : "");
12258                         print_verifier_state(env, state->frame[state->curframe], true);
12259                         do_print_state = false;
12260                 }
12261
12262                 if (env->log.level & BPF_LOG_LEVEL) {
12263                         const struct bpf_insn_cbs cbs = {
12264                                 .cb_call        = disasm_kfunc_name,
12265                                 .cb_print       = verbose,
12266                                 .private_data   = env,
12267                         };
12268
12269                         if (verifier_state_scratched(env))
12270                                 print_insn_state(env, state->frame[state->curframe]);
12271
12272                         verbose_linfo(env, env->insn_idx, "; ");
12273                         env->prev_log_len = env->log.len_used;
12274                         verbose(env, "%d: ", env->insn_idx);
12275                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12276                         env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12277                         env->prev_log_len = env->log.len_used;
12278                 }
12279
12280                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12281                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12282                                                            env->prev_insn_idx);
12283                         if (err)
12284                                 return err;
12285                 }
12286
12287                 regs = cur_regs(env);
12288                 sanitize_mark_insn_seen(env);
12289                 prev_insn_idx = env->insn_idx;
12290
12291                 if (class == BPF_ALU || class == BPF_ALU64) {
12292                         err = check_alu_op(env, insn);
12293                         if (err)
12294                                 return err;
12295
12296                 } else if (class == BPF_LDX) {
12297                         enum bpf_reg_type *prev_src_type, src_reg_type;
12298
12299                         /* check for reserved fields is already done */
12300
12301                         /* check src operand */
12302                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12303                         if (err)
12304                                 return err;
12305
12306                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12307                         if (err)
12308                                 return err;
12309
12310                         src_reg_type = regs[insn->src_reg].type;
12311
12312                         /* check that memory (src_reg + off) is readable,
12313                          * the state of dst_reg will be updated by this func
12314                          */
12315                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
12316                                                insn->off, BPF_SIZE(insn->code),
12317                                                BPF_READ, insn->dst_reg, false);
12318                         if (err)
12319                                 return err;
12320
12321                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12322
12323                         if (*prev_src_type == NOT_INIT) {
12324                                 /* saw a valid insn
12325                                  * dst_reg = *(u32 *)(src_reg + off)
12326                                  * save type to validate intersecting paths
12327                                  */
12328                                 *prev_src_type = src_reg_type;
12329
12330                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12331                                 /* ABuser program is trying to use the same insn
12332                                  * dst_reg = *(u32*) (src_reg + off)
12333                                  * with different pointer types:
12334                                  * src_reg == ctx in one branch and
12335                                  * src_reg == stack|map in some other branch.
12336                                  * Reject it.
12337                                  */
12338                                 verbose(env, "same insn cannot be used with different pointers\n");
12339                                 return -EINVAL;
12340                         }
12341
12342                 } else if (class == BPF_STX) {
12343                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
12344
12345                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12346                                 err = check_atomic(env, env->insn_idx, insn);
12347                                 if (err)
12348                                         return err;
12349                                 env->insn_idx++;
12350                                 continue;
12351                         }
12352
12353                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12354                                 verbose(env, "BPF_STX uses reserved fields\n");
12355                                 return -EINVAL;
12356                         }
12357
12358                         /* check src1 operand */
12359                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12360                         if (err)
12361                                 return err;
12362                         /* check src2 operand */
12363                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12364                         if (err)
12365                                 return err;
12366
12367                         dst_reg_type = regs[insn->dst_reg].type;
12368
12369                         /* check that memory (dst_reg + off) is writeable */
12370                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12371                                                insn->off, BPF_SIZE(insn->code),
12372                                                BPF_WRITE, insn->src_reg, false);
12373                         if (err)
12374                                 return err;
12375
12376                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12377
12378                         if (*prev_dst_type == NOT_INIT) {
12379                                 *prev_dst_type = dst_reg_type;
12380                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12381                                 verbose(env, "same insn cannot be used with different pointers\n");
12382                                 return -EINVAL;
12383                         }
12384
12385                 } else if (class == BPF_ST) {
12386                         if (BPF_MODE(insn->code) != BPF_MEM ||
12387                             insn->src_reg != BPF_REG_0) {
12388                                 verbose(env, "BPF_ST uses reserved fields\n");
12389                                 return -EINVAL;
12390                         }
12391                         /* check src operand */
12392                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12393                         if (err)
12394                                 return err;
12395
12396                         if (is_ctx_reg(env, insn->dst_reg)) {
12397                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12398                                         insn->dst_reg,
12399                                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12400                                 return -EACCES;
12401                         }
12402
12403                         /* check that memory (dst_reg + off) is writeable */
12404                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12405                                                insn->off, BPF_SIZE(insn->code),
12406                                                BPF_WRITE, -1, false);
12407                         if (err)
12408                                 return err;
12409
12410                 } else if (class == BPF_JMP || class == BPF_JMP32) {
12411                         u8 opcode = BPF_OP(insn->code);
12412
12413                         env->jmps_processed++;
12414                         if (opcode == BPF_CALL) {
12415                                 if (BPF_SRC(insn->code) != BPF_K ||
12416                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12417                                      && insn->off != 0) ||
12418                                     (insn->src_reg != BPF_REG_0 &&
12419                                      insn->src_reg != BPF_PSEUDO_CALL &&
12420                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12421                                     insn->dst_reg != BPF_REG_0 ||
12422                                     class == BPF_JMP32) {
12423                                         verbose(env, "BPF_CALL uses reserved fields\n");
12424                                         return -EINVAL;
12425                                 }
12426
12427                                 if (env->cur_state->active_spin_lock &&
12428                                     (insn->src_reg == BPF_PSEUDO_CALL ||
12429                                      insn->imm != BPF_FUNC_spin_unlock)) {
12430                                         verbose(env, "function calls are not allowed while holding a lock\n");
12431                                         return -EINVAL;
12432                                 }
12433                                 if (insn->src_reg == BPF_PSEUDO_CALL)
12434                                         err = check_func_call(env, insn, &env->insn_idx);
12435                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12436                                         err = check_kfunc_call(env, insn, &env->insn_idx);
12437                                 else
12438                                         err = check_helper_call(env, insn, &env->insn_idx);
12439                                 if (err)
12440                                         return err;
12441                         } else if (opcode == BPF_JA) {
12442                                 if (BPF_SRC(insn->code) != BPF_K ||
12443                                     insn->imm != 0 ||
12444                                     insn->src_reg != BPF_REG_0 ||
12445                                     insn->dst_reg != BPF_REG_0 ||
12446                                     class == BPF_JMP32) {
12447                                         verbose(env, "BPF_JA uses reserved fields\n");
12448                                         return -EINVAL;
12449                                 }
12450
12451                                 env->insn_idx += insn->off + 1;
12452                                 continue;
12453
12454                         } else if (opcode == BPF_EXIT) {
12455                                 if (BPF_SRC(insn->code) != BPF_K ||
12456                                     insn->imm != 0 ||
12457                                     insn->src_reg != BPF_REG_0 ||
12458                                     insn->dst_reg != BPF_REG_0 ||
12459                                     class == BPF_JMP32) {
12460                                         verbose(env, "BPF_EXIT uses reserved fields\n");
12461                                         return -EINVAL;
12462                                 }
12463
12464                                 if (env->cur_state->active_spin_lock) {
12465                                         verbose(env, "bpf_spin_unlock is missing\n");
12466                                         return -EINVAL;
12467                                 }
12468
12469                                 /* We must do check_reference_leak here before
12470                                  * prepare_func_exit to handle the case when
12471                                  * state->curframe > 0, it may be a callback
12472                                  * function, for which reference_state must
12473                                  * match caller reference state when it exits.
12474                                  */
12475                                 err = check_reference_leak(env);
12476                                 if (err)
12477                                         return err;
12478
12479                                 if (state->curframe) {
12480                                         /* exit from nested function */
12481                                         err = prepare_func_exit(env, &env->insn_idx);
12482                                         if (err)
12483                                                 return err;
12484                                         do_print_state = true;
12485                                         continue;
12486                                 }
12487
12488                                 err = check_return_code(env);
12489                                 if (err)
12490                                         return err;
12491 process_bpf_exit:
12492                                 mark_verifier_state_scratched(env);
12493                                 update_branch_counts(env, env->cur_state);
12494                                 err = pop_stack(env, &prev_insn_idx,
12495                                                 &env->insn_idx, pop_log);
12496                                 if (err < 0) {
12497                                         if (err != -ENOENT)
12498                                                 return err;
12499                                         break;
12500                                 } else {
12501                                         do_print_state = true;
12502                                         continue;
12503                                 }
12504                         } else {
12505                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12506                                 if (err)
12507                                         return err;
12508                         }
12509                 } else if (class == BPF_LD) {
12510                         u8 mode = BPF_MODE(insn->code);
12511
12512                         if (mode == BPF_ABS || mode == BPF_IND) {
12513                                 err = check_ld_abs(env, insn);
12514                                 if (err)
12515                                         return err;
12516
12517                         } else if (mode == BPF_IMM) {
12518                                 err = check_ld_imm(env, insn);
12519                                 if (err)
12520                                         return err;
12521
12522                                 env->insn_idx++;
12523                                 sanitize_mark_insn_seen(env);
12524                         } else {
12525                                 verbose(env, "invalid BPF_LD mode\n");
12526                                 return -EINVAL;
12527                         }
12528                 } else {
12529                         verbose(env, "unknown insn class %d\n", class);
12530                         return -EINVAL;
12531                 }
12532
12533                 env->insn_idx++;
12534         }
12535
12536         return 0;
12537 }
12538
12539 static int find_btf_percpu_datasec(struct btf *btf)
12540 {
12541         const struct btf_type *t;
12542         const char *tname;
12543         int i, n;
12544
12545         /*
12546          * Both vmlinux and module each have their own ".data..percpu"
12547          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12548          * types to look at only module's own BTF types.
12549          */
12550         n = btf_nr_types(btf);
12551         if (btf_is_module(btf))
12552                 i = btf_nr_types(btf_vmlinux);
12553         else
12554                 i = 1;
12555
12556         for(; i < n; i++) {
12557                 t = btf_type_by_id(btf, i);
12558                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12559                         continue;
12560
12561                 tname = btf_name_by_offset(btf, t->name_off);
12562                 if (!strcmp(tname, ".data..percpu"))
12563                         return i;
12564         }
12565
12566         return -ENOENT;
12567 }
12568
12569 /* replace pseudo btf_id with kernel symbol address */
12570 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12571                                struct bpf_insn *insn,
12572                                struct bpf_insn_aux_data *aux)
12573 {
12574         const struct btf_var_secinfo *vsi;
12575         const struct btf_type *datasec;
12576         struct btf_mod_pair *btf_mod;
12577         const struct btf_type *t;
12578         const char *sym_name;
12579         bool percpu = false;
12580         u32 type, id = insn->imm;
12581         struct btf *btf;
12582         s32 datasec_id;
12583         u64 addr;
12584         int i, btf_fd, err;
12585
12586         btf_fd = insn[1].imm;
12587         if (btf_fd) {
12588                 btf = btf_get_by_fd(btf_fd);
12589                 if (IS_ERR(btf)) {
12590                         verbose(env, "invalid module BTF object FD specified.\n");
12591                         return -EINVAL;
12592                 }
12593         } else {
12594                 if (!btf_vmlinux) {
12595                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12596                         return -EINVAL;
12597                 }
12598                 btf = btf_vmlinux;
12599                 btf_get(btf);
12600         }
12601
12602         t = btf_type_by_id(btf, id);
12603         if (!t) {
12604                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12605                 err = -ENOENT;
12606                 goto err_put;
12607         }
12608
12609         if (!btf_type_is_var(t)) {
12610                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12611                 err = -EINVAL;
12612                 goto err_put;
12613         }
12614
12615         sym_name = btf_name_by_offset(btf, t->name_off);
12616         addr = kallsyms_lookup_name(sym_name);
12617         if (!addr) {
12618                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12619                         sym_name);
12620                 err = -ENOENT;
12621                 goto err_put;
12622         }
12623
12624         datasec_id = find_btf_percpu_datasec(btf);
12625         if (datasec_id > 0) {
12626                 datasec = btf_type_by_id(btf, datasec_id);
12627                 for_each_vsi(i, datasec, vsi) {
12628                         if (vsi->type == id) {
12629                                 percpu = true;
12630                                 break;
12631                         }
12632                 }
12633         }
12634
12635         insn[0].imm = (u32)addr;
12636         insn[1].imm = addr >> 32;
12637
12638         type = t->type;
12639         t = btf_type_skip_modifiers(btf, type, NULL);
12640         if (percpu) {
12641                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12642                 aux->btf_var.btf = btf;
12643                 aux->btf_var.btf_id = type;
12644         } else if (!btf_type_is_struct(t)) {
12645                 const struct btf_type *ret;
12646                 const char *tname;
12647                 u32 tsize;
12648
12649                 /* resolve the type size of ksym. */
12650                 ret = btf_resolve_size(btf, t, &tsize);
12651                 if (IS_ERR(ret)) {
12652                         tname = btf_name_by_offset(btf, t->name_off);
12653                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12654                                 tname, PTR_ERR(ret));
12655                         err = -EINVAL;
12656                         goto err_put;
12657                 }
12658                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12659                 aux->btf_var.mem_size = tsize;
12660         } else {
12661                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12662                 aux->btf_var.btf = btf;
12663                 aux->btf_var.btf_id = type;
12664         }
12665
12666         /* check whether we recorded this BTF (and maybe module) already */
12667         for (i = 0; i < env->used_btf_cnt; i++) {
12668                 if (env->used_btfs[i].btf == btf) {
12669                         btf_put(btf);
12670                         return 0;
12671                 }
12672         }
12673
12674         if (env->used_btf_cnt >= MAX_USED_BTFS) {
12675                 err = -E2BIG;
12676                 goto err_put;
12677         }
12678
12679         btf_mod = &env->used_btfs[env->used_btf_cnt];
12680         btf_mod->btf = btf;
12681         btf_mod->module = NULL;
12682
12683         /* if we reference variables from kernel module, bump its refcount */
12684         if (btf_is_module(btf)) {
12685                 btf_mod->module = btf_try_get_module(btf);
12686                 if (!btf_mod->module) {
12687                         err = -ENXIO;
12688                         goto err_put;
12689                 }
12690         }
12691
12692         env->used_btf_cnt++;
12693
12694         return 0;
12695 err_put:
12696         btf_put(btf);
12697         return err;
12698 }
12699
12700 static bool is_tracing_prog_type(enum bpf_prog_type type)
12701 {
12702         switch (type) {
12703         case BPF_PROG_TYPE_KPROBE:
12704         case BPF_PROG_TYPE_TRACEPOINT:
12705         case BPF_PROG_TYPE_PERF_EVENT:
12706         case BPF_PROG_TYPE_RAW_TRACEPOINT:
12707         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12708                 return true;
12709         default:
12710                 return false;
12711         }
12712 }
12713
12714 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12715                                         struct bpf_map *map,
12716                                         struct bpf_prog *prog)
12717
12718 {
12719         enum bpf_prog_type prog_type = resolve_prog_type(prog);
12720
12721         if (map_value_has_spin_lock(map)) {
12722                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12723                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12724                         return -EINVAL;
12725                 }
12726
12727                 if (is_tracing_prog_type(prog_type)) {
12728                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12729                         return -EINVAL;
12730                 }
12731
12732                 if (prog->aux->sleepable) {
12733                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12734                         return -EINVAL;
12735                 }
12736         }
12737
12738         if (map_value_has_timer(map)) {
12739                 if (is_tracing_prog_type(prog_type)) {
12740                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
12741                         return -EINVAL;
12742                 }
12743         }
12744
12745         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12746             !bpf_offload_prog_map_match(prog, map)) {
12747                 verbose(env, "offload device mismatch between prog and map\n");
12748                 return -EINVAL;
12749         }
12750
12751         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12752                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12753                 return -EINVAL;
12754         }
12755
12756         if (prog->aux->sleepable)
12757                 switch (map->map_type) {
12758                 case BPF_MAP_TYPE_HASH:
12759                 case BPF_MAP_TYPE_LRU_HASH:
12760                 case BPF_MAP_TYPE_ARRAY:
12761                 case BPF_MAP_TYPE_PERCPU_HASH:
12762                 case BPF_MAP_TYPE_PERCPU_ARRAY:
12763                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12764                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12765                 case BPF_MAP_TYPE_HASH_OF_MAPS:
12766                 case BPF_MAP_TYPE_RINGBUF:
12767                 case BPF_MAP_TYPE_USER_RINGBUF:
12768                 case BPF_MAP_TYPE_INODE_STORAGE:
12769                 case BPF_MAP_TYPE_SK_STORAGE:
12770                 case BPF_MAP_TYPE_TASK_STORAGE:
12771                         break;
12772                 default:
12773                         verbose(env,
12774                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12775                         return -EINVAL;
12776                 }
12777
12778         return 0;
12779 }
12780
12781 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12782 {
12783         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12784                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12785 }
12786
12787 /* find and rewrite pseudo imm in ld_imm64 instructions:
12788  *
12789  * 1. if it accesses map FD, replace it with actual map pointer.
12790  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12791  *
12792  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12793  */
12794 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12795 {
12796         struct bpf_insn *insn = env->prog->insnsi;
12797         int insn_cnt = env->prog->len;
12798         int i, j, err;
12799
12800         err = bpf_prog_calc_tag(env->prog);
12801         if (err)
12802                 return err;
12803
12804         for (i = 0; i < insn_cnt; i++, insn++) {
12805                 if (BPF_CLASS(insn->code) == BPF_LDX &&
12806                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12807                         verbose(env, "BPF_LDX uses reserved fields\n");
12808                         return -EINVAL;
12809                 }
12810
12811                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12812                         struct bpf_insn_aux_data *aux;
12813                         struct bpf_map *map;
12814                         struct fd f;
12815                         u64 addr;
12816                         u32 fd;
12817
12818                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
12819                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12820                             insn[1].off != 0) {
12821                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
12822                                 return -EINVAL;
12823                         }
12824
12825                         if (insn[0].src_reg == 0)
12826                                 /* valid generic load 64-bit imm */
12827                                 goto next_insn;
12828
12829                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12830                                 aux = &env->insn_aux_data[i];
12831                                 err = check_pseudo_btf_id(env, insn, aux);
12832                                 if (err)
12833                                         return err;
12834                                 goto next_insn;
12835                         }
12836
12837                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12838                                 aux = &env->insn_aux_data[i];
12839                                 aux->ptr_type = PTR_TO_FUNC;
12840                                 goto next_insn;
12841                         }
12842
12843                         /* In final convert_pseudo_ld_imm64() step, this is
12844                          * converted into regular 64-bit imm load insn.
12845                          */
12846                         switch (insn[0].src_reg) {
12847                         case BPF_PSEUDO_MAP_VALUE:
12848                         case BPF_PSEUDO_MAP_IDX_VALUE:
12849                                 break;
12850                         case BPF_PSEUDO_MAP_FD:
12851                         case BPF_PSEUDO_MAP_IDX:
12852                                 if (insn[1].imm == 0)
12853                                         break;
12854                                 fallthrough;
12855                         default:
12856                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12857                                 return -EINVAL;
12858                         }
12859
12860                         switch (insn[0].src_reg) {
12861                         case BPF_PSEUDO_MAP_IDX_VALUE:
12862                         case BPF_PSEUDO_MAP_IDX:
12863                                 if (bpfptr_is_null(env->fd_array)) {
12864                                         verbose(env, "fd_idx without fd_array is invalid\n");
12865                                         return -EPROTO;
12866                                 }
12867                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12868                                                             insn[0].imm * sizeof(fd),
12869                                                             sizeof(fd)))
12870                                         return -EFAULT;
12871                                 break;
12872                         default:
12873                                 fd = insn[0].imm;
12874                                 break;
12875                         }
12876
12877                         f = fdget(fd);
12878                         map = __bpf_map_get(f);
12879                         if (IS_ERR(map)) {
12880                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12881                                         insn[0].imm);
12882                                 return PTR_ERR(map);
12883                         }
12884
12885                         err = check_map_prog_compatibility(env, map, env->prog);
12886                         if (err) {
12887                                 fdput(f);
12888                                 return err;
12889                         }
12890
12891                         aux = &env->insn_aux_data[i];
12892                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12893                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12894                                 addr = (unsigned long)map;
12895                         } else {
12896                                 u32 off = insn[1].imm;
12897
12898                                 if (off >= BPF_MAX_VAR_OFF) {
12899                                         verbose(env, "direct value offset of %u is not allowed\n", off);
12900                                         fdput(f);
12901                                         return -EINVAL;
12902                                 }
12903
12904                                 if (!map->ops->map_direct_value_addr) {
12905                                         verbose(env, "no direct value access support for this map type\n");
12906                                         fdput(f);
12907                                         return -EINVAL;
12908                                 }
12909
12910                                 err = map->ops->map_direct_value_addr(map, &addr, off);
12911                                 if (err) {
12912                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12913                                                 map->value_size, off);
12914                                         fdput(f);
12915                                         return err;
12916                                 }
12917
12918                                 aux->map_off = off;
12919                                 addr += off;
12920                         }
12921
12922                         insn[0].imm = (u32)addr;
12923                         insn[1].imm = addr >> 32;
12924
12925                         /* check whether we recorded this map already */
12926                         for (j = 0; j < env->used_map_cnt; j++) {
12927                                 if (env->used_maps[j] == map) {
12928                                         aux->map_index = j;
12929                                         fdput(f);
12930                                         goto next_insn;
12931                                 }
12932                         }
12933
12934                         if (env->used_map_cnt >= MAX_USED_MAPS) {
12935                                 fdput(f);
12936                                 return -E2BIG;
12937                         }
12938
12939                         /* hold the map. If the program is rejected by verifier,
12940                          * the map will be released by release_maps() or it
12941                          * will be used by the valid program until it's unloaded
12942                          * and all maps are released in free_used_maps()
12943                          */
12944                         bpf_map_inc(map);
12945
12946                         aux->map_index = env->used_map_cnt;
12947                         env->used_maps[env->used_map_cnt++] = map;
12948
12949                         if (bpf_map_is_cgroup_storage(map) &&
12950                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
12951                                 verbose(env, "only one cgroup storage of each type is allowed\n");
12952                                 fdput(f);
12953                                 return -EBUSY;
12954                         }
12955
12956                         fdput(f);
12957 next_insn:
12958                         insn++;
12959                         i++;
12960                         continue;
12961                 }
12962
12963                 /* Basic sanity check before we invest more work here. */
12964                 if (!bpf_opcode_in_insntable(insn->code)) {
12965                         verbose(env, "unknown opcode %02x\n", insn->code);
12966                         return -EINVAL;
12967                 }
12968         }
12969
12970         /* now all pseudo BPF_LD_IMM64 instructions load valid
12971          * 'struct bpf_map *' into a register instead of user map_fd.
12972          * These pointers will be used later by verifier to validate map access.
12973          */
12974         return 0;
12975 }
12976
12977 /* drop refcnt of maps used by the rejected program */
12978 static void release_maps(struct bpf_verifier_env *env)
12979 {
12980         __bpf_free_used_maps(env->prog->aux, env->used_maps,
12981                              env->used_map_cnt);
12982 }
12983
12984 /* drop refcnt of maps used by the rejected program */
12985 static void release_btfs(struct bpf_verifier_env *env)
12986 {
12987         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12988                              env->used_btf_cnt);
12989 }
12990
12991 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12992 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12993 {
12994         struct bpf_insn *insn = env->prog->insnsi;
12995         int insn_cnt = env->prog->len;
12996         int i;
12997
12998         for (i = 0; i < insn_cnt; i++, insn++) {
12999                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
13000                         continue;
13001                 if (insn->src_reg == BPF_PSEUDO_FUNC)
13002                         continue;
13003                 insn->src_reg = 0;
13004         }
13005 }
13006
13007 /* single env->prog->insni[off] instruction was replaced with the range
13008  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
13009  * [0, off) and [off, end) to new locations, so the patched range stays zero
13010  */
13011 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
13012                                  struct bpf_insn_aux_data *new_data,
13013                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
13014 {
13015         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
13016         struct bpf_insn *insn = new_prog->insnsi;
13017         u32 old_seen = old_data[off].seen;
13018         u32 prog_len;
13019         int i;
13020
13021         /* aux info at OFF always needs adjustment, no matter fast path
13022          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13023          * original insn at old prog.
13024          */
13025         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13026
13027         if (cnt == 1)
13028                 return;
13029         prog_len = new_prog->len;
13030
13031         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13032         memcpy(new_data + off + cnt - 1, old_data + off,
13033                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13034         for (i = off; i < off + cnt - 1; i++) {
13035                 /* Expand insni[off]'s seen count to the patched range. */
13036                 new_data[i].seen = old_seen;
13037                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
13038         }
13039         env->insn_aux_data = new_data;
13040         vfree(old_data);
13041 }
13042
13043 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13044 {
13045         int i;
13046
13047         if (len == 1)
13048                 return;
13049         /* NOTE: fake 'exit' subprog should be updated as well. */
13050         for (i = 0; i <= env->subprog_cnt; i++) {
13051                 if (env->subprog_info[i].start <= off)
13052                         continue;
13053                 env->subprog_info[i].start += len - 1;
13054         }
13055 }
13056
13057 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13058 {
13059         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13060         int i, sz = prog->aux->size_poke_tab;
13061         struct bpf_jit_poke_descriptor *desc;
13062
13063         for (i = 0; i < sz; i++) {
13064                 desc = &tab[i];
13065                 if (desc->insn_idx <= off)
13066                         continue;
13067                 desc->insn_idx += len - 1;
13068         }
13069 }
13070
13071 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13072                                             const struct bpf_insn *patch, u32 len)
13073 {
13074         struct bpf_prog *new_prog;
13075         struct bpf_insn_aux_data *new_data = NULL;
13076
13077         if (len > 1) {
13078                 new_data = vzalloc(array_size(env->prog->len + len - 1,
13079                                               sizeof(struct bpf_insn_aux_data)));
13080                 if (!new_data)
13081                         return NULL;
13082         }
13083
13084         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13085         if (IS_ERR(new_prog)) {
13086                 if (PTR_ERR(new_prog) == -ERANGE)
13087                         verbose(env,
13088                                 "insn %d cannot be patched due to 16-bit range\n",
13089                                 env->insn_aux_data[off].orig_idx);
13090                 vfree(new_data);
13091                 return NULL;
13092         }
13093         adjust_insn_aux_data(env, new_data, new_prog, off, len);
13094         adjust_subprog_starts(env, off, len);
13095         adjust_poke_descs(new_prog, off, len);
13096         return new_prog;
13097 }
13098
13099 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13100                                               u32 off, u32 cnt)
13101 {
13102         int i, j;
13103
13104         /* find first prog starting at or after off (first to remove) */
13105         for (i = 0; i < env->subprog_cnt; i++)
13106                 if (env->subprog_info[i].start >= off)
13107                         break;
13108         /* find first prog starting at or after off + cnt (first to stay) */
13109         for (j = i; j < env->subprog_cnt; j++)
13110                 if (env->subprog_info[j].start >= off + cnt)
13111                         break;
13112         /* if j doesn't start exactly at off + cnt, we are just removing
13113          * the front of previous prog
13114          */
13115         if (env->subprog_info[j].start != off + cnt)
13116                 j--;
13117
13118         if (j > i) {
13119                 struct bpf_prog_aux *aux = env->prog->aux;
13120                 int move;
13121
13122                 /* move fake 'exit' subprog as well */
13123                 move = env->subprog_cnt + 1 - j;
13124
13125                 memmove(env->subprog_info + i,
13126                         env->subprog_info + j,
13127                         sizeof(*env->subprog_info) * move);
13128                 env->subprog_cnt -= j - i;
13129
13130                 /* remove func_info */
13131                 if (aux->func_info) {
13132                         move = aux->func_info_cnt - j;
13133
13134                         memmove(aux->func_info + i,
13135                                 aux->func_info + j,
13136                                 sizeof(*aux->func_info) * move);
13137                         aux->func_info_cnt -= j - i;
13138                         /* func_info->insn_off is set after all code rewrites,
13139                          * in adjust_btf_func() - no need to adjust
13140                          */
13141                 }
13142         } else {
13143                 /* convert i from "first prog to remove" to "first to adjust" */
13144                 if (env->subprog_info[i].start == off)
13145                         i++;
13146         }
13147
13148         /* update fake 'exit' subprog as well */
13149         for (; i <= env->subprog_cnt; i++)
13150                 env->subprog_info[i].start -= cnt;
13151
13152         return 0;
13153 }
13154
13155 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13156                                       u32 cnt)
13157 {
13158         struct bpf_prog *prog = env->prog;
13159         u32 i, l_off, l_cnt, nr_linfo;
13160         struct bpf_line_info *linfo;
13161
13162         nr_linfo = prog->aux->nr_linfo;
13163         if (!nr_linfo)
13164                 return 0;
13165
13166         linfo = prog->aux->linfo;
13167
13168         /* find first line info to remove, count lines to be removed */
13169         for (i = 0; i < nr_linfo; i++)
13170                 if (linfo[i].insn_off >= off)
13171                         break;
13172
13173         l_off = i;
13174         l_cnt = 0;
13175         for (; i < nr_linfo; i++)
13176                 if (linfo[i].insn_off < off + cnt)
13177                         l_cnt++;
13178                 else
13179                         break;
13180
13181         /* First live insn doesn't match first live linfo, it needs to "inherit"
13182          * last removed linfo.  prog is already modified, so prog->len == off
13183          * means no live instructions after (tail of the program was removed).
13184          */
13185         if (prog->len != off && l_cnt &&
13186             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13187                 l_cnt--;
13188                 linfo[--i].insn_off = off + cnt;
13189         }
13190
13191         /* remove the line info which refer to the removed instructions */
13192         if (l_cnt) {
13193                 memmove(linfo + l_off, linfo + i,
13194                         sizeof(*linfo) * (nr_linfo - i));
13195
13196                 prog->aux->nr_linfo -= l_cnt;
13197                 nr_linfo = prog->aux->nr_linfo;
13198         }
13199
13200         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13201         for (i = l_off; i < nr_linfo; i++)
13202                 linfo[i].insn_off -= cnt;
13203
13204         /* fix up all subprogs (incl. 'exit') which start >= off */
13205         for (i = 0; i <= env->subprog_cnt; i++)
13206                 if (env->subprog_info[i].linfo_idx > l_off) {
13207                         /* program may have started in the removed region but
13208                          * may not be fully removed
13209                          */
13210                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13211                                 env->subprog_info[i].linfo_idx -= l_cnt;
13212                         else
13213                                 env->subprog_info[i].linfo_idx = l_off;
13214                 }
13215
13216         return 0;
13217 }
13218
13219 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13220 {
13221         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13222         unsigned int orig_prog_len = env->prog->len;
13223         int err;
13224
13225         if (bpf_prog_is_dev_bound(env->prog->aux))
13226                 bpf_prog_offload_remove_insns(env, off, cnt);
13227
13228         err = bpf_remove_insns(env->prog, off, cnt);
13229         if (err)
13230                 return err;
13231
13232         err = adjust_subprog_starts_after_remove(env, off, cnt);
13233         if (err)
13234                 return err;
13235
13236         err = bpf_adj_linfo_after_remove(env, off, cnt);
13237         if (err)
13238                 return err;
13239
13240         memmove(aux_data + off, aux_data + off + cnt,
13241                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13242
13243         return 0;
13244 }
13245
13246 /* The verifier does more data flow analysis than llvm and will not
13247  * explore branches that are dead at run time. Malicious programs can
13248  * have dead code too. Therefore replace all dead at-run-time code
13249  * with 'ja -1'.
13250  *
13251  * Just nops are not optimal, e.g. if they would sit at the end of the
13252  * program and through another bug we would manage to jump there, then
13253  * we'd execute beyond program memory otherwise. Returning exception
13254  * code also wouldn't work since we can have subprogs where the dead
13255  * code could be located.
13256  */
13257 static void sanitize_dead_code(struct bpf_verifier_env *env)
13258 {
13259         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13260         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13261         struct bpf_insn *insn = env->prog->insnsi;
13262         const int insn_cnt = env->prog->len;
13263         int i;
13264
13265         for (i = 0; i < insn_cnt; i++) {
13266                 if (aux_data[i].seen)
13267                         continue;
13268                 memcpy(insn + i, &trap, sizeof(trap));
13269                 aux_data[i].zext_dst = false;
13270         }
13271 }
13272
13273 static bool insn_is_cond_jump(u8 code)
13274 {
13275         u8 op;
13276
13277         if (BPF_CLASS(code) == BPF_JMP32)
13278                 return true;
13279
13280         if (BPF_CLASS(code) != BPF_JMP)
13281                 return false;
13282
13283         op = BPF_OP(code);
13284         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13285 }
13286
13287 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13288 {
13289         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13290         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13291         struct bpf_insn *insn = env->prog->insnsi;
13292         const int insn_cnt = env->prog->len;
13293         int i;
13294
13295         for (i = 0; i < insn_cnt; i++, insn++) {
13296                 if (!insn_is_cond_jump(insn->code))
13297                         continue;
13298
13299                 if (!aux_data[i + 1].seen)
13300                         ja.off = insn->off;
13301                 else if (!aux_data[i + 1 + insn->off].seen)
13302                         ja.off = 0;
13303                 else
13304                         continue;
13305
13306                 if (bpf_prog_is_dev_bound(env->prog->aux))
13307                         bpf_prog_offload_replace_insn(env, i, &ja);
13308
13309                 memcpy(insn, &ja, sizeof(ja));
13310         }
13311 }
13312
13313 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13314 {
13315         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13316         int insn_cnt = env->prog->len;
13317         int i, err;
13318
13319         for (i = 0; i < insn_cnt; i++) {
13320                 int j;
13321
13322                 j = 0;
13323                 while (i + j < insn_cnt && !aux_data[i + j].seen)
13324                         j++;
13325                 if (!j)
13326                         continue;
13327
13328                 err = verifier_remove_insns(env, i, j);
13329                 if (err)
13330                         return err;
13331                 insn_cnt = env->prog->len;
13332         }
13333
13334         return 0;
13335 }
13336
13337 static int opt_remove_nops(struct bpf_verifier_env *env)
13338 {
13339         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13340         struct bpf_insn *insn = env->prog->insnsi;
13341         int insn_cnt = env->prog->len;
13342         int i, err;
13343
13344         for (i = 0; i < insn_cnt; i++) {
13345                 if (memcmp(&insn[i], &ja, sizeof(ja)))
13346                         continue;
13347
13348                 err = verifier_remove_insns(env, i, 1);
13349                 if (err)
13350                         return err;
13351                 insn_cnt--;
13352                 i--;
13353         }
13354
13355         return 0;
13356 }
13357
13358 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13359                                          const union bpf_attr *attr)
13360 {
13361         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13362         struct bpf_insn_aux_data *aux = env->insn_aux_data;
13363         int i, patch_len, delta = 0, len = env->prog->len;
13364         struct bpf_insn *insns = env->prog->insnsi;
13365         struct bpf_prog *new_prog;
13366         bool rnd_hi32;
13367
13368         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13369         zext_patch[1] = BPF_ZEXT_REG(0);
13370         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13371         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13372         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13373         for (i = 0; i < len; i++) {
13374                 int adj_idx = i + delta;
13375                 struct bpf_insn insn;
13376                 int load_reg;
13377
13378                 insn = insns[adj_idx];
13379                 load_reg = insn_def_regno(&insn);
13380                 if (!aux[adj_idx].zext_dst) {
13381                         u8 code, class;
13382                         u32 imm_rnd;
13383
13384                         if (!rnd_hi32)
13385                                 continue;
13386
13387                         code = insn.code;
13388                         class = BPF_CLASS(code);
13389                         if (load_reg == -1)
13390                                 continue;
13391
13392                         /* NOTE: arg "reg" (the fourth one) is only used for
13393                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
13394                          *       here.
13395                          */
13396                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13397                                 if (class == BPF_LD &&
13398                                     BPF_MODE(code) == BPF_IMM)
13399                                         i++;
13400                                 continue;
13401                         }
13402
13403                         /* ctx load could be transformed into wider load. */
13404                         if (class == BPF_LDX &&
13405                             aux[adj_idx].ptr_type == PTR_TO_CTX)
13406                                 continue;
13407
13408                         imm_rnd = get_random_u32();
13409                         rnd_hi32_patch[0] = insn;
13410                         rnd_hi32_patch[1].imm = imm_rnd;
13411                         rnd_hi32_patch[3].dst_reg = load_reg;
13412                         patch = rnd_hi32_patch;
13413                         patch_len = 4;
13414                         goto apply_patch_buffer;
13415                 }
13416
13417                 /* Add in an zero-extend instruction if a) the JIT has requested
13418                  * it or b) it's a CMPXCHG.
13419                  *
13420                  * The latter is because: BPF_CMPXCHG always loads a value into
13421                  * R0, therefore always zero-extends. However some archs'
13422                  * equivalent instruction only does this load when the
13423                  * comparison is successful. This detail of CMPXCHG is
13424                  * orthogonal to the general zero-extension behaviour of the
13425                  * CPU, so it's treated independently of bpf_jit_needs_zext.
13426                  */
13427                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13428                         continue;
13429
13430                 /* Zero-extension is done by the caller. */
13431                 if (bpf_pseudo_kfunc_call(&insn))
13432                         continue;
13433
13434                 if (WARN_ON(load_reg == -1)) {
13435                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13436                         return -EFAULT;
13437                 }
13438
13439                 zext_patch[0] = insn;
13440                 zext_patch[1].dst_reg = load_reg;
13441                 zext_patch[1].src_reg = load_reg;
13442                 patch = zext_patch;
13443                 patch_len = 2;
13444 apply_patch_buffer:
13445                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13446                 if (!new_prog)
13447                         return -ENOMEM;
13448                 env->prog = new_prog;
13449                 insns = new_prog->insnsi;
13450                 aux = env->insn_aux_data;
13451                 delta += patch_len - 1;
13452         }
13453
13454         return 0;
13455 }
13456
13457 /* convert load instructions that access fields of a context type into a
13458  * sequence of instructions that access fields of the underlying structure:
13459  *     struct __sk_buff    -> struct sk_buff
13460  *     struct bpf_sock_ops -> struct sock
13461  */
13462 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13463 {
13464         const struct bpf_verifier_ops *ops = env->ops;
13465         int i, cnt, size, ctx_field_size, delta = 0;
13466         const int insn_cnt = env->prog->len;
13467         struct bpf_insn insn_buf[16], *insn;
13468         u32 target_size, size_default, off;
13469         struct bpf_prog *new_prog;
13470         enum bpf_access_type type;
13471         bool is_narrower_load;
13472
13473         if (ops->gen_prologue || env->seen_direct_write) {
13474                 if (!ops->gen_prologue) {
13475                         verbose(env, "bpf verifier is misconfigured\n");
13476                         return -EINVAL;
13477                 }
13478                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13479                                         env->prog);
13480                 if (cnt >= ARRAY_SIZE(insn_buf)) {
13481                         verbose(env, "bpf verifier is misconfigured\n");
13482                         return -EINVAL;
13483                 } else if (cnt) {
13484                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13485                         if (!new_prog)
13486                                 return -ENOMEM;
13487
13488                         env->prog = new_prog;
13489                         delta += cnt - 1;
13490                 }
13491         }
13492
13493         if (bpf_prog_is_dev_bound(env->prog->aux))
13494                 return 0;
13495
13496         insn = env->prog->insnsi + delta;
13497
13498         for (i = 0; i < insn_cnt; i++, insn++) {
13499                 bpf_convert_ctx_access_t convert_ctx_access;
13500                 bool ctx_access;
13501
13502                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13503                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13504                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13505                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13506                         type = BPF_READ;
13507                         ctx_access = true;
13508                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13509                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13510                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13511                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13512                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13513                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13514                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13515                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13516                         type = BPF_WRITE;
13517                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13518                 } else {
13519                         continue;
13520                 }
13521
13522                 if (type == BPF_WRITE &&
13523                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
13524                         struct bpf_insn patch[] = {
13525                                 *insn,
13526                                 BPF_ST_NOSPEC(),
13527                         };
13528
13529                         cnt = ARRAY_SIZE(patch);
13530                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13531                         if (!new_prog)
13532                                 return -ENOMEM;
13533
13534                         delta    += cnt - 1;
13535                         env->prog = new_prog;
13536                         insn      = new_prog->insnsi + i + delta;
13537                         continue;
13538                 }
13539
13540                 if (!ctx_access)
13541                         continue;
13542
13543                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13544                 case PTR_TO_CTX:
13545                         if (!ops->convert_ctx_access)
13546                                 continue;
13547                         convert_ctx_access = ops->convert_ctx_access;
13548                         break;
13549                 case PTR_TO_SOCKET:
13550                 case PTR_TO_SOCK_COMMON:
13551                         convert_ctx_access = bpf_sock_convert_ctx_access;
13552                         break;
13553                 case PTR_TO_TCP_SOCK:
13554                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13555                         break;
13556                 case PTR_TO_XDP_SOCK:
13557                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13558                         break;
13559                 case PTR_TO_BTF_ID:
13560                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13561                         if (type == BPF_READ) {
13562                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
13563                                         BPF_SIZE((insn)->code);
13564                                 env->prog->aux->num_exentries++;
13565                         }
13566                         continue;
13567                 default:
13568                         continue;
13569                 }
13570
13571                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13572                 size = BPF_LDST_BYTES(insn);
13573
13574                 /* If the read access is a narrower load of the field,
13575                  * convert to a 4/8-byte load, to minimum program type specific
13576                  * convert_ctx_access changes. If conversion is successful,
13577                  * we will apply proper mask to the result.
13578                  */
13579                 is_narrower_load = size < ctx_field_size;
13580                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13581                 off = insn->off;
13582                 if (is_narrower_load) {
13583                         u8 size_code;
13584
13585                         if (type == BPF_WRITE) {
13586                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13587                                 return -EINVAL;
13588                         }
13589
13590                         size_code = BPF_H;
13591                         if (ctx_field_size == 4)
13592                                 size_code = BPF_W;
13593                         else if (ctx_field_size == 8)
13594                                 size_code = BPF_DW;
13595
13596                         insn->off = off & ~(size_default - 1);
13597                         insn->code = BPF_LDX | BPF_MEM | size_code;
13598                 }
13599
13600                 target_size = 0;
13601                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13602                                          &target_size);
13603                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13604                     (ctx_field_size && !target_size)) {
13605                         verbose(env, "bpf verifier is misconfigured\n");
13606                         return -EINVAL;
13607                 }
13608
13609                 if (is_narrower_load && size < target_size) {
13610                         u8 shift = bpf_ctx_narrow_access_offset(
13611                                 off, size, size_default) * 8;
13612                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13613                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13614                                 return -EINVAL;
13615                         }
13616                         if (ctx_field_size <= 4) {
13617                                 if (shift)
13618                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13619                                                                         insn->dst_reg,
13620                                                                         shift);
13621                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13622                                                                 (1 << size * 8) - 1);
13623                         } else {
13624                                 if (shift)
13625                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13626                                                                         insn->dst_reg,
13627                                                                         shift);
13628                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13629                                                                 (1ULL << size * 8) - 1);
13630                         }
13631                 }
13632
13633                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13634                 if (!new_prog)
13635                         return -ENOMEM;
13636
13637                 delta += cnt - 1;
13638
13639                 /* keep walking new program and skip insns we just inserted */
13640                 env->prog = new_prog;
13641                 insn      = new_prog->insnsi + i + delta;
13642         }
13643
13644         return 0;
13645 }
13646
13647 static int jit_subprogs(struct bpf_verifier_env *env)
13648 {
13649         struct bpf_prog *prog = env->prog, **func, *tmp;
13650         int i, j, subprog_start, subprog_end = 0, len, subprog;
13651         struct bpf_map *map_ptr;
13652         struct bpf_insn *insn;
13653         void *old_bpf_func;
13654         int err, num_exentries;
13655
13656         if (env->subprog_cnt <= 1)
13657                 return 0;
13658
13659         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13660                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13661                         continue;
13662
13663                 /* Upon error here we cannot fall back to interpreter but
13664                  * need a hard reject of the program. Thus -EFAULT is
13665                  * propagated in any case.
13666                  */
13667                 subprog = find_subprog(env, i + insn->imm + 1);
13668                 if (subprog < 0) {
13669                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13670                                   i + insn->imm + 1);
13671                         return -EFAULT;
13672                 }
13673                 /* temporarily remember subprog id inside insn instead of
13674                  * aux_data, since next loop will split up all insns into funcs
13675                  */
13676                 insn->off = subprog;
13677                 /* remember original imm in case JIT fails and fallback
13678                  * to interpreter will be needed
13679                  */
13680                 env->insn_aux_data[i].call_imm = insn->imm;
13681                 /* point imm to __bpf_call_base+1 from JITs point of view */
13682                 insn->imm = 1;
13683                 if (bpf_pseudo_func(insn))
13684                         /* jit (e.g. x86_64) may emit fewer instructions
13685                          * if it learns a u32 imm is the same as a u64 imm.
13686                          * Force a non zero here.
13687                          */
13688                         insn[1].imm = 1;
13689         }
13690
13691         err = bpf_prog_alloc_jited_linfo(prog);
13692         if (err)
13693                 goto out_undo_insn;
13694
13695         err = -ENOMEM;
13696         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13697         if (!func)
13698                 goto out_undo_insn;
13699
13700         for (i = 0; i < env->subprog_cnt; i++) {
13701                 subprog_start = subprog_end;
13702                 subprog_end = env->subprog_info[i + 1].start;
13703
13704                 len = subprog_end - subprog_start;
13705                 /* bpf_prog_run() doesn't call subprogs directly,
13706                  * hence main prog stats include the runtime of subprogs.
13707                  * subprogs don't have IDs and not reachable via prog_get_next_id
13708                  * func[i]->stats will never be accessed and stays NULL
13709                  */
13710                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13711                 if (!func[i])
13712                         goto out_free;
13713                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13714                        len * sizeof(struct bpf_insn));
13715                 func[i]->type = prog->type;
13716                 func[i]->len = len;
13717                 if (bpf_prog_calc_tag(func[i]))
13718                         goto out_free;
13719                 func[i]->is_func = 1;
13720                 func[i]->aux->func_idx = i;
13721                 /* Below members will be freed only at prog->aux */
13722                 func[i]->aux->btf = prog->aux->btf;
13723                 func[i]->aux->func_info = prog->aux->func_info;
13724                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13725                 func[i]->aux->poke_tab = prog->aux->poke_tab;
13726                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13727
13728                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13729                         struct bpf_jit_poke_descriptor *poke;
13730
13731                         poke = &prog->aux->poke_tab[j];
13732                         if (poke->insn_idx < subprog_end &&
13733                             poke->insn_idx >= subprog_start)
13734                                 poke->aux = func[i]->aux;
13735                 }
13736
13737                 func[i]->aux->name[0] = 'F';
13738                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13739                 func[i]->jit_requested = 1;
13740                 func[i]->blinding_requested = prog->blinding_requested;
13741                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13742                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13743                 func[i]->aux->linfo = prog->aux->linfo;
13744                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13745                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13746                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13747                 num_exentries = 0;
13748                 insn = func[i]->insnsi;
13749                 for (j = 0; j < func[i]->len; j++, insn++) {
13750                         if (BPF_CLASS(insn->code) == BPF_LDX &&
13751                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
13752                                 num_exentries++;
13753                 }
13754                 func[i]->aux->num_exentries = num_exentries;
13755                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13756                 func[i] = bpf_int_jit_compile(func[i]);
13757                 if (!func[i]->jited) {
13758                         err = -ENOTSUPP;
13759                         goto out_free;
13760                 }
13761                 cond_resched();
13762         }
13763
13764         /* at this point all bpf functions were successfully JITed
13765          * now populate all bpf_calls with correct addresses and
13766          * run last pass of JIT
13767          */
13768         for (i = 0; i < env->subprog_cnt; i++) {
13769                 insn = func[i]->insnsi;
13770                 for (j = 0; j < func[i]->len; j++, insn++) {
13771                         if (bpf_pseudo_func(insn)) {
13772                                 subprog = insn->off;
13773                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13774                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13775                                 continue;
13776                         }
13777                         if (!bpf_pseudo_call(insn))
13778                                 continue;
13779                         subprog = insn->off;
13780                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13781                 }
13782
13783                 /* we use the aux data to keep a list of the start addresses
13784                  * of the JITed images for each function in the program
13785                  *
13786                  * for some architectures, such as powerpc64, the imm field
13787                  * might not be large enough to hold the offset of the start
13788                  * address of the callee's JITed image from __bpf_call_base
13789                  *
13790                  * in such cases, we can lookup the start address of a callee
13791                  * by using its subprog id, available from the off field of
13792                  * the call instruction, as an index for this list
13793                  */
13794                 func[i]->aux->func = func;
13795                 func[i]->aux->func_cnt = env->subprog_cnt;
13796         }
13797         for (i = 0; i < env->subprog_cnt; i++) {
13798                 old_bpf_func = func[i]->bpf_func;
13799                 tmp = bpf_int_jit_compile(func[i]);
13800                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13801                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13802                         err = -ENOTSUPP;
13803                         goto out_free;
13804                 }
13805                 cond_resched();
13806         }
13807
13808         /* finally lock prog and jit images for all functions and
13809          * populate kallsysm
13810          */
13811         for (i = 0; i < env->subprog_cnt; i++) {
13812                 bpf_prog_lock_ro(func[i]);
13813                 bpf_prog_kallsyms_add(func[i]);
13814         }
13815
13816         /* Last step: make now unused interpreter insns from main
13817          * prog consistent for later dump requests, so they can
13818          * later look the same as if they were interpreted only.
13819          */
13820         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13821                 if (bpf_pseudo_func(insn)) {
13822                         insn[0].imm = env->insn_aux_data[i].call_imm;
13823                         insn[1].imm = insn->off;
13824                         insn->off = 0;
13825                         continue;
13826                 }
13827                 if (!bpf_pseudo_call(insn))
13828                         continue;
13829                 insn->off = env->insn_aux_data[i].call_imm;
13830                 subprog = find_subprog(env, i + insn->off + 1);
13831                 insn->imm = subprog;
13832         }
13833
13834         prog->jited = 1;
13835         prog->bpf_func = func[0]->bpf_func;
13836         prog->jited_len = func[0]->jited_len;
13837         prog->aux->func = func;
13838         prog->aux->func_cnt = env->subprog_cnt;
13839         bpf_prog_jit_attempt_done(prog);
13840         return 0;
13841 out_free:
13842         /* We failed JIT'ing, so at this point we need to unregister poke
13843          * descriptors from subprogs, so that kernel is not attempting to
13844          * patch it anymore as we're freeing the subprog JIT memory.
13845          */
13846         for (i = 0; i < prog->aux->size_poke_tab; i++) {
13847                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13848                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13849         }
13850         /* At this point we're guaranteed that poke descriptors are not
13851          * live anymore. We can just unlink its descriptor table as it's
13852          * released with the main prog.
13853          */
13854         for (i = 0; i < env->subprog_cnt; i++) {
13855                 if (!func[i])
13856                         continue;
13857                 func[i]->aux->poke_tab = NULL;
13858                 bpf_jit_free(func[i]);
13859         }
13860         kfree(func);
13861 out_undo_insn:
13862         /* cleanup main prog to be interpreted */
13863         prog->jit_requested = 0;
13864         prog->blinding_requested = 0;
13865         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13866                 if (!bpf_pseudo_call(insn))
13867                         continue;
13868                 insn->off = 0;
13869                 insn->imm = env->insn_aux_data[i].call_imm;
13870         }
13871         bpf_prog_jit_attempt_done(prog);
13872         return err;
13873 }
13874
13875 static int fixup_call_args(struct bpf_verifier_env *env)
13876 {
13877 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13878         struct bpf_prog *prog = env->prog;
13879         struct bpf_insn *insn = prog->insnsi;
13880         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13881         int i, depth;
13882 #endif
13883         int err = 0;
13884
13885         if (env->prog->jit_requested &&
13886             !bpf_prog_is_dev_bound(env->prog->aux)) {
13887                 err = jit_subprogs(env);
13888                 if (err == 0)
13889                         return 0;
13890                 if (err == -EFAULT)
13891                         return err;
13892         }
13893 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13894         if (has_kfunc_call) {
13895                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13896                 return -EINVAL;
13897         }
13898         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13899                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13900                  * have to be rejected, since interpreter doesn't support them yet.
13901                  */
13902                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13903                 return -EINVAL;
13904         }
13905         for (i = 0; i < prog->len; i++, insn++) {
13906                 if (bpf_pseudo_func(insn)) {
13907                         /* When JIT fails the progs with callback calls
13908                          * have to be rejected, since interpreter doesn't support them yet.
13909                          */
13910                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
13911                         return -EINVAL;
13912                 }
13913
13914                 if (!bpf_pseudo_call(insn))
13915                         continue;
13916                 depth = get_callee_stack_depth(env, insn, i);
13917                 if (depth < 0)
13918                         return depth;
13919                 bpf_patch_call_args(insn, depth);
13920         }
13921         err = 0;
13922 #endif
13923         return err;
13924 }
13925
13926 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13927                             struct bpf_insn *insn)
13928 {
13929         const struct bpf_kfunc_desc *desc;
13930
13931         if (!insn->imm) {
13932                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13933                 return -EINVAL;
13934         }
13935
13936         /* insn->imm has the btf func_id. Replace it with
13937          * an address (relative to __bpf_base_call).
13938          */
13939         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13940         if (!desc) {
13941                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13942                         insn->imm);
13943                 return -EFAULT;
13944         }
13945
13946         insn->imm = desc->imm;
13947
13948         return 0;
13949 }
13950
13951 /* Do various post-verification rewrites in a single program pass.
13952  * These rewrites simplify JIT and interpreter implementations.
13953  */
13954 static int do_misc_fixups(struct bpf_verifier_env *env)
13955 {
13956         struct bpf_prog *prog = env->prog;
13957         enum bpf_attach_type eatype = prog->expected_attach_type;
13958         enum bpf_prog_type prog_type = resolve_prog_type(prog);
13959         struct bpf_insn *insn = prog->insnsi;
13960         const struct bpf_func_proto *fn;
13961         const int insn_cnt = prog->len;
13962         const struct bpf_map_ops *ops;
13963         struct bpf_insn_aux_data *aux;
13964         struct bpf_insn insn_buf[16];
13965         struct bpf_prog *new_prog;
13966         struct bpf_map *map_ptr;
13967         int i, ret, cnt, delta = 0;
13968
13969         for (i = 0; i < insn_cnt; i++, insn++) {
13970                 /* Make divide-by-zero exceptions impossible. */
13971                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13972                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13973                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13974                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13975                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13976                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13977                         struct bpf_insn *patchlet;
13978                         struct bpf_insn chk_and_div[] = {
13979                                 /* [R,W]x div 0 -> 0 */
13980                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13981                                              BPF_JNE | BPF_K, insn->src_reg,
13982                                              0, 2, 0),
13983                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13984                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13985                                 *insn,
13986                         };
13987                         struct bpf_insn chk_and_mod[] = {
13988                                 /* [R,W]x mod 0 -> [R,W]x */
13989                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13990                                              BPF_JEQ | BPF_K, insn->src_reg,
13991                                              0, 1 + (is64 ? 0 : 1), 0),
13992                                 *insn,
13993                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13994                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13995                         };
13996
13997                         patchlet = isdiv ? chk_and_div : chk_and_mod;
13998                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13999                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
14000
14001                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
14002                         if (!new_prog)
14003                                 return -ENOMEM;
14004
14005                         delta    += cnt - 1;
14006                         env->prog = prog = new_prog;
14007                         insn      = new_prog->insnsi + i + delta;
14008                         continue;
14009                 }
14010
14011                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
14012                 if (BPF_CLASS(insn->code) == BPF_LD &&
14013                     (BPF_MODE(insn->code) == BPF_ABS ||
14014                      BPF_MODE(insn->code) == BPF_IND)) {
14015                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
14016                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14017                                 verbose(env, "bpf verifier is misconfigured\n");
14018                                 return -EINVAL;
14019                         }
14020
14021                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14022                         if (!new_prog)
14023                                 return -ENOMEM;
14024
14025                         delta    += cnt - 1;
14026                         env->prog = prog = new_prog;
14027                         insn      = new_prog->insnsi + i + delta;
14028                         continue;
14029                 }
14030
14031                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
14032                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14033                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14034                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14035                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14036                         struct bpf_insn *patch = &insn_buf[0];
14037                         bool issrc, isneg, isimm;
14038                         u32 off_reg;
14039
14040                         aux = &env->insn_aux_data[i + delta];
14041                         if (!aux->alu_state ||
14042                             aux->alu_state == BPF_ALU_NON_POINTER)
14043                                 continue;
14044
14045                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14046                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14047                                 BPF_ALU_SANITIZE_SRC;
14048                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14049
14050                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
14051                         if (isimm) {
14052                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14053                         } else {
14054                                 if (isneg)
14055                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14056                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14057                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14058                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14059                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14060                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14061                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14062                         }
14063                         if (!issrc)
14064                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14065                         insn->src_reg = BPF_REG_AX;
14066                         if (isneg)
14067                                 insn->code = insn->code == code_add ?
14068                                              code_sub : code_add;
14069                         *patch++ = *insn;
14070                         if (issrc && isneg && !isimm)
14071                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14072                         cnt = patch - insn_buf;
14073
14074                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14075                         if (!new_prog)
14076                                 return -ENOMEM;
14077
14078                         delta    += cnt - 1;
14079                         env->prog = prog = new_prog;
14080                         insn      = new_prog->insnsi + i + delta;
14081                         continue;
14082                 }
14083
14084                 if (insn->code != (BPF_JMP | BPF_CALL))
14085                         continue;
14086                 if (insn->src_reg == BPF_PSEUDO_CALL)
14087                         continue;
14088                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14089                         ret = fixup_kfunc_call(env, insn);
14090                         if (ret)
14091                                 return ret;
14092                         continue;
14093                 }
14094
14095                 if (insn->imm == BPF_FUNC_get_route_realm)
14096                         prog->dst_needed = 1;
14097                 if (insn->imm == BPF_FUNC_get_prandom_u32)
14098                         bpf_user_rnd_init_once();
14099                 if (insn->imm == BPF_FUNC_override_return)
14100                         prog->kprobe_override = 1;
14101                 if (insn->imm == BPF_FUNC_tail_call) {
14102                         /* If we tail call into other programs, we
14103                          * cannot make any assumptions since they can
14104                          * be replaced dynamically during runtime in
14105                          * the program array.
14106                          */
14107                         prog->cb_access = 1;
14108                         if (!allow_tail_call_in_subprogs(env))
14109                                 prog->aux->stack_depth = MAX_BPF_STACK;
14110                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14111
14112                         /* mark bpf_tail_call as different opcode to avoid
14113                          * conditional branch in the interpreter for every normal
14114                          * call and to prevent accidental JITing by JIT compiler
14115                          * that doesn't support bpf_tail_call yet
14116                          */
14117                         insn->imm = 0;
14118                         insn->code = BPF_JMP | BPF_TAIL_CALL;
14119
14120                         aux = &env->insn_aux_data[i + delta];
14121                         if (env->bpf_capable && !prog->blinding_requested &&
14122                             prog->jit_requested &&
14123                             !bpf_map_key_poisoned(aux) &&
14124                             !bpf_map_ptr_poisoned(aux) &&
14125                             !bpf_map_ptr_unpriv(aux)) {
14126                                 struct bpf_jit_poke_descriptor desc = {
14127                                         .reason = BPF_POKE_REASON_TAIL_CALL,
14128                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14129                                         .tail_call.key = bpf_map_key_immediate(aux),
14130                                         .insn_idx = i + delta,
14131                                 };
14132
14133                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14134                                 if (ret < 0) {
14135                                         verbose(env, "adding tail call poke descriptor failed\n");
14136                                         return ret;
14137                                 }
14138
14139                                 insn->imm = ret + 1;
14140                                 continue;
14141                         }
14142
14143                         if (!bpf_map_ptr_unpriv(aux))
14144                                 continue;
14145
14146                         /* instead of changing every JIT dealing with tail_call
14147                          * emit two extra insns:
14148                          * if (index >= max_entries) goto out;
14149                          * index &= array->index_mask;
14150                          * to avoid out-of-bounds cpu speculation
14151                          */
14152                         if (bpf_map_ptr_poisoned(aux)) {
14153                                 verbose(env, "tail_call abusing map_ptr\n");
14154                                 return -EINVAL;
14155                         }
14156
14157                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14158                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14159                                                   map_ptr->max_entries, 2);
14160                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14161                                                     container_of(map_ptr,
14162                                                                  struct bpf_array,
14163                                                                  map)->index_mask);
14164                         insn_buf[2] = *insn;
14165                         cnt = 3;
14166                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14167                         if (!new_prog)
14168                                 return -ENOMEM;
14169
14170                         delta    += cnt - 1;
14171                         env->prog = prog = new_prog;
14172                         insn      = new_prog->insnsi + i + delta;
14173                         continue;
14174                 }
14175
14176                 if (insn->imm == BPF_FUNC_timer_set_callback) {
14177                         /* The verifier will process callback_fn as many times as necessary
14178                          * with different maps and the register states prepared by
14179                          * set_timer_callback_state will be accurate.
14180                          *
14181                          * The following use case is valid:
14182                          *   map1 is shared by prog1, prog2, prog3.
14183                          *   prog1 calls bpf_timer_init for some map1 elements
14184                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
14185                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
14186                          *   prog3 calls bpf_timer_start for some map1 elements.
14187                          *     Those that were not both bpf_timer_init-ed and
14188                          *     bpf_timer_set_callback-ed will return -EINVAL.
14189                          */
14190                         struct bpf_insn ld_addrs[2] = {
14191                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14192                         };
14193
14194                         insn_buf[0] = ld_addrs[0];
14195                         insn_buf[1] = ld_addrs[1];
14196                         insn_buf[2] = *insn;
14197                         cnt = 3;
14198
14199                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14200                         if (!new_prog)
14201                                 return -ENOMEM;
14202
14203                         delta    += cnt - 1;
14204                         env->prog = prog = new_prog;
14205                         insn      = new_prog->insnsi + i + delta;
14206                         goto patch_call_imm;
14207                 }
14208
14209                 if (insn->imm == BPF_FUNC_task_storage_get ||
14210                     insn->imm == BPF_FUNC_sk_storage_get ||
14211                     insn->imm == BPF_FUNC_inode_storage_get) {
14212                         if (env->prog->aux->sleepable)
14213                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14214                         else
14215                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14216                         insn_buf[1] = *insn;
14217                         cnt = 2;
14218
14219                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14220                         if (!new_prog)
14221                                 return -ENOMEM;
14222
14223                         delta += cnt - 1;
14224                         env->prog = prog = new_prog;
14225                         insn = new_prog->insnsi + i + delta;
14226                         goto patch_call_imm;
14227                 }
14228
14229                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14230                  * and other inlining handlers are currently limited to 64 bit
14231                  * only.
14232                  */
14233                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14234                     (insn->imm == BPF_FUNC_map_lookup_elem ||
14235                      insn->imm == BPF_FUNC_map_update_elem ||
14236                      insn->imm == BPF_FUNC_map_delete_elem ||
14237                      insn->imm == BPF_FUNC_map_push_elem   ||
14238                      insn->imm == BPF_FUNC_map_pop_elem    ||
14239                      insn->imm == BPF_FUNC_map_peek_elem   ||
14240                      insn->imm == BPF_FUNC_redirect_map    ||
14241                      insn->imm == BPF_FUNC_for_each_map_elem ||
14242                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14243                         aux = &env->insn_aux_data[i + delta];
14244                         if (bpf_map_ptr_poisoned(aux))
14245                                 goto patch_call_imm;
14246
14247                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14248                         ops = map_ptr->ops;
14249                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
14250                             ops->map_gen_lookup) {
14251                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14252                                 if (cnt == -EOPNOTSUPP)
14253                                         goto patch_map_ops_generic;
14254                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14255                                         verbose(env, "bpf verifier is misconfigured\n");
14256                                         return -EINVAL;
14257                                 }
14258
14259                                 new_prog = bpf_patch_insn_data(env, i + delta,
14260                                                                insn_buf, cnt);
14261                                 if (!new_prog)
14262                                         return -ENOMEM;
14263
14264                                 delta    += cnt - 1;
14265                                 env->prog = prog = new_prog;
14266                                 insn      = new_prog->insnsi + i + delta;
14267                                 continue;
14268                         }
14269
14270                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14271                                      (void *(*)(struct bpf_map *map, void *key))NULL));
14272                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14273                                      (int (*)(struct bpf_map *map, void *key))NULL));
14274                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14275                                      (int (*)(struct bpf_map *map, void *key, void *value,
14276                                               u64 flags))NULL));
14277                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14278                                      (int (*)(struct bpf_map *map, void *value,
14279                                               u64 flags))NULL));
14280                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14281                                      (int (*)(struct bpf_map *map, void *value))NULL));
14282                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14283                                      (int (*)(struct bpf_map *map, void *value))NULL));
14284                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
14285                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14286                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14287                                      (int (*)(struct bpf_map *map,
14288                                               bpf_callback_t callback_fn,
14289                                               void *callback_ctx,
14290                                               u64 flags))NULL));
14291                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14292                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14293
14294 patch_map_ops_generic:
14295                         switch (insn->imm) {
14296                         case BPF_FUNC_map_lookup_elem:
14297                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14298                                 continue;
14299                         case BPF_FUNC_map_update_elem:
14300                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14301                                 continue;
14302                         case BPF_FUNC_map_delete_elem:
14303                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14304                                 continue;
14305                         case BPF_FUNC_map_push_elem:
14306                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14307                                 continue;
14308                         case BPF_FUNC_map_pop_elem:
14309                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14310                                 continue;
14311                         case BPF_FUNC_map_peek_elem:
14312                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14313                                 continue;
14314                         case BPF_FUNC_redirect_map:
14315                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14316                                 continue;
14317                         case BPF_FUNC_for_each_map_elem:
14318                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14319                                 continue;
14320                         case BPF_FUNC_map_lookup_percpu_elem:
14321                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14322                                 continue;
14323                         }
14324
14325                         goto patch_call_imm;
14326                 }
14327
14328                 /* Implement bpf_jiffies64 inline. */
14329                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14330                     insn->imm == BPF_FUNC_jiffies64) {
14331                         struct bpf_insn ld_jiffies_addr[2] = {
14332                                 BPF_LD_IMM64(BPF_REG_0,
14333                                              (unsigned long)&jiffies),
14334                         };
14335
14336                         insn_buf[0] = ld_jiffies_addr[0];
14337                         insn_buf[1] = ld_jiffies_addr[1];
14338                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14339                                                   BPF_REG_0, 0);
14340                         cnt = 3;
14341
14342                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14343                                                        cnt);
14344                         if (!new_prog)
14345                                 return -ENOMEM;
14346
14347                         delta    += cnt - 1;
14348                         env->prog = prog = new_prog;
14349                         insn      = new_prog->insnsi + i + delta;
14350                         continue;
14351                 }
14352
14353                 /* Implement bpf_get_func_arg inline. */
14354                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14355                     insn->imm == BPF_FUNC_get_func_arg) {
14356                         /* Load nr_args from ctx - 8 */
14357                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14358                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14359                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14360                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14361                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14362                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14363                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14364                         insn_buf[7] = BPF_JMP_A(1);
14365                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14366                         cnt = 9;
14367
14368                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14369                         if (!new_prog)
14370                                 return -ENOMEM;
14371
14372                         delta    += cnt - 1;
14373                         env->prog = prog = new_prog;
14374                         insn      = new_prog->insnsi + i + delta;
14375                         continue;
14376                 }
14377
14378                 /* Implement bpf_get_func_ret inline. */
14379                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14380                     insn->imm == BPF_FUNC_get_func_ret) {
14381                         if (eatype == BPF_TRACE_FEXIT ||
14382                             eatype == BPF_MODIFY_RETURN) {
14383                                 /* Load nr_args from ctx - 8 */
14384                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14385                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14386                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14387                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14388                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14389                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14390                                 cnt = 6;
14391                         } else {
14392                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14393                                 cnt = 1;
14394                         }
14395
14396                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14397                         if (!new_prog)
14398                                 return -ENOMEM;
14399
14400                         delta    += cnt - 1;
14401                         env->prog = prog = new_prog;
14402                         insn      = new_prog->insnsi + i + delta;
14403                         continue;
14404                 }
14405
14406                 /* Implement get_func_arg_cnt inline. */
14407                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14408                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
14409                         /* Load nr_args from ctx - 8 */
14410                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14411
14412                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14413                         if (!new_prog)
14414                                 return -ENOMEM;
14415
14416                         env->prog = prog = new_prog;
14417                         insn      = new_prog->insnsi + i + delta;
14418                         continue;
14419                 }
14420
14421                 /* Implement bpf_get_func_ip inline. */
14422                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14423                     insn->imm == BPF_FUNC_get_func_ip) {
14424                         /* Load IP address from ctx - 16 */
14425                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14426
14427                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14428                         if (!new_prog)
14429                                 return -ENOMEM;
14430
14431                         env->prog = prog = new_prog;
14432                         insn      = new_prog->insnsi + i + delta;
14433                         continue;
14434                 }
14435
14436 patch_call_imm:
14437                 fn = env->ops->get_func_proto(insn->imm, env->prog);
14438                 /* all functions that have prototype and verifier allowed
14439                  * programs to call them, must be real in-kernel functions
14440                  */
14441                 if (!fn->func) {
14442                         verbose(env,
14443                                 "kernel subsystem misconfigured func %s#%d\n",
14444                                 func_id_name(insn->imm), insn->imm);
14445                         return -EFAULT;
14446                 }
14447                 insn->imm = fn->func - __bpf_call_base;
14448         }
14449
14450         /* Since poke tab is now finalized, publish aux to tracker. */
14451         for (i = 0; i < prog->aux->size_poke_tab; i++) {
14452                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14453                 if (!map_ptr->ops->map_poke_track ||
14454                     !map_ptr->ops->map_poke_untrack ||
14455                     !map_ptr->ops->map_poke_run) {
14456                         verbose(env, "bpf verifier is misconfigured\n");
14457                         return -EINVAL;
14458                 }
14459
14460                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14461                 if (ret < 0) {
14462                         verbose(env, "tracking tail call prog failed\n");
14463                         return ret;
14464                 }
14465         }
14466
14467         sort_kfunc_descs_by_imm(env->prog);
14468
14469         return 0;
14470 }
14471
14472 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14473                                         int position,
14474                                         s32 stack_base,
14475                                         u32 callback_subprogno,
14476                                         u32 *cnt)
14477 {
14478         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14479         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14480         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14481         int reg_loop_max = BPF_REG_6;
14482         int reg_loop_cnt = BPF_REG_7;
14483         int reg_loop_ctx = BPF_REG_8;
14484
14485         struct bpf_prog *new_prog;
14486         u32 callback_start;
14487         u32 call_insn_offset;
14488         s32 callback_offset;
14489
14490         /* This represents an inlined version of bpf_iter.c:bpf_loop,
14491          * be careful to modify this code in sync.
14492          */
14493         struct bpf_insn insn_buf[] = {
14494                 /* Return error and jump to the end of the patch if
14495                  * expected number of iterations is too big.
14496                  */
14497                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14498                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14499                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14500                 /* spill R6, R7, R8 to use these as loop vars */
14501                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14502                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14503                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14504                 /* initialize loop vars */
14505                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14506                 BPF_MOV32_IMM(reg_loop_cnt, 0),
14507                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14508                 /* loop header,
14509                  * if reg_loop_cnt >= reg_loop_max skip the loop body
14510                  */
14511                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14512                 /* callback call,
14513                  * correct callback offset would be set after patching
14514                  */
14515                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14516                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14517                 BPF_CALL_REL(0),
14518                 /* increment loop counter */
14519                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14520                 /* jump to loop header if callback returned 0 */
14521                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14522                 /* return value of bpf_loop,
14523                  * set R0 to the number of iterations
14524                  */
14525                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14526                 /* restore original values of R6, R7, R8 */
14527                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14528                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14529                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14530         };
14531
14532         *cnt = ARRAY_SIZE(insn_buf);
14533         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14534         if (!new_prog)
14535                 return new_prog;
14536
14537         /* callback start is known only after patching */
14538         callback_start = env->subprog_info[callback_subprogno].start;
14539         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14540         call_insn_offset = position + 12;
14541         callback_offset = callback_start - call_insn_offset - 1;
14542         new_prog->insnsi[call_insn_offset].imm = callback_offset;
14543
14544         return new_prog;
14545 }
14546
14547 static bool is_bpf_loop_call(struct bpf_insn *insn)
14548 {
14549         return insn->code == (BPF_JMP | BPF_CALL) &&
14550                 insn->src_reg == 0 &&
14551                 insn->imm == BPF_FUNC_loop;
14552 }
14553
14554 /* For all sub-programs in the program (including main) check
14555  * insn_aux_data to see if there are bpf_loop calls that require
14556  * inlining. If such calls are found the calls are replaced with a
14557  * sequence of instructions produced by `inline_bpf_loop` function and
14558  * subprog stack_depth is increased by the size of 3 registers.
14559  * This stack space is used to spill values of the R6, R7, R8.  These
14560  * registers are used to store the loop bound, counter and context
14561  * variables.
14562  */
14563 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14564 {
14565         struct bpf_subprog_info *subprogs = env->subprog_info;
14566         int i, cur_subprog = 0, cnt, delta = 0;
14567         struct bpf_insn *insn = env->prog->insnsi;
14568         int insn_cnt = env->prog->len;
14569         u16 stack_depth = subprogs[cur_subprog].stack_depth;
14570         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14571         u16 stack_depth_extra = 0;
14572
14573         for (i = 0; i < insn_cnt; i++, insn++) {
14574                 struct bpf_loop_inline_state *inline_state =
14575                         &env->insn_aux_data[i + delta].loop_inline_state;
14576
14577                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14578                         struct bpf_prog *new_prog;
14579
14580                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14581                         new_prog = inline_bpf_loop(env,
14582                                                    i + delta,
14583                                                    -(stack_depth + stack_depth_extra),
14584                                                    inline_state->callback_subprogno,
14585                                                    &cnt);
14586                         if (!new_prog)
14587                                 return -ENOMEM;
14588
14589                         delta     += cnt - 1;
14590                         env->prog  = new_prog;
14591                         insn       = new_prog->insnsi + i + delta;
14592                 }
14593
14594                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14595                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
14596                         cur_subprog++;
14597                         stack_depth = subprogs[cur_subprog].stack_depth;
14598                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14599                         stack_depth_extra = 0;
14600                 }
14601         }
14602
14603         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14604
14605         return 0;
14606 }
14607
14608 static void free_states(struct bpf_verifier_env *env)
14609 {
14610         struct bpf_verifier_state_list *sl, *sln;
14611         int i;
14612
14613         sl = env->free_list;
14614         while (sl) {
14615                 sln = sl->next;
14616                 free_verifier_state(&sl->state, false);
14617                 kfree(sl);
14618                 sl = sln;
14619         }
14620         env->free_list = NULL;
14621
14622         if (!env->explored_states)
14623                 return;
14624
14625         for (i = 0; i < state_htab_size(env); i++) {
14626                 sl = env->explored_states[i];
14627
14628                 while (sl) {
14629                         sln = sl->next;
14630                         free_verifier_state(&sl->state, false);
14631                         kfree(sl);
14632                         sl = sln;
14633                 }
14634                 env->explored_states[i] = NULL;
14635         }
14636 }
14637
14638 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14639 {
14640         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14641         struct bpf_verifier_state *state;
14642         struct bpf_reg_state *regs;
14643         int ret, i;
14644
14645         env->prev_linfo = NULL;
14646         env->pass_cnt++;
14647
14648         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14649         if (!state)
14650                 return -ENOMEM;
14651         state->curframe = 0;
14652         state->speculative = false;
14653         state->branches = 1;
14654         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14655         if (!state->frame[0]) {
14656                 kfree(state);
14657                 return -ENOMEM;
14658         }
14659         env->cur_state = state;
14660         init_func_state(env, state->frame[0],
14661                         BPF_MAIN_FUNC /* callsite */,
14662                         0 /* frameno */,
14663                         subprog);
14664
14665         regs = state->frame[state->curframe]->regs;
14666         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14667                 ret = btf_prepare_func_args(env, subprog, regs);
14668                 if (ret)
14669                         goto out;
14670                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14671                         if (regs[i].type == PTR_TO_CTX)
14672                                 mark_reg_known_zero(env, regs, i);
14673                         else if (regs[i].type == SCALAR_VALUE)
14674                                 mark_reg_unknown(env, regs, i);
14675                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
14676                                 const u32 mem_size = regs[i].mem_size;
14677
14678                                 mark_reg_known_zero(env, regs, i);
14679                                 regs[i].mem_size = mem_size;
14680                                 regs[i].id = ++env->id_gen;
14681                         }
14682                 }
14683         } else {
14684                 /* 1st arg to a function */
14685                 regs[BPF_REG_1].type = PTR_TO_CTX;
14686                 mark_reg_known_zero(env, regs, BPF_REG_1);
14687                 ret = btf_check_subprog_arg_match(env, subprog, regs);
14688                 if (ret == -EFAULT)
14689                         /* unlikely verifier bug. abort.
14690                          * ret == 0 and ret < 0 are sadly acceptable for
14691                          * main() function due to backward compatibility.
14692                          * Like socket filter program may be written as:
14693                          * int bpf_prog(struct pt_regs *ctx)
14694                          * and never dereference that ctx in the program.
14695                          * 'struct pt_regs' is a type mismatch for socket
14696                          * filter that should be using 'struct __sk_buff'.
14697                          */
14698                         goto out;
14699         }
14700
14701         ret = do_check(env);
14702 out:
14703         /* check for NULL is necessary, since cur_state can be freed inside
14704          * do_check() under memory pressure.
14705          */
14706         if (env->cur_state) {
14707                 free_verifier_state(env->cur_state, true);
14708                 env->cur_state = NULL;
14709         }
14710         while (!pop_stack(env, NULL, NULL, false));
14711         if (!ret && pop_log)
14712                 bpf_vlog_reset(&env->log, 0);
14713         free_states(env);
14714         return ret;
14715 }
14716
14717 /* Verify all global functions in a BPF program one by one based on their BTF.
14718  * All global functions must pass verification. Otherwise the whole program is rejected.
14719  * Consider:
14720  * int bar(int);
14721  * int foo(int f)
14722  * {
14723  *    return bar(f);
14724  * }
14725  * int bar(int b)
14726  * {
14727  *    ...
14728  * }
14729  * foo() will be verified first for R1=any_scalar_value. During verification it
14730  * will be assumed that bar() already verified successfully and call to bar()
14731  * from foo() will be checked for type match only. Later bar() will be verified
14732  * independently to check that it's safe for R1=any_scalar_value.
14733  */
14734 static int do_check_subprogs(struct bpf_verifier_env *env)
14735 {
14736         struct bpf_prog_aux *aux = env->prog->aux;
14737         int i, ret;
14738
14739         if (!aux->func_info)
14740                 return 0;
14741
14742         for (i = 1; i < env->subprog_cnt; i++) {
14743                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14744                         continue;
14745                 env->insn_idx = env->subprog_info[i].start;
14746                 WARN_ON_ONCE(env->insn_idx == 0);
14747                 ret = do_check_common(env, i);
14748                 if (ret) {
14749                         return ret;
14750                 } else if (env->log.level & BPF_LOG_LEVEL) {
14751                         verbose(env,
14752                                 "Func#%d is safe for any args that match its prototype\n",
14753                                 i);
14754                 }
14755         }
14756         return 0;
14757 }
14758
14759 static int do_check_main(struct bpf_verifier_env *env)
14760 {
14761         int ret;
14762
14763         env->insn_idx = 0;
14764         ret = do_check_common(env, 0);
14765         if (!ret)
14766                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14767         return ret;
14768 }
14769
14770
14771 static void print_verification_stats(struct bpf_verifier_env *env)
14772 {
14773         int i;
14774
14775         if (env->log.level & BPF_LOG_STATS) {
14776                 verbose(env, "verification time %lld usec\n",
14777                         div_u64(env->verification_time, 1000));
14778                 verbose(env, "stack depth ");
14779                 for (i = 0; i < env->subprog_cnt; i++) {
14780                         u32 depth = env->subprog_info[i].stack_depth;
14781
14782                         verbose(env, "%d", depth);
14783                         if (i + 1 < env->subprog_cnt)
14784                                 verbose(env, "+");
14785                 }
14786                 verbose(env, "\n");
14787         }
14788         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14789                 "total_states %d peak_states %d mark_read %d\n",
14790                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14791                 env->max_states_per_insn, env->total_states,
14792                 env->peak_states, env->longest_mark_read_walk);
14793 }
14794
14795 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14796 {
14797         const struct btf_type *t, *func_proto;
14798         const struct bpf_struct_ops *st_ops;
14799         const struct btf_member *member;
14800         struct bpf_prog *prog = env->prog;
14801         u32 btf_id, member_idx;
14802         const char *mname;
14803
14804         if (!prog->gpl_compatible) {
14805                 verbose(env, "struct ops programs must have a GPL compatible license\n");
14806                 return -EINVAL;
14807         }
14808
14809         btf_id = prog->aux->attach_btf_id;
14810         st_ops = bpf_struct_ops_find(btf_id);
14811         if (!st_ops) {
14812                 verbose(env, "attach_btf_id %u is not a supported struct\n",
14813                         btf_id);
14814                 return -ENOTSUPP;
14815         }
14816
14817         t = st_ops->type;
14818         member_idx = prog->expected_attach_type;
14819         if (member_idx >= btf_type_vlen(t)) {
14820                 verbose(env, "attach to invalid member idx %u of struct %s\n",
14821                         member_idx, st_ops->name);
14822                 return -EINVAL;
14823         }
14824
14825         member = &btf_type_member(t)[member_idx];
14826         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14827         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14828                                                NULL);
14829         if (!func_proto) {
14830                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14831                         mname, member_idx, st_ops->name);
14832                 return -EINVAL;
14833         }
14834
14835         if (st_ops->check_member) {
14836                 int err = st_ops->check_member(t, member);
14837
14838                 if (err) {
14839                         verbose(env, "attach to unsupported member %s of struct %s\n",
14840                                 mname, st_ops->name);
14841                         return err;
14842                 }
14843         }
14844
14845         prog->aux->attach_func_proto = func_proto;
14846         prog->aux->attach_func_name = mname;
14847         env->ops = st_ops->verifier_ops;
14848
14849         return 0;
14850 }
14851 #define SECURITY_PREFIX "security_"
14852
14853 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14854 {
14855         if (within_error_injection_list(addr) ||
14856             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14857                 return 0;
14858
14859         return -EINVAL;
14860 }
14861
14862 /* list of non-sleepable functions that are otherwise on
14863  * ALLOW_ERROR_INJECTION list
14864  */
14865 BTF_SET_START(btf_non_sleepable_error_inject)
14866 /* Three functions below can be called from sleepable and non-sleepable context.
14867  * Assume non-sleepable from bpf safety point of view.
14868  */
14869 BTF_ID(func, __filemap_add_folio)
14870 BTF_ID(func, should_fail_alloc_page)
14871 BTF_ID(func, should_failslab)
14872 BTF_SET_END(btf_non_sleepable_error_inject)
14873
14874 static int check_non_sleepable_error_inject(u32 btf_id)
14875 {
14876         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14877 }
14878
14879 int bpf_check_attach_target(struct bpf_verifier_log *log,
14880                             const struct bpf_prog *prog,
14881                             const struct bpf_prog *tgt_prog,
14882                             u32 btf_id,
14883                             struct bpf_attach_target_info *tgt_info)
14884 {
14885         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14886         const char prefix[] = "btf_trace_";
14887         int ret = 0, subprog = -1, i;
14888         const struct btf_type *t;
14889         bool conservative = true;
14890         const char *tname;
14891         struct btf *btf;
14892         long addr = 0;
14893
14894         if (!btf_id) {
14895                 bpf_log(log, "Tracing programs must provide btf_id\n");
14896                 return -EINVAL;
14897         }
14898         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14899         if (!btf) {
14900                 bpf_log(log,
14901                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14902                 return -EINVAL;
14903         }
14904         t = btf_type_by_id(btf, btf_id);
14905         if (!t) {
14906                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14907                 return -EINVAL;
14908         }
14909         tname = btf_name_by_offset(btf, t->name_off);
14910         if (!tname) {
14911                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14912                 return -EINVAL;
14913         }
14914         if (tgt_prog) {
14915                 struct bpf_prog_aux *aux = tgt_prog->aux;
14916
14917                 for (i = 0; i < aux->func_info_cnt; i++)
14918                         if (aux->func_info[i].type_id == btf_id) {
14919                                 subprog = i;
14920                                 break;
14921                         }
14922                 if (subprog == -1) {
14923                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
14924                         return -EINVAL;
14925                 }
14926                 conservative = aux->func_info_aux[subprog].unreliable;
14927                 if (prog_extension) {
14928                         if (conservative) {
14929                                 bpf_log(log,
14930                                         "Cannot replace static functions\n");
14931                                 return -EINVAL;
14932                         }
14933                         if (!prog->jit_requested) {
14934                                 bpf_log(log,
14935                                         "Extension programs should be JITed\n");
14936                                 return -EINVAL;
14937                         }
14938                 }
14939                 if (!tgt_prog->jited) {
14940                         bpf_log(log, "Can attach to only JITed progs\n");
14941                         return -EINVAL;
14942                 }
14943                 if (tgt_prog->type == prog->type) {
14944                         /* Cannot fentry/fexit another fentry/fexit program.
14945                          * Cannot attach program extension to another extension.
14946                          * It's ok to attach fentry/fexit to extension program.
14947                          */
14948                         bpf_log(log, "Cannot recursively attach\n");
14949                         return -EINVAL;
14950                 }
14951                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14952                     prog_extension &&
14953                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14954                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14955                         /* Program extensions can extend all program types
14956                          * except fentry/fexit. The reason is the following.
14957                          * The fentry/fexit programs are used for performance
14958                          * analysis, stats and can be attached to any program
14959                          * type except themselves. When extension program is
14960                          * replacing XDP function it is necessary to allow
14961                          * performance analysis of all functions. Both original
14962                          * XDP program and its program extension. Hence
14963                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14964                          * allowed. If extending of fentry/fexit was allowed it
14965                          * would be possible to create long call chain
14966                          * fentry->extension->fentry->extension beyond
14967                          * reasonable stack size. Hence extending fentry is not
14968                          * allowed.
14969                          */
14970                         bpf_log(log, "Cannot extend fentry/fexit\n");
14971                         return -EINVAL;
14972                 }
14973         } else {
14974                 if (prog_extension) {
14975                         bpf_log(log, "Cannot replace kernel functions\n");
14976                         return -EINVAL;
14977                 }
14978         }
14979
14980         switch (prog->expected_attach_type) {
14981         case BPF_TRACE_RAW_TP:
14982                 if (tgt_prog) {
14983                         bpf_log(log,
14984                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14985                         return -EINVAL;
14986                 }
14987                 if (!btf_type_is_typedef(t)) {
14988                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
14989                                 btf_id);
14990                         return -EINVAL;
14991                 }
14992                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14993                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14994                                 btf_id, tname);
14995                         return -EINVAL;
14996                 }
14997                 tname += sizeof(prefix) - 1;
14998                 t = btf_type_by_id(btf, t->type);
14999                 if (!btf_type_is_ptr(t))
15000                         /* should never happen in valid vmlinux build */
15001                         return -EINVAL;
15002                 t = btf_type_by_id(btf, t->type);
15003                 if (!btf_type_is_func_proto(t))
15004                         /* should never happen in valid vmlinux build */
15005                         return -EINVAL;
15006
15007                 break;
15008         case BPF_TRACE_ITER:
15009                 if (!btf_type_is_func(t)) {
15010                         bpf_log(log, "attach_btf_id %u is not a function\n",
15011                                 btf_id);
15012                         return -EINVAL;
15013                 }
15014                 t = btf_type_by_id(btf, t->type);
15015                 if (!btf_type_is_func_proto(t))
15016                         return -EINVAL;
15017                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15018                 if (ret)
15019                         return ret;
15020                 break;
15021         default:
15022                 if (!prog_extension)
15023                         return -EINVAL;
15024                 fallthrough;
15025         case BPF_MODIFY_RETURN:
15026         case BPF_LSM_MAC:
15027         case BPF_LSM_CGROUP:
15028         case BPF_TRACE_FENTRY:
15029         case BPF_TRACE_FEXIT:
15030                 if (!btf_type_is_func(t)) {
15031                         bpf_log(log, "attach_btf_id %u is not a function\n",
15032                                 btf_id);
15033                         return -EINVAL;
15034                 }
15035                 if (prog_extension &&
15036                     btf_check_type_match(log, prog, btf, t))
15037                         return -EINVAL;
15038                 t = btf_type_by_id(btf, t->type);
15039                 if (!btf_type_is_func_proto(t))
15040                         return -EINVAL;
15041
15042                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15043                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15044                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15045                         return -EINVAL;
15046
15047                 if (tgt_prog && conservative)
15048                         t = NULL;
15049
15050                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15051                 if (ret < 0)
15052                         return ret;
15053
15054                 if (tgt_prog) {
15055                         if (subprog == 0)
15056                                 addr = (long) tgt_prog->bpf_func;
15057                         else
15058                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15059                 } else {
15060                         addr = kallsyms_lookup_name(tname);
15061                         if (!addr) {
15062                                 bpf_log(log,
15063                                         "The address of function %s cannot be found\n",
15064                                         tname);
15065                                 return -ENOENT;
15066                         }
15067                 }
15068
15069                 if (prog->aux->sleepable) {
15070                         ret = -EINVAL;
15071                         switch (prog->type) {
15072                         case BPF_PROG_TYPE_TRACING:
15073                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15074                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15075                                  */
15076                                 if (!check_non_sleepable_error_inject(btf_id) &&
15077                                     within_error_injection_list(addr))
15078                                         ret = 0;
15079                                 break;
15080                         case BPF_PROG_TYPE_LSM:
15081                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15082                                  * Only some of them are sleepable.
15083                                  */
15084                                 if (bpf_lsm_is_sleepable_hook(btf_id))
15085                                         ret = 0;
15086                                 break;
15087                         default:
15088                                 break;
15089                         }
15090                         if (ret) {
15091                                 bpf_log(log, "%s is not sleepable\n", tname);
15092                                 return ret;
15093                         }
15094                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15095                         if (tgt_prog) {
15096                                 bpf_log(log, "can't modify return codes of BPF programs\n");
15097                                 return -EINVAL;
15098                         }
15099                         ret = check_attach_modify_return(addr, tname);
15100                         if (ret) {
15101                                 bpf_log(log, "%s() is not modifiable\n", tname);
15102                                 return ret;
15103                         }
15104                 }
15105
15106                 break;
15107         }
15108         tgt_info->tgt_addr = addr;
15109         tgt_info->tgt_name = tname;
15110         tgt_info->tgt_type = t;
15111         return 0;
15112 }
15113
15114 BTF_SET_START(btf_id_deny)
15115 BTF_ID_UNUSED
15116 #ifdef CONFIG_SMP
15117 BTF_ID(func, migrate_disable)
15118 BTF_ID(func, migrate_enable)
15119 #endif
15120 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15121 BTF_ID(func, rcu_read_unlock_strict)
15122 #endif
15123 BTF_SET_END(btf_id_deny)
15124
15125 static int check_attach_btf_id(struct bpf_verifier_env *env)
15126 {
15127         struct bpf_prog *prog = env->prog;
15128         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15129         struct bpf_attach_target_info tgt_info = {};
15130         u32 btf_id = prog->aux->attach_btf_id;
15131         struct bpf_trampoline *tr;
15132         int ret;
15133         u64 key;
15134
15135         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15136                 if (prog->aux->sleepable)
15137                         /* attach_btf_id checked to be zero already */
15138                         return 0;
15139                 verbose(env, "Syscall programs can only be sleepable\n");
15140                 return -EINVAL;
15141         }
15142
15143         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15144             prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15145                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15146                 return -EINVAL;
15147         }
15148
15149         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15150                 return check_struct_ops_btf_id(env);
15151
15152         if (prog->type != BPF_PROG_TYPE_TRACING &&
15153             prog->type != BPF_PROG_TYPE_LSM &&
15154             prog->type != BPF_PROG_TYPE_EXT)
15155                 return 0;
15156
15157         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15158         if (ret)
15159                 return ret;
15160
15161         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15162                 /* to make freplace equivalent to their targets, they need to
15163                  * inherit env->ops and expected_attach_type for the rest of the
15164                  * verification
15165                  */
15166                 env->ops = bpf_verifier_ops[tgt_prog->type];
15167                 prog->expected_attach_type = tgt_prog->expected_attach_type;
15168         }
15169
15170         /* store info about the attachment target that will be used later */
15171         prog->aux->attach_func_proto = tgt_info.tgt_type;
15172         prog->aux->attach_func_name = tgt_info.tgt_name;
15173
15174         if (tgt_prog) {
15175                 prog->aux->saved_dst_prog_type = tgt_prog->type;
15176                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15177         }
15178
15179         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15180                 prog->aux->attach_btf_trace = true;
15181                 return 0;
15182         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15183                 if (!bpf_iter_prog_supported(prog))
15184                         return -EINVAL;
15185                 return 0;
15186         }
15187
15188         if (prog->type == BPF_PROG_TYPE_LSM) {
15189                 ret = bpf_lsm_verify_prog(&env->log, prog);
15190                 if (ret < 0)
15191                         return ret;
15192         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15193                    btf_id_set_contains(&btf_id_deny, btf_id)) {
15194                 return -EINVAL;
15195         }
15196
15197         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15198         tr = bpf_trampoline_get(key, &tgt_info);
15199         if (!tr)
15200                 return -ENOMEM;
15201
15202         prog->aux->dst_trampoline = tr;
15203         return 0;
15204 }
15205
15206 struct btf *bpf_get_btf_vmlinux(void)
15207 {
15208         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15209                 mutex_lock(&bpf_verifier_lock);
15210                 if (!btf_vmlinux)
15211                         btf_vmlinux = btf_parse_vmlinux();
15212                 mutex_unlock(&bpf_verifier_lock);
15213         }
15214         return btf_vmlinux;
15215 }
15216
15217 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15218 {
15219         u64 start_time = ktime_get_ns();
15220         struct bpf_verifier_env *env;
15221         struct bpf_verifier_log *log;
15222         int i, len, ret = -EINVAL;
15223         bool is_priv;
15224
15225         /* no program is valid */
15226         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15227                 return -EINVAL;
15228
15229         /* 'struct bpf_verifier_env' can be global, but since it's not small,
15230          * allocate/free it every time bpf_check() is called
15231          */
15232         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15233         if (!env)
15234                 return -ENOMEM;
15235         log = &env->log;
15236
15237         len = (*prog)->len;
15238         env->insn_aux_data =
15239                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15240         ret = -ENOMEM;
15241         if (!env->insn_aux_data)
15242                 goto err_free_env;
15243         for (i = 0; i < len; i++)
15244                 env->insn_aux_data[i].orig_idx = i;
15245         env->prog = *prog;
15246         env->ops = bpf_verifier_ops[env->prog->type];
15247         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15248         is_priv = bpf_capable();
15249
15250         bpf_get_btf_vmlinux();
15251
15252         /* grab the mutex to protect few globals used by verifier */
15253         if (!is_priv)
15254                 mutex_lock(&bpf_verifier_lock);
15255
15256         if (attr->log_level || attr->log_buf || attr->log_size) {
15257                 /* user requested verbose verifier output
15258                  * and supplied buffer to store the verification trace
15259                  */
15260                 log->level = attr->log_level;
15261                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15262                 log->len_total = attr->log_size;
15263
15264                 /* log attributes have to be sane */
15265                 if (!bpf_verifier_log_attr_valid(log)) {
15266                         ret = -EINVAL;
15267                         goto err_unlock;
15268                 }
15269         }
15270
15271         mark_verifier_state_clean(env);
15272
15273         if (IS_ERR(btf_vmlinux)) {
15274                 /* Either gcc or pahole or kernel are broken. */
15275                 verbose(env, "in-kernel BTF is malformed\n");
15276                 ret = PTR_ERR(btf_vmlinux);
15277                 goto skip_full_check;
15278         }
15279
15280         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15281         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15282                 env->strict_alignment = true;
15283         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15284                 env->strict_alignment = false;
15285
15286         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15287         env->allow_uninit_stack = bpf_allow_uninit_stack();
15288         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15289         env->bypass_spec_v1 = bpf_bypass_spec_v1();
15290         env->bypass_spec_v4 = bpf_bypass_spec_v4();
15291         env->bpf_capable = bpf_capable();
15292
15293         if (is_priv)
15294                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15295
15296         env->explored_states = kvcalloc(state_htab_size(env),
15297                                        sizeof(struct bpf_verifier_state_list *),
15298                                        GFP_USER);
15299         ret = -ENOMEM;
15300         if (!env->explored_states)
15301                 goto skip_full_check;
15302
15303         ret = add_subprog_and_kfunc(env);
15304         if (ret < 0)
15305                 goto skip_full_check;
15306
15307         ret = check_subprogs(env);
15308         if (ret < 0)
15309                 goto skip_full_check;
15310
15311         ret = check_btf_info(env, attr, uattr);
15312         if (ret < 0)
15313                 goto skip_full_check;
15314
15315         ret = check_attach_btf_id(env);
15316         if (ret)
15317                 goto skip_full_check;
15318
15319         ret = resolve_pseudo_ldimm64(env);
15320         if (ret < 0)
15321                 goto skip_full_check;
15322
15323         if (bpf_prog_is_dev_bound(env->prog->aux)) {
15324                 ret = bpf_prog_offload_verifier_prep(env->prog);
15325                 if (ret)
15326                         goto skip_full_check;
15327         }
15328
15329         ret = check_cfg(env);
15330         if (ret < 0)
15331                 goto skip_full_check;
15332
15333         ret = do_check_subprogs(env);
15334         ret = ret ?: do_check_main(env);
15335
15336         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15337                 ret = bpf_prog_offload_finalize(env);
15338
15339 skip_full_check:
15340         kvfree(env->explored_states);
15341
15342         if (ret == 0)
15343                 ret = check_max_stack_depth(env);
15344
15345         /* instruction rewrites happen after this point */
15346         if (ret == 0)
15347                 ret = optimize_bpf_loop(env);
15348
15349         if (is_priv) {
15350                 if (ret == 0)
15351                         opt_hard_wire_dead_code_branches(env);
15352                 if (ret == 0)
15353                         ret = opt_remove_dead_code(env);
15354                 if (ret == 0)
15355                         ret = opt_remove_nops(env);
15356         } else {
15357                 if (ret == 0)
15358                         sanitize_dead_code(env);
15359         }
15360
15361         if (ret == 0)
15362                 /* program is valid, convert *(u32*)(ctx + off) accesses */
15363                 ret = convert_ctx_accesses(env);
15364
15365         if (ret == 0)
15366                 ret = do_misc_fixups(env);
15367
15368         /* do 32-bit optimization after insn patching has done so those patched
15369          * insns could be handled correctly.
15370          */
15371         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15372                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15373                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15374                                                                      : false;
15375         }
15376
15377         if (ret == 0)
15378                 ret = fixup_call_args(env);
15379
15380         env->verification_time = ktime_get_ns() - start_time;
15381         print_verification_stats(env);
15382         env->prog->aux->verified_insns = env->insn_processed;
15383
15384         if (log->level && bpf_verifier_log_full(log))
15385                 ret = -ENOSPC;
15386         if (log->level && !log->ubuf) {
15387                 ret = -EFAULT;
15388                 goto err_release_maps;
15389         }
15390
15391         if (ret)
15392                 goto err_release_maps;
15393
15394         if (env->used_map_cnt) {
15395                 /* if program passed verifier, update used_maps in bpf_prog_info */
15396                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15397                                                           sizeof(env->used_maps[0]),
15398                                                           GFP_KERNEL);
15399
15400                 if (!env->prog->aux->used_maps) {
15401                         ret = -ENOMEM;
15402                         goto err_release_maps;
15403                 }
15404
15405                 memcpy(env->prog->aux->used_maps, env->used_maps,
15406                        sizeof(env->used_maps[0]) * env->used_map_cnt);
15407                 env->prog->aux->used_map_cnt = env->used_map_cnt;
15408         }
15409         if (env->used_btf_cnt) {
15410                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15411                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15412                                                           sizeof(env->used_btfs[0]),
15413                                                           GFP_KERNEL);
15414                 if (!env->prog->aux->used_btfs) {
15415                         ret = -ENOMEM;
15416                         goto err_release_maps;
15417                 }
15418
15419                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15420                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15421                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15422         }
15423         if (env->used_map_cnt || env->used_btf_cnt) {
15424                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15425                  * bpf_ld_imm64 instructions
15426                  */
15427                 convert_pseudo_ld_imm64(env);
15428         }
15429
15430         adjust_btf_func(env);
15431
15432 err_release_maps:
15433         if (!env->prog->aux->used_maps)
15434                 /* if we didn't copy map pointers into bpf_prog_info, release
15435                  * them now. Otherwise free_used_maps() will release them.
15436                  */
15437                 release_maps(env);
15438         if (!env->prog->aux->used_btfs)
15439                 release_btfs(env);
15440
15441         /* extension progs temporarily inherit the attach_type of their targets
15442            for verification purposes, so set it back to zero before returning
15443          */
15444         if (env->prog->type == BPF_PROG_TYPE_EXT)
15445                 env->prog->expected_attach_type = 0;
15446
15447         *prog = env->prog;
15448 err_unlock:
15449         if (!is_priv)
15450                 mutex_unlock(&bpf_verifier_lock);
15451         vfree(env->insn_aux_data);
15452 err_free_env:
15453         kfree(env);
15454         return ret;
15455 }