treewide: use get_random_u32() when possible
[linux-block.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 bytes;
1004
1005         if (ZERO_OR_NULL_PTR(src))
1006                 goto out;
1007
1008         if (unlikely(check_mul_overflow(n, size, &bytes)))
1009                 return NULL;
1010
1011         if (ksize(dst) < bytes) {
1012                 kfree(dst);
1013                 dst = kmalloc_track_caller(bytes, flags);
1014                 if (!dst)
1015                         return NULL;
1016         }
1017
1018         memcpy(dst, src, bytes);
1019 out:
1020         return dst ? dst : ZERO_SIZE_PTR;
1021 }
1022
1023 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1024  * small to hold new_n items. new items are zeroed out if the array grows.
1025  *
1026  * Contrary to krealloc_array, does not free arr if new_n is zero.
1027  */
1028 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1029 {
1030         if (!new_n || old_n == new_n)
1031                 goto out;
1032
1033         arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
1034         if (!arr)
1035                 return NULL;
1036
1037         if (new_n > old_n)
1038                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1039
1040 out:
1041         return arr ? arr : ZERO_SIZE_PTR;
1042 }
1043
1044 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1045 {
1046         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1047                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1048         if (!dst->refs)
1049                 return -ENOMEM;
1050
1051         dst->acquired_refs = src->acquired_refs;
1052         return 0;
1053 }
1054
1055 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1056 {
1057         size_t n = src->allocated_stack / BPF_REG_SIZE;
1058
1059         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1060                                 GFP_KERNEL);
1061         if (!dst->stack)
1062                 return -ENOMEM;
1063
1064         dst->allocated_stack = src->allocated_stack;
1065         return 0;
1066 }
1067
1068 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1069 {
1070         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1071                                     sizeof(struct bpf_reference_state));
1072         if (!state->refs)
1073                 return -ENOMEM;
1074
1075         state->acquired_refs = n;
1076         return 0;
1077 }
1078
1079 static int grow_stack_state(struct bpf_func_state *state, int size)
1080 {
1081         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1082
1083         if (old_n >= n)
1084                 return 0;
1085
1086         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1087         if (!state->stack)
1088                 return -ENOMEM;
1089
1090         state->allocated_stack = size;
1091         return 0;
1092 }
1093
1094 /* Acquire a pointer id from the env and update the state->refs to include
1095  * this new pointer reference.
1096  * On success, returns a valid pointer id to associate with the register
1097  * On failure, returns a negative errno.
1098  */
1099 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1100 {
1101         struct bpf_func_state *state = cur_func(env);
1102         int new_ofs = state->acquired_refs;
1103         int id, err;
1104
1105         err = resize_reference_state(state, state->acquired_refs + 1);
1106         if (err)
1107                 return err;
1108         id = ++env->id_gen;
1109         state->refs[new_ofs].id = id;
1110         state->refs[new_ofs].insn_idx = insn_idx;
1111         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1112
1113         return id;
1114 }
1115
1116 /* release function corresponding to acquire_reference_state(). Idempotent. */
1117 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1118 {
1119         int i, last_idx;
1120
1121         last_idx = state->acquired_refs - 1;
1122         for (i = 0; i < state->acquired_refs; i++) {
1123                 if (state->refs[i].id == ptr_id) {
1124                         /* Cannot release caller references in callbacks */
1125                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1126                                 return -EINVAL;
1127                         if (last_idx && i != last_idx)
1128                                 memcpy(&state->refs[i], &state->refs[last_idx],
1129                                        sizeof(*state->refs));
1130                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1131                         state->acquired_refs--;
1132                         return 0;
1133                 }
1134         }
1135         return -EINVAL;
1136 }
1137
1138 static void free_func_state(struct bpf_func_state *state)
1139 {
1140         if (!state)
1141                 return;
1142         kfree(state->refs);
1143         kfree(state->stack);
1144         kfree(state);
1145 }
1146
1147 static void clear_jmp_history(struct bpf_verifier_state *state)
1148 {
1149         kfree(state->jmp_history);
1150         state->jmp_history = NULL;
1151         state->jmp_history_cnt = 0;
1152 }
1153
1154 static void free_verifier_state(struct bpf_verifier_state *state,
1155                                 bool free_self)
1156 {
1157         int i;
1158
1159         for (i = 0; i <= state->curframe; i++) {
1160                 free_func_state(state->frame[i]);
1161                 state->frame[i] = NULL;
1162         }
1163         clear_jmp_history(state);
1164         if (free_self)
1165                 kfree(state);
1166 }
1167
1168 /* copy verifier state from src to dst growing dst stack space
1169  * when necessary to accommodate larger src stack
1170  */
1171 static int copy_func_state(struct bpf_func_state *dst,
1172                            const struct bpf_func_state *src)
1173 {
1174         int err;
1175
1176         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1177         err = copy_reference_state(dst, src);
1178         if (err)
1179                 return err;
1180         return copy_stack_state(dst, src);
1181 }
1182
1183 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1184                                const struct bpf_verifier_state *src)
1185 {
1186         struct bpf_func_state *dst;
1187         int i, err;
1188
1189         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1190                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1191                                             GFP_USER);
1192         if (!dst_state->jmp_history)
1193                 return -ENOMEM;
1194         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1195
1196         /* if dst has more stack frames then src frame, free them */
1197         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1198                 free_func_state(dst_state->frame[i]);
1199                 dst_state->frame[i] = NULL;
1200         }
1201         dst_state->speculative = src->speculative;
1202         dst_state->curframe = src->curframe;
1203         dst_state->active_spin_lock = src->active_spin_lock;
1204         dst_state->branches = src->branches;
1205         dst_state->parent = src->parent;
1206         dst_state->first_insn_idx = src->first_insn_idx;
1207         dst_state->last_insn_idx = src->last_insn_idx;
1208         for (i = 0; i <= src->curframe; i++) {
1209                 dst = dst_state->frame[i];
1210                 if (!dst) {
1211                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1212                         if (!dst)
1213                                 return -ENOMEM;
1214                         dst_state->frame[i] = dst;
1215                 }
1216                 err = copy_func_state(dst, src->frame[i]);
1217                 if (err)
1218                         return err;
1219         }
1220         return 0;
1221 }
1222
1223 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1224 {
1225         while (st) {
1226                 u32 br = --st->branches;
1227
1228                 /* WARN_ON(br > 1) technically makes sense here,
1229                  * but see comment in push_stack(), hence:
1230                  */
1231                 WARN_ONCE((int)br < 0,
1232                           "BUG update_branch_counts:branches_to_explore=%d\n",
1233                           br);
1234                 if (br)
1235                         break;
1236                 st = st->parent;
1237         }
1238 }
1239
1240 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1241                      int *insn_idx, bool pop_log)
1242 {
1243         struct bpf_verifier_state *cur = env->cur_state;
1244         struct bpf_verifier_stack_elem *elem, *head = env->head;
1245         int err;
1246
1247         if (env->head == NULL)
1248                 return -ENOENT;
1249
1250         if (cur) {
1251                 err = copy_verifier_state(cur, &head->st);
1252                 if (err)
1253                         return err;
1254         }
1255         if (pop_log)
1256                 bpf_vlog_reset(&env->log, head->log_pos);
1257         if (insn_idx)
1258                 *insn_idx = head->insn_idx;
1259         if (prev_insn_idx)
1260                 *prev_insn_idx = head->prev_insn_idx;
1261         elem = head->next;
1262         free_verifier_state(&head->st, false);
1263         kfree(head);
1264         env->head = elem;
1265         env->stack_size--;
1266         return 0;
1267 }
1268
1269 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1270                                              int insn_idx, int prev_insn_idx,
1271                                              bool speculative)
1272 {
1273         struct bpf_verifier_state *cur = env->cur_state;
1274         struct bpf_verifier_stack_elem *elem;
1275         int err;
1276
1277         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1278         if (!elem)
1279                 goto err;
1280
1281         elem->insn_idx = insn_idx;
1282         elem->prev_insn_idx = prev_insn_idx;
1283         elem->next = env->head;
1284         elem->log_pos = env->log.len_used;
1285         env->head = elem;
1286         env->stack_size++;
1287         err = copy_verifier_state(&elem->st, cur);
1288         if (err)
1289                 goto err;
1290         elem->st.speculative |= speculative;
1291         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1292                 verbose(env, "The sequence of %d jumps is too complex.\n",
1293                         env->stack_size);
1294                 goto err;
1295         }
1296         if (elem->st.parent) {
1297                 ++elem->st.parent->branches;
1298                 /* WARN_ON(branches > 2) technically makes sense here,
1299                  * but
1300                  * 1. speculative states will bump 'branches' for non-branch
1301                  * instructions
1302                  * 2. is_state_visited() heuristics may decide not to create
1303                  * a new state for a sequence of branches and all such current
1304                  * and cloned states will be pointing to a single parent state
1305                  * which might have large 'branches' count.
1306                  */
1307         }
1308         return &elem->st;
1309 err:
1310         free_verifier_state(env->cur_state, true);
1311         env->cur_state = NULL;
1312         /* pop all elements and return */
1313         while (!pop_stack(env, NULL, NULL, false));
1314         return NULL;
1315 }
1316
1317 #define CALLER_SAVED_REGS 6
1318 static const int caller_saved[CALLER_SAVED_REGS] = {
1319         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1320 };
1321
1322 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1323                                 struct bpf_reg_state *reg);
1324
1325 /* This helper doesn't clear reg->id */
1326 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1327 {
1328         reg->var_off = tnum_const(imm);
1329         reg->smin_value = (s64)imm;
1330         reg->smax_value = (s64)imm;
1331         reg->umin_value = imm;
1332         reg->umax_value = imm;
1333
1334         reg->s32_min_value = (s32)imm;
1335         reg->s32_max_value = (s32)imm;
1336         reg->u32_min_value = (u32)imm;
1337         reg->u32_max_value = (u32)imm;
1338 }
1339
1340 /* Mark the unknown part of a register (variable offset or scalar value) as
1341  * known to have the value @imm.
1342  */
1343 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1344 {
1345         /* Clear id, off, and union(map_ptr, range) */
1346         memset(((u8 *)reg) + sizeof(reg->type), 0,
1347                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1348         ___mark_reg_known(reg, imm);
1349 }
1350
1351 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1352 {
1353         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1354         reg->s32_min_value = (s32)imm;
1355         reg->s32_max_value = (s32)imm;
1356         reg->u32_min_value = (u32)imm;
1357         reg->u32_max_value = (u32)imm;
1358 }
1359
1360 /* Mark the 'variable offset' part of a register as zero.  This should be
1361  * used only on registers holding a pointer type.
1362  */
1363 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1364 {
1365         __mark_reg_known(reg, 0);
1366 }
1367
1368 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1369 {
1370         __mark_reg_known(reg, 0);
1371         reg->type = SCALAR_VALUE;
1372 }
1373
1374 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1375                                 struct bpf_reg_state *regs, u32 regno)
1376 {
1377         if (WARN_ON(regno >= MAX_BPF_REG)) {
1378                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1379                 /* Something bad happened, let's kill all regs */
1380                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1381                         __mark_reg_not_init(env, regs + regno);
1382                 return;
1383         }
1384         __mark_reg_known_zero(regs + regno);
1385 }
1386
1387 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1388 {
1389         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1390                 const struct bpf_map *map = reg->map_ptr;
1391
1392                 if (map->inner_map_meta) {
1393                         reg->type = CONST_PTR_TO_MAP;
1394                         reg->map_ptr = map->inner_map_meta;
1395                         /* transfer reg's id which is unique for every map_lookup_elem
1396                          * as UID of the inner map.
1397                          */
1398                         if (map_value_has_timer(map->inner_map_meta))
1399                                 reg->map_uid = reg->id;
1400                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1401                         reg->type = PTR_TO_XDP_SOCK;
1402                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1403                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1404                         reg->type = PTR_TO_SOCKET;
1405                 } else {
1406                         reg->type = PTR_TO_MAP_VALUE;
1407                 }
1408                 return;
1409         }
1410
1411         reg->type &= ~PTR_MAYBE_NULL;
1412 }
1413
1414 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1415 {
1416         return type_is_pkt_pointer(reg->type);
1417 }
1418
1419 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1420 {
1421         return reg_is_pkt_pointer(reg) ||
1422                reg->type == PTR_TO_PACKET_END;
1423 }
1424
1425 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1426 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1427                                     enum bpf_reg_type which)
1428 {
1429         /* The register can already have a range from prior markings.
1430          * This is fine as long as it hasn't been advanced from its
1431          * origin.
1432          */
1433         return reg->type == which &&
1434                reg->id == 0 &&
1435                reg->off == 0 &&
1436                tnum_equals_const(reg->var_off, 0);
1437 }
1438
1439 /* Reset the min/max bounds of a register */
1440 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1441 {
1442         reg->smin_value = S64_MIN;
1443         reg->smax_value = S64_MAX;
1444         reg->umin_value = 0;
1445         reg->umax_value = U64_MAX;
1446
1447         reg->s32_min_value = S32_MIN;
1448         reg->s32_max_value = S32_MAX;
1449         reg->u32_min_value = 0;
1450         reg->u32_max_value = U32_MAX;
1451 }
1452
1453 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1454 {
1455         reg->smin_value = S64_MIN;
1456         reg->smax_value = S64_MAX;
1457         reg->umin_value = 0;
1458         reg->umax_value = U64_MAX;
1459 }
1460
1461 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1462 {
1463         reg->s32_min_value = S32_MIN;
1464         reg->s32_max_value = S32_MAX;
1465         reg->u32_min_value = 0;
1466         reg->u32_max_value = U32_MAX;
1467 }
1468
1469 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1470 {
1471         struct tnum var32_off = tnum_subreg(reg->var_off);
1472
1473         /* min signed is max(sign bit) | min(other bits) */
1474         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1475                         var32_off.value | (var32_off.mask & S32_MIN));
1476         /* max signed is min(sign bit) | max(other bits) */
1477         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1478                         var32_off.value | (var32_off.mask & S32_MAX));
1479         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1480         reg->u32_max_value = min(reg->u32_max_value,
1481                                  (u32)(var32_off.value | var32_off.mask));
1482 }
1483
1484 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1485 {
1486         /* min signed is max(sign bit) | min(other bits) */
1487         reg->smin_value = max_t(s64, reg->smin_value,
1488                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1489         /* max signed is min(sign bit) | max(other bits) */
1490         reg->smax_value = min_t(s64, reg->smax_value,
1491                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1492         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1493         reg->umax_value = min(reg->umax_value,
1494                               reg->var_off.value | reg->var_off.mask);
1495 }
1496
1497 static void __update_reg_bounds(struct bpf_reg_state *reg)
1498 {
1499         __update_reg32_bounds(reg);
1500         __update_reg64_bounds(reg);
1501 }
1502
1503 /* Uses signed min/max values to inform unsigned, and vice-versa */
1504 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1505 {
1506         /* Learn sign from signed bounds.
1507          * If we cannot cross the sign boundary, then signed and unsigned bounds
1508          * are the same, so combine.  This works even in the negative case, e.g.
1509          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1510          */
1511         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1512                 reg->s32_min_value = reg->u32_min_value =
1513                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1514                 reg->s32_max_value = reg->u32_max_value =
1515                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1516                 return;
1517         }
1518         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1519          * boundary, so we must be careful.
1520          */
1521         if ((s32)reg->u32_max_value >= 0) {
1522                 /* Positive.  We can't learn anything from the smin, but smax
1523                  * is positive, hence safe.
1524                  */
1525                 reg->s32_min_value = reg->u32_min_value;
1526                 reg->s32_max_value = reg->u32_max_value =
1527                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1528         } else if ((s32)reg->u32_min_value < 0) {
1529                 /* Negative.  We can't learn anything from the smax, but smin
1530                  * is negative, hence safe.
1531                  */
1532                 reg->s32_min_value = reg->u32_min_value =
1533                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1534                 reg->s32_max_value = reg->u32_max_value;
1535         }
1536 }
1537
1538 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1539 {
1540         /* Learn sign from signed bounds.
1541          * If we cannot cross the sign boundary, then signed and unsigned bounds
1542          * are the same, so combine.  This works even in the negative case, e.g.
1543          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1544          */
1545         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1546                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1547                                                           reg->umin_value);
1548                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1549                                                           reg->umax_value);
1550                 return;
1551         }
1552         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1553          * boundary, so we must be careful.
1554          */
1555         if ((s64)reg->umax_value >= 0) {
1556                 /* Positive.  We can't learn anything from the smin, but smax
1557                  * is positive, hence safe.
1558                  */
1559                 reg->smin_value = reg->umin_value;
1560                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1561                                                           reg->umax_value);
1562         } else if ((s64)reg->umin_value < 0) {
1563                 /* Negative.  We can't learn anything from the smax, but smin
1564                  * is negative, hence safe.
1565                  */
1566                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1567                                                           reg->umin_value);
1568                 reg->smax_value = reg->umax_value;
1569         }
1570 }
1571
1572 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1573 {
1574         __reg32_deduce_bounds(reg);
1575         __reg64_deduce_bounds(reg);
1576 }
1577
1578 /* Attempts to improve var_off based on unsigned min/max information */
1579 static void __reg_bound_offset(struct bpf_reg_state *reg)
1580 {
1581         struct tnum var64_off = tnum_intersect(reg->var_off,
1582                                                tnum_range(reg->umin_value,
1583                                                           reg->umax_value));
1584         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1585                                                 tnum_range(reg->u32_min_value,
1586                                                            reg->u32_max_value));
1587
1588         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1589 }
1590
1591 static void reg_bounds_sync(struct bpf_reg_state *reg)
1592 {
1593         /* We might have learned new bounds from the var_off. */
1594         __update_reg_bounds(reg);
1595         /* We might have learned something about the sign bit. */
1596         __reg_deduce_bounds(reg);
1597         /* We might have learned some bits from the bounds. */
1598         __reg_bound_offset(reg);
1599         /* Intersecting with the old var_off might have improved our bounds
1600          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1601          * then new var_off is (0; 0x7f...fc) which improves our umax.
1602          */
1603         __update_reg_bounds(reg);
1604 }
1605
1606 static bool __reg32_bound_s64(s32 a)
1607 {
1608         return a >= 0 && a <= S32_MAX;
1609 }
1610
1611 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1612 {
1613         reg->umin_value = reg->u32_min_value;
1614         reg->umax_value = reg->u32_max_value;
1615
1616         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1617          * be positive otherwise set to worse case bounds and refine later
1618          * from tnum.
1619          */
1620         if (__reg32_bound_s64(reg->s32_min_value) &&
1621             __reg32_bound_s64(reg->s32_max_value)) {
1622                 reg->smin_value = reg->s32_min_value;
1623                 reg->smax_value = reg->s32_max_value;
1624         } else {
1625                 reg->smin_value = 0;
1626                 reg->smax_value = U32_MAX;
1627         }
1628 }
1629
1630 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1631 {
1632         /* special case when 64-bit register has upper 32-bit register
1633          * zeroed. Typically happens after zext or <<32, >>32 sequence
1634          * allowing us to use 32-bit bounds directly,
1635          */
1636         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1637                 __reg_assign_32_into_64(reg);
1638         } else {
1639                 /* Otherwise the best we can do is push lower 32bit known and
1640                  * unknown bits into register (var_off set from jmp logic)
1641                  * then learn as much as possible from the 64-bit tnum
1642                  * known and unknown bits. The previous smin/smax bounds are
1643                  * invalid here because of jmp32 compare so mark them unknown
1644                  * so they do not impact tnum bounds calculation.
1645                  */
1646                 __mark_reg64_unbounded(reg);
1647         }
1648         reg_bounds_sync(reg);
1649 }
1650
1651 static bool __reg64_bound_s32(s64 a)
1652 {
1653         return a >= S32_MIN && a <= S32_MAX;
1654 }
1655
1656 static bool __reg64_bound_u32(u64 a)
1657 {
1658         return a >= U32_MIN && a <= U32_MAX;
1659 }
1660
1661 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1662 {
1663         __mark_reg32_unbounded(reg);
1664         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1665                 reg->s32_min_value = (s32)reg->smin_value;
1666                 reg->s32_max_value = (s32)reg->smax_value;
1667         }
1668         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1669                 reg->u32_min_value = (u32)reg->umin_value;
1670                 reg->u32_max_value = (u32)reg->umax_value;
1671         }
1672         reg_bounds_sync(reg);
1673 }
1674
1675 /* Mark a register as having a completely unknown (scalar) value. */
1676 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1677                                struct bpf_reg_state *reg)
1678 {
1679         /*
1680          * Clear type, id, off, and union(map_ptr, range) and
1681          * padding between 'type' and union
1682          */
1683         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1684         reg->type = SCALAR_VALUE;
1685         reg->var_off = tnum_unknown;
1686         reg->frameno = 0;
1687         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1688         __mark_reg_unbounded(reg);
1689 }
1690
1691 static void mark_reg_unknown(struct bpf_verifier_env *env,
1692                              struct bpf_reg_state *regs, u32 regno)
1693 {
1694         if (WARN_ON(regno >= MAX_BPF_REG)) {
1695                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1696                 /* Something bad happened, let's kill all regs except FP */
1697                 for (regno = 0; regno < BPF_REG_FP; regno++)
1698                         __mark_reg_not_init(env, regs + regno);
1699                 return;
1700         }
1701         __mark_reg_unknown(env, regs + regno);
1702 }
1703
1704 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1705                                 struct bpf_reg_state *reg)
1706 {
1707         __mark_reg_unknown(env, reg);
1708         reg->type = NOT_INIT;
1709 }
1710
1711 static void mark_reg_not_init(struct bpf_verifier_env *env,
1712                               struct bpf_reg_state *regs, u32 regno)
1713 {
1714         if (WARN_ON(regno >= MAX_BPF_REG)) {
1715                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1716                 /* Something bad happened, let's kill all regs except FP */
1717                 for (regno = 0; regno < BPF_REG_FP; regno++)
1718                         __mark_reg_not_init(env, regs + regno);
1719                 return;
1720         }
1721         __mark_reg_not_init(env, regs + regno);
1722 }
1723
1724 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1725                             struct bpf_reg_state *regs, u32 regno,
1726                             enum bpf_reg_type reg_type,
1727                             struct btf *btf, u32 btf_id,
1728                             enum bpf_type_flag flag)
1729 {
1730         if (reg_type == SCALAR_VALUE) {
1731                 mark_reg_unknown(env, regs, regno);
1732                 return;
1733         }
1734         mark_reg_known_zero(env, regs, regno);
1735         regs[regno].type = PTR_TO_BTF_ID | flag;
1736         regs[regno].btf = btf;
1737         regs[regno].btf_id = btf_id;
1738 }
1739
1740 #define DEF_NOT_SUBREG  (0)
1741 static void init_reg_state(struct bpf_verifier_env *env,
1742                            struct bpf_func_state *state)
1743 {
1744         struct bpf_reg_state *regs = state->regs;
1745         int i;
1746
1747         for (i = 0; i < MAX_BPF_REG; i++) {
1748                 mark_reg_not_init(env, regs, i);
1749                 regs[i].live = REG_LIVE_NONE;
1750                 regs[i].parent = NULL;
1751                 regs[i].subreg_def = DEF_NOT_SUBREG;
1752         }
1753
1754         /* frame pointer */
1755         regs[BPF_REG_FP].type = PTR_TO_STACK;
1756         mark_reg_known_zero(env, regs, BPF_REG_FP);
1757         regs[BPF_REG_FP].frameno = state->frameno;
1758 }
1759
1760 #define BPF_MAIN_FUNC (-1)
1761 static void init_func_state(struct bpf_verifier_env *env,
1762                             struct bpf_func_state *state,
1763                             int callsite, int frameno, int subprogno)
1764 {
1765         state->callsite = callsite;
1766         state->frameno = frameno;
1767         state->subprogno = subprogno;
1768         state->callback_ret_range = tnum_range(0, 0);
1769         init_reg_state(env, state);
1770         mark_verifier_state_scratched(env);
1771 }
1772
1773 /* Similar to push_stack(), but for async callbacks */
1774 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1775                                                 int insn_idx, int prev_insn_idx,
1776                                                 int subprog)
1777 {
1778         struct bpf_verifier_stack_elem *elem;
1779         struct bpf_func_state *frame;
1780
1781         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1782         if (!elem)
1783                 goto err;
1784
1785         elem->insn_idx = insn_idx;
1786         elem->prev_insn_idx = prev_insn_idx;
1787         elem->next = env->head;
1788         elem->log_pos = env->log.len_used;
1789         env->head = elem;
1790         env->stack_size++;
1791         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1792                 verbose(env,
1793                         "The sequence of %d jumps is too complex for async cb.\n",
1794                         env->stack_size);
1795                 goto err;
1796         }
1797         /* Unlike push_stack() do not copy_verifier_state().
1798          * The caller state doesn't matter.
1799          * This is async callback. It starts in a fresh stack.
1800          * Initialize it similar to do_check_common().
1801          */
1802         elem->st.branches = 1;
1803         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1804         if (!frame)
1805                 goto err;
1806         init_func_state(env, frame,
1807                         BPF_MAIN_FUNC /* callsite */,
1808                         0 /* frameno within this callchain */,
1809                         subprog /* subprog number within this prog */);
1810         elem->st.frame[0] = frame;
1811         return &elem->st;
1812 err:
1813         free_verifier_state(env->cur_state, true);
1814         env->cur_state = NULL;
1815         /* pop all elements and return */
1816         while (!pop_stack(env, NULL, NULL, false));
1817         return NULL;
1818 }
1819
1820
1821 enum reg_arg_type {
1822         SRC_OP,         /* register is used as source operand */
1823         DST_OP,         /* register is used as destination operand */
1824         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1825 };
1826
1827 static int cmp_subprogs(const void *a, const void *b)
1828 {
1829         return ((struct bpf_subprog_info *)a)->start -
1830                ((struct bpf_subprog_info *)b)->start;
1831 }
1832
1833 static int find_subprog(struct bpf_verifier_env *env, int off)
1834 {
1835         struct bpf_subprog_info *p;
1836
1837         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1838                     sizeof(env->subprog_info[0]), cmp_subprogs);
1839         if (!p)
1840                 return -ENOENT;
1841         return p - env->subprog_info;
1842
1843 }
1844
1845 static int add_subprog(struct bpf_verifier_env *env, int off)
1846 {
1847         int insn_cnt = env->prog->len;
1848         int ret;
1849
1850         if (off >= insn_cnt || off < 0) {
1851                 verbose(env, "call to invalid destination\n");
1852                 return -EINVAL;
1853         }
1854         ret = find_subprog(env, off);
1855         if (ret >= 0)
1856                 return ret;
1857         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1858                 verbose(env, "too many subprograms\n");
1859                 return -E2BIG;
1860         }
1861         /* determine subprog starts. The end is one before the next starts */
1862         env->subprog_info[env->subprog_cnt++].start = off;
1863         sort(env->subprog_info, env->subprog_cnt,
1864              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1865         return env->subprog_cnt - 1;
1866 }
1867
1868 #define MAX_KFUNC_DESCS 256
1869 #define MAX_KFUNC_BTFS  256
1870
1871 struct bpf_kfunc_desc {
1872         struct btf_func_model func_model;
1873         u32 func_id;
1874         s32 imm;
1875         u16 offset;
1876 };
1877
1878 struct bpf_kfunc_btf {
1879         struct btf *btf;
1880         struct module *module;
1881         u16 offset;
1882 };
1883
1884 struct bpf_kfunc_desc_tab {
1885         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1886         u32 nr_descs;
1887 };
1888
1889 struct bpf_kfunc_btf_tab {
1890         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1891         u32 nr_descs;
1892 };
1893
1894 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1895 {
1896         const struct bpf_kfunc_desc *d0 = a;
1897         const struct bpf_kfunc_desc *d1 = b;
1898
1899         /* func_id is not greater than BTF_MAX_TYPE */
1900         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1901 }
1902
1903 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1904 {
1905         const struct bpf_kfunc_btf *d0 = a;
1906         const struct bpf_kfunc_btf *d1 = b;
1907
1908         return d0->offset - d1->offset;
1909 }
1910
1911 static const struct bpf_kfunc_desc *
1912 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1913 {
1914         struct bpf_kfunc_desc desc = {
1915                 .func_id = func_id,
1916                 .offset = offset,
1917         };
1918         struct bpf_kfunc_desc_tab *tab;
1919
1920         tab = prog->aux->kfunc_tab;
1921         return bsearch(&desc, tab->descs, tab->nr_descs,
1922                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1923 }
1924
1925 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1926                                          s16 offset)
1927 {
1928         struct bpf_kfunc_btf kf_btf = { .offset = offset };
1929         struct bpf_kfunc_btf_tab *tab;
1930         struct bpf_kfunc_btf *b;
1931         struct module *mod;
1932         struct btf *btf;
1933         int btf_fd;
1934
1935         tab = env->prog->aux->kfunc_btf_tab;
1936         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1937                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1938         if (!b) {
1939                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1940                         verbose(env, "too many different module BTFs\n");
1941                         return ERR_PTR(-E2BIG);
1942                 }
1943
1944                 if (bpfptr_is_null(env->fd_array)) {
1945                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1946                         return ERR_PTR(-EPROTO);
1947                 }
1948
1949                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1950                                             offset * sizeof(btf_fd),
1951                                             sizeof(btf_fd)))
1952                         return ERR_PTR(-EFAULT);
1953
1954                 btf = btf_get_by_fd(btf_fd);
1955                 if (IS_ERR(btf)) {
1956                         verbose(env, "invalid module BTF fd specified\n");
1957                         return btf;
1958                 }
1959
1960                 if (!btf_is_module(btf)) {
1961                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
1962                         btf_put(btf);
1963                         return ERR_PTR(-EINVAL);
1964                 }
1965
1966                 mod = btf_try_get_module(btf);
1967                 if (!mod) {
1968                         btf_put(btf);
1969                         return ERR_PTR(-ENXIO);
1970                 }
1971
1972                 b = &tab->descs[tab->nr_descs++];
1973                 b->btf = btf;
1974                 b->module = mod;
1975                 b->offset = offset;
1976
1977                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1978                      kfunc_btf_cmp_by_off, NULL);
1979         }
1980         return b->btf;
1981 }
1982
1983 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1984 {
1985         if (!tab)
1986                 return;
1987
1988         while (tab->nr_descs--) {
1989                 module_put(tab->descs[tab->nr_descs].module);
1990                 btf_put(tab->descs[tab->nr_descs].btf);
1991         }
1992         kfree(tab);
1993 }
1994
1995 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
1996 {
1997         if (offset) {
1998                 if (offset < 0) {
1999                         /* In the future, this can be allowed to increase limit
2000                          * of fd index into fd_array, interpreted as u16.
2001                          */
2002                         verbose(env, "negative offset disallowed for kernel module function call\n");
2003                         return ERR_PTR(-EINVAL);
2004                 }
2005
2006                 return __find_kfunc_desc_btf(env, offset);
2007         }
2008         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2009 }
2010
2011 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2012 {
2013         const struct btf_type *func, *func_proto;
2014         struct bpf_kfunc_btf_tab *btf_tab;
2015         struct bpf_kfunc_desc_tab *tab;
2016         struct bpf_prog_aux *prog_aux;
2017         struct bpf_kfunc_desc *desc;
2018         const char *func_name;
2019         struct btf *desc_btf;
2020         unsigned long call_imm;
2021         unsigned long addr;
2022         int err;
2023
2024         prog_aux = env->prog->aux;
2025         tab = prog_aux->kfunc_tab;
2026         btf_tab = prog_aux->kfunc_btf_tab;
2027         if (!tab) {
2028                 if (!btf_vmlinux) {
2029                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2030                         return -ENOTSUPP;
2031                 }
2032
2033                 if (!env->prog->jit_requested) {
2034                         verbose(env, "JIT is required for calling kernel function\n");
2035                         return -ENOTSUPP;
2036                 }
2037
2038                 if (!bpf_jit_supports_kfunc_call()) {
2039                         verbose(env, "JIT does not support calling kernel function\n");
2040                         return -ENOTSUPP;
2041                 }
2042
2043                 if (!env->prog->gpl_compatible) {
2044                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2045                         return -EINVAL;
2046                 }
2047
2048                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2049                 if (!tab)
2050                         return -ENOMEM;
2051                 prog_aux->kfunc_tab = tab;
2052         }
2053
2054         /* func_id == 0 is always invalid, but instead of returning an error, be
2055          * conservative and wait until the code elimination pass before returning
2056          * error, so that invalid calls that get pruned out can be in BPF programs
2057          * loaded from userspace.  It is also required that offset be untouched
2058          * for such calls.
2059          */
2060         if (!func_id && !offset)
2061                 return 0;
2062
2063         if (!btf_tab && offset) {
2064                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2065                 if (!btf_tab)
2066                         return -ENOMEM;
2067                 prog_aux->kfunc_btf_tab = btf_tab;
2068         }
2069
2070         desc_btf = find_kfunc_desc_btf(env, offset);
2071         if (IS_ERR(desc_btf)) {
2072                 verbose(env, "failed to find BTF for kernel function\n");
2073                 return PTR_ERR(desc_btf);
2074         }
2075
2076         if (find_kfunc_desc(env->prog, func_id, offset))
2077                 return 0;
2078
2079         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2080                 verbose(env, "too many different kernel function calls\n");
2081                 return -E2BIG;
2082         }
2083
2084         func = btf_type_by_id(desc_btf, func_id);
2085         if (!func || !btf_type_is_func(func)) {
2086                 verbose(env, "kernel btf_id %u is not a function\n",
2087                         func_id);
2088                 return -EINVAL;
2089         }
2090         func_proto = btf_type_by_id(desc_btf, func->type);
2091         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2092                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2093                         func_id);
2094                 return -EINVAL;
2095         }
2096
2097         func_name = btf_name_by_offset(desc_btf, func->name_off);
2098         addr = kallsyms_lookup_name(func_name);
2099         if (!addr) {
2100                 verbose(env, "cannot find address for kernel function %s\n",
2101                         func_name);
2102                 return -EINVAL;
2103         }
2104
2105         call_imm = BPF_CALL_IMM(addr);
2106         /* Check whether or not the relative offset overflows desc->imm */
2107         if ((unsigned long)(s32)call_imm != call_imm) {
2108                 verbose(env, "address of kernel function %s is out of range\n",
2109                         func_name);
2110                 return -EINVAL;
2111         }
2112
2113         desc = &tab->descs[tab->nr_descs++];
2114         desc->func_id = func_id;
2115         desc->imm = call_imm;
2116         desc->offset = offset;
2117         err = btf_distill_func_proto(&env->log, desc_btf,
2118                                      func_proto, func_name,
2119                                      &desc->func_model);
2120         if (!err)
2121                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2122                      kfunc_desc_cmp_by_id_off, NULL);
2123         return err;
2124 }
2125
2126 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2127 {
2128         const struct bpf_kfunc_desc *d0 = a;
2129         const struct bpf_kfunc_desc *d1 = b;
2130
2131         if (d0->imm > d1->imm)
2132                 return 1;
2133         else if (d0->imm < d1->imm)
2134                 return -1;
2135         return 0;
2136 }
2137
2138 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2139 {
2140         struct bpf_kfunc_desc_tab *tab;
2141
2142         tab = prog->aux->kfunc_tab;
2143         if (!tab)
2144                 return;
2145
2146         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2147              kfunc_desc_cmp_by_imm, NULL);
2148 }
2149
2150 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2151 {
2152         return !!prog->aux->kfunc_tab;
2153 }
2154
2155 const struct btf_func_model *
2156 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2157                          const struct bpf_insn *insn)
2158 {
2159         const struct bpf_kfunc_desc desc = {
2160                 .imm = insn->imm,
2161         };
2162         const struct bpf_kfunc_desc *res;
2163         struct bpf_kfunc_desc_tab *tab;
2164
2165         tab = prog->aux->kfunc_tab;
2166         res = bsearch(&desc, tab->descs, tab->nr_descs,
2167                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2168
2169         return res ? &res->func_model : NULL;
2170 }
2171
2172 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2173 {
2174         struct bpf_subprog_info *subprog = env->subprog_info;
2175         struct bpf_insn *insn = env->prog->insnsi;
2176         int i, ret, insn_cnt = env->prog->len;
2177
2178         /* Add entry function. */
2179         ret = add_subprog(env, 0);
2180         if (ret)
2181                 return ret;
2182
2183         for (i = 0; i < insn_cnt; i++, insn++) {
2184                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2185                     !bpf_pseudo_kfunc_call(insn))
2186                         continue;
2187
2188                 if (!env->bpf_capable) {
2189                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2190                         return -EPERM;
2191                 }
2192
2193                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2194                         ret = add_subprog(env, i + insn->imm + 1);
2195                 else
2196                         ret = add_kfunc_call(env, insn->imm, insn->off);
2197
2198                 if (ret < 0)
2199                         return ret;
2200         }
2201
2202         /* Add a fake 'exit' subprog which could simplify subprog iteration
2203          * logic. 'subprog_cnt' should not be increased.
2204          */
2205         subprog[env->subprog_cnt].start = insn_cnt;
2206
2207         if (env->log.level & BPF_LOG_LEVEL2)
2208                 for (i = 0; i < env->subprog_cnt; i++)
2209                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2210
2211         return 0;
2212 }
2213
2214 static int check_subprogs(struct bpf_verifier_env *env)
2215 {
2216         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2217         struct bpf_subprog_info *subprog = env->subprog_info;
2218         struct bpf_insn *insn = env->prog->insnsi;
2219         int insn_cnt = env->prog->len;
2220
2221         /* now check that all jumps are within the same subprog */
2222         subprog_start = subprog[cur_subprog].start;
2223         subprog_end = subprog[cur_subprog + 1].start;
2224         for (i = 0; i < insn_cnt; i++) {
2225                 u8 code = insn[i].code;
2226
2227                 if (code == (BPF_JMP | BPF_CALL) &&
2228                     insn[i].imm == BPF_FUNC_tail_call &&
2229                     insn[i].src_reg != BPF_PSEUDO_CALL)
2230                         subprog[cur_subprog].has_tail_call = true;
2231                 if (BPF_CLASS(code) == BPF_LD &&
2232                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2233                         subprog[cur_subprog].has_ld_abs = true;
2234                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2235                         goto next;
2236                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2237                         goto next;
2238                 off = i + insn[i].off + 1;
2239                 if (off < subprog_start || off >= subprog_end) {
2240                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2241                         return -EINVAL;
2242                 }
2243 next:
2244                 if (i == subprog_end - 1) {
2245                         /* to avoid fall-through from one subprog into another
2246                          * the last insn of the subprog should be either exit
2247                          * or unconditional jump back
2248                          */
2249                         if (code != (BPF_JMP | BPF_EXIT) &&
2250                             code != (BPF_JMP | BPF_JA)) {
2251                                 verbose(env, "last insn is not an exit or jmp\n");
2252                                 return -EINVAL;
2253                         }
2254                         subprog_start = subprog_end;
2255                         cur_subprog++;
2256                         if (cur_subprog < env->subprog_cnt)
2257                                 subprog_end = subprog[cur_subprog + 1].start;
2258                 }
2259         }
2260         return 0;
2261 }
2262
2263 /* Parentage chain of this register (or stack slot) should take care of all
2264  * issues like callee-saved registers, stack slot allocation time, etc.
2265  */
2266 static int mark_reg_read(struct bpf_verifier_env *env,
2267                          const struct bpf_reg_state *state,
2268                          struct bpf_reg_state *parent, u8 flag)
2269 {
2270         bool writes = parent == state->parent; /* Observe write marks */
2271         int cnt = 0;
2272
2273         while (parent) {
2274                 /* if read wasn't screened by an earlier write ... */
2275                 if (writes && state->live & REG_LIVE_WRITTEN)
2276                         break;
2277                 if (parent->live & REG_LIVE_DONE) {
2278                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2279                                 reg_type_str(env, parent->type),
2280                                 parent->var_off.value, parent->off);
2281                         return -EFAULT;
2282                 }
2283                 /* The first condition is more likely to be true than the
2284                  * second, checked it first.
2285                  */
2286                 if ((parent->live & REG_LIVE_READ) == flag ||
2287                     parent->live & REG_LIVE_READ64)
2288                         /* The parentage chain never changes and
2289                          * this parent was already marked as LIVE_READ.
2290                          * There is no need to keep walking the chain again and
2291                          * keep re-marking all parents as LIVE_READ.
2292                          * This case happens when the same register is read
2293                          * multiple times without writes into it in-between.
2294                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2295                          * then no need to set the weak REG_LIVE_READ32.
2296                          */
2297                         break;
2298                 /* ... then we depend on parent's value */
2299                 parent->live |= flag;
2300                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2301                 if (flag == REG_LIVE_READ64)
2302                         parent->live &= ~REG_LIVE_READ32;
2303                 state = parent;
2304                 parent = state->parent;
2305                 writes = true;
2306                 cnt++;
2307         }
2308
2309         if (env->longest_mark_read_walk < cnt)
2310                 env->longest_mark_read_walk = cnt;
2311         return 0;
2312 }
2313
2314 /* This function is supposed to be used by the following 32-bit optimization
2315  * code only. It returns TRUE if the source or destination register operates
2316  * on 64-bit, otherwise return FALSE.
2317  */
2318 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2319                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2320 {
2321         u8 code, class, op;
2322
2323         code = insn->code;
2324         class = BPF_CLASS(code);
2325         op = BPF_OP(code);
2326         if (class == BPF_JMP) {
2327                 /* BPF_EXIT for "main" will reach here. Return TRUE
2328                  * conservatively.
2329                  */
2330                 if (op == BPF_EXIT)
2331                         return true;
2332                 if (op == BPF_CALL) {
2333                         /* BPF to BPF call will reach here because of marking
2334                          * caller saved clobber with DST_OP_NO_MARK for which we
2335                          * don't care the register def because they are anyway
2336                          * marked as NOT_INIT already.
2337                          */
2338                         if (insn->src_reg == BPF_PSEUDO_CALL)
2339                                 return false;
2340                         /* Helper call will reach here because of arg type
2341                          * check, conservatively return TRUE.
2342                          */
2343                         if (t == SRC_OP)
2344                                 return true;
2345
2346                         return false;
2347                 }
2348         }
2349
2350         if (class == BPF_ALU64 || class == BPF_JMP ||
2351             /* BPF_END always use BPF_ALU class. */
2352             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2353                 return true;
2354
2355         if (class == BPF_ALU || class == BPF_JMP32)
2356                 return false;
2357
2358         if (class == BPF_LDX) {
2359                 if (t != SRC_OP)
2360                         return BPF_SIZE(code) == BPF_DW;
2361                 /* LDX source must be ptr. */
2362                 return true;
2363         }
2364
2365         if (class == BPF_STX) {
2366                 /* BPF_STX (including atomic variants) has multiple source
2367                  * operands, one of which is a ptr. Check whether the caller is
2368                  * asking about it.
2369                  */
2370                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2371                         return true;
2372                 return BPF_SIZE(code) == BPF_DW;
2373         }
2374
2375         if (class == BPF_LD) {
2376                 u8 mode = BPF_MODE(code);
2377
2378                 /* LD_IMM64 */
2379                 if (mode == BPF_IMM)
2380                         return true;
2381
2382                 /* Both LD_IND and LD_ABS return 32-bit data. */
2383                 if (t != SRC_OP)
2384                         return  false;
2385
2386                 /* Implicit ctx ptr. */
2387                 if (regno == BPF_REG_6)
2388                         return true;
2389
2390                 /* Explicit source could be any width. */
2391                 return true;
2392         }
2393
2394         if (class == BPF_ST)
2395                 /* The only source register for BPF_ST is a ptr. */
2396                 return true;
2397
2398         /* Conservatively return true at default. */
2399         return true;
2400 }
2401
2402 /* Return the regno defined by the insn, or -1. */
2403 static int insn_def_regno(const struct bpf_insn *insn)
2404 {
2405         switch (BPF_CLASS(insn->code)) {
2406         case BPF_JMP:
2407         case BPF_JMP32:
2408         case BPF_ST:
2409                 return -1;
2410         case BPF_STX:
2411                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2412                     (insn->imm & BPF_FETCH)) {
2413                         if (insn->imm == BPF_CMPXCHG)
2414                                 return BPF_REG_0;
2415                         else
2416                                 return insn->src_reg;
2417                 } else {
2418                         return -1;
2419                 }
2420         default:
2421                 return insn->dst_reg;
2422         }
2423 }
2424
2425 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2426 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2427 {
2428         int dst_reg = insn_def_regno(insn);
2429
2430         if (dst_reg == -1)
2431                 return false;
2432
2433         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2434 }
2435
2436 static void mark_insn_zext(struct bpf_verifier_env *env,
2437                            struct bpf_reg_state *reg)
2438 {
2439         s32 def_idx = reg->subreg_def;
2440
2441         if (def_idx == DEF_NOT_SUBREG)
2442                 return;
2443
2444         env->insn_aux_data[def_idx - 1].zext_dst = true;
2445         /* The dst will be zero extended, so won't be sub-register anymore. */
2446         reg->subreg_def = DEF_NOT_SUBREG;
2447 }
2448
2449 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2450                          enum reg_arg_type t)
2451 {
2452         struct bpf_verifier_state *vstate = env->cur_state;
2453         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2454         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2455         struct bpf_reg_state *reg, *regs = state->regs;
2456         bool rw64;
2457
2458         if (regno >= MAX_BPF_REG) {
2459                 verbose(env, "R%d is invalid\n", regno);
2460                 return -EINVAL;
2461         }
2462
2463         mark_reg_scratched(env, regno);
2464
2465         reg = &regs[regno];
2466         rw64 = is_reg64(env, insn, regno, reg, t);
2467         if (t == SRC_OP) {
2468                 /* check whether register used as source operand can be read */
2469                 if (reg->type == NOT_INIT) {
2470                         verbose(env, "R%d !read_ok\n", regno);
2471                         return -EACCES;
2472                 }
2473                 /* We don't need to worry about FP liveness because it's read-only */
2474                 if (regno == BPF_REG_FP)
2475                         return 0;
2476
2477                 if (rw64)
2478                         mark_insn_zext(env, reg);
2479
2480                 return mark_reg_read(env, reg, reg->parent,
2481                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2482         } else {
2483                 /* check whether register used as dest operand can be written to */
2484                 if (regno == BPF_REG_FP) {
2485                         verbose(env, "frame pointer is read only\n");
2486                         return -EACCES;
2487                 }
2488                 reg->live |= REG_LIVE_WRITTEN;
2489                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2490                 if (t == DST_OP)
2491                         mark_reg_unknown(env, regs, regno);
2492         }
2493         return 0;
2494 }
2495
2496 /* for any branch, call, exit record the history of jmps in the given state */
2497 static int push_jmp_history(struct bpf_verifier_env *env,
2498                             struct bpf_verifier_state *cur)
2499 {
2500         u32 cnt = cur->jmp_history_cnt;
2501         struct bpf_idx_pair *p;
2502
2503         cnt++;
2504         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2505         if (!p)
2506                 return -ENOMEM;
2507         p[cnt - 1].idx = env->insn_idx;
2508         p[cnt - 1].prev_idx = env->prev_insn_idx;
2509         cur->jmp_history = p;
2510         cur->jmp_history_cnt = cnt;
2511         return 0;
2512 }
2513
2514 /* Backtrack one insn at a time. If idx is not at the top of recorded
2515  * history then previous instruction came from straight line execution.
2516  */
2517 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2518                              u32 *history)
2519 {
2520         u32 cnt = *history;
2521
2522         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2523                 i = st->jmp_history[cnt - 1].prev_idx;
2524                 (*history)--;
2525         } else {
2526                 i--;
2527         }
2528         return i;
2529 }
2530
2531 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2532 {
2533         const struct btf_type *func;
2534         struct btf *desc_btf;
2535
2536         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2537                 return NULL;
2538
2539         desc_btf = find_kfunc_desc_btf(data, insn->off);
2540         if (IS_ERR(desc_btf))
2541                 return "<error>";
2542
2543         func = btf_type_by_id(desc_btf, insn->imm);
2544         return btf_name_by_offset(desc_btf, func->name_off);
2545 }
2546
2547 /* For given verifier state backtrack_insn() is called from the last insn to
2548  * the first insn. Its purpose is to compute a bitmask of registers and
2549  * stack slots that needs precision in the parent verifier state.
2550  */
2551 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2552                           u32 *reg_mask, u64 *stack_mask)
2553 {
2554         const struct bpf_insn_cbs cbs = {
2555                 .cb_call        = disasm_kfunc_name,
2556                 .cb_print       = verbose,
2557                 .private_data   = env,
2558         };
2559         struct bpf_insn *insn = env->prog->insnsi + idx;
2560         u8 class = BPF_CLASS(insn->code);
2561         u8 opcode = BPF_OP(insn->code);
2562         u8 mode = BPF_MODE(insn->code);
2563         u32 dreg = 1u << insn->dst_reg;
2564         u32 sreg = 1u << insn->src_reg;
2565         u32 spi;
2566
2567         if (insn->code == 0)
2568                 return 0;
2569         if (env->log.level & BPF_LOG_LEVEL2) {
2570                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2571                 verbose(env, "%d: ", idx);
2572                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2573         }
2574
2575         if (class == BPF_ALU || class == BPF_ALU64) {
2576                 if (!(*reg_mask & dreg))
2577                         return 0;
2578                 if (opcode == BPF_MOV) {
2579                         if (BPF_SRC(insn->code) == BPF_X) {
2580                                 /* dreg = sreg
2581                                  * dreg needs precision after this insn
2582                                  * sreg needs precision before this insn
2583                                  */
2584                                 *reg_mask &= ~dreg;
2585                                 *reg_mask |= sreg;
2586                         } else {
2587                                 /* dreg = K
2588                                  * dreg needs precision after this insn.
2589                                  * Corresponding register is already marked
2590                                  * as precise=true in this verifier state.
2591                                  * No further markings in parent are necessary
2592                                  */
2593                                 *reg_mask &= ~dreg;
2594                         }
2595                 } else {
2596                         if (BPF_SRC(insn->code) == BPF_X) {
2597                                 /* dreg += sreg
2598                                  * both dreg and sreg need precision
2599                                  * before this insn
2600                                  */
2601                                 *reg_mask |= sreg;
2602                         } /* else dreg += K
2603                            * dreg still needs precision before this insn
2604                            */
2605                 }
2606         } else if (class == BPF_LDX) {
2607                 if (!(*reg_mask & dreg))
2608                         return 0;
2609                 *reg_mask &= ~dreg;
2610
2611                 /* scalars can only be spilled into stack w/o losing precision.
2612                  * Load from any other memory can be zero extended.
2613                  * The desire to keep that precision is already indicated
2614                  * by 'precise' mark in corresponding register of this state.
2615                  * No further tracking necessary.
2616                  */
2617                 if (insn->src_reg != BPF_REG_FP)
2618                         return 0;
2619
2620                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2621                  * that [fp - off] slot contains scalar that needs to be
2622                  * tracked with precision
2623                  */
2624                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2625                 if (spi >= 64) {
2626                         verbose(env, "BUG spi %d\n", spi);
2627                         WARN_ONCE(1, "verifier backtracking bug");
2628                         return -EFAULT;
2629                 }
2630                 *stack_mask |= 1ull << spi;
2631         } else if (class == BPF_STX || class == BPF_ST) {
2632                 if (*reg_mask & dreg)
2633                         /* stx & st shouldn't be using _scalar_ dst_reg
2634                          * to access memory. It means backtracking
2635                          * encountered a case of pointer subtraction.
2636                          */
2637                         return -ENOTSUPP;
2638                 /* scalars can only be spilled into stack */
2639                 if (insn->dst_reg != BPF_REG_FP)
2640                         return 0;
2641                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2642                 if (spi >= 64) {
2643                         verbose(env, "BUG spi %d\n", spi);
2644                         WARN_ONCE(1, "verifier backtracking bug");
2645                         return -EFAULT;
2646                 }
2647                 if (!(*stack_mask & (1ull << spi)))
2648                         return 0;
2649                 *stack_mask &= ~(1ull << spi);
2650                 if (class == BPF_STX)
2651                         *reg_mask |= sreg;
2652         } else if (class == BPF_JMP || class == BPF_JMP32) {
2653                 if (opcode == BPF_CALL) {
2654                         if (insn->src_reg == BPF_PSEUDO_CALL)
2655                                 return -ENOTSUPP;
2656                         /* regular helper call sets R0 */
2657                         *reg_mask &= ~1;
2658                         if (*reg_mask & 0x3f) {
2659                                 /* if backtracing was looking for registers R1-R5
2660                                  * they should have been found already.
2661                                  */
2662                                 verbose(env, "BUG regs %x\n", *reg_mask);
2663                                 WARN_ONCE(1, "verifier backtracking bug");
2664                                 return -EFAULT;
2665                         }
2666                 } else if (opcode == BPF_EXIT) {
2667                         return -ENOTSUPP;
2668                 }
2669         } else if (class == BPF_LD) {
2670                 if (!(*reg_mask & dreg))
2671                         return 0;
2672                 *reg_mask &= ~dreg;
2673                 /* It's ld_imm64 or ld_abs or ld_ind.
2674                  * For ld_imm64 no further tracking of precision
2675                  * into parent is necessary
2676                  */
2677                 if (mode == BPF_IND || mode == BPF_ABS)
2678                         /* to be analyzed */
2679                         return -ENOTSUPP;
2680         }
2681         return 0;
2682 }
2683
2684 /* the scalar precision tracking algorithm:
2685  * . at the start all registers have precise=false.
2686  * . scalar ranges are tracked as normal through alu and jmp insns.
2687  * . once precise value of the scalar register is used in:
2688  *   .  ptr + scalar alu
2689  *   . if (scalar cond K|scalar)
2690  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2691  *   backtrack through the verifier states and mark all registers and
2692  *   stack slots with spilled constants that these scalar regisers
2693  *   should be precise.
2694  * . during state pruning two registers (or spilled stack slots)
2695  *   are equivalent if both are not precise.
2696  *
2697  * Note the verifier cannot simply walk register parentage chain,
2698  * since many different registers and stack slots could have been
2699  * used to compute single precise scalar.
2700  *
2701  * The approach of starting with precise=true for all registers and then
2702  * backtrack to mark a register as not precise when the verifier detects
2703  * that program doesn't care about specific value (e.g., when helper
2704  * takes register as ARG_ANYTHING parameter) is not safe.
2705  *
2706  * It's ok to walk single parentage chain of the verifier states.
2707  * It's possible that this backtracking will go all the way till 1st insn.
2708  * All other branches will be explored for needing precision later.
2709  *
2710  * The backtracking needs to deal with cases like:
2711  *   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)
2712  * r9 -= r8
2713  * r5 = r9
2714  * if r5 > 0x79f goto pc+7
2715  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2716  * r5 += 1
2717  * ...
2718  * call bpf_perf_event_output#25
2719  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2720  *
2721  * and this case:
2722  * r6 = 1
2723  * call foo // uses callee's r6 inside to compute r0
2724  * r0 += r6
2725  * if r0 == 0 goto
2726  *
2727  * to track above reg_mask/stack_mask needs to be independent for each frame.
2728  *
2729  * Also if parent's curframe > frame where backtracking started,
2730  * the verifier need to mark registers in both frames, otherwise callees
2731  * may incorrectly prune callers. This is similar to
2732  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2733  *
2734  * For now backtracking falls back into conservative marking.
2735  */
2736 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2737                                      struct bpf_verifier_state *st)
2738 {
2739         struct bpf_func_state *func;
2740         struct bpf_reg_state *reg;
2741         int i, j;
2742
2743         /* big hammer: mark all scalars precise in this path.
2744          * pop_stack may still get !precise scalars.
2745          */
2746         for (; st; st = st->parent)
2747                 for (i = 0; i <= st->curframe; i++) {
2748                         func = st->frame[i];
2749                         for (j = 0; j < BPF_REG_FP; j++) {
2750                                 reg = &func->regs[j];
2751                                 if (reg->type != SCALAR_VALUE)
2752                                         continue;
2753                                 reg->precise = true;
2754                         }
2755                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2756                                 if (!is_spilled_reg(&func->stack[j]))
2757                                         continue;
2758                                 reg = &func->stack[j].spilled_ptr;
2759                                 if (reg->type != SCALAR_VALUE)
2760                                         continue;
2761                                 reg->precise = true;
2762                         }
2763                 }
2764 }
2765
2766 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2767                                   int spi)
2768 {
2769         struct bpf_verifier_state *st = env->cur_state;
2770         int first_idx = st->first_insn_idx;
2771         int last_idx = env->insn_idx;
2772         struct bpf_func_state *func;
2773         struct bpf_reg_state *reg;
2774         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2775         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2776         bool skip_first = true;
2777         bool new_marks = false;
2778         int i, err;
2779
2780         if (!env->bpf_capable)
2781                 return 0;
2782
2783         func = st->frame[st->curframe];
2784         if (regno >= 0) {
2785                 reg = &func->regs[regno];
2786                 if (reg->type != SCALAR_VALUE) {
2787                         WARN_ONCE(1, "backtracing misuse");
2788                         return -EFAULT;
2789                 }
2790                 if (!reg->precise)
2791                         new_marks = true;
2792                 else
2793                         reg_mask = 0;
2794                 reg->precise = true;
2795         }
2796
2797         while (spi >= 0) {
2798                 if (!is_spilled_reg(&func->stack[spi])) {
2799                         stack_mask = 0;
2800                         break;
2801                 }
2802                 reg = &func->stack[spi].spilled_ptr;
2803                 if (reg->type != SCALAR_VALUE) {
2804                         stack_mask = 0;
2805                         break;
2806                 }
2807                 if (!reg->precise)
2808                         new_marks = true;
2809                 else
2810                         stack_mask = 0;
2811                 reg->precise = true;
2812                 break;
2813         }
2814
2815         if (!new_marks)
2816                 return 0;
2817         if (!reg_mask && !stack_mask)
2818                 return 0;
2819         for (;;) {
2820                 DECLARE_BITMAP(mask, 64);
2821                 u32 history = st->jmp_history_cnt;
2822
2823                 if (env->log.level & BPF_LOG_LEVEL2)
2824                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2825                 for (i = last_idx;;) {
2826                         if (skip_first) {
2827                                 err = 0;
2828                                 skip_first = false;
2829                         } else {
2830                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2831                         }
2832                         if (err == -ENOTSUPP) {
2833                                 mark_all_scalars_precise(env, st);
2834                                 return 0;
2835                         } else if (err) {
2836                                 return err;
2837                         }
2838                         if (!reg_mask && !stack_mask)
2839                                 /* Found assignment(s) into tracked register in this state.
2840                                  * Since this state is already marked, just return.
2841                                  * Nothing to be tracked further in the parent state.
2842                                  */
2843                                 return 0;
2844                         if (i == first_idx)
2845                                 break;
2846                         i = get_prev_insn_idx(st, i, &history);
2847                         if (i >= env->prog->len) {
2848                                 /* This can happen if backtracking reached insn 0
2849                                  * and there are still reg_mask or stack_mask
2850                                  * to backtrack.
2851                                  * It means the backtracking missed the spot where
2852                                  * particular register was initialized with a constant.
2853                                  */
2854                                 verbose(env, "BUG backtracking idx %d\n", i);
2855                                 WARN_ONCE(1, "verifier backtracking bug");
2856                                 return -EFAULT;
2857                         }
2858                 }
2859                 st = st->parent;
2860                 if (!st)
2861                         break;
2862
2863                 new_marks = false;
2864                 func = st->frame[st->curframe];
2865                 bitmap_from_u64(mask, reg_mask);
2866                 for_each_set_bit(i, mask, 32) {
2867                         reg = &func->regs[i];
2868                         if (reg->type != SCALAR_VALUE) {
2869                                 reg_mask &= ~(1u << i);
2870                                 continue;
2871                         }
2872                         if (!reg->precise)
2873                                 new_marks = true;
2874                         reg->precise = true;
2875                 }
2876
2877                 bitmap_from_u64(mask, stack_mask);
2878                 for_each_set_bit(i, mask, 64) {
2879                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2880                                 /* the sequence of instructions:
2881                                  * 2: (bf) r3 = r10
2882                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2883                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2884                                  * doesn't contain jmps. It's backtracked
2885                                  * as a single block.
2886                                  * During backtracking insn 3 is not recognized as
2887                                  * stack access, so at the end of backtracking
2888                                  * stack slot fp-8 is still marked in stack_mask.
2889                                  * However the parent state may not have accessed
2890                                  * fp-8 and it's "unallocated" stack space.
2891                                  * In such case fallback to conservative.
2892                                  */
2893                                 mark_all_scalars_precise(env, st);
2894                                 return 0;
2895                         }
2896
2897                         if (!is_spilled_reg(&func->stack[i])) {
2898                                 stack_mask &= ~(1ull << i);
2899                                 continue;
2900                         }
2901                         reg = &func->stack[i].spilled_ptr;
2902                         if (reg->type != SCALAR_VALUE) {
2903                                 stack_mask &= ~(1ull << i);
2904                                 continue;
2905                         }
2906                         if (!reg->precise)
2907                                 new_marks = true;
2908                         reg->precise = true;
2909                 }
2910                 if (env->log.level & BPF_LOG_LEVEL2) {
2911                         verbose(env, "parent %s regs=%x stack=%llx marks:",
2912                                 new_marks ? "didn't have" : "already had",
2913                                 reg_mask, stack_mask);
2914                         print_verifier_state(env, func, true);
2915                 }
2916
2917                 if (!reg_mask && !stack_mask)
2918                         break;
2919                 if (!new_marks)
2920                         break;
2921
2922                 last_idx = st->last_insn_idx;
2923                 first_idx = st->first_insn_idx;
2924         }
2925         return 0;
2926 }
2927
2928 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2929 {
2930         return __mark_chain_precision(env, regno, -1);
2931 }
2932
2933 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2934 {
2935         return __mark_chain_precision(env, -1, spi);
2936 }
2937
2938 static bool is_spillable_regtype(enum bpf_reg_type type)
2939 {
2940         switch (base_type(type)) {
2941         case PTR_TO_MAP_VALUE:
2942         case PTR_TO_STACK:
2943         case PTR_TO_CTX:
2944         case PTR_TO_PACKET:
2945         case PTR_TO_PACKET_META:
2946         case PTR_TO_PACKET_END:
2947         case PTR_TO_FLOW_KEYS:
2948         case CONST_PTR_TO_MAP:
2949         case PTR_TO_SOCKET:
2950         case PTR_TO_SOCK_COMMON:
2951         case PTR_TO_TCP_SOCK:
2952         case PTR_TO_XDP_SOCK:
2953         case PTR_TO_BTF_ID:
2954         case PTR_TO_BUF:
2955         case PTR_TO_MEM:
2956         case PTR_TO_FUNC:
2957         case PTR_TO_MAP_KEY:
2958                 return true;
2959         default:
2960                 return false;
2961         }
2962 }
2963
2964 /* Does this register contain a constant zero? */
2965 static bool register_is_null(struct bpf_reg_state *reg)
2966 {
2967         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2968 }
2969
2970 static bool register_is_const(struct bpf_reg_state *reg)
2971 {
2972         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2973 }
2974
2975 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2976 {
2977         return tnum_is_unknown(reg->var_off) &&
2978                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2979                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2980                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2981                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2982 }
2983
2984 static bool register_is_bounded(struct bpf_reg_state *reg)
2985 {
2986         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2987 }
2988
2989 static bool __is_pointer_value(bool allow_ptr_leaks,
2990                                const struct bpf_reg_state *reg)
2991 {
2992         if (allow_ptr_leaks)
2993                 return false;
2994
2995         return reg->type != SCALAR_VALUE;
2996 }
2997
2998 static void save_register_state(struct bpf_func_state *state,
2999                                 int spi, struct bpf_reg_state *reg,
3000                                 int size)
3001 {
3002         int i;
3003
3004         state->stack[spi].spilled_ptr = *reg;
3005         if (size == BPF_REG_SIZE)
3006                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3007
3008         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3009                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3010
3011         /* size < 8 bytes spill */
3012         for (; i; i--)
3013                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3014 }
3015
3016 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3017  * stack boundary and alignment are checked in check_mem_access()
3018  */
3019 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3020                                        /* stack frame we're writing to */
3021                                        struct bpf_func_state *state,
3022                                        int off, int size, int value_regno,
3023                                        int insn_idx)
3024 {
3025         struct bpf_func_state *cur; /* state of the current function */
3026         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3027         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3028         struct bpf_reg_state *reg = NULL;
3029
3030         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3031         if (err)
3032                 return err;
3033         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3034          * so it's aligned access and [off, off + size) are within stack limits
3035          */
3036         if (!env->allow_ptr_leaks &&
3037             state->stack[spi].slot_type[0] == STACK_SPILL &&
3038             size != BPF_REG_SIZE) {
3039                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3040                 return -EACCES;
3041         }
3042
3043         cur = env->cur_state->frame[env->cur_state->curframe];
3044         if (value_regno >= 0)
3045                 reg = &cur->regs[value_regno];
3046         if (!env->bypass_spec_v4) {
3047                 bool sanitize = reg && is_spillable_regtype(reg->type);
3048
3049                 for (i = 0; i < size; i++) {
3050                         if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3051                                 sanitize = true;
3052                                 break;
3053                         }
3054                 }
3055
3056                 if (sanitize)
3057                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3058         }
3059
3060         mark_stack_slot_scratched(env, spi);
3061         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3062             !register_is_null(reg) && env->bpf_capable) {
3063                 if (dst_reg != BPF_REG_FP) {
3064                         /* The backtracking logic can only recognize explicit
3065                          * stack slot address like [fp - 8]. Other spill of
3066                          * scalar via different register has to be conservative.
3067                          * Backtrack from here and mark all registers as precise
3068                          * that contributed into 'reg' being a constant.
3069                          */
3070                         err = mark_chain_precision(env, value_regno);
3071                         if (err)
3072                                 return err;
3073                 }
3074                 save_register_state(state, spi, reg, size);
3075         } else if (reg && is_spillable_regtype(reg->type)) {
3076                 /* register containing pointer is being spilled into stack */
3077                 if (size != BPF_REG_SIZE) {
3078                         verbose_linfo(env, insn_idx, "; ");
3079                         verbose(env, "invalid size of register spill\n");
3080                         return -EACCES;
3081                 }
3082                 if (state != cur && reg->type == PTR_TO_STACK) {
3083                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3084                         return -EINVAL;
3085                 }
3086                 save_register_state(state, spi, reg, size);
3087         } else {
3088                 u8 type = STACK_MISC;
3089
3090                 /* regular write of data into stack destroys any spilled ptr */
3091                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3092                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3093                 if (is_spilled_reg(&state->stack[spi]))
3094                         for (i = 0; i < BPF_REG_SIZE; i++)
3095                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3096
3097                 /* only mark the slot as written if all 8 bytes were written
3098                  * otherwise read propagation may incorrectly stop too soon
3099                  * when stack slots are partially written.
3100                  * This heuristic means that read propagation will be
3101                  * conservative, since it will add reg_live_read marks
3102                  * to stack slots all the way to first state when programs
3103                  * writes+reads less than 8 bytes
3104                  */
3105                 if (size == BPF_REG_SIZE)
3106                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3107
3108                 /* when we zero initialize stack slots mark them as such */
3109                 if (reg && register_is_null(reg)) {
3110                         /* backtracking doesn't work for STACK_ZERO yet. */
3111                         err = mark_chain_precision(env, value_regno);
3112                         if (err)
3113                                 return err;
3114                         type = STACK_ZERO;
3115                 }
3116
3117                 /* Mark slots affected by this stack write. */
3118                 for (i = 0; i < size; i++)
3119                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3120                                 type;
3121         }
3122         return 0;
3123 }
3124
3125 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3126  * known to contain a variable offset.
3127  * This function checks whether the write is permitted and conservatively
3128  * tracks the effects of the write, considering that each stack slot in the
3129  * dynamic range is potentially written to.
3130  *
3131  * 'off' includes 'regno->off'.
3132  * 'value_regno' can be -1, meaning that an unknown value is being written to
3133  * the stack.
3134  *
3135  * Spilled pointers in range are not marked as written because we don't know
3136  * what's going to be actually written. This means that read propagation for
3137  * future reads cannot be terminated by this write.
3138  *
3139  * For privileged programs, uninitialized stack slots are considered
3140  * initialized by this write (even though we don't know exactly what offsets
3141  * are going to be written to). The idea is that we don't want the verifier to
3142  * reject future reads that access slots written to through variable offsets.
3143  */
3144 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3145                                      /* func where register points to */
3146                                      struct bpf_func_state *state,
3147                                      int ptr_regno, int off, int size,
3148                                      int value_regno, int insn_idx)
3149 {
3150         struct bpf_func_state *cur; /* state of the current function */
3151         int min_off, max_off;
3152         int i, err;
3153         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3154         bool writing_zero = false;
3155         /* set if the fact that we're writing a zero is used to let any
3156          * stack slots remain STACK_ZERO
3157          */
3158         bool zero_used = false;
3159
3160         cur = env->cur_state->frame[env->cur_state->curframe];
3161         ptr_reg = &cur->regs[ptr_regno];
3162         min_off = ptr_reg->smin_value + off;
3163         max_off = ptr_reg->smax_value + off + size;
3164         if (value_regno >= 0)
3165                 value_reg = &cur->regs[value_regno];
3166         if (value_reg && register_is_null(value_reg))
3167                 writing_zero = true;
3168
3169         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3170         if (err)
3171                 return err;
3172
3173
3174         /* Variable offset writes destroy any spilled pointers in range. */
3175         for (i = min_off; i < max_off; i++) {
3176                 u8 new_type, *stype;
3177                 int slot, spi;
3178
3179                 slot = -i - 1;
3180                 spi = slot / BPF_REG_SIZE;
3181                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3182                 mark_stack_slot_scratched(env, spi);
3183
3184                 if (!env->allow_ptr_leaks
3185                                 && *stype != NOT_INIT
3186                                 && *stype != SCALAR_VALUE) {
3187                         /* Reject the write if there's are spilled pointers in
3188                          * range. If we didn't reject here, the ptr status
3189                          * would be erased below (even though not all slots are
3190                          * actually overwritten), possibly opening the door to
3191                          * leaks.
3192                          */
3193                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3194                                 insn_idx, i);
3195                         return -EINVAL;
3196                 }
3197
3198                 /* Erase all spilled pointers. */
3199                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3200
3201                 /* Update the slot type. */
3202                 new_type = STACK_MISC;
3203                 if (writing_zero && *stype == STACK_ZERO) {
3204                         new_type = STACK_ZERO;
3205                         zero_used = true;
3206                 }
3207                 /* If the slot is STACK_INVALID, we check whether it's OK to
3208                  * pretend that it will be initialized by this write. The slot
3209                  * might not actually be written to, and so if we mark it as
3210                  * initialized future reads might leak uninitialized memory.
3211                  * For privileged programs, we will accept such reads to slots
3212                  * that may or may not be written because, if we're reject
3213                  * them, the error would be too confusing.
3214                  */
3215                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3216                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3217                                         insn_idx, i);
3218                         return -EINVAL;
3219                 }
3220                 *stype = new_type;
3221         }
3222         if (zero_used) {
3223                 /* backtracking doesn't work for STACK_ZERO yet. */
3224                 err = mark_chain_precision(env, value_regno);
3225                 if (err)
3226                         return err;
3227         }
3228         return 0;
3229 }
3230
3231 /* When register 'dst_regno' is assigned some values from stack[min_off,
3232  * max_off), we set the register's type according to the types of the
3233  * respective stack slots. If all the stack values are known to be zeros, then
3234  * so is the destination reg. Otherwise, the register is considered to be
3235  * SCALAR. This function does not deal with register filling; the caller must
3236  * ensure that all spilled registers in the stack range have been marked as
3237  * read.
3238  */
3239 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3240                                 /* func where src register points to */
3241                                 struct bpf_func_state *ptr_state,
3242                                 int min_off, int max_off, int dst_regno)
3243 {
3244         struct bpf_verifier_state *vstate = env->cur_state;
3245         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3246         int i, slot, spi;
3247         u8 *stype;
3248         int zeros = 0;
3249
3250         for (i = min_off; i < max_off; i++) {
3251                 slot = -i - 1;
3252                 spi = slot / BPF_REG_SIZE;
3253                 stype = ptr_state->stack[spi].slot_type;
3254                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3255                         break;
3256                 zeros++;
3257         }
3258         if (zeros == max_off - min_off) {
3259                 /* any access_size read into register is zero extended,
3260                  * so the whole register == const_zero
3261                  */
3262                 __mark_reg_const_zero(&state->regs[dst_regno]);
3263                 /* backtracking doesn't support STACK_ZERO yet,
3264                  * so mark it precise here, so that later
3265                  * backtracking can stop here.
3266                  * Backtracking may not need this if this register
3267                  * doesn't participate in pointer adjustment.
3268                  * Forward propagation of precise flag is not
3269                  * necessary either. This mark is only to stop
3270                  * backtracking. Any register that contributed
3271                  * to const 0 was marked precise before spill.
3272                  */
3273                 state->regs[dst_regno].precise = true;
3274         } else {
3275                 /* have read misc data from the stack */
3276                 mark_reg_unknown(env, state->regs, dst_regno);
3277         }
3278         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3279 }
3280
3281 /* Read the stack at 'off' and put the results into the register indicated by
3282  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3283  * spilled reg.
3284  *
3285  * 'dst_regno' can be -1, meaning that the read value is not going to a
3286  * register.
3287  *
3288  * The access is assumed to be within the current stack bounds.
3289  */
3290 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3291                                       /* func where src register points to */
3292                                       struct bpf_func_state *reg_state,
3293                                       int off, int size, int dst_regno)
3294 {
3295         struct bpf_verifier_state *vstate = env->cur_state;
3296         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3297         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3298         struct bpf_reg_state *reg;
3299         u8 *stype, type;
3300
3301         stype = reg_state->stack[spi].slot_type;
3302         reg = &reg_state->stack[spi].spilled_ptr;
3303
3304         if (is_spilled_reg(&reg_state->stack[spi])) {
3305                 u8 spill_size = 1;
3306
3307                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3308                         spill_size++;
3309
3310                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3311                         if (reg->type != SCALAR_VALUE) {
3312                                 verbose_linfo(env, env->insn_idx, "; ");
3313                                 verbose(env, "invalid size of register fill\n");
3314                                 return -EACCES;
3315                         }
3316
3317                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3318                         if (dst_regno < 0)
3319                                 return 0;
3320
3321                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
3322                                 /* The earlier check_reg_arg() has decided the
3323                                  * subreg_def for this insn.  Save it first.
3324                                  */
3325                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
3326
3327                                 state->regs[dst_regno] = *reg;
3328                                 state->regs[dst_regno].subreg_def = subreg_def;
3329                         } else {
3330                                 for (i = 0; i < size; i++) {
3331                                         type = stype[(slot - i) % BPF_REG_SIZE];
3332                                         if (type == STACK_SPILL)
3333                                                 continue;
3334                                         if (type == STACK_MISC)
3335                                                 continue;
3336                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3337                                                 off, i, size);
3338                                         return -EACCES;
3339                                 }
3340                                 mark_reg_unknown(env, state->regs, dst_regno);
3341                         }
3342                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3343                         return 0;
3344                 }
3345
3346                 if (dst_regno >= 0) {
3347                         /* restore register state from stack */
3348                         state->regs[dst_regno] = *reg;
3349                         /* mark reg as written since spilled pointer state likely
3350                          * has its liveness marks cleared by is_state_visited()
3351                          * which resets stack/reg liveness for state transitions
3352                          */
3353                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3354                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3355                         /* If dst_regno==-1, the caller is asking us whether
3356                          * it is acceptable to use this value as a SCALAR_VALUE
3357                          * (e.g. for XADD).
3358                          * We must not allow unprivileged callers to do that
3359                          * with spilled pointers.
3360                          */
3361                         verbose(env, "leaking pointer from stack off %d\n",
3362                                 off);
3363                         return -EACCES;
3364                 }
3365                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3366         } else {
3367                 for (i = 0; i < size; i++) {
3368                         type = stype[(slot - i) % BPF_REG_SIZE];
3369                         if (type == STACK_MISC)
3370                                 continue;
3371                         if (type == STACK_ZERO)
3372                                 continue;
3373                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3374                                 off, i, size);
3375                         return -EACCES;
3376                 }
3377                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3378                 if (dst_regno >= 0)
3379                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3380         }
3381         return 0;
3382 }
3383
3384 enum bpf_access_src {
3385         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3386         ACCESS_HELPER = 2,  /* the access is performed by a helper */
3387 };
3388
3389 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3390                                          int regno, int off, int access_size,
3391                                          bool zero_size_allowed,
3392                                          enum bpf_access_src type,
3393                                          struct bpf_call_arg_meta *meta);
3394
3395 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3396 {
3397         return cur_regs(env) + regno;
3398 }
3399
3400 /* Read the stack at 'ptr_regno + off' and put the result into the register
3401  * 'dst_regno'.
3402  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3403  * but not its variable offset.
3404  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3405  *
3406  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3407  * filling registers (i.e. reads of spilled register cannot be detected when
3408  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3409  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3410  * offset; for a fixed offset check_stack_read_fixed_off should be used
3411  * instead.
3412  */
3413 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3414                                     int ptr_regno, int off, int size, int dst_regno)
3415 {
3416         /* The state of the source register. */
3417         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3418         struct bpf_func_state *ptr_state = func(env, reg);
3419         int err;
3420         int min_off, max_off;
3421
3422         /* Note that we pass a NULL meta, so raw access will not be permitted.
3423          */
3424         err = check_stack_range_initialized(env, ptr_regno, off, size,
3425                                             false, ACCESS_DIRECT, NULL);
3426         if (err)
3427                 return err;
3428
3429         min_off = reg->smin_value + off;
3430         max_off = reg->smax_value + off;
3431         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3432         return 0;
3433 }
3434
3435 /* check_stack_read dispatches to check_stack_read_fixed_off or
3436  * check_stack_read_var_off.
3437  *
3438  * The caller must ensure that the offset falls within the allocated stack
3439  * bounds.
3440  *
3441  * 'dst_regno' is a register which will receive the value from the stack. It
3442  * can be -1, meaning that the read value is not going to a register.
3443  */
3444 static int check_stack_read(struct bpf_verifier_env *env,
3445                             int ptr_regno, int off, int size,
3446                             int dst_regno)
3447 {
3448         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3449         struct bpf_func_state *state = func(env, reg);
3450         int err;
3451         /* Some accesses are only permitted with a static offset. */
3452         bool var_off = !tnum_is_const(reg->var_off);
3453
3454         /* The offset is required to be static when reads don't go to a
3455          * register, in order to not leak pointers (see
3456          * check_stack_read_fixed_off).
3457          */
3458         if (dst_regno < 0 && var_off) {
3459                 char tn_buf[48];
3460
3461                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3462                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3463                         tn_buf, off, size);
3464                 return -EACCES;
3465         }
3466         /* Variable offset is prohibited for unprivileged mode for simplicity
3467          * since it requires corresponding support in Spectre masking for stack
3468          * ALU. See also retrieve_ptr_limit().
3469          */
3470         if (!env->bypass_spec_v1 && var_off) {
3471                 char tn_buf[48];
3472
3473                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3474                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3475                                 ptr_regno, tn_buf);
3476                 return -EACCES;
3477         }
3478
3479         if (!var_off) {
3480                 off += reg->var_off.value;
3481                 err = check_stack_read_fixed_off(env, state, off, size,
3482                                                  dst_regno);
3483         } else {
3484                 /* Variable offset stack reads need more conservative handling
3485                  * than fixed offset ones. Note that dst_regno >= 0 on this
3486                  * branch.
3487                  */
3488                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3489                                                dst_regno);
3490         }
3491         return err;
3492 }
3493
3494
3495 /* check_stack_write dispatches to check_stack_write_fixed_off or
3496  * check_stack_write_var_off.
3497  *
3498  * 'ptr_regno' is the register used as a pointer into the stack.
3499  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3500  * 'value_regno' is the register whose value we're writing to the stack. It can
3501  * be -1, meaning that we're not writing from a register.
3502  *
3503  * The caller must ensure that the offset falls within the maximum stack size.
3504  */
3505 static int check_stack_write(struct bpf_verifier_env *env,
3506                              int ptr_regno, int off, int size,
3507                              int value_regno, int insn_idx)
3508 {
3509         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3510         struct bpf_func_state *state = func(env, reg);
3511         int err;
3512
3513         if (tnum_is_const(reg->var_off)) {
3514                 off += reg->var_off.value;
3515                 err = check_stack_write_fixed_off(env, state, off, size,
3516                                                   value_regno, insn_idx);
3517         } else {
3518                 /* Variable offset stack reads need more conservative handling
3519                  * than fixed offset ones.
3520                  */
3521                 err = check_stack_write_var_off(env, state,
3522                                                 ptr_regno, off, size,
3523                                                 value_regno, insn_idx);
3524         }
3525         return err;
3526 }
3527
3528 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3529                                  int off, int size, enum bpf_access_type type)
3530 {
3531         struct bpf_reg_state *regs = cur_regs(env);
3532         struct bpf_map *map = regs[regno].map_ptr;
3533         u32 cap = bpf_map_flags_to_cap(map);
3534
3535         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3536                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3537                         map->value_size, off, size);
3538                 return -EACCES;
3539         }
3540
3541         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3542                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3543                         map->value_size, off, size);
3544                 return -EACCES;
3545         }
3546
3547         return 0;
3548 }
3549
3550 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3551 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3552                               int off, int size, u32 mem_size,
3553                               bool zero_size_allowed)
3554 {
3555         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3556         struct bpf_reg_state *reg;
3557
3558         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3559                 return 0;
3560
3561         reg = &cur_regs(env)[regno];
3562         switch (reg->type) {
3563         case PTR_TO_MAP_KEY:
3564                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3565                         mem_size, off, size);
3566                 break;
3567         case PTR_TO_MAP_VALUE:
3568                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3569                         mem_size, off, size);
3570                 break;
3571         case PTR_TO_PACKET:
3572         case PTR_TO_PACKET_META:
3573         case PTR_TO_PACKET_END:
3574                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3575                         off, size, regno, reg->id, off, mem_size);
3576                 break;
3577         case PTR_TO_MEM:
3578         default:
3579                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3580                         mem_size, off, size);
3581         }
3582
3583         return -EACCES;
3584 }
3585
3586 /* check read/write into a memory region with possible variable offset */
3587 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3588                                    int off, int size, u32 mem_size,
3589                                    bool zero_size_allowed)
3590 {
3591         struct bpf_verifier_state *vstate = env->cur_state;
3592         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3593         struct bpf_reg_state *reg = &state->regs[regno];
3594         int err;
3595
3596         /* We may have adjusted the register pointing to memory region, so we
3597          * need to try adding each of min_value and max_value to off
3598          * to make sure our theoretical access will be safe.
3599          *
3600          * The minimum value is only important with signed
3601          * comparisons where we can't assume the floor of a
3602          * value is 0.  If we are using signed variables for our
3603          * index'es we need to make sure that whatever we use
3604          * will have a set floor within our range.
3605          */
3606         if (reg->smin_value < 0 &&
3607             (reg->smin_value == S64_MIN ||
3608              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3609               reg->smin_value + off < 0)) {
3610                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3611                         regno);
3612                 return -EACCES;
3613         }
3614         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3615                                  mem_size, zero_size_allowed);
3616         if (err) {
3617                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3618                         regno);
3619                 return err;
3620         }
3621
3622         /* If we haven't set a max value then we need to bail since we can't be
3623          * sure we won't do bad things.
3624          * If reg->umax_value + off could overflow, treat that as unbounded too.
3625          */
3626         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3627                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3628                         regno);
3629                 return -EACCES;
3630         }
3631         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3632                                  mem_size, zero_size_allowed);
3633         if (err) {
3634                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3635                         regno);
3636                 return err;
3637         }
3638
3639         return 0;
3640 }
3641
3642 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3643                                const struct bpf_reg_state *reg, int regno,
3644                                bool fixed_off_ok)
3645 {
3646         /* Access to this pointer-typed register or passing it to a helper
3647          * is only allowed in its original, unmodified form.
3648          */
3649
3650         if (reg->off < 0) {
3651                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3652                         reg_type_str(env, reg->type), regno, reg->off);
3653                 return -EACCES;
3654         }
3655
3656         if (!fixed_off_ok && reg->off) {
3657                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3658                         reg_type_str(env, reg->type), regno, reg->off);
3659                 return -EACCES;
3660         }
3661
3662         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3663                 char tn_buf[48];
3664
3665                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3666                 verbose(env, "variable %s access var_off=%s disallowed\n",
3667                         reg_type_str(env, reg->type), tn_buf);
3668                 return -EACCES;
3669         }
3670
3671         return 0;
3672 }
3673
3674 int check_ptr_off_reg(struct bpf_verifier_env *env,
3675                       const struct bpf_reg_state *reg, int regno)
3676 {
3677         return __check_ptr_off_reg(env, reg, regno, false);
3678 }
3679
3680 static int map_kptr_match_type(struct bpf_verifier_env *env,
3681                                struct bpf_map_value_off_desc *off_desc,
3682                                struct bpf_reg_state *reg, u32 regno)
3683 {
3684         const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3685         int perm_flags = PTR_MAYBE_NULL;
3686         const char *reg_name = "";
3687
3688         /* Only unreferenced case accepts untrusted pointers */
3689         if (off_desc->type == BPF_KPTR_UNREF)
3690                 perm_flags |= PTR_UNTRUSTED;
3691
3692         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3693                 goto bad_type;
3694
3695         if (!btf_is_kernel(reg->btf)) {
3696                 verbose(env, "R%d must point to kernel BTF\n", regno);
3697                 return -EINVAL;
3698         }
3699         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3700         reg_name = kernel_type_name(reg->btf, reg->btf_id);
3701
3702         /* For ref_ptr case, release function check should ensure we get one
3703          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3704          * normal store of unreferenced kptr, we must ensure var_off is zero.
3705          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3706          * reg->off and reg->ref_obj_id are not needed here.
3707          */
3708         if (__check_ptr_off_reg(env, reg, regno, true))
3709                 return -EACCES;
3710
3711         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3712          * we also need to take into account the reg->off.
3713          *
3714          * We want to support cases like:
3715          *
3716          * struct foo {
3717          *         struct bar br;
3718          *         struct baz bz;
3719          * };
3720          *
3721          * struct foo *v;
3722          * v = func();        // PTR_TO_BTF_ID
3723          * val->foo = v;      // reg->off is zero, btf and btf_id match type
3724          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3725          *                    // first member type of struct after comparison fails
3726          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3727          *                    // to match type
3728          *
3729          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3730          * is zero. We must also ensure that btf_struct_ids_match does not walk
3731          * the struct to match type against first member of struct, i.e. reject
3732          * second case from above. Hence, when type is BPF_KPTR_REF, we set
3733          * strict mode to true for type match.
3734          */
3735         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3736                                   off_desc->kptr.btf, off_desc->kptr.btf_id,
3737                                   off_desc->type == BPF_KPTR_REF))
3738                 goto bad_type;
3739         return 0;
3740 bad_type:
3741         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3742                 reg_type_str(env, reg->type), reg_name);
3743         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3744         if (off_desc->type == BPF_KPTR_UNREF)
3745                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3746                         targ_name);
3747         else
3748                 verbose(env, "\n");
3749         return -EINVAL;
3750 }
3751
3752 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3753                                  int value_regno, int insn_idx,
3754                                  struct bpf_map_value_off_desc *off_desc)
3755 {
3756         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3757         int class = BPF_CLASS(insn->code);
3758         struct bpf_reg_state *val_reg;
3759
3760         /* Things we already checked for in check_map_access and caller:
3761          *  - Reject cases where variable offset may touch kptr
3762          *  - size of access (must be BPF_DW)
3763          *  - tnum_is_const(reg->var_off)
3764          *  - off_desc->offset == off + reg->var_off.value
3765          */
3766         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3767         if (BPF_MODE(insn->code) != BPF_MEM) {
3768                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3769                 return -EACCES;
3770         }
3771
3772         /* We only allow loading referenced kptr, since it will be marked as
3773          * untrusted, similar to unreferenced kptr.
3774          */
3775         if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3776                 verbose(env, "store to referenced kptr disallowed\n");
3777                 return -EACCES;
3778         }
3779
3780         if (class == BPF_LDX) {
3781                 val_reg = reg_state(env, value_regno);
3782                 /* We can simply mark the value_regno receiving the pointer
3783                  * value from map as PTR_TO_BTF_ID, with the correct type.
3784                  */
3785                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3786                                 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3787                 /* For mark_ptr_or_null_reg */
3788                 val_reg->id = ++env->id_gen;
3789         } else if (class == BPF_STX) {
3790                 val_reg = reg_state(env, value_regno);
3791                 if (!register_is_null(val_reg) &&
3792                     map_kptr_match_type(env, off_desc, val_reg, value_regno))
3793                         return -EACCES;
3794         } else if (class == BPF_ST) {
3795                 if (insn->imm) {
3796                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3797                                 off_desc->offset);
3798                         return -EACCES;
3799                 }
3800         } else {
3801                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3802                 return -EACCES;
3803         }
3804         return 0;
3805 }
3806
3807 /* check read/write into a map element with possible variable offset */
3808 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3809                             int off, int size, bool zero_size_allowed,
3810                             enum bpf_access_src src)
3811 {
3812         struct bpf_verifier_state *vstate = env->cur_state;
3813         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3814         struct bpf_reg_state *reg = &state->regs[regno];
3815         struct bpf_map *map = reg->map_ptr;
3816         int err;
3817
3818         err = check_mem_region_access(env, regno, off, size, map->value_size,
3819                                       zero_size_allowed);
3820         if (err)
3821                 return err;
3822
3823         if (map_value_has_spin_lock(map)) {
3824                 u32 lock = map->spin_lock_off;
3825
3826                 /* if any part of struct bpf_spin_lock can be touched by
3827                  * load/store reject this program.
3828                  * To check that [x1, x2) overlaps with [y1, y2)
3829                  * it is sufficient to check x1 < y2 && y1 < x2.
3830                  */
3831                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3832                      lock < reg->umax_value + off + size) {
3833                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3834                         return -EACCES;
3835                 }
3836         }
3837         if (map_value_has_timer(map)) {
3838                 u32 t = map->timer_off;
3839
3840                 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3841                      t < reg->umax_value + off + size) {
3842                         verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3843                         return -EACCES;
3844                 }
3845         }
3846         if (map_value_has_kptrs(map)) {
3847                 struct bpf_map_value_off *tab = map->kptr_off_tab;
3848                 int i;
3849
3850                 for (i = 0; i < tab->nr_off; i++) {
3851                         u32 p = tab->off[i].offset;
3852
3853                         if (reg->smin_value + off < p + sizeof(u64) &&
3854                             p < reg->umax_value + off + size) {
3855                                 if (src != ACCESS_DIRECT) {
3856                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
3857                                         return -EACCES;
3858                                 }
3859                                 if (!tnum_is_const(reg->var_off)) {
3860                                         verbose(env, "kptr access cannot have variable offset\n");
3861                                         return -EACCES;
3862                                 }
3863                                 if (p != off + reg->var_off.value) {
3864                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3865                                                 p, off + reg->var_off.value);
3866                                         return -EACCES;
3867                                 }
3868                                 if (size != bpf_size_to_bytes(BPF_DW)) {
3869                                         verbose(env, "kptr access size must be BPF_DW\n");
3870                                         return -EACCES;
3871                                 }
3872                                 break;
3873                         }
3874                 }
3875         }
3876         return err;
3877 }
3878
3879 #define MAX_PACKET_OFF 0xffff
3880
3881 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3882                                        const struct bpf_call_arg_meta *meta,
3883                                        enum bpf_access_type t)
3884 {
3885         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3886
3887         switch (prog_type) {
3888         /* Program types only with direct read access go here! */
3889         case BPF_PROG_TYPE_LWT_IN:
3890         case BPF_PROG_TYPE_LWT_OUT:
3891         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3892         case BPF_PROG_TYPE_SK_REUSEPORT:
3893         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3894         case BPF_PROG_TYPE_CGROUP_SKB:
3895                 if (t == BPF_WRITE)
3896                         return false;
3897                 fallthrough;
3898
3899         /* Program types with direct read + write access go here! */
3900         case BPF_PROG_TYPE_SCHED_CLS:
3901         case BPF_PROG_TYPE_SCHED_ACT:
3902         case BPF_PROG_TYPE_XDP:
3903         case BPF_PROG_TYPE_LWT_XMIT:
3904         case BPF_PROG_TYPE_SK_SKB:
3905         case BPF_PROG_TYPE_SK_MSG:
3906                 if (meta)
3907                         return meta->pkt_access;
3908
3909                 env->seen_direct_write = true;
3910                 return true;
3911
3912         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3913                 if (t == BPF_WRITE)
3914                         env->seen_direct_write = true;
3915
3916                 return true;
3917
3918         default:
3919                 return false;
3920         }
3921 }
3922
3923 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3924                                int size, bool zero_size_allowed)
3925 {
3926         struct bpf_reg_state *regs = cur_regs(env);
3927         struct bpf_reg_state *reg = &regs[regno];
3928         int err;
3929
3930         /* We may have added a variable offset to the packet pointer; but any
3931          * reg->range we have comes after that.  We are only checking the fixed
3932          * offset.
3933          */
3934
3935         /* We don't allow negative numbers, because we aren't tracking enough
3936          * detail to prove they're safe.
3937          */
3938         if (reg->smin_value < 0) {
3939                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3940                         regno);
3941                 return -EACCES;
3942         }
3943
3944         err = reg->range < 0 ? -EINVAL :
3945               __check_mem_access(env, regno, off, size, reg->range,
3946                                  zero_size_allowed);
3947         if (err) {
3948                 verbose(env, "R%d offset is outside of the packet\n", regno);
3949                 return err;
3950         }
3951
3952         /* __check_mem_access has made sure "off + size - 1" is within u16.
3953          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3954          * otherwise find_good_pkt_pointers would have refused to set range info
3955          * that __check_mem_access would have rejected this pkt access.
3956          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3957          */
3958         env->prog->aux->max_pkt_offset =
3959                 max_t(u32, env->prog->aux->max_pkt_offset,
3960                       off + reg->umax_value + size - 1);
3961
3962         return err;
3963 }
3964
3965 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3966 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3967                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
3968                             struct btf **btf, u32 *btf_id)
3969 {
3970         struct bpf_insn_access_aux info = {
3971                 .reg_type = *reg_type,
3972                 .log = &env->log,
3973         };
3974
3975         if (env->ops->is_valid_access &&
3976             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3977                 /* A non zero info.ctx_field_size indicates that this field is a
3978                  * candidate for later verifier transformation to load the whole
3979                  * field and then apply a mask when accessed with a narrower
3980                  * access than actual ctx access size. A zero info.ctx_field_size
3981                  * will only allow for whole field access and rejects any other
3982                  * type of narrower access.
3983                  */
3984                 *reg_type = info.reg_type;
3985
3986                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3987                         *btf = info.btf;
3988                         *btf_id = info.btf_id;
3989                 } else {
3990                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3991                 }
3992                 /* remember the offset of last byte accessed in ctx */
3993                 if (env->prog->aux->max_ctx_offset < off + size)
3994                         env->prog->aux->max_ctx_offset = off + size;
3995                 return 0;
3996         }
3997
3998         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3999         return -EACCES;
4000 }
4001
4002 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4003                                   int size)
4004 {
4005         if (size < 0 || off < 0 ||
4006             (u64)off + size > sizeof(struct bpf_flow_keys)) {
4007                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4008                         off, size);
4009                 return -EACCES;
4010         }
4011         return 0;
4012 }
4013
4014 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4015                              u32 regno, int off, int size,
4016                              enum bpf_access_type t)
4017 {
4018         struct bpf_reg_state *regs = cur_regs(env);
4019         struct bpf_reg_state *reg = &regs[regno];
4020         struct bpf_insn_access_aux info = {};
4021         bool valid;
4022
4023         if (reg->smin_value < 0) {
4024                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4025                         regno);
4026                 return -EACCES;
4027         }
4028
4029         switch (reg->type) {
4030         case PTR_TO_SOCK_COMMON:
4031                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4032                 break;
4033         case PTR_TO_SOCKET:
4034                 valid = bpf_sock_is_valid_access(off, size, t, &info);
4035                 break;
4036         case PTR_TO_TCP_SOCK:
4037                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4038                 break;
4039         case PTR_TO_XDP_SOCK:
4040                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4041                 break;
4042         default:
4043                 valid = false;
4044         }
4045
4046
4047         if (valid) {
4048                 env->insn_aux_data[insn_idx].ctx_field_size =
4049                         info.ctx_field_size;
4050                 return 0;
4051         }
4052
4053         verbose(env, "R%d invalid %s access off=%d size=%d\n",
4054                 regno, reg_type_str(env, reg->type), off, size);
4055
4056         return -EACCES;
4057 }
4058
4059 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4060 {
4061         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4062 }
4063
4064 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4065 {
4066         const struct bpf_reg_state *reg = reg_state(env, regno);
4067
4068         return reg->type == PTR_TO_CTX;
4069 }
4070
4071 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4072 {
4073         const struct bpf_reg_state *reg = reg_state(env, regno);
4074
4075         return type_is_sk_pointer(reg->type);
4076 }
4077
4078 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4079 {
4080         const struct bpf_reg_state *reg = reg_state(env, regno);
4081
4082         return type_is_pkt_pointer(reg->type);
4083 }
4084
4085 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4086 {
4087         const struct bpf_reg_state *reg = reg_state(env, regno);
4088
4089         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4090         return reg->type == PTR_TO_FLOW_KEYS;
4091 }
4092
4093 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4094                                    const struct bpf_reg_state *reg,
4095                                    int off, int size, bool strict)
4096 {
4097         struct tnum reg_off;
4098         int ip_align;
4099
4100         /* Byte size accesses are always allowed. */
4101         if (!strict || size == 1)
4102                 return 0;
4103
4104         /* For platforms that do not have a Kconfig enabling
4105          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4106          * NET_IP_ALIGN is universally set to '2'.  And on platforms
4107          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4108          * to this code only in strict mode where we want to emulate
4109          * the NET_IP_ALIGN==2 checking.  Therefore use an
4110          * unconditional IP align value of '2'.
4111          */
4112         ip_align = 2;
4113
4114         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4115         if (!tnum_is_aligned(reg_off, size)) {
4116                 char tn_buf[48];
4117
4118                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4119                 verbose(env,
4120                         "misaligned packet access off %d+%s+%d+%d size %d\n",
4121                         ip_align, tn_buf, reg->off, off, size);
4122                 return -EACCES;
4123         }
4124
4125         return 0;
4126 }
4127
4128 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4129                                        const struct bpf_reg_state *reg,
4130                                        const char *pointer_desc,
4131                                        int off, int size, bool strict)
4132 {
4133         struct tnum reg_off;
4134
4135         /* Byte size accesses are always allowed. */
4136         if (!strict || size == 1)
4137                 return 0;
4138
4139         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4140         if (!tnum_is_aligned(reg_off, size)) {
4141                 char tn_buf[48];
4142
4143                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4144                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4145                         pointer_desc, tn_buf, reg->off, off, size);
4146                 return -EACCES;
4147         }
4148
4149         return 0;
4150 }
4151
4152 static int check_ptr_alignment(struct bpf_verifier_env *env,
4153                                const struct bpf_reg_state *reg, int off,
4154                                int size, bool strict_alignment_once)
4155 {
4156         bool strict = env->strict_alignment || strict_alignment_once;
4157         const char *pointer_desc = "";
4158
4159         switch (reg->type) {
4160         case PTR_TO_PACKET:
4161         case PTR_TO_PACKET_META:
4162                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4163                  * right in front, treat it the very same way.
4164                  */
4165                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4166         case PTR_TO_FLOW_KEYS:
4167                 pointer_desc = "flow keys ";
4168                 break;
4169         case PTR_TO_MAP_KEY:
4170                 pointer_desc = "key ";
4171                 break;
4172         case PTR_TO_MAP_VALUE:
4173                 pointer_desc = "value ";
4174                 break;
4175         case PTR_TO_CTX:
4176                 pointer_desc = "context ";
4177                 break;
4178         case PTR_TO_STACK:
4179                 pointer_desc = "stack ";
4180                 /* The stack spill tracking logic in check_stack_write_fixed_off()
4181                  * and check_stack_read_fixed_off() relies on stack accesses being
4182                  * aligned.
4183                  */
4184                 strict = true;
4185                 break;
4186         case PTR_TO_SOCKET:
4187                 pointer_desc = "sock ";
4188                 break;
4189         case PTR_TO_SOCK_COMMON:
4190                 pointer_desc = "sock_common ";
4191                 break;
4192         case PTR_TO_TCP_SOCK:
4193                 pointer_desc = "tcp_sock ";
4194                 break;
4195         case PTR_TO_XDP_SOCK:
4196                 pointer_desc = "xdp_sock ";
4197                 break;
4198         default:
4199                 break;
4200         }
4201         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4202                                            strict);
4203 }
4204
4205 static int update_stack_depth(struct bpf_verifier_env *env,
4206                               const struct bpf_func_state *func,
4207                               int off)
4208 {
4209         u16 stack = env->subprog_info[func->subprogno].stack_depth;
4210
4211         if (stack >= -off)
4212                 return 0;
4213
4214         /* update known max for given subprogram */
4215         env->subprog_info[func->subprogno].stack_depth = -off;
4216         return 0;
4217 }
4218
4219 /* starting from main bpf function walk all instructions of the function
4220  * and recursively walk all callees that given function can call.
4221  * Ignore jump and exit insns.
4222  * Since recursion is prevented by check_cfg() this algorithm
4223  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4224  */
4225 static int check_max_stack_depth(struct bpf_verifier_env *env)
4226 {
4227         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4228         struct bpf_subprog_info *subprog = env->subprog_info;
4229         struct bpf_insn *insn = env->prog->insnsi;
4230         bool tail_call_reachable = false;
4231         int ret_insn[MAX_CALL_FRAMES];
4232         int ret_prog[MAX_CALL_FRAMES];
4233         int j;
4234
4235 process_func:
4236         /* protect against potential stack overflow that might happen when
4237          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4238          * depth for such case down to 256 so that the worst case scenario
4239          * would result in 8k stack size (32 which is tailcall limit * 256 =
4240          * 8k).
4241          *
4242          * To get the idea what might happen, see an example:
4243          * func1 -> sub rsp, 128
4244          *  subfunc1 -> sub rsp, 256
4245          *  tailcall1 -> add rsp, 256
4246          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4247          *   subfunc2 -> sub rsp, 64
4248          *   subfunc22 -> sub rsp, 128
4249          *   tailcall2 -> add rsp, 128
4250          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4251          *
4252          * tailcall will unwind the current stack frame but it will not get rid
4253          * of caller's stack as shown on the example above.
4254          */
4255         if (idx && subprog[idx].has_tail_call && depth >= 256) {
4256                 verbose(env,
4257                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4258                         depth);
4259                 return -EACCES;
4260         }
4261         /* round up to 32-bytes, since this is granularity
4262          * of interpreter stack size
4263          */
4264         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4265         if (depth > MAX_BPF_STACK) {
4266                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4267                         frame + 1, depth);
4268                 return -EACCES;
4269         }
4270 continue_func:
4271         subprog_end = subprog[idx + 1].start;
4272         for (; i < subprog_end; i++) {
4273                 int next_insn;
4274
4275                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4276                         continue;
4277                 /* remember insn and function to return to */
4278                 ret_insn[frame] = i + 1;
4279                 ret_prog[frame] = idx;
4280
4281                 /* find the callee */
4282                 next_insn = i + insn[i].imm + 1;
4283                 idx = find_subprog(env, next_insn);
4284                 if (idx < 0) {
4285                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4286                                   next_insn);
4287                         return -EFAULT;
4288                 }
4289                 if (subprog[idx].is_async_cb) {
4290                         if (subprog[idx].has_tail_call) {
4291                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4292                                 return -EFAULT;
4293                         }
4294                          /* async callbacks don't increase bpf prog stack size */
4295                         continue;
4296                 }
4297                 i = next_insn;
4298
4299                 if (subprog[idx].has_tail_call)
4300                         tail_call_reachable = true;
4301
4302                 frame++;
4303                 if (frame >= MAX_CALL_FRAMES) {
4304                         verbose(env, "the call stack of %d frames is too deep !\n",
4305                                 frame);
4306                         return -E2BIG;
4307                 }
4308                 goto process_func;
4309         }
4310         /* if tail call got detected across bpf2bpf calls then mark each of the
4311          * currently present subprog frames as tail call reachable subprogs;
4312          * this info will be utilized by JIT so that we will be preserving the
4313          * tail call counter throughout bpf2bpf calls combined with tailcalls
4314          */
4315         if (tail_call_reachable)
4316                 for (j = 0; j < frame; j++)
4317                         subprog[ret_prog[j]].tail_call_reachable = true;
4318         if (subprog[0].tail_call_reachable)
4319                 env->prog->aux->tail_call_reachable = true;
4320
4321         /* end of for() loop means the last insn of the 'subprog'
4322          * was reached. Doesn't matter whether it was JA or EXIT
4323          */
4324         if (frame == 0)
4325                 return 0;
4326         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4327         frame--;
4328         i = ret_insn[frame];
4329         idx = ret_prog[frame];
4330         goto continue_func;
4331 }
4332
4333 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4334 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4335                                   const struct bpf_insn *insn, int idx)
4336 {
4337         int start = idx + insn->imm + 1, subprog;
4338
4339         subprog = find_subprog(env, start);
4340         if (subprog < 0) {
4341                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4342                           start);
4343                 return -EFAULT;
4344         }
4345         return env->subprog_info[subprog].stack_depth;
4346 }
4347 #endif
4348
4349 static int __check_buffer_access(struct bpf_verifier_env *env,
4350                                  const char *buf_info,
4351                                  const struct bpf_reg_state *reg,
4352                                  int regno, int off, int size)
4353 {
4354         if (off < 0) {
4355                 verbose(env,
4356                         "R%d invalid %s buffer access: off=%d, size=%d\n",
4357                         regno, buf_info, off, size);
4358                 return -EACCES;
4359         }
4360         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4361                 char tn_buf[48];
4362
4363                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4364                 verbose(env,
4365                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4366                         regno, off, tn_buf);
4367                 return -EACCES;
4368         }
4369
4370         return 0;
4371 }
4372
4373 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4374                                   const struct bpf_reg_state *reg,
4375                                   int regno, int off, int size)
4376 {
4377         int err;
4378
4379         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4380         if (err)
4381                 return err;
4382
4383         if (off + size > env->prog->aux->max_tp_access)
4384                 env->prog->aux->max_tp_access = off + size;
4385
4386         return 0;
4387 }
4388
4389 static int check_buffer_access(struct bpf_verifier_env *env,
4390                                const struct bpf_reg_state *reg,
4391                                int regno, int off, int size,
4392                                bool zero_size_allowed,
4393                                u32 *max_access)
4394 {
4395         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4396         int err;
4397
4398         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4399         if (err)
4400                 return err;
4401
4402         if (off + size > *max_access)
4403                 *max_access = off + size;
4404
4405         return 0;
4406 }
4407
4408 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4409 static void zext_32_to_64(struct bpf_reg_state *reg)
4410 {
4411         reg->var_off = tnum_subreg(reg->var_off);
4412         __reg_assign_32_into_64(reg);
4413 }
4414
4415 /* truncate register to smaller size (in bytes)
4416  * must be called with size < BPF_REG_SIZE
4417  */
4418 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4419 {
4420         u64 mask;
4421
4422         /* clear high bits in bit representation */
4423         reg->var_off = tnum_cast(reg->var_off, size);
4424
4425         /* fix arithmetic bounds */
4426         mask = ((u64)1 << (size * 8)) - 1;
4427         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4428                 reg->umin_value &= mask;
4429                 reg->umax_value &= mask;
4430         } else {
4431                 reg->umin_value = 0;
4432                 reg->umax_value = mask;
4433         }
4434         reg->smin_value = reg->umin_value;
4435         reg->smax_value = reg->umax_value;
4436
4437         /* If size is smaller than 32bit register the 32bit register
4438          * values are also truncated so we push 64-bit bounds into
4439          * 32-bit bounds. Above were truncated < 32-bits already.
4440          */
4441         if (size >= 4)
4442                 return;
4443         __reg_combine_64_into_32(reg);
4444 }
4445
4446 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4447 {
4448         /* A map is considered read-only if the following condition are true:
4449          *
4450          * 1) BPF program side cannot change any of the map content. The
4451          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4452          *    and was set at map creation time.
4453          * 2) The map value(s) have been initialized from user space by a
4454          *    loader and then "frozen", such that no new map update/delete
4455          *    operations from syscall side are possible for the rest of
4456          *    the map's lifetime from that point onwards.
4457          * 3) Any parallel/pending map update/delete operations from syscall
4458          *    side have been completed. Only after that point, it's safe to
4459          *    assume that map value(s) are immutable.
4460          */
4461         return (map->map_flags & BPF_F_RDONLY_PROG) &&
4462                READ_ONCE(map->frozen) &&
4463                !bpf_map_write_active(map);
4464 }
4465
4466 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4467 {
4468         void *ptr;
4469         u64 addr;
4470         int err;
4471
4472         err = map->ops->map_direct_value_addr(map, &addr, off);
4473         if (err)
4474                 return err;
4475         ptr = (void *)(long)addr + off;
4476
4477         switch (size) {
4478         case sizeof(u8):
4479                 *val = (u64)*(u8 *)ptr;
4480                 break;
4481         case sizeof(u16):
4482                 *val = (u64)*(u16 *)ptr;
4483                 break;
4484         case sizeof(u32):
4485                 *val = (u64)*(u32 *)ptr;
4486                 break;
4487         case sizeof(u64):
4488                 *val = *(u64 *)ptr;
4489                 break;
4490         default:
4491                 return -EINVAL;
4492         }
4493         return 0;
4494 }
4495
4496 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4497                                    struct bpf_reg_state *regs,
4498                                    int regno, int off, int size,
4499                                    enum bpf_access_type atype,
4500                                    int value_regno)
4501 {
4502         struct bpf_reg_state *reg = regs + regno;
4503         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4504         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4505         enum bpf_type_flag flag = 0;
4506         u32 btf_id;
4507         int ret;
4508
4509         if (off < 0) {
4510                 verbose(env,
4511                         "R%d is ptr_%s invalid negative access: off=%d\n",
4512                         regno, tname, off);
4513                 return -EACCES;
4514         }
4515         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4516                 char tn_buf[48];
4517
4518                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4519                 verbose(env,
4520                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4521                         regno, tname, off, tn_buf);
4522                 return -EACCES;
4523         }
4524
4525         if (reg->type & MEM_USER) {
4526                 verbose(env,
4527                         "R%d is ptr_%s access user memory: off=%d\n",
4528                         regno, tname, off);
4529                 return -EACCES;
4530         }
4531
4532         if (reg->type & MEM_PERCPU) {
4533                 verbose(env,
4534                         "R%d is ptr_%s access percpu memory: off=%d\n",
4535                         regno, tname, off);
4536                 return -EACCES;
4537         }
4538
4539         if (env->ops->btf_struct_access) {
4540                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4541                                                   off, size, atype, &btf_id, &flag);
4542         } else {
4543                 if (atype != BPF_READ) {
4544                         verbose(env, "only read is supported\n");
4545                         return -EACCES;
4546                 }
4547
4548                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4549                                         atype, &btf_id, &flag);
4550         }
4551
4552         if (ret < 0)
4553                 return ret;
4554
4555         /* If this is an untrusted pointer, all pointers formed by walking it
4556          * also inherit the untrusted flag.
4557          */
4558         if (type_flag(reg->type) & PTR_UNTRUSTED)
4559                 flag |= PTR_UNTRUSTED;
4560
4561         if (atype == BPF_READ && value_regno >= 0)
4562                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4563
4564         return 0;
4565 }
4566
4567 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4568                                    struct bpf_reg_state *regs,
4569                                    int regno, int off, int size,
4570                                    enum bpf_access_type atype,
4571                                    int value_regno)
4572 {
4573         struct bpf_reg_state *reg = regs + regno;
4574         struct bpf_map *map = reg->map_ptr;
4575         enum bpf_type_flag flag = 0;
4576         const struct btf_type *t;
4577         const char *tname;
4578         u32 btf_id;
4579         int ret;
4580
4581         if (!btf_vmlinux) {
4582                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4583                 return -ENOTSUPP;
4584         }
4585
4586         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4587                 verbose(env, "map_ptr access not supported for map type %d\n",
4588                         map->map_type);
4589                 return -ENOTSUPP;
4590         }
4591
4592         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4593         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4594
4595         if (!env->allow_ptr_to_map_access) {
4596                 verbose(env,
4597                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4598                         tname);
4599                 return -EPERM;
4600         }
4601
4602         if (off < 0) {
4603                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4604                         regno, tname, off);
4605                 return -EACCES;
4606         }
4607
4608         if (atype != BPF_READ) {
4609                 verbose(env, "only read from %s is supported\n", tname);
4610                 return -EACCES;
4611         }
4612
4613         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4614         if (ret < 0)
4615                 return ret;
4616
4617         if (value_regno >= 0)
4618                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4619
4620         return 0;
4621 }
4622
4623 /* Check that the stack access at the given offset is within bounds. The
4624  * maximum valid offset is -1.
4625  *
4626  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4627  * -state->allocated_stack for reads.
4628  */
4629 static int check_stack_slot_within_bounds(int off,
4630                                           struct bpf_func_state *state,
4631                                           enum bpf_access_type t)
4632 {
4633         int min_valid_off;
4634
4635         if (t == BPF_WRITE)
4636                 min_valid_off = -MAX_BPF_STACK;
4637         else
4638                 min_valid_off = -state->allocated_stack;
4639
4640         if (off < min_valid_off || off > -1)
4641                 return -EACCES;
4642         return 0;
4643 }
4644
4645 /* Check that the stack access at 'regno + off' falls within the maximum stack
4646  * bounds.
4647  *
4648  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4649  */
4650 static int check_stack_access_within_bounds(
4651                 struct bpf_verifier_env *env,
4652                 int regno, int off, int access_size,
4653                 enum bpf_access_src src, enum bpf_access_type type)
4654 {
4655         struct bpf_reg_state *regs = cur_regs(env);
4656         struct bpf_reg_state *reg = regs + regno;
4657         struct bpf_func_state *state = func(env, reg);
4658         int min_off, max_off;
4659         int err;
4660         char *err_extra;
4661
4662         if (src == ACCESS_HELPER)
4663                 /* We don't know if helpers are reading or writing (or both). */
4664                 err_extra = " indirect access to";
4665         else if (type == BPF_READ)
4666                 err_extra = " read from";
4667         else
4668                 err_extra = " write to";
4669
4670         if (tnum_is_const(reg->var_off)) {
4671                 min_off = reg->var_off.value + off;
4672                 if (access_size > 0)
4673                         max_off = min_off + access_size - 1;
4674                 else
4675                         max_off = min_off;
4676         } else {
4677                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4678                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4679                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4680                                 err_extra, regno);
4681                         return -EACCES;
4682                 }
4683                 min_off = reg->smin_value + off;
4684                 if (access_size > 0)
4685                         max_off = reg->smax_value + off + access_size - 1;
4686                 else
4687                         max_off = min_off;
4688         }
4689
4690         err = check_stack_slot_within_bounds(min_off, state, type);
4691         if (!err)
4692                 err = check_stack_slot_within_bounds(max_off, state, type);
4693
4694         if (err) {
4695                 if (tnum_is_const(reg->var_off)) {
4696                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4697                                 err_extra, regno, off, access_size);
4698                 } else {
4699                         char tn_buf[48];
4700
4701                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4702                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4703                                 err_extra, regno, tn_buf, access_size);
4704                 }
4705         }
4706         return err;
4707 }
4708
4709 /* check whether memory at (regno + off) is accessible for t = (read | write)
4710  * if t==write, value_regno is a register which value is stored into memory
4711  * if t==read, value_regno is a register which will receive the value from memory
4712  * if t==write && value_regno==-1, some unknown value is stored into memory
4713  * if t==read && value_regno==-1, don't care what we read from memory
4714  */
4715 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4716                             int off, int bpf_size, enum bpf_access_type t,
4717                             int value_regno, bool strict_alignment_once)
4718 {
4719         struct bpf_reg_state *regs = cur_regs(env);
4720         struct bpf_reg_state *reg = regs + regno;
4721         struct bpf_func_state *state;
4722         int size, err = 0;
4723
4724         size = bpf_size_to_bytes(bpf_size);
4725         if (size < 0)
4726                 return size;
4727
4728         /* alignment checks will add in reg->off themselves */
4729         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4730         if (err)
4731                 return err;
4732
4733         /* for access checks, reg->off is just part of off */
4734         off += reg->off;
4735
4736         if (reg->type == PTR_TO_MAP_KEY) {
4737                 if (t == BPF_WRITE) {
4738                         verbose(env, "write to change key R%d not allowed\n", regno);
4739                         return -EACCES;
4740                 }
4741
4742                 err = check_mem_region_access(env, regno, off, size,
4743                                               reg->map_ptr->key_size, false);
4744                 if (err)
4745                         return err;
4746                 if (value_regno >= 0)
4747                         mark_reg_unknown(env, regs, value_regno);
4748         } else if (reg->type == PTR_TO_MAP_VALUE) {
4749                 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4750
4751                 if (t == BPF_WRITE && value_regno >= 0 &&
4752                     is_pointer_value(env, value_regno)) {
4753                         verbose(env, "R%d leaks addr into map\n", value_regno);
4754                         return -EACCES;
4755                 }
4756                 err = check_map_access_type(env, regno, off, size, t);
4757                 if (err)
4758                         return err;
4759                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4760                 if (err)
4761                         return err;
4762                 if (tnum_is_const(reg->var_off))
4763                         kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4764                                                                   off + reg->var_off.value);
4765                 if (kptr_off_desc) {
4766                         err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4767                                                     kptr_off_desc);
4768                 } else if (t == BPF_READ && value_regno >= 0) {
4769                         struct bpf_map *map = reg->map_ptr;
4770
4771                         /* if map is read-only, track its contents as scalars */
4772                         if (tnum_is_const(reg->var_off) &&
4773                             bpf_map_is_rdonly(map) &&
4774                             map->ops->map_direct_value_addr) {
4775                                 int map_off = off + reg->var_off.value;
4776                                 u64 val = 0;
4777
4778                                 err = bpf_map_direct_read(map, map_off, size,
4779                                                           &val);
4780                                 if (err)
4781                                         return err;
4782
4783                                 regs[value_regno].type = SCALAR_VALUE;
4784                                 __mark_reg_known(&regs[value_regno], val);
4785                         } else {
4786                                 mark_reg_unknown(env, regs, value_regno);
4787                         }
4788                 }
4789         } else if (base_type(reg->type) == PTR_TO_MEM) {
4790                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4791
4792                 if (type_may_be_null(reg->type)) {
4793                         verbose(env, "R%d invalid mem access '%s'\n", regno,
4794                                 reg_type_str(env, reg->type));
4795                         return -EACCES;
4796                 }
4797
4798                 if (t == BPF_WRITE && rdonly_mem) {
4799                         verbose(env, "R%d cannot write into %s\n",
4800                                 regno, reg_type_str(env, reg->type));
4801                         return -EACCES;
4802                 }
4803
4804                 if (t == BPF_WRITE && value_regno >= 0 &&
4805                     is_pointer_value(env, value_regno)) {
4806                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4807                         return -EACCES;
4808                 }
4809
4810                 err = check_mem_region_access(env, regno, off, size,
4811                                               reg->mem_size, false);
4812                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4813                         mark_reg_unknown(env, regs, value_regno);
4814         } else if (reg->type == PTR_TO_CTX) {
4815                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4816                 struct btf *btf = NULL;
4817                 u32 btf_id = 0;
4818
4819                 if (t == BPF_WRITE && value_regno >= 0 &&
4820                     is_pointer_value(env, value_regno)) {
4821                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4822                         return -EACCES;
4823                 }
4824
4825                 err = check_ptr_off_reg(env, reg, regno);
4826                 if (err < 0)
4827                         return err;
4828
4829                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4830                                        &btf_id);
4831                 if (err)
4832                         verbose_linfo(env, insn_idx, "; ");
4833                 if (!err && t == BPF_READ && value_regno >= 0) {
4834                         /* ctx access returns either a scalar, or a
4835                          * PTR_TO_PACKET[_META,_END]. In the latter
4836                          * case, we know the offset is zero.
4837                          */
4838                         if (reg_type == SCALAR_VALUE) {
4839                                 mark_reg_unknown(env, regs, value_regno);
4840                         } else {
4841                                 mark_reg_known_zero(env, regs,
4842                                                     value_regno);
4843                                 if (type_may_be_null(reg_type))
4844                                         regs[value_regno].id = ++env->id_gen;
4845                                 /* A load of ctx field could have different
4846                                  * actual load size with the one encoded in the
4847                                  * insn. When the dst is PTR, it is for sure not
4848                                  * a sub-register.
4849                                  */
4850                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4851                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4852                                         regs[value_regno].btf = btf;
4853                                         regs[value_regno].btf_id = btf_id;
4854                                 }
4855                         }
4856                         regs[value_regno].type = reg_type;
4857                 }
4858
4859         } else if (reg->type == PTR_TO_STACK) {
4860                 /* Basic bounds checks. */
4861                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4862                 if (err)
4863                         return err;
4864
4865                 state = func(env, reg);
4866                 err = update_stack_depth(env, state, off);
4867                 if (err)
4868                         return err;
4869
4870                 if (t == BPF_READ)
4871                         err = check_stack_read(env, regno, off, size,
4872                                                value_regno);
4873                 else
4874                         err = check_stack_write(env, regno, off, size,
4875                                                 value_regno, insn_idx);
4876         } else if (reg_is_pkt_pointer(reg)) {
4877                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4878                         verbose(env, "cannot write into packet\n");
4879                         return -EACCES;
4880                 }
4881                 if (t == BPF_WRITE && value_regno >= 0 &&
4882                     is_pointer_value(env, value_regno)) {
4883                         verbose(env, "R%d leaks addr into packet\n",
4884                                 value_regno);
4885                         return -EACCES;
4886                 }
4887                 err = check_packet_access(env, regno, off, size, false);
4888                 if (!err && t == BPF_READ && value_regno >= 0)
4889                         mark_reg_unknown(env, regs, value_regno);
4890         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4891                 if (t == BPF_WRITE && value_regno >= 0 &&
4892                     is_pointer_value(env, value_regno)) {
4893                         verbose(env, "R%d leaks addr into flow keys\n",
4894                                 value_regno);
4895                         return -EACCES;
4896                 }
4897
4898                 err = check_flow_keys_access(env, off, size);
4899                 if (!err && t == BPF_READ && value_regno >= 0)
4900                         mark_reg_unknown(env, regs, value_regno);
4901         } else if (type_is_sk_pointer(reg->type)) {
4902                 if (t == BPF_WRITE) {
4903                         verbose(env, "R%d cannot write into %s\n",
4904                                 regno, reg_type_str(env, reg->type));
4905                         return -EACCES;
4906                 }
4907                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4908                 if (!err && value_regno >= 0)
4909                         mark_reg_unknown(env, regs, value_regno);
4910         } else if (reg->type == PTR_TO_TP_BUFFER) {
4911                 err = check_tp_buffer_access(env, reg, regno, off, size);
4912                 if (!err && t == BPF_READ && value_regno >= 0)
4913                         mark_reg_unknown(env, regs, value_regno);
4914         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4915                    !type_may_be_null(reg->type)) {
4916                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4917                                               value_regno);
4918         } else if (reg->type == CONST_PTR_TO_MAP) {
4919                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4920                                               value_regno);
4921         } else if (base_type(reg->type) == PTR_TO_BUF) {
4922                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4923                 u32 *max_access;
4924
4925                 if (rdonly_mem) {
4926                         if (t == BPF_WRITE) {
4927                                 verbose(env, "R%d cannot write into %s\n",
4928                                         regno, reg_type_str(env, reg->type));
4929                                 return -EACCES;
4930                         }
4931                         max_access = &env->prog->aux->max_rdonly_access;
4932                 } else {
4933                         max_access = &env->prog->aux->max_rdwr_access;
4934                 }
4935
4936                 err = check_buffer_access(env, reg, regno, off, size, false,
4937                                           max_access);
4938
4939                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4940                         mark_reg_unknown(env, regs, value_regno);
4941         } else {
4942                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4943                         reg_type_str(env, reg->type));
4944                 return -EACCES;
4945         }
4946
4947         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4948             regs[value_regno].type == SCALAR_VALUE) {
4949                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4950                 coerce_reg_to_size(&regs[value_regno], size);
4951         }
4952         return err;
4953 }
4954
4955 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4956 {
4957         int load_reg;
4958         int err;
4959
4960         switch (insn->imm) {
4961         case BPF_ADD:
4962         case BPF_ADD | BPF_FETCH:
4963         case BPF_AND:
4964         case BPF_AND | BPF_FETCH:
4965         case BPF_OR:
4966         case BPF_OR | BPF_FETCH:
4967         case BPF_XOR:
4968         case BPF_XOR | BPF_FETCH:
4969         case BPF_XCHG:
4970         case BPF_CMPXCHG:
4971                 break;
4972         default:
4973                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4974                 return -EINVAL;
4975         }
4976
4977         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4978                 verbose(env, "invalid atomic operand size\n");
4979                 return -EINVAL;
4980         }
4981
4982         /* check src1 operand */
4983         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4984         if (err)
4985                 return err;
4986
4987         /* check src2 operand */
4988         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4989         if (err)
4990                 return err;
4991
4992         if (insn->imm == BPF_CMPXCHG) {
4993                 /* Check comparison of R0 with memory location */
4994                 const u32 aux_reg = BPF_REG_0;
4995
4996                 err = check_reg_arg(env, aux_reg, SRC_OP);
4997                 if (err)
4998                         return err;
4999
5000                 if (is_pointer_value(env, aux_reg)) {
5001                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
5002                         return -EACCES;
5003                 }
5004         }
5005
5006         if (is_pointer_value(env, insn->src_reg)) {
5007                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5008                 return -EACCES;
5009         }
5010
5011         if (is_ctx_reg(env, insn->dst_reg) ||
5012             is_pkt_reg(env, insn->dst_reg) ||
5013             is_flow_key_reg(env, insn->dst_reg) ||
5014             is_sk_reg(env, insn->dst_reg)) {
5015                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5016                         insn->dst_reg,
5017                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5018                 return -EACCES;
5019         }
5020
5021         if (insn->imm & BPF_FETCH) {
5022                 if (insn->imm == BPF_CMPXCHG)
5023                         load_reg = BPF_REG_0;
5024                 else
5025                         load_reg = insn->src_reg;
5026
5027                 /* check and record load of old value */
5028                 err = check_reg_arg(env, load_reg, DST_OP);
5029                 if (err)
5030                         return err;
5031         } else {
5032                 /* This instruction accesses a memory location but doesn't
5033                  * actually load it into a register.
5034                  */
5035                 load_reg = -1;
5036         }
5037
5038         /* Check whether we can read the memory, with second call for fetch
5039          * case to simulate the register fill.
5040          */
5041         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5042                                BPF_SIZE(insn->code), BPF_READ, -1, true);
5043         if (!err && load_reg >= 0)
5044                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5045                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
5046                                        true);
5047         if (err)
5048                 return err;
5049
5050         /* Check whether we can write into the same memory. */
5051         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5052                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5053         if (err)
5054                 return err;
5055
5056         return 0;
5057 }
5058
5059 /* When register 'regno' is used to read the stack (either directly or through
5060  * a helper function) make sure that it's within stack boundary and, depending
5061  * on the access type, that all elements of the stack are initialized.
5062  *
5063  * 'off' includes 'regno->off', but not its dynamic part (if any).
5064  *
5065  * All registers that have been spilled on the stack in the slots within the
5066  * read offsets are marked as read.
5067  */
5068 static int check_stack_range_initialized(
5069                 struct bpf_verifier_env *env, int regno, int off,
5070                 int access_size, bool zero_size_allowed,
5071                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5072 {
5073         struct bpf_reg_state *reg = reg_state(env, regno);
5074         struct bpf_func_state *state = func(env, reg);
5075         int err, min_off, max_off, i, j, slot, spi;
5076         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5077         enum bpf_access_type bounds_check_type;
5078         /* Some accesses can write anything into the stack, others are
5079          * read-only.
5080          */
5081         bool clobber = false;
5082
5083         if (access_size == 0 && !zero_size_allowed) {
5084                 verbose(env, "invalid zero-sized read\n");
5085                 return -EACCES;
5086         }
5087
5088         if (type == ACCESS_HELPER) {
5089                 /* The bounds checks for writes are more permissive than for
5090                  * reads. However, if raw_mode is not set, we'll do extra
5091                  * checks below.
5092                  */
5093                 bounds_check_type = BPF_WRITE;
5094                 clobber = true;
5095         } else {
5096                 bounds_check_type = BPF_READ;
5097         }
5098         err = check_stack_access_within_bounds(env, regno, off, access_size,
5099                                                type, bounds_check_type);
5100         if (err)
5101                 return err;
5102
5103
5104         if (tnum_is_const(reg->var_off)) {
5105                 min_off = max_off = reg->var_off.value + off;
5106         } else {
5107                 /* Variable offset is prohibited for unprivileged mode for
5108                  * simplicity since it requires corresponding support in
5109                  * Spectre masking for stack ALU.
5110                  * See also retrieve_ptr_limit().
5111                  */
5112                 if (!env->bypass_spec_v1) {
5113                         char tn_buf[48];
5114
5115                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5116                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5117                                 regno, err_extra, tn_buf);
5118                         return -EACCES;
5119                 }
5120                 /* Only initialized buffer on stack is allowed to be accessed
5121                  * with variable offset. With uninitialized buffer it's hard to
5122                  * guarantee that whole memory is marked as initialized on
5123                  * helper return since specific bounds are unknown what may
5124                  * cause uninitialized stack leaking.
5125                  */
5126                 if (meta && meta->raw_mode)
5127                         meta = NULL;
5128
5129                 min_off = reg->smin_value + off;
5130                 max_off = reg->smax_value + off;
5131         }
5132
5133         if (meta && meta->raw_mode) {
5134                 meta->access_size = access_size;
5135                 meta->regno = regno;
5136                 return 0;
5137         }
5138
5139         for (i = min_off; i < max_off + access_size; i++) {
5140                 u8 *stype;
5141
5142                 slot = -i - 1;
5143                 spi = slot / BPF_REG_SIZE;
5144                 if (state->allocated_stack <= slot)
5145                         goto err;
5146                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5147                 if (*stype == STACK_MISC)
5148                         goto mark;
5149                 if (*stype == STACK_ZERO) {
5150                         if (clobber) {
5151                                 /* helper can write anything into the stack */
5152                                 *stype = STACK_MISC;
5153                         }
5154                         goto mark;
5155                 }
5156
5157                 if (is_spilled_reg(&state->stack[spi]) &&
5158                     base_type(state->stack[spi].spilled_ptr.type) == PTR_TO_BTF_ID)
5159                         goto mark;
5160
5161                 if (is_spilled_reg(&state->stack[spi]) &&
5162                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5163                      env->allow_ptr_leaks)) {
5164                         if (clobber) {
5165                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5166                                 for (j = 0; j < BPF_REG_SIZE; j++)
5167                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5168                         }
5169                         goto mark;
5170                 }
5171
5172 err:
5173                 if (tnum_is_const(reg->var_off)) {
5174                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5175                                 err_extra, regno, min_off, i - min_off, access_size);
5176                 } else {
5177                         char tn_buf[48];
5178
5179                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5180                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5181                                 err_extra, regno, tn_buf, i - min_off, access_size);
5182                 }
5183                 return -EACCES;
5184 mark:
5185                 /* reading any byte out of 8-byte 'spill_slot' will cause
5186                  * the whole slot to be marked as 'read'
5187                  */
5188                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5189                               state->stack[spi].spilled_ptr.parent,
5190                               REG_LIVE_READ64);
5191         }
5192         return update_stack_depth(env, state, min_off);
5193 }
5194
5195 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5196                                    int access_size, bool zero_size_allowed,
5197                                    struct bpf_call_arg_meta *meta)
5198 {
5199         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5200         u32 *max_access;
5201
5202         switch (base_type(reg->type)) {
5203         case PTR_TO_PACKET:
5204         case PTR_TO_PACKET_META:
5205                 return check_packet_access(env, regno, reg->off, access_size,
5206                                            zero_size_allowed);
5207         case PTR_TO_MAP_KEY:
5208                 if (meta && meta->raw_mode) {
5209                         verbose(env, "R%d cannot write into %s\n", regno,
5210                                 reg_type_str(env, reg->type));
5211                         return -EACCES;
5212                 }
5213                 return check_mem_region_access(env, regno, reg->off, access_size,
5214                                                reg->map_ptr->key_size, false);
5215         case PTR_TO_MAP_VALUE:
5216                 if (check_map_access_type(env, regno, reg->off, access_size,
5217                                           meta && meta->raw_mode ? BPF_WRITE :
5218                                           BPF_READ))
5219                         return -EACCES;
5220                 return check_map_access(env, regno, reg->off, access_size,
5221                                         zero_size_allowed, ACCESS_HELPER);
5222         case PTR_TO_MEM:
5223                 if (type_is_rdonly_mem(reg->type)) {
5224                         if (meta && meta->raw_mode) {
5225                                 verbose(env, "R%d cannot write into %s\n", regno,
5226                                         reg_type_str(env, reg->type));
5227                                 return -EACCES;
5228                         }
5229                 }
5230                 return check_mem_region_access(env, regno, reg->off,
5231                                                access_size, reg->mem_size,
5232                                                zero_size_allowed);
5233         case PTR_TO_BUF:
5234                 if (type_is_rdonly_mem(reg->type)) {
5235                         if (meta && meta->raw_mode) {
5236                                 verbose(env, "R%d cannot write into %s\n", regno,
5237                                         reg_type_str(env, reg->type));
5238                                 return -EACCES;
5239                         }
5240
5241                         max_access = &env->prog->aux->max_rdonly_access;
5242                 } else {
5243                         max_access = &env->prog->aux->max_rdwr_access;
5244                 }
5245                 return check_buffer_access(env, reg, regno, reg->off,
5246                                            access_size, zero_size_allowed,
5247                                            max_access);
5248         case PTR_TO_STACK:
5249                 return check_stack_range_initialized(
5250                                 env,
5251                                 regno, reg->off, access_size,
5252                                 zero_size_allowed, ACCESS_HELPER, meta);
5253         case PTR_TO_CTX:
5254                 /* in case the function doesn't know how to access the context,
5255                  * (because we are in a program of type SYSCALL for example), we
5256                  * can not statically check its size.
5257                  * Dynamically check it now.
5258                  */
5259                 if (!env->ops->convert_ctx_access) {
5260                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5261                         int offset = access_size - 1;
5262
5263                         /* Allow zero-byte read from PTR_TO_CTX */
5264                         if (access_size == 0)
5265                                 return zero_size_allowed ? 0 : -EACCES;
5266
5267                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5268                                                 atype, -1, false);
5269                 }
5270
5271                 fallthrough;
5272         default: /* scalar_value or invalid ptr */
5273                 /* Allow zero-byte read from NULL, regardless of pointer type */
5274                 if (zero_size_allowed && access_size == 0 &&
5275                     register_is_null(reg))
5276                         return 0;
5277
5278                 verbose(env, "R%d type=%s ", regno,
5279                         reg_type_str(env, reg->type));
5280                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5281                 return -EACCES;
5282         }
5283 }
5284
5285 static int check_mem_size_reg(struct bpf_verifier_env *env,
5286                               struct bpf_reg_state *reg, u32 regno,
5287                               bool zero_size_allowed,
5288                               struct bpf_call_arg_meta *meta)
5289 {
5290         int err;
5291
5292         /* This is used to refine r0 return value bounds for helpers
5293          * that enforce this value as an upper bound on return values.
5294          * See do_refine_retval_range() for helpers that can refine
5295          * the return value. C type of helper is u32 so we pull register
5296          * bound from umax_value however, if negative verifier errors
5297          * out. Only upper bounds can be learned because retval is an
5298          * int type and negative retvals are allowed.
5299          */
5300         meta->msize_max_value = reg->umax_value;
5301
5302         /* The register is SCALAR_VALUE; the access check
5303          * happens using its boundaries.
5304          */
5305         if (!tnum_is_const(reg->var_off))
5306                 /* For unprivileged variable accesses, disable raw
5307                  * mode so that the program is required to
5308                  * initialize all the memory that the helper could
5309                  * just partially fill up.
5310                  */
5311                 meta = NULL;
5312
5313         if (reg->smin_value < 0) {
5314                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5315                         regno);
5316                 return -EACCES;
5317         }
5318
5319         if (reg->umin_value == 0) {
5320                 err = check_helper_mem_access(env, regno - 1, 0,
5321                                               zero_size_allowed,
5322                                               meta);
5323                 if (err)
5324                         return err;
5325         }
5326
5327         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5328                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5329                         regno);
5330                 return -EACCES;
5331         }
5332         err = check_helper_mem_access(env, regno - 1,
5333                                       reg->umax_value,
5334                                       zero_size_allowed, meta);
5335         if (!err)
5336                 err = mark_chain_precision(env, regno);
5337         return err;
5338 }
5339
5340 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5341                    u32 regno, u32 mem_size)
5342 {
5343         bool may_be_null = type_may_be_null(reg->type);
5344         struct bpf_reg_state saved_reg;
5345         struct bpf_call_arg_meta meta;
5346         int err;
5347
5348         if (register_is_null(reg))
5349                 return 0;
5350
5351         memset(&meta, 0, sizeof(meta));
5352         /* Assuming that the register contains a value check if the memory
5353          * access is safe. Temporarily save and restore the register's state as
5354          * the conversion shouldn't be visible to a caller.
5355          */
5356         if (may_be_null) {
5357                 saved_reg = *reg;
5358                 mark_ptr_not_null_reg(reg);
5359         }
5360
5361         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5362         /* Check access for BPF_WRITE */
5363         meta.raw_mode = true;
5364         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5365
5366         if (may_be_null)
5367                 *reg = saved_reg;
5368
5369         return err;
5370 }
5371
5372 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5373                              u32 regno)
5374 {
5375         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5376         bool may_be_null = type_may_be_null(mem_reg->type);
5377         struct bpf_reg_state saved_reg;
5378         struct bpf_call_arg_meta meta;
5379         int err;
5380
5381         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5382
5383         memset(&meta, 0, sizeof(meta));
5384
5385         if (may_be_null) {
5386                 saved_reg = *mem_reg;
5387                 mark_ptr_not_null_reg(mem_reg);
5388         }
5389
5390         err = check_mem_size_reg(env, reg, regno, true, &meta);
5391         /* Check access for BPF_WRITE */
5392         meta.raw_mode = true;
5393         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5394
5395         if (may_be_null)
5396                 *mem_reg = saved_reg;
5397         return err;
5398 }
5399
5400 /* Implementation details:
5401  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5402  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5403  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5404  * value_or_null->value transition, since the verifier only cares about
5405  * the range of access to valid map value pointer and doesn't care about actual
5406  * address of the map element.
5407  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5408  * reg->id > 0 after value_or_null->value transition. By doing so
5409  * two bpf_map_lookups will be considered two different pointers that
5410  * point to different bpf_spin_locks.
5411  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5412  * dead-locks.
5413  * Since only one bpf_spin_lock is allowed the checks are simpler than
5414  * reg_is_refcounted() logic. The verifier needs to remember only
5415  * one spin_lock instead of array of acquired_refs.
5416  * cur_state->active_spin_lock remembers which map value element got locked
5417  * and clears it after bpf_spin_unlock.
5418  */
5419 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5420                              bool is_lock)
5421 {
5422         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5423         struct bpf_verifier_state *cur = env->cur_state;
5424         bool is_const = tnum_is_const(reg->var_off);
5425         struct bpf_map *map = reg->map_ptr;
5426         u64 val = reg->var_off.value;
5427
5428         if (!is_const) {
5429                 verbose(env,
5430                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5431                         regno);
5432                 return -EINVAL;
5433         }
5434         if (!map->btf) {
5435                 verbose(env,
5436                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5437                         map->name);
5438                 return -EINVAL;
5439         }
5440         if (!map_value_has_spin_lock(map)) {
5441                 if (map->spin_lock_off == -E2BIG)
5442                         verbose(env,
5443                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5444                                 map->name);
5445                 else if (map->spin_lock_off == -ENOENT)
5446                         verbose(env,
5447                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5448                                 map->name);
5449                 else
5450                         verbose(env,
5451                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5452                                 map->name);
5453                 return -EINVAL;
5454         }
5455         if (map->spin_lock_off != val + reg->off) {
5456                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5457                         val + reg->off);
5458                 return -EINVAL;
5459         }
5460         if (is_lock) {
5461                 if (cur->active_spin_lock) {
5462                         verbose(env,
5463                                 "Locking two bpf_spin_locks are not allowed\n");
5464                         return -EINVAL;
5465                 }
5466                 cur->active_spin_lock = reg->id;
5467         } else {
5468                 if (!cur->active_spin_lock) {
5469                         verbose(env, "bpf_spin_unlock without taking a lock\n");
5470                         return -EINVAL;
5471                 }
5472                 if (cur->active_spin_lock != reg->id) {
5473                         verbose(env, "bpf_spin_unlock of different lock\n");
5474                         return -EINVAL;
5475                 }
5476                 cur->active_spin_lock = 0;
5477         }
5478         return 0;
5479 }
5480
5481 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5482                               struct bpf_call_arg_meta *meta)
5483 {
5484         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5485         bool is_const = tnum_is_const(reg->var_off);
5486         struct bpf_map *map = reg->map_ptr;
5487         u64 val = reg->var_off.value;
5488
5489         if (!is_const) {
5490                 verbose(env,
5491                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5492                         regno);
5493                 return -EINVAL;
5494         }
5495         if (!map->btf) {
5496                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5497                         map->name);
5498                 return -EINVAL;
5499         }
5500         if (!map_value_has_timer(map)) {
5501                 if (map->timer_off == -E2BIG)
5502                         verbose(env,
5503                                 "map '%s' has more than one 'struct bpf_timer'\n",
5504                                 map->name);
5505                 else if (map->timer_off == -ENOENT)
5506                         verbose(env,
5507                                 "map '%s' doesn't have 'struct bpf_timer'\n",
5508                                 map->name);
5509                 else
5510                         verbose(env,
5511                                 "map '%s' is not a struct type or bpf_timer is mangled\n",
5512                                 map->name);
5513                 return -EINVAL;
5514         }
5515         if (map->timer_off != val + reg->off) {
5516                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5517                         val + reg->off, map->timer_off);
5518                 return -EINVAL;
5519         }
5520         if (meta->map_ptr) {
5521                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5522                 return -EFAULT;
5523         }
5524         meta->map_uid = reg->map_uid;
5525         meta->map_ptr = map;
5526         return 0;
5527 }
5528
5529 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5530                              struct bpf_call_arg_meta *meta)
5531 {
5532         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5533         struct bpf_map_value_off_desc *off_desc;
5534         struct bpf_map *map_ptr = reg->map_ptr;
5535         u32 kptr_off;
5536         int ret;
5537
5538         if (!tnum_is_const(reg->var_off)) {
5539                 verbose(env,
5540                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5541                         regno);
5542                 return -EINVAL;
5543         }
5544         if (!map_ptr->btf) {
5545                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5546                         map_ptr->name);
5547                 return -EINVAL;
5548         }
5549         if (!map_value_has_kptrs(map_ptr)) {
5550                 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5551                 if (ret == -E2BIG)
5552                         verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5553                                 BPF_MAP_VALUE_OFF_MAX);
5554                 else if (ret == -EEXIST)
5555                         verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5556                 else
5557                         verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5558                 return -EINVAL;
5559         }
5560
5561         meta->map_ptr = map_ptr;
5562         kptr_off = reg->off + reg->var_off.value;
5563         off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5564         if (!off_desc) {
5565                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5566                 return -EACCES;
5567         }
5568         if (off_desc->type != BPF_KPTR_REF) {
5569                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5570                 return -EACCES;
5571         }
5572         meta->kptr_off_desc = off_desc;
5573         return 0;
5574 }
5575
5576 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5577 {
5578         return type == ARG_CONST_SIZE ||
5579                type == ARG_CONST_SIZE_OR_ZERO;
5580 }
5581
5582 static bool arg_type_is_release(enum bpf_arg_type type)
5583 {
5584         return type & OBJ_RELEASE;
5585 }
5586
5587 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5588 {
5589         return base_type(type) == ARG_PTR_TO_DYNPTR;
5590 }
5591
5592 static int int_ptr_type_to_size(enum bpf_arg_type type)
5593 {
5594         if (type == ARG_PTR_TO_INT)
5595                 return sizeof(u32);
5596         else if (type == ARG_PTR_TO_LONG)
5597                 return sizeof(u64);
5598
5599         return -EINVAL;
5600 }
5601
5602 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5603                                  const struct bpf_call_arg_meta *meta,
5604                                  enum bpf_arg_type *arg_type)
5605 {
5606         if (!meta->map_ptr) {
5607                 /* kernel subsystem misconfigured verifier */
5608                 verbose(env, "invalid map_ptr to access map->type\n");
5609                 return -EACCES;
5610         }
5611
5612         switch (meta->map_ptr->map_type) {
5613         case BPF_MAP_TYPE_SOCKMAP:
5614         case BPF_MAP_TYPE_SOCKHASH:
5615                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5616                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5617                 } else {
5618                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
5619                         return -EINVAL;
5620                 }
5621                 break;
5622         case BPF_MAP_TYPE_BLOOM_FILTER:
5623                 if (meta->func_id == BPF_FUNC_map_peek_elem)
5624                         *arg_type = ARG_PTR_TO_MAP_VALUE;
5625                 break;
5626         default:
5627                 break;
5628         }
5629         return 0;
5630 }
5631
5632 struct bpf_reg_types {
5633         const enum bpf_reg_type types[10];
5634         u32 *btf_id;
5635 };
5636
5637 static const struct bpf_reg_types map_key_value_types = {
5638         .types = {
5639                 PTR_TO_STACK,
5640                 PTR_TO_PACKET,
5641                 PTR_TO_PACKET_META,
5642                 PTR_TO_MAP_KEY,
5643                 PTR_TO_MAP_VALUE,
5644         },
5645 };
5646
5647 static const struct bpf_reg_types sock_types = {
5648         .types = {
5649                 PTR_TO_SOCK_COMMON,
5650                 PTR_TO_SOCKET,
5651                 PTR_TO_TCP_SOCK,
5652                 PTR_TO_XDP_SOCK,
5653         },
5654 };
5655
5656 #ifdef CONFIG_NET
5657 static const struct bpf_reg_types btf_id_sock_common_types = {
5658         .types = {
5659                 PTR_TO_SOCK_COMMON,
5660                 PTR_TO_SOCKET,
5661                 PTR_TO_TCP_SOCK,
5662                 PTR_TO_XDP_SOCK,
5663                 PTR_TO_BTF_ID,
5664         },
5665         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5666 };
5667 #endif
5668
5669 static const struct bpf_reg_types mem_types = {
5670         .types = {
5671                 PTR_TO_STACK,
5672                 PTR_TO_PACKET,
5673                 PTR_TO_PACKET_META,
5674                 PTR_TO_MAP_KEY,
5675                 PTR_TO_MAP_VALUE,
5676                 PTR_TO_MEM,
5677                 PTR_TO_MEM | MEM_ALLOC,
5678                 PTR_TO_BUF,
5679         },
5680 };
5681
5682 static const struct bpf_reg_types int_ptr_types = {
5683         .types = {
5684                 PTR_TO_STACK,
5685                 PTR_TO_PACKET,
5686                 PTR_TO_PACKET_META,
5687                 PTR_TO_MAP_KEY,
5688                 PTR_TO_MAP_VALUE,
5689         },
5690 };
5691
5692 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5693 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5694 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5695 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5696 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5697 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5698 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5699 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5700 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5701 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5702 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5703 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5704 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5705 static const struct bpf_reg_types dynptr_types = {
5706         .types = {
5707                 PTR_TO_STACK,
5708                 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5709         }
5710 };
5711
5712 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5713         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
5714         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
5715         [ARG_CONST_SIZE]                = &scalar_types,
5716         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
5717         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
5718         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
5719         [ARG_PTR_TO_CTX]                = &context_types,
5720         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
5721 #ifdef CONFIG_NET
5722         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5723 #endif
5724         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
5725         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
5726         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
5727         [ARG_PTR_TO_MEM]                = &mem_types,
5728         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
5729         [ARG_PTR_TO_INT]                = &int_ptr_types,
5730         [ARG_PTR_TO_LONG]               = &int_ptr_types,
5731         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
5732         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
5733         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
5734         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
5735         [ARG_PTR_TO_TIMER]              = &timer_types,
5736         [ARG_PTR_TO_KPTR]               = &kptr_types,
5737         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
5738 };
5739
5740 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5741                           enum bpf_arg_type arg_type,
5742                           const u32 *arg_btf_id,
5743                           struct bpf_call_arg_meta *meta)
5744 {
5745         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5746         enum bpf_reg_type expected, type = reg->type;
5747         const struct bpf_reg_types *compatible;
5748         int i, j;
5749
5750         compatible = compatible_reg_types[base_type(arg_type)];
5751         if (!compatible) {
5752                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5753                 return -EFAULT;
5754         }
5755
5756         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5757          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5758          *
5759          * Same for MAYBE_NULL:
5760          *
5761          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5762          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5763          *
5764          * Therefore we fold these flags depending on the arg_type before comparison.
5765          */
5766         if (arg_type & MEM_RDONLY)
5767                 type &= ~MEM_RDONLY;
5768         if (arg_type & PTR_MAYBE_NULL)
5769                 type &= ~PTR_MAYBE_NULL;
5770
5771         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5772                 expected = compatible->types[i];
5773                 if (expected == NOT_INIT)
5774                         break;
5775
5776                 if (type == expected)
5777                         goto found;
5778         }
5779
5780         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5781         for (j = 0; j + 1 < i; j++)
5782                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5783         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5784         return -EACCES;
5785
5786 found:
5787         if (reg->type == PTR_TO_BTF_ID) {
5788                 /* For bpf_sk_release, it needs to match against first member
5789                  * 'struct sock_common', hence make an exception for it. This
5790                  * allows bpf_sk_release to work for multiple socket types.
5791                  */
5792                 bool strict_type_match = arg_type_is_release(arg_type) &&
5793                                          meta->func_id != BPF_FUNC_sk_release;
5794
5795                 if (!arg_btf_id) {
5796                         if (!compatible->btf_id) {
5797                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5798                                 return -EFAULT;
5799                         }
5800                         arg_btf_id = compatible->btf_id;
5801                 }
5802
5803                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5804                         if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5805                                 return -EACCES;
5806                 } else {
5807                         if (arg_btf_id == BPF_PTR_POISON) {
5808                                 verbose(env, "verifier internal error:");
5809                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5810                                         regno);
5811                                 return -EACCES;
5812                         }
5813
5814                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5815                                                   btf_vmlinux, *arg_btf_id,
5816                                                   strict_type_match)) {
5817                                 verbose(env, "R%d is of type %s but %s is expected\n",
5818                                         regno, kernel_type_name(reg->btf, reg->btf_id),
5819                                         kernel_type_name(btf_vmlinux, *arg_btf_id));
5820                                 return -EACCES;
5821                         }
5822                 }
5823         }
5824
5825         return 0;
5826 }
5827
5828 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5829                            const struct bpf_reg_state *reg, int regno,
5830                            enum bpf_arg_type arg_type)
5831 {
5832         enum bpf_reg_type type = reg->type;
5833         bool fixed_off_ok = false;
5834
5835         switch ((u32)type) {
5836         /* Pointer types where reg offset is explicitly allowed: */
5837         case PTR_TO_STACK:
5838                 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5839                         verbose(env, "cannot pass in dynptr at an offset\n");
5840                         return -EINVAL;
5841                 }
5842                 fallthrough;
5843         case PTR_TO_PACKET:
5844         case PTR_TO_PACKET_META:
5845         case PTR_TO_MAP_KEY:
5846         case PTR_TO_MAP_VALUE:
5847         case PTR_TO_MEM:
5848         case PTR_TO_MEM | MEM_RDONLY:
5849         case PTR_TO_MEM | MEM_ALLOC:
5850         case PTR_TO_BUF:
5851         case PTR_TO_BUF | MEM_RDONLY:
5852         case SCALAR_VALUE:
5853                 /* Some of the argument types nevertheless require a
5854                  * zero register offset.
5855                  */
5856                 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5857                         return 0;
5858                 break;
5859         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5860          * fixed offset.
5861          */
5862         case PTR_TO_BTF_ID:
5863                 /* When referenced PTR_TO_BTF_ID is passed to release function,
5864                  * it's fixed offset must be 0. In the other cases, fixed offset
5865                  * can be non-zero.
5866                  */
5867                 if (arg_type_is_release(arg_type) && reg->off) {
5868                         verbose(env, "R%d must have zero offset when passed to release func\n",
5869                                 regno);
5870                         return -EINVAL;
5871                 }
5872                 /* For arg is release pointer, fixed_off_ok must be false, but
5873                  * we already checked and rejected reg->off != 0 above, so set
5874                  * to true to allow fixed offset for all other cases.
5875                  */
5876                 fixed_off_ok = true;
5877                 break;
5878         default:
5879                 break;
5880         }
5881         return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5882 }
5883
5884 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5885 {
5886         struct bpf_func_state *state = func(env, reg);
5887         int spi = get_spi(reg->off);
5888
5889         return state->stack[spi].spilled_ptr.id;
5890 }
5891
5892 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5893                           struct bpf_call_arg_meta *meta,
5894                           const struct bpf_func_proto *fn)
5895 {
5896         u32 regno = BPF_REG_1 + arg;
5897         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5898         enum bpf_arg_type arg_type = fn->arg_type[arg];
5899         enum bpf_reg_type type = reg->type;
5900         u32 *arg_btf_id = NULL;
5901         int err = 0;
5902
5903         if (arg_type == ARG_DONTCARE)
5904                 return 0;
5905
5906         err = check_reg_arg(env, regno, SRC_OP);
5907         if (err)
5908                 return err;
5909
5910         if (arg_type == ARG_ANYTHING) {
5911                 if (is_pointer_value(env, regno)) {
5912                         verbose(env, "R%d leaks addr into helper function\n",
5913                                 regno);
5914                         return -EACCES;
5915                 }
5916                 return 0;
5917         }
5918
5919         if (type_is_pkt_pointer(type) &&
5920             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5921                 verbose(env, "helper access to the packet is not allowed\n");
5922                 return -EACCES;
5923         }
5924
5925         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5926                 err = resolve_map_arg_type(env, meta, &arg_type);
5927                 if (err)
5928                         return err;
5929         }
5930
5931         if (register_is_null(reg) && type_may_be_null(arg_type))
5932                 /* A NULL register has a SCALAR_VALUE type, so skip
5933                  * type checking.
5934                  */
5935                 goto skip_type_check;
5936
5937         /* arg_btf_id and arg_size are in a union. */
5938         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5939                 arg_btf_id = fn->arg_btf_id[arg];
5940
5941         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5942         if (err)
5943                 return err;
5944
5945         err = check_func_arg_reg_off(env, reg, regno, arg_type);
5946         if (err)
5947                 return err;
5948
5949 skip_type_check:
5950         if (arg_type_is_release(arg_type)) {
5951                 if (arg_type_is_dynptr(arg_type)) {
5952                         struct bpf_func_state *state = func(env, reg);
5953                         int spi = get_spi(reg->off);
5954
5955                         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
5956                             !state->stack[spi].spilled_ptr.id) {
5957                                 verbose(env, "arg %d is an unacquired reference\n", regno);
5958                                 return -EINVAL;
5959                         }
5960                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
5961                         verbose(env, "R%d must be referenced when passed to release function\n",
5962                                 regno);
5963                         return -EINVAL;
5964                 }
5965                 if (meta->release_regno) {
5966                         verbose(env, "verifier internal error: more than one release argument\n");
5967                         return -EFAULT;
5968                 }
5969                 meta->release_regno = regno;
5970         }
5971
5972         if (reg->ref_obj_id) {
5973                 if (meta->ref_obj_id) {
5974                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5975                                 regno, reg->ref_obj_id,
5976                                 meta->ref_obj_id);
5977                         return -EFAULT;
5978                 }
5979                 meta->ref_obj_id = reg->ref_obj_id;
5980         }
5981
5982         switch (base_type(arg_type)) {
5983         case ARG_CONST_MAP_PTR:
5984                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5985                 if (meta->map_ptr) {
5986                         /* Use map_uid (which is unique id of inner map) to reject:
5987                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5988                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5989                          * if (inner_map1 && inner_map2) {
5990                          *     timer = bpf_map_lookup_elem(inner_map1);
5991                          *     if (timer)
5992                          *         // mismatch would have been allowed
5993                          *         bpf_timer_init(timer, inner_map2);
5994                          * }
5995                          *
5996                          * Comparing map_ptr is enough to distinguish normal and outer maps.
5997                          */
5998                         if (meta->map_ptr != reg->map_ptr ||
5999                             meta->map_uid != reg->map_uid) {
6000                                 verbose(env,
6001                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6002                                         meta->map_uid, reg->map_uid);
6003                                 return -EINVAL;
6004                         }
6005                 }
6006                 meta->map_ptr = reg->map_ptr;
6007                 meta->map_uid = reg->map_uid;
6008                 break;
6009         case ARG_PTR_TO_MAP_KEY:
6010                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6011                  * check that [key, key + map->key_size) are within
6012                  * stack limits and initialized
6013                  */
6014                 if (!meta->map_ptr) {
6015                         /* in function declaration map_ptr must come before
6016                          * map_key, so that it's verified and known before
6017                          * we have to check map_key here. Otherwise it means
6018                          * that kernel subsystem misconfigured verifier
6019                          */
6020                         verbose(env, "invalid map_ptr to access map->key\n");
6021                         return -EACCES;
6022                 }
6023                 err = check_helper_mem_access(env, regno,
6024                                               meta->map_ptr->key_size, false,
6025                                               NULL);
6026                 break;
6027         case ARG_PTR_TO_MAP_VALUE:
6028                 if (type_may_be_null(arg_type) && register_is_null(reg))
6029                         return 0;
6030
6031                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6032                  * check [value, value + map->value_size) validity
6033                  */
6034                 if (!meta->map_ptr) {
6035                         /* kernel subsystem misconfigured verifier */
6036                         verbose(env, "invalid map_ptr to access map->value\n");
6037                         return -EACCES;
6038                 }
6039                 meta->raw_mode = arg_type & MEM_UNINIT;
6040                 err = check_helper_mem_access(env, regno,
6041                                               meta->map_ptr->value_size, false,
6042                                               meta);
6043                 break;
6044         case ARG_PTR_TO_PERCPU_BTF_ID:
6045                 if (!reg->btf_id) {
6046                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6047                         return -EACCES;
6048                 }
6049                 meta->ret_btf = reg->btf;
6050                 meta->ret_btf_id = reg->btf_id;
6051                 break;
6052         case ARG_PTR_TO_SPIN_LOCK:
6053                 if (meta->func_id == BPF_FUNC_spin_lock) {
6054                         if (process_spin_lock(env, regno, true))
6055                                 return -EACCES;
6056                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6057                         if (process_spin_lock(env, regno, false))
6058                                 return -EACCES;
6059                 } else {
6060                         verbose(env, "verifier internal error\n");
6061                         return -EFAULT;
6062                 }
6063                 break;
6064         case ARG_PTR_TO_TIMER:
6065                 if (process_timer_func(env, regno, meta))
6066                         return -EACCES;
6067                 break;
6068         case ARG_PTR_TO_FUNC:
6069                 meta->subprogno = reg->subprogno;
6070                 break;
6071         case ARG_PTR_TO_MEM:
6072                 /* The access to this pointer is only checked when we hit the
6073                  * next is_mem_size argument below.
6074                  */
6075                 meta->raw_mode = arg_type & MEM_UNINIT;
6076                 if (arg_type & MEM_FIXED_SIZE) {
6077                         err = check_helper_mem_access(env, regno,
6078                                                       fn->arg_size[arg], false,
6079                                                       meta);
6080                 }
6081                 break;
6082         case ARG_CONST_SIZE:
6083                 err = check_mem_size_reg(env, reg, regno, false, meta);
6084                 break;
6085         case ARG_CONST_SIZE_OR_ZERO:
6086                 err = check_mem_size_reg(env, reg, regno, true, meta);
6087                 break;
6088         case ARG_PTR_TO_DYNPTR:
6089                 /* We only need to check for initialized / uninitialized helper
6090                  * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6091                  * assumption is that if it is, that a helper function
6092                  * initialized the dynptr on behalf of the BPF program.
6093                  */
6094                 if (base_type(reg->type) == PTR_TO_DYNPTR)
6095                         break;
6096                 if (arg_type & MEM_UNINIT) {
6097                         if (!is_dynptr_reg_valid_uninit(env, reg)) {
6098                                 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6099                                 return -EINVAL;
6100                         }
6101
6102                         /* We only support one dynptr being uninitialized at the moment,
6103                          * which is sufficient for the helper functions we have right now.
6104                          */
6105                         if (meta->uninit_dynptr_regno) {
6106                                 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6107                                 return -EFAULT;
6108                         }
6109
6110                         meta->uninit_dynptr_regno = regno;
6111                 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6112                         verbose(env,
6113                                 "Expected an initialized dynptr as arg #%d\n",
6114                                 arg + 1);
6115                         return -EINVAL;
6116                 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6117                         const char *err_extra = "";
6118
6119                         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6120                         case DYNPTR_TYPE_LOCAL:
6121                                 err_extra = "local";
6122                                 break;
6123                         case DYNPTR_TYPE_RINGBUF:
6124                                 err_extra = "ringbuf";
6125                                 break;
6126                         default:
6127                                 err_extra = "<unknown>";
6128                                 break;
6129                         }
6130                         verbose(env,
6131                                 "Expected a dynptr of type %s as arg #%d\n",
6132                                 err_extra, arg + 1);
6133                         return -EINVAL;
6134                 }
6135                 break;
6136         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6137                 if (!tnum_is_const(reg->var_off)) {
6138                         verbose(env, "R%d is not a known constant'\n",
6139                                 regno);
6140                         return -EACCES;
6141                 }
6142                 meta->mem_size = reg->var_off.value;
6143                 err = mark_chain_precision(env, regno);
6144                 if (err)
6145                         return err;
6146                 break;
6147         case ARG_PTR_TO_INT:
6148         case ARG_PTR_TO_LONG:
6149         {
6150                 int size = int_ptr_type_to_size(arg_type);
6151
6152                 err = check_helper_mem_access(env, regno, size, false, meta);
6153                 if (err)
6154                         return err;
6155                 err = check_ptr_alignment(env, reg, 0, size, true);
6156                 break;
6157         }
6158         case ARG_PTR_TO_CONST_STR:
6159         {
6160                 struct bpf_map *map = reg->map_ptr;
6161                 int map_off;
6162                 u64 map_addr;
6163                 char *str_ptr;
6164
6165                 if (!bpf_map_is_rdonly(map)) {
6166                         verbose(env, "R%d does not point to a readonly map'\n", regno);
6167                         return -EACCES;
6168                 }
6169
6170                 if (!tnum_is_const(reg->var_off)) {
6171                         verbose(env, "R%d is not a constant address'\n", regno);
6172                         return -EACCES;
6173                 }
6174
6175                 if (!map->ops->map_direct_value_addr) {
6176                         verbose(env, "no direct value access support for this map type\n");
6177                         return -EACCES;
6178                 }
6179
6180                 err = check_map_access(env, regno, reg->off,
6181                                        map->value_size - reg->off, false,
6182                                        ACCESS_HELPER);
6183                 if (err)
6184                         return err;
6185
6186                 map_off = reg->off + reg->var_off.value;
6187                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6188                 if (err) {
6189                         verbose(env, "direct value access on string failed\n");
6190                         return err;
6191                 }
6192
6193                 str_ptr = (char *)(long)(map_addr);
6194                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6195                         verbose(env, "string is not zero-terminated\n");
6196                         return -EINVAL;
6197                 }
6198                 break;
6199         }
6200         case ARG_PTR_TO_KPTR:
6201                 if (process_kptr_func(env, regno, meta))
6202                         return -EACCES;
6203                 break;
6204         }
6205
6206         return err;
6207 }
6208
6209 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6210 {
6211         enum bpf_attach_type eatype = env->prog->expected_attach_type;
6212         enum bpf_prog_type type = resolve_prog_type(env->prog);
6213
6214         if (func_id != BPF_FUNC_map_update_elem)
6215                 return false;
6216
6217         /* It's not possible to get access to a locked struct sock in these
6218          * contexts, so updating is safe.
6219          */
6220         switch (type) {
6221         case BPF_PROG_TYPE_TRACING:
6222                 if (eatype == BPF_TRACE_ITER)
6223                         return true;
6224                 break;
6225         case BPF_PROG_TYPE_SOCKET_FILTER:
6226         case BPF_PROG_TYPE_SCHED_CLS:
6227         case BPF_PROG_TYPE_SCHED_ACT:
6228         case BPF_PROG_TYPE_XDP:
6229         case BPF_PROG_TYPE_SK_REUSEPORT:
6230         case BPF_PROG_TYPE_FLOW_DISSECTOR:
6231         case BPF_PROG_TYPE_SK_LOOKUP:
6232                 return true;
6233         default:
6234                 break;
6235         }
6236
6237         verbose(env, "cannot update sockmap in this context\n");
6238         return false;
6239 }
6240
6241 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6242 {
6243         return env->prog->jit_requested &&
6244                bpf_jit_supports_subprog_tailcalls();
6245 }
6246
6247 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6248                                         struct bpf_map *map, int func_id)
6249 {
6250         if (!map)
6251                 return 0;
6252
6253         /* We need a two way check, first is from map perspective ... */
6254         switch (map->map_type) {
6255         case BPF_MAP_TYPE_PROG_ARRAY:
6256                 if (func_id != BPF_FUNC_tail_call)
6257                         goto error;
6258                 break;
6259         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6260                 if (func_id != BPF_FUNC_perf_event_read &&
6261                     func_id != BPF_FUNC_perf_event_output &&
6262                     func_id != BPF_FUNC_skb_output &&
6263                     func_id != BPF_FUNC_perf_event_read_value &&
6264                     func_id != BPF_FUNC_xdp_output)
6265                         goto error;
6266                 break;
6267         case BPF_MAP_TYPE_RINGBUF:
6268                 if (func_id != BPF_FUNC_ringbuf_output &&
6269                     func_id != BPF_FUNC_ringbuf_reserve &&
6270                     func_id != BPF_FUNC_ringbuf_query &&
6271                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6272                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6273                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
6274                         goto error;
6275                 break;
6276         case BPF_MAP_TYPE_USER_RINGBUF:
6277                 if (func_id != BPF_FUNC_user_ringbuf_drain)
6278                         goto error;
6279                 break;
6280         case BPF_MAP_TYPE_STACK_TRACE:
6281                 if (func_id != BPF_FUNC_get_stackid)
6282                         goto error;
6283                 break;
6284         case BPF_MAP_TYPE_CGROUP_ARRAY:
6285                 if (func_id != BPF_FUNC_skb_under_cgroup &&
6286                     func_id != BPF_FUNC_current_task_under_cgroup)
6287                         goto error;
6288                 break;
6289         case BPF_MAP_TYPE_CGROUP_STORAGE:
6290         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6291                 if (func_id != BPF_FUNC_get_local_storage)
6292                         goto error;
6293                 break;
6294         case BPF_MAP_TYPE_DEVMAP:
6295         case BPF_MAP_TYPE_DEVMAP_HASH:
6296                 if (func_id != BPF_FUNC_redirect_map &&
6297                     func_id != BPF_FUNC_map_lookup_elem)
6298                         goto error;
6299                 break;
6300         /* Restrict bpf side of cpumap and xskmap, open when use-cases
6301          * appear.
6302          */
6303         case BPF_MAP_TYPE_CPUMAP:
6304                 if (func_id != BPF_FUNC_redirect_map)
6305                         goto error;
6306                 break;
6307         case BPF_MAP_TYPE_XSKMAP:
6308                 if (func_id != BPF_FUNC_redirect_map &&
6309                     func_id != BPF_FUNC_map_lookup_elem)
6310                         goto error;
6311                 break;
6312         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6313         case BPF_MAP_TYPE_HASH_OF_MAPS:
6314                 if (func_id != BPF_FUNC_map_lookup_elem)
6315                         goto error;
6316                 break;
6317         case BPF_MAP_TYPE_SOCKMAP:
6318                 if (func_id != BPF_FUNC_sk_redirect_map &&
6319                     func_id != BPF_FUNC_sock_map_update &&
6320                     func_id != BPF_FUNC_map_delete_elem &&
6321                     func_id != BPF_FUNC_msg_redirect_map &&
6322                     func_id != BPF_FUNC_sk_select_reuseport &&
6323                     func_id != BPF_FUNC_map_lookup_elem &&
6324                     !may_update_sockmap(env, func_id))
6325                         goto error;
6326                 break;
6327         case BPF_MAP_TYPE_SOCKHASH:
6328                 if (func_id != BPF_FUNC_sk_redirect_hash &&
6329                     func_id != BPF_FUNC_sock_hash_update &&
6330                     func_id != BPF_FUNC_map_delete_elem &&
6331                     func_id != BPF_FUNC_msg_redirect_hash &&
6332                     func_id != BPF_FUNC_sk_select_reuseport &&
6333                     func_id != BPF_FUNC_map_lookup_elem &&
6334                     !may_update_sockmap(env, func_id))
6335                         goto error;
6336                 break;
6337         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6338                 if (func_id != BPF_FUNC_sk_select_reuseport)
6339                         goto error;
6340                 break;
6341         case BPF_MAP_TYPE_QUEUE:
6342         case BPF_MAP_TYPE_STACK:
6343                 if (func_id != BPF_FUNC_map_peek_elem &&
6344                     func_id != BPF_FUNC_map_pop_elem &&
6345                     func_id != BPF_FUNC_map_push_elem)
6346                         goto error;
6347                 break;
6348         case BPF_MAP_TYPE_SK_STORAGE:
6349                 if (func_id != BPF_FUNC_sk_storage_get &&
6350                     func_id != BPF_FUNC_sk_storage_delete)
6351                         goto error;
6352                 break;
6353         case BPF_MAP_TYPE_INODE_STORAGE:
6354                 if (func_id != BPF_FUNC_inode_storage_get &&
6355                     func_id != BPF_FUNC_inode_storage_delete)
6356                         goto error;
6357                 break;
6358         case BPF_MAP_TYPE_TASK_STORAGE:
6359                 if (func_id != BPF_FUNC_task_storage_get &&
6360                     func_id != BPF_FUNC_task_storage_delete)
6361                         goto error;
6362                 break;
6363         case BPF_MAP_TYPE_BLOOM_FILTER:
6364                 if (func_id != BPF_FUNC_map_peek_elem &&
6365                     func_id != BPF_FUNC_map_push_elem)
6366                         goto error;
6367                 break;
6368         default:
6369                 break;
6370         }
6371
6372         /* ... and second from the function itself. */
6373         switch (func_id) {
6374         case BPF_FUNC_tail_call:
6375                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6376                         goto error;
6377                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6378                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6379                         return -EINVAL;
6380                 }
6381                 break;
6382         case BPF_FUNC_perf_event_read:
6383         case BPF_FUNC_perf_event_output:
6384         case BPF_FUNC_perf_event_read_value:
6385         case BPF_FUNC_skb_output:
6386         case BPF_FUNC_xdp_output:
6387                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6388                         goto error;
6389                 break;
6390         case BPF_FUNC_ringbuf_output:
6391         case BPF_FUNC_ringbuf_reserve:
6392         case BPF_FUNC_ringbuf_query:
6393         case BPF_FUNC_ringbuf_reserve_dynptr:
6394         case BPF_FUNC_ringbuf_submit_dynptr:
6395         case BPF_FUNC_ringbuf_discard_dynptr:
6396                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6397                         goto error;
6398                 break;
6399         case BPF_FUNC_user_ringbuf_drain:
6400                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6401                         goto error;
6402                 break;
6403         case BPF_FUNC_get_stackid:
6404                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6405                         goto error;
6406                 break;
6407         case BPF_FUNC_current_task_under_cgroup:
6408         case BPF_FUNC_skb_under_cgroup:
6409                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6410                         goto error;
6411                 break;
6412         case BPF_FUNC_redirect_map:
6413                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6414                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6415                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
6416                     map->map_type != BPF_MAP_TYPE_XSKMAP)
6417                         goto error;
6418                 break;
6419         case BPF_FUNC_sk_redirect_map:
6420         case BPF_FUNC_msg_redirect_map:
6421         case BPF_FUNC_sock_map_update:
6422                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6423                         goto error;
6424                 break;
6425         case BPF_FUNC_sk_redirect_hash:
6426         case BPF_FUNC_msg_redirect_hash:
6427         case BPF_FUNC_sock_hash_update:
6428                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6429                         goto error;
6430                 break;
6431         case BPF_FUNC_get_local_storage:
6432                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6433                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6434                         goto error;
6435                 break;
6436         case BPF_FUNC_sk_select_reuseport:
6437                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6438                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6439                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
6440                         goto error;
6441                 break;
6442         case BPF_FUNC_map_pop_elem:
6443                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6444                     map->map_type != BPF_MAP_TYPE_STACK)
6445                         goto error;
6446                 break;
6447         case BPF_FUNC_map_peek_elem:
6448         case BPF_FUNC_map_push_elem:
6449                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6450                     map->map_type != BPF_MAP_TYPE_STACK &&
6451                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6452                         goto error;
6453                 break;
6454         case BPF_FUNC_map_lookup_percpu_elem:
6455                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6456                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6457                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6458                         goto error;
6459                 break;
6460         case BPF_FUNC_sk_storage_get:
6461         case BPF_FUNC_sk_storage_delete:
6462                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6463                         goto error;
6464                 break;
6465         case BPF_FUNC_inode_storage_get:
6466         case BPF_FUNC_inode_storage_delete:
6467                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6468                         goto error;
6469                 break;
6470         case BPF_FUNC_task_storage_get:
6471         case BPF_FUNC_task_storage_delete:
6472                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6473                         goto error;
6474                 break;
6475         default:
6476                 break;
6477         }
6478
6479         return 0;
6480 error:
6481         verbose(env, "cannot pass map_type %d into func %s#%d\n",
6482                 map->map_type, func_id_name(func_id), func_id);
6483         return -EINVAL;
6484 }
6485
6486 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6487 {
6488         int count = 0;
6489
6490         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6491                 count++;
6492         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6493                 count++;
6494         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6495                 count++;
6496         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6497                 count++;
6498         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6499                 count++;
6500
6501         /* We only support one arg being in raw mode at the moment,
6502          * which is sufficient for the helper functions we have
6503          * right now.
6504          */
6505         return count <= 1;
6506 }
6507
6508 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6509 {
6510         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6511         bool has_size = fn->arg_size[arg] != 0;
6512         bool is_next_size = false;
6513
6514         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6515                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6516
6517         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6518                 return is_next_size;
6519
6520         return has_size == is_next_size || is_next_size == is_fixed;
6521 }
6522
6523 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6524 {
6525         /* bpf_xxx(..., buf, len) call will access 'len'
6526          * bytes from memory 'buf'. Both arg types need
6527          * to be paired, so make sure there's no buggy
6528          * helper function specification.
6529          */
6530         if (arg_type_is_mem_size(fn->arg1_type) ||
6531             check_args_pair_invalid(fn, 0) ||
6532             check_args_pair_invalid(fn, 1) ||
6533             check_args_pair_invalid(fn, 2) ||
6534             check_args_pair_invalid(fn, 3) ||
6535             check_args_pair_invalid(fn, 4))
6536                 return false;
6537
6538         return true;
6539 }
6540
6541 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6542 {
6543         int i;
6544
6545         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6546                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6547                         return false;
6548
6549                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6550                     /* arg_btf_id and arg_size are in a union. */
6551                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6552                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6553                         return false;
6554         }
6555
6556         return true;
6557 }
6558
6559 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6560 {
6561         return check_raw_mode_ok(fn) &&
6562                check_arg_pair_ok(fn) &&
6563                check_btf_id_ok(fn) ? 0 : -EINVAL;
6564 }
6565
6566 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6567  * are now invalid, so turn them into unknown SCALAR_VALUE.
6568  */
6569 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6570 {
6571         struct bpf_func_state *state;
6572         struct bpf_reg_state *reg;
6573
6574         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6575                 if (reg_is_pkt_pointer_any(reg))
6576                         __mark_reg_unknown(env, reg);
6577         }));
6578 }
6579
6580 enum {
6581         AT_PKT_END = -1,
6582         BEYOND_PKT_END = -2,
6583 };
6584
6585 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6586 {
6587         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6588         struct bpf_reg_state *reg = &state->regs[regn];
6589
6590         if (reg->type != PTR_TO_PACKET)
6591                 /* PTR_TO_PACKET_META is not supported yet */
6592                 return;
6593
6594         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6595          * How far beyond pkt_end it goes is unknown.
6596          * if (!range_open) it's the case of pkt >= pkt_end
6597          * if (range_open) it's the case of pkt > pkt_end
6598          * hence this pointer is at least 1 byte bigger than pkt_end
6599          */
6600         if (range_open)
6601                 reg->range = BEYOND_PKT_END;
6602         else
6603                 reg->range = AT_PKT_END;
6604 }
6605
6606 /* The pointer with the specified id has released its reference to kernel
6607  * resources. Identify all copies of the same pointer and clear the reference.
6608  */
6609 static int release_reference(struct bpf_verifier_env *env,
6610                              int ref_obj_id)
6611 {
6612         struct bpf_func_state *state;
6613         struct bpf_reg_state *reg;
6614         int err;
6615
6616         err = release_reference_state(cur_func(env), ref_obj_id);
6617         if (err)
6618                 return err;
6619
6620         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6621                 if (reg->ref_obj_id == ref_obj_id)
6622                         __mark_reg_unknown(env, reg);
6623         }));
6624
6625         return 0;
6626 }
6627
6628 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6629                                     struct bpf_reg_state *regs)
6630 {
6631         int i;
6632
6633         /* after the call registers r0 - r5 were scratched */
6634         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6635                 mark_reg_not_init(env, regs, caller_saved[i]);
6636                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6637         }
6638 }
6639
6640 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6641                                    struct bpf_func_state *caller,
6642                                    struct bpf_func_state *callee,
6643                                    int insn_idx);
6644
6645 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6646                              int *insn_idx, int subprog,
6647                              set_callee_state_fn set_callee_state_cb)
6648 {
6649         struct bpf_verifier_state *state = env->cur_state;
6650         struct bpf_func_info_aux *func_info_aux;
6651         struct bpf_func_state *caller, *callee;
6652         int err;
6653         bool is_global = false;
6654
6655         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6656                 verbose(env, "the call stack of %d frames is too deep\n",
6657                         state->curframe + 2);
6658                 return -E2BIG;
6659         }
6660
6661         caller = state->frame[state->curframe];
6662         if (state->frame[state->curframe + 1]) {
6663                 verbose(env, "verifier bug. Frame %d already allocated\n",
6664                         state->curframe + 1);
6665                 return -EFAULT;
6666         }
6667
6668         func_info_aux = env->prog->aux->func_info_aux;
6669         if (func_info_aux)
6670                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6671         err = btf_check_subprog_call(env, subprog, caller->regs);
6672         if (err == -EFAULT)
6673                 return err;
6674         if (is_global) {
6675                 if (err) {
6676                         verbose(env, "Caller passes invalid args into func#%d\n",
6677                                 subprog);
6678                         return err;
6679                 } else {
6680                         if (env->log.level & BPF_LOG_LEVEL)
6681                                 verbose(env,
6682                                         "Func#%d is global and valid. Skipping.\n",
6683                                         subprog);
6684                         clear_caller_saved_regs(env, caller->regs);
6685
6686                         /* All global functions return a 64-bit SCALAR_VALUE */
6687                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
6688                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6689
6690                         /* continue with next insn after call */
6691                         return 0;
6692                 }
6693         }
6694
6695         if (insn->code == (BPF_JMP | BPF_CALL) &&
6696             insn->src_reg == 0 &&
6697             insn->imm == BPF_FUNC_timer_set_callback) {
6698                 struct bpf_verifier_state *async_cb;
6699
6700                 /* there is no real recursion here. timer callbacks are async */
6701                 env->subprog_info[subprog].is_async_cb = true;
6702                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6703                                          *insn_idx, subprog);
6704                 if (!async_cb)
6705                         return -EFAULT;
6706                 callee = async_cb->frame[0];
6707                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6708
6709                 /* Convert bpf_timer_set_callback() args into timer callback args */
6710                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6711                 if (err)
6712                         return err;
6713
6714                 clear_caller_saved_regs(env, caller->regs);
6715                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6716                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6717                 /* continue with next insn after call */
6718                 return 0;
6719         }
6720
6721         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6722         if (!callee)
6723                 return -ENOMEM;
6724         state->frame[state->curframe + 1] = callee;
6725
6726         /* callee cannot access r0, r6 - r9 for reading and has to write
6727          * into its own stack before reading from it.
6728          * callee can read/write into caller's stack
6729          */
6730         init_func_state(env, callee,
6731                         /* remember the callsite, it will be used by bpf_exit */
6732                         *insn_idx /* callsite */,
6733                         state->curframe + 1 /* frameno within this callchain */,
6734                         subprog /* subprog number within this prog */);
6735
6736         /* Transfer references to the callee */
6737         err = copy_reference_state(callee, caller);
6738         if (err)
6739                 return err;
6740
6741         err = set_callee_state_cb(env, caller, callee, *insn_idx);
6742         if (err)
6743                 return err;
6744
6745         clear_caller_saved_regs(env, caller->regs);
6746
6747         /* only increment it after check_reg_arg() finished */
6748         state->curframe++;
6749
6750         /* and go analyze first insn of the callee */
6751         *insn_idx = env->subprog_info[subprog].start - 1;
6752
6753         if (env->log.level & BPF_LOG_LEVEL) {
6754                 verbose(env, "caller:\n");
6755                 print_verifier_state(env, caller, true);
6756                 verbose(env, "callee:\n");
6757                 print_verifier_state(env, callee, true);
6758         }
6759         return 0;
6760 }
6761
6762 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6763                                    struct bpf_func_state *caller,
6764                                    struct bpf_func_state *callee)
6765 {
6766         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6767          *      void *callback_ctx, u64 flags);
6768          * callback_fn(struct bpf_map *map, void *key, void *value,
6769          *      void *callback_ctx);
6770          */
6771         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6772
6773         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6774         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6775         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6776
6777         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6778         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6779         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6780
6781         /* pointer to stack or null */
6782         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6783
6784         /* unused */
6785         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6786         return 0;
6787 }
6788
6789 static int set_callee_state(struct bpf_verifier_env *env,
6790                             struct bpf_func_state *caller,
6791                             struct bpf_func_state *callee, int insn_idx)
6792 {
6793         int i;
6794
6795         /* copy r1 - r5 args that callee can access.  The copy includes parent
6796          * pointers, which connects us up to the liveness chain
6797          */
6798         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6799                 callee->regs[i] = caller->regs[i];
6800         return 0;
6801 }
6802
6803 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6804                            int *insn_idx)
6805 {
6806         int subprog, target_insn;
6807
6808         target_insn = *insn_idx + insn->imm + 1;
6809         subprog = find_subprog(env, target_insn);
6810         if (subprog < 0) {
6811                 verbose(env, "verifier bug. No program starts at insn %d\n",
6812                         target_insn);
6813                 return -EFAULT;
6814         }
6815
6816         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6817 }
6818
6819 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6820                                        struct bpf_func_state *caller,
6821                                        struct bpf_func_state *callee,
6822                                        int insn_idx)
6823 {
6824         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6825         struct bpf_map *map;
6826         int err;
6827
6828         if (bpf_map_ptr_poisoned(insn_aux)) {
6829                 verbose(env, "tail_call abusing map_ptr\n");
6830                 return -EINVAL;
6831         }
6832
6833         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6834         if (!map->ops->map_set_for_each_callback_args ||
6835             !map->ops->map_for_each_callback) {
6836                 verbose(env, "callback function not allowed for map\n");
6837                 return -ENOTSUPP;
6838         }
6839
6840         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6841         if (err)
6842                 return err;
6843
6844         callee->in_callback_fn = true;
6845         callee->callback_ret_range = tnum_range(0, 1);
6846         return 0;
6847 }
6848
6849 static int set_loop_callback_state(struct bpf_verifier_env *env,
6850                                    struct bpf_func_state *caller,
6851                                    struct bpf_func_state *callee,
6852                                    int insn_idx)
6853 {
6854         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6855          *          u64 flags);
6856          * callback_fn(u32 index, void *callback_ctx);
6857          */
6858         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6859         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6860
6861         /* unused */
6862         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6863         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6864         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6865
6866         callee->in_callback_fn = true;
6867         callee->callback_ret_range = tnum_range(0, 1);
6868         return 0;
6869 }
6870
6871 static int set_timer_callback_state(struct bpf_verifier_env *env,
6872                                     struct bpf_func_state *caller,
6873                                     struct bpf_func_state *callee,
6874                                     int insn_idx)
6875 {
6876         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6877
6878         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6879          * callback_fn(struct bpf_map *map, void *key, void *value);
6880          */
6881         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6882         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6883         callee->regs[BPF_REG_1].map_ptr = map_ptr;
6884
6885         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6886         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6887         callee->regs[BPF_REG_2].map_ptr = map_ptr;
6888
6889         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6890         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6891         callee->regs[BPF_REG_3].map_ptr = map_ptr;
6892
6893         /* unused */
6894         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6895         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6896         callee->in_async_callback_fn = true;
6897         callee->callback_ret_range = tnum_range(0, 1);
6898         return 0;
6899 }
6900
6901 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6902                                        struct bpf_func_state *caller,
6903                                        struct bpf_func_state *callee,
6904                                        int insn_idx)
6905 {
6906         /* bpf_find_vma(struct task_struct *task, u64 addr,
6907          *               void *callback_fn, void *callback_ctx, u64 flags)
6908          * (callback_fn)(struct task_struct *task,
6909          *               struct vm_area_struct *vma, void *callback_ctx);
6910          */
6911         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6912
6913         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6914         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6915         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6916         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6917
6918         /* pointer to stack or null */
6919         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6920
6921         /* unused */
6922         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6923         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6924         callee->in_callback_fn = true;
6925         callee->callback_ret_range = tnum_range(0, 1);
6926         return 0;
6927 }
6928
6929 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
6930                                            struct bpf_func_state *caller,
6931                                            struct bpf_func_state *callee,
6932                                            int insn_idx)
6933 {
6934         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
6935          *                        callback_ctx, u64 flags);
6936          * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
6937          */
6938         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
6939         callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
6940         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6941         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6942
6943         /* unused */
6944         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6945         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6946         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6947
6948         callee->in_callback_fn = true;
6949         return 0;
6950 }
6951
6952 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6953 {
6954         struct bpf_verifier_state *state = env->cur_state;
6955         struct bpf_func_state *caller, *callee;
6956         struct bpf_reg_state *r0;
6957         int err;
6958
6959         callee = state->frame[state->curframe];
6960         r0 = &callee->regs[BPF_REG_0];
6961         if (r0->type == PTR_TO_STACK) {
6962                 /* technically it's ok to return caller's stack pointer
6963                  * (or caller's caller's pointer) back to the caller,
6964                  * since these pointers are valid. Only current stack
6965                  * pointer will be invalid as soon as function exits,
6966                  * but let's be conservative
6967                  */
6968                 verbose(env, "cannot return stack pointer to the caller\n");
6969                 return -EINVAL;
6970         }
6971
6972         state->curframe--;
6973         caller = state->frame[state->curframe];
6974         if (callee->in_callback_fn) {
6975                 /* enforce R0 return value range [0, 1]. */
6976                 struct tnum range = callee->callback_ret_range;
6977
6978                 if (r0->type != SCALAR_VALUE) {
6979                         verbose(env, "R0 not a scalar value\n");
6980                         return -EACCES;
6981                 }
6982                 if (!tnum_in(range, r0->var_off)) {
6983                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6984                         return -EINVAL;
6985                 }
6986         } else {
6987                 /* return to the caller whatever r0 had in the callee */
6988                 caller->regs[BPF_REG_0] = *r0;
6989         }
6990
6991         /* callback_fn frame should have released its own additions to parent's
6992          * reference state at this point, or check_reference_leak would
6993          * complain, hence it must be the same as the caller. There is no need
6994          * to copy it back.
6995          */
6996         if (!callee->in_callback_fn) {
6997                 /* Transfer references to the caller */
6998                 err = copy_reference_state(caller, callee);
6999                 if (err)
7000                         return err;
7001         }
7002
7003         *insn_idx = callee->callsite + 1;
7004         if (env->log.level & BPF_LOG_LEVEL) {
7005                 verbose(env, "returning from callee:\n");
7006                 print_verifier_state(env, callee, true);
7007                 verbose(env, "to caller at %d:\n", *insn_idx);
7008                 print_verifier_state(env, caller, true);
7009         }
7010         /* clear everything in the callee */
7011         free_func_state(callee);
7012         state->frame[state->curframe + 1] = NULL;
7013         return 0;
7014 }
7015
7016 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7017                                    int func_id,
7018                                    struct bpf_call_arg_meta *meta)
7019 {
7020         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7021
7022         if (ret_type != RET_INTEGER ||
7023             (func_id != BPF_FUNC_get_stack &&
7024              func_id != BPF_FUNC_get_task_stack &&
7025              func_id != BPF_FUNC_probe_read_str &&
7026              func_id != BPF_FUNC_probe_read_kernel_str &&
7027              func_id != BPF_FUNC_probe_read_user_str))
7028                 return;
7029
7030         ret_reg->smax_value = meta->msize_max_value;
7031         ret_reg->s32_max_value = meta->msize_max_value;
7032         ret_reg->smin_value = -MAX_ERRNO;
7033         ret_reg->s32_min_value = -MAX_ERRNO;
7034         reg_bounds_sync(ret_reg);
7035 }
7036
7037 static int
7038 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7039                 int func_id, int insn_idx)
7040 {
7041         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7042         struct bpf_map *map = meta->map_ptr;
7043
7044         if (func_id != BPF_FUNC_tail_call &&
7045             func_id != BPF_FUNC_map_lookup_elem &&
7046             func_id != BPF_FUNC_map_update_elem &&
7047             func_id != BPF_FUNC_map_delete_elem &&
7048             func_id != BPF_FUNC_map_push_elem &&
7049             func_id != BPF_FUNC_map_pop_elem &&
7050             func_id != BPF_FUNC_map_peek_elem &&
7051             func_id != BPF_FUNC_for_each_map_elem &&
7052             func_id != BPF_FUNC_redirect_map &&
7053             func_id != BPF_FUNC_map_lookup_percpu_elem)
7054                 return 0;
7055
7056         if (map == NULL) {
7057                 verbose(env, "kernel subsystem misconfigured verifier\n");
7058                 return -EINVAL;
7059         }
7060
7061         /* In case of read-only, some additional restrictions
7062          * need to be applied in order to prevent altering the
7063          * state of the map from program side.
7064          */
7065         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7066             (func_id == BPF_FUNC_map_delete_elem ||
7067              func_id == BPF_FUNC_map_update_elem ||
7068              func_id == BPF_FUNC_map_push_elem ||
7069              func_id == BPF_FUNC_map_pop_elem)) {
7070                 verbose(env, "write into map forbidden\n");
7071                 return -EACCES;
7072         }
7073
7074         if (!BPF_MAP_PTR(aux->map_ptr_state))
7075                 bpf_map_ptr_store(aux, meta->map_ptr,
7076                                   !meta->map_ptr->bypass_spec_v1);
7077         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7078                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7079                                   !meta->map_ptr->bypass_spec_v1);
7080         return 0;
7081 }
7082
7083 static int
7084 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7085                 int func_id, int insn_idx)
7086 {
7087         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7088         struct bpf_reg_state *regs = cur_regs(env), *reg;
7089         struct bpf_map *map = meta->map_ptr;
7090         u64 val, max;
7091         int err;
7092
7093         if (func_id != BPF_FUNC_tail_call)
7094                 return 0;
7095         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7096                 verbose(env, "kernel subsystem misconfigured verifier\n");
7097                 return -EINVAL;
7098         }
7099
7100         reg = &regs[BPF_REG_3];
7101         val = reg->var_off.value;
7102         max = map->max_entries;
7103
7104         if (!(register_is_const(reg) && val < max)) {
7105                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7106                 return 0;
7107         }
7108
7109         err = mark_chain_precision(env, BPF_REG_3);
7110         if (err)
7111                 return err;
7112         if (bpf_map_key_unseen(aux))
7113                 bpf_map_key_store(aux, val);
7114         else if (!bpf_map_key_poisoned(aux) &&
7115                   bpf_map_key_immediate(aux) != val)
7116                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7117         return 0;
7118 }
7119
7120 static int check_reference_leak(struct bpf_verifier_env *env)
7121 {
7122         struct bpf_func_state *state = cur_func(env);
7123         bool refs_lingering = false;
7124         int i;
7125
7126         if (state->frameno && !state->in_callback_fn)
7127                 return 0;
7128
7129         for (i = 0; i < state->acquired_refs; i++) {
7130                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7131                         continue;
7132                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7133                         state->refs[i].id, state->refs[i].insn_idx);
7134                 refs_lingering = true;
7135         }
7136         return refs_lingering ? -EINVAL : 0;
7137 }
7138
7139 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7140                                    struct bpf_reg_state *regs)
7141 {
7142         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7143         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7144         struct bpf_map *fmt_map = fmt_reg->map_ptr;
7145         int err, fmt_map_off, num_args;
7146         u64 fmt_addr;
7147         char *fmt;
7148
7149         /* data must be an array of u64 */
7150         if (data_len_reg->var_off.value % 8)
7151                 return -EINVAL;
7152         num_args = data_len_reg->var_off.value / 8;
7153
7154         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7155          * and map_direct_value_addr is set.
7156          */
7157         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7158         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7159                                                   fmt_map_off);
7160         if (err) {
7161                 verbose(env, "verifier bug\n");
7162                 return -EFAULT;
7163         }
7164         fmt = (char *)(long)fmt_addr + fmt_map_off;
7165
7166         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7167          * can focus on validating the format specifiers.
7168          */
7169         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7170         if (err < 0)
7171                 verbose(env, "Invalid format string\n");
7172
7173         return err;
7174 }
7175
7176 static int check_get_func_ip(struct bpf_verifier_env *env)
7177 {
7178         enum bpf_prog_type type = resolve_prog_type(env->prog);
7179         int func_id = BPF_FUNC_get_func_ip;
7180
7181         if (type == BPF_PROG_TYPE_TRACING) {
7182                 if (!bpf_prog_has_trampoline(env->prog)) {
7183                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7184                                 func_id_name(func_id), func_id);
7185                         return -ENOTSUPP;
7186                 }
7187                 return 0;
7188         } else if (type == BPF_PROG_TYPE_KPROBE) {
7189                 return 0;
7190         }
7191
7192         verbose(env, "func %s#%d not supported for program type %d\n",
7193                 func_id_name(func_id), func_id, type);
7194         return -ENOTSUPP;
7195 }
7196
7197 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7198 {
7199         return &env->insn_aux_data[env->insn_idx];
7200 }
7201
7202 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7203 {
7204         struct bpf_reg_state *regs = cur_regs(env);
7205         struct bpf_reg_state *reg = &regs[BPF_REG_4];
7206         bool reg_is_null = register_is_null(reg);
7207
7208         if (reg_is_null)
7209                 mark_chain_precision(env, BPF_REG_4);
7210
7211         return reg_is_null;
7212 }
7213
7214 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7215 {
7216         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7217
7218         if (!state->initialized) {
7219                 state->initialized = 1;
7220                 state->fit_for_inline = loop_flag_is_zero(env);
7221                 state->callback_subprogno = subprogno;
7222                 return;
7223         }
7224
7225         if (!state->fit_for_inline)
7226                 return;
7227
7228         state->fit_for_inline = (loop_flag_is_zero(env) &&
7229                                  state->callback_subprogno == subprogno);
7230 }
7231
7232 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7233                              int *insn_idx_p)
7234 {
7235         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7236         const struct bpf_func_proto *fn = NULL;
7237         enum bpf_return_type ret_type;
7238         enum bpf_type_flag ret_flag;
7239         struct bpf_reg_state *regs;
7240         struct bpf_call_arg_meta meta;
7241         int insn_idx = *insn_idx_p;
7242         bool changes_data;
7243         int i, err, func_id;
7244
7245         /* find function prototype */
7246         func_id = insn->imm;
7247         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7248                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7249                         func_id);
7250                 return -EINVAL;
7251         }
7252
7253         if (env->ops->get_func_proto)
7254                 fn = env->ops->get_func_proto(func_id, env->prog);
7255         if (!fn) {
7256                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7257                         func_id);
7258                 return -EINVAL;
7259         }
7260
7261         /* eBPF programs must be GPL compatible to use GPL-ed functions */
7262         if (!env->prog->gpl_compatible && fn->gpl_only) {
7263                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7264                 return -EINVAL;
7265         }
7266
7267         if (fn->allowed && !fn->allowed(env->prog)) {
7268                 verbose(env, "helper call is not allowed in probe\n");
7269                 return -EINVAL;
7270         }
7271
7272         /* With LD_ABS/IND some JITs save/restore skb from r1. */
7273         changes_data = bpf_helper_changes_pkt_data(fn->func);
7274         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7275                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7276                         func_id_name(func_id), func_id);
7277                 return -EINVAL;
7278         }
7279
7280         memset(&meta, 0, sizeof(meta));
7281         meta.pkt_access = fn->pkt_access;
7282
7283         err = check_func_proto(fn, func_id);
7284         if (err) {
7285                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7286                         func_id_name(func_id), func_id);
7287                 return err;
7288         }
7289
7290         meta.func_id = func_id;
7291         /* check args */
7292         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7293                 err = check_func_arg(env, i, &meta, fn);
7294                 if (err)
7295                         return err;
7296         }
7297
7298         err = record_func_map(env, &meta, func_id, insn_idx);
7299         if (err)
7300                 return err;
7301
7302         err = record_func_key(env, &meta, func_id, insn_idx);
7303         if (err)
7304                 return err;
7305
7306         /* Mark slots with STACK_MISC in case of raw mode, stack offset
7307          * is inferred from register state.
7308          */
7309         for (i = 0; i < meta.access_size; i++) {
7310                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7311                                        BPF_WRITE, -1, false);
7312                 if (err)
7313                         return err;
7314         }
7315
7316         regs = cur_regs(env);
7317
7318         if (meta.uninit_dynptr_regno) {
7319                 /* we write BPF_DW bits (8 bytes) at a time */
7320                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7321                         err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7322                                                i, BPF_DW, BPF_WRITE, -1, false);
7323                         if (err)
7324                                 return err;
7325                 }
7326
7327                 err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7328                                               fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7329                                               insn_idx);
7330                 if (err)
7331                         return err;
7332         }
7333
7334         if (meta.release_regno) {
7335                 err = -EINVAL;
7336                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7337                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7338                 else if (meta.ref_obj_id)
7339                         err = release_reference(env, meta.ref_obj_id);
7340                 /* meta.ref_obj_id can only be 0 if register that is meant to be
7341                  * released is NULL, which must be > R0.
7342                  */
7343                 else if (register_is_null(&regs[meta.release_regno]))
7344                         err = 0;
7345                 if (err) {
7346                         verbose(env, "func %s#%d reference has not been acquired before\n",
7347                                 func_id_name(func_id), func_id);
7348                         return err;
7349                 }
7350         }
7351
7352         switch (func_id) {
7353         case BPF_FUNC_tail_call:
7354                 err = check_reference_leak(env);
7355                 if (err) {
7356                         verbose(env, "tail_call would lead to reference leak\n");
7357                         return err;
7358                 }
7359                 break;
7360         case BPF_FUNC_get_local_storage:
7361                 /* check that flags argument in get_local_storage(map, flags) is 0,
7362                  * this is required because get_local_storage() can't return an error.
7363                  */
7364                 if (!register_is_null(&regs[BPF_REG_2])) {
7365                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7366                         return -EINVAL;
7367                 }
7368                 break;
7369         case BPF_FUNC_for_each_map_elem:
7370                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7371                                         set_map_elem_callback_state);
7372                 break;
7373         case BPF_FUNC_timer_set_callback:
7374                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7375                                         set_timer_callback_state);
7376                 break;
7377         case BPF_FUNC_find_vma:
7378                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7379                                         set_find_vma_callback_state);
7380                 break;
7381         case BPF_FUNC_snprintf:
7382                 err = check_bpf_snprintf_call(env, regs);
7383                 break;
7384         case BPF_FUNC_loop:
7385                 update_loop_inline_state(env, meta.subprogno);
7386                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7387                                         set_loop_callback_state);
7388                 break;
7389         case BPF_FUNC_dynptr_from_mem:
7390                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7391                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7392                                 reg_type_str(env, regs[BPF_REG_1].type));
7393                         return -EACCES;
7394                 }
7395                 break;
7396         case BPF_FUNC_set_retval:
7397                 if (prog_type == BPF_PROG_TYPE_LSM &&
7398                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7399                         if (!env->prog->aux->attach_func_proto->type) {
7400                                 /* Make sure programs that attach to void
7401                                  * hooks don't try to modify return value.
7402                                  */
7403                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7404                                 return -EINVAL;
7405                         }
7406                 }
7407                 break;
7408         case BPF_FUNC_dynptr_data:
7409                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7410                         if (arg_type_is_dynptr(fn->arg_type[i])) {
7411                                 struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7412
7413                                 if (meta.ref_obj_id) {
7414                                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7415                                         return -EFAULT;
7416                                 }
7417
7418                                 if (base_type(reg->type) != PTR_TO_DYNPTR)
7419                                         /* Find the id of the dynptr we're
7420                                          * tracking the reference of
7421                                          */
7422                                         meta.ref_obj_id = stack_slot_get_id(env, reg);
7423                                 break;
7424                         }
7425                 }
7426                 if (i == MAX_BPF_FUNC_REG_ARGS) {
7427                         verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7428                         return -EFAULT;
7429                 }
7430                 break;
7431         case BPF_FUNC_user_ringbuf_drain:
7432                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7433                                         set_user_ringbuf_callback_state);
7434                 break;
7435         }
7436
7437         if (err)
7438                 return err;
7439
7440         /* reset caller saved regs */
7441         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7442                 mark_reg_not_init(env, regs, caller_saved[i]);
7443                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7444         }
7445
7446         /* helper call returns 64-bit value. */
7447         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7448
7449         /* update return register (already marked as written above) */
7450         ret_type = fn->ret_type;
7451         ret_flag = type_flag(ret_type);
7452
7453         switch (base_type(ret_type)) {
7454         case RET_INTEGER:
7455                 /* sets type to SCALAR_VALUE */
7456                 mark_reg_unknown(env, regs, BPF_REG_0);
7457                 break;
7458         case RET_VOID:
7459                 regs[BPF_REG_0].type = NOT_INIT;
7460                 break;
7461         case RET_PTR_TO_MAP_VALUE:
7462                 /* There is no offset yet applied, variable or fixed */
7463                 mark_reg_known_zero(env, regs, BPF_REG_0);
7464                 /* remember map_ptr, so that check_map_access()
7465                  * can check 'value_size' boundary of memory access
7466                  * to map element returned from bpf_map_lookup_elem()
7467                  */
7468                 if (meta.map_ptr == NULL) {
7469                         verbose(env,
7470                                 "kernel subsystem misconfigured verifier\n");
7471                         return -EINVAL;
7472                 }
7473                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7474                 regs[BPF_REG_0].map_uid = meta.map_uid;
7475                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7476                 if (!type_may_be_null(ret_type) &&
7477                     map_value_has_spin_lock(meta.map_ptr)) {
7478                         regs[BPF_REG_0].id = ++env->id_gen;
7479                 }
7480                 break;
7481         case RET_PTR_TO_SOCKET:
7482                 mark_reg_known_zero(env, regs, BPF_REG_0);
7483                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7484                 break;
7485         case RET_PTR_TO_SOCK_COMMON:
7486                 mark_reg_known_zero(env, regs, BPF_REG_0);
7487                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7488                 break;
7489         case RET_PTR_TO_TCP_SOCK:
7490                 mark_reg_known_zero(env, regs, BPF_REG_0);
7491                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7492                 break;
7493         case RET_PTR_TO_ALLOC_MEM:
7494                 mark_reg_known_zero(env, regs, BPF_REG_0);
7495                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7496                 regs[BPF_REG_0].mem_size = meta.mem_size;
7497                 break;
7498         case RET_PTR_TO_MEM_OR_BTF_ID:
7499         {
7500                 const struct btf_type *t;
7501
7502                 mark_reg_known_zero(env, regs, BPF_REG_0);
7503                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7504                 if (!btf_type_is_struct(t)) {
7505                         u32 tsize;
7506                         const struct btf_type *ret;
7507                         const char *tname;
7508
7509                         /* resolve the type size of ksym. */
7510                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7511                         if (IS_ERR(ret)) {
7512                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7513                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7514                                         tname, PTR_ERR(ret));
7515                                 return -EINVAL;
7516                         }
7517                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7518                         regs[BPF_REG_0].mem_size = tsize;
7519                 } else {
7520                         /* MEM_RDONLY may be carried from ret_flag, but it
7521                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7522                          * it will confuse the check of PTR_TO_BTF_ID in
7523                          * check_mem_access().
7524                          */
7525                         ret_flag &= ~MEM_RDONLY;
7526
7527                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7528                         regs[BPF_REG_0].btf = meta.ret_btf;
7529                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7530                 }
7531                 break;
7532         }
7533         case RET_PTR_TO_BTF_ID:
7534         {
7535                 struct btf *ret_btf;
7536                 int ret_btf_id;
7537
7538                 mark_reg_known_zero(env, regs, BPF_REG_0);
7539                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7540                 if (func_id == BPF_FUNC_kptr_xchg) {
7541                         ret_btf = meta.kptr_off_desc->kptr.btf;
7542                         ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7543                 } else {
7544                         if (fn->ret_btf_id == BPF_PTR_POISON) {
7545                                 verbose(env, "verifier internal error:");
7546                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7547                                         func_id_name(func_id));
7548                                 return -EINVAL;
7549                         }
7550                         ret_btf = btf_vmlinux;
7551                         ret_btf_id = *fn->ret_btf_id;
7552                 }
7553                 if (ret_btf_id == 0) {
7554                         verbose(env, "invalid return type %u of func %s#%d\n",
7555                                 base_type(ret_type), func_id_name(func_id),
7556                                 func_id);
7557                         return -EINVAL;
7558                 }
7559                 regs[BPF_REG_0].btf = ret_btf;
7560                 regs[BPF_REG_0].btf_id = ret_btf_id;
7561                 break;
7562         }
7563         default:
7564                 verbose(env, "unknown return type %u of func %s#%d\n",
7565                         base_type(ret_type), func_id_name(func_id), func_id);
7566                 return -EINVAL;
7567         }
7568
7569         if (type_may_be_null(regs[BPF_REG_0].type))
7570                 regs[BPF_REG_0].id = ++env->id_gen;
7571
7572         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7573                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7574                         func_id_name(func_id), func_id);
7575                 return -EFAULT;
7576         }
7577
7578         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7579                 /* For release_reference() */
7580                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7581         } else if (is_acquire_function(func_id, meta.map_ptr)) {
7582                 int id = acquire_reference_state(env, insn_idx);
7583
7584                 if (id < 0)
7585                         return id;
7586                 /* For mark_ptr_or_null_reg() */
7587                 regs[BPF_REG_0].id = id;
7588                 /* For release_reference() */
7589                 regs[BPF_REG_0].ref_obj_id = id;
7590         }
7591
7592         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7593
7594         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7595         if (err)
7596                 return err;
7597
7598         if ((func_id == BPF_FUNC_get_stack ||
7599              func_id == BPF_FUNC_get_task_stack) &&
7600             !env->prog->has_callchain_buf) {
7601                 const char *err_str;
7602
7603 #ifdef CONFIG_PERF_EVENTS
7604                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7605                 err_str = "cannot get callchain buffer for func %s#%d\n";
7606 #else
7607                 err = -ENOTSUPP;
7608                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7609 #endif
7610                 if (err) {
7611                         verbose(env, err_str, func_id_name(func_id), func_id);
7612                         return err;
7613                 }
7614
7615                 env->prog->has_callchain_buf = true;
7616         }
7617
7618         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7619                 env->prog->call_get_stack = true;
7620
7621         if (func_id == BPF_FUNC_get_func_ip) {
7622                 if (check_get_func_ip(env))
7623                         return -ENOTSUPP;
7624                 env->prog->call_get_func_ip = true;
7625         }
7626
7627         if (changes_data)
7628                 clear_all_pkt_pointers(env);
7629         return 0;
7630 }
7631
7632 /* mark_btf_func_reg_size() is used when the reg size is determined by
7633  * the BTF func_proto's return value size and argument.
7634  */
7635 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7636                                    size_t reg_size)
7637 {
7638         struct bpf_reg_state *reg = &cur_regs(env)[regno];
7639
7640         if (regno == BPF_REG_0) {
7641                 /* Function return value */
7642                 reg->live |= REG_LIVE_WRITTEN;
7643                 reg->subreg_def = reg_size == sizeof(u64) ?
7644                         DEF_NOT_SUBREG : env->insn_idx + 1;
7645         } else {
7646                 /* Function argument */
7647                 if (reg_size == sizeof(u64)) {
7648                         mark_insn_zext(env, reg);
7649                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7650                 } else {
7651                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7652                 }
7653         }
7654 }
7655
7656 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7657                             int *insn_idx_p)
7658 {
7659         const struct btf_type *t, *func, *func_proto, *ptr_type;
7660         struct bpf_reg_state *regs = cur_regs(env);
7661         struct bpf_kfunc_arg_meta meta = { 0 };
7662         const char *func_name, *ptr_type_name;
7663         u32 i, nargs, func_id, ptr_type_id;
7664         int err, insn_idx = *insn_idx_p;
7665         const struct btf_param *args;
7666         struct btf *desc_btf;
7667         u32 *kfunc_flags;
7668         bool acq;
7669
7670         /* skip for now, but return error when we find this in fixup_kfunc_call */
7671         if (!insn->imm)
7672                 return 0;
7673
7674         desc_btf = find_kfunc_desc_btf(env, insn->off);
7675         if (IS_ERR(desc_btf))
7676                 return PTR_ERR(desc_btf);
7677
7678         func_id = insn->imm;
7679         func = btf_type_by_id(desc_btf, func_id);
7680         func_name = btf_name_by_offset(desc_btf, func->name_off);
7681         func_proto = btf_type_by_id(desc_btf, func->type);
7682
7683         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7684         if (!kfunc_flags) {
7685                 verbose(env, "calling kernel function %s is not allowed\n",
7686                         func_name);
7687                 return -EACCES;
7688         }
7689         if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7690                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7691                 return -EACCES;
7692         }
7693
7694         acq = *kfunc_flags & KF_ACQUIRE;
7695
7696         meta.flags = *kfunc_flags;
7697
7698         /* Check the arguments */
7699         err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7700         if (err < 0)
7701                 return err;
7702         /* In case of release function, we get register number of refcounted
7703          * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7704          */
7705         if (err) {
7706                 err = release_reference(env, regs[err].ref_obj_id);
7707                 if (err) {
7708                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7709                                 func_name, func_id);
7710                         return err;
7711                 }
7712         }
7713
7714         for (i = 0; i < CALLER_SAVED_REGS; i++)
7715                 mark_reg_not_init(env, regs, caller_saved[i]);
7716
7717         /* Check return type */
7718         t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7719
7720         if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7721                 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7722                 return -EINVAL;
7723         }
7724
7725         if (btf_type_is_scalar(t)) {
7726                 mark_reg_unknown(env, regs, BPF_REG_0);
7727                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7728         } else if (btf_type_is_ptr(t)) {
7729                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7730                                                    &ptr_type_id);
7731                 if (!btf_type_is_struct(ptr_type)) {
7732                         if (!meta.r0_size) {
7733                                 ptr_type_name = btf_name_by_offset(desc_btf,
7734                                                                    ptr_type->name_off);
7735                                 verbose(env,
7736                                         "kernel function %s returns pointer type %s %s is not supported\n",
7737                                         func_name,
7738                                         btf_type_str(ptr_type),
7739                                         ptr_type_name);
7740                                 return -EINVAL;
7741                         }
7742
7743                         mark_reg_known_zero(env, regs, BPF_REG_0);
7744                         regs[BPF_REG_0].type = PTR_TO_MEM;
7745                         regs[BPF_REG_0].mem_size = meta.r0_size;
7746
7747                         if (meta.r0_rdonly)
7748                                 regs[BPF_REG_0].type |= MEM_RDONLY;
7749
7750                         /* Ensures we don't access the memory after a release_reference() */
7751                         if (meta.ref_obj_id)
7752                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7753                 } else {
7754                         mark_reg_known_zero(env, regs, BPF_REG_0);
7755                         regs[BPF_REG_0].btf = desc_btf;
7756                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7757                         regs[BPF_REG_0].btf_id = ptr_type_id;
7758                 }
7759                 if (*kfunc_flags & KF_RET_NULL) {
7760                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7761                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7762                         regs[BPF_REG_0].id = ++env->id_gen;
7763                 }
7764                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7765                 if (acq) {
7766                         int id = acquire_reference_state(env, insn_idx);
7767
7768                         if (id < 0)
7769                                 return id;
7770                         regs[BPF_REG_0].id = id;
7771                         regs[BPF_REG_0].ref_obj_id = id;
7772                 }
7773         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7774
7775         nargs = btf_type_vlen(func_proto);
7776         args = (const struct btf_param *)(func_proto + 1);
7777         for (i = 0; i < nargs; i++) {
7778                 u32 regno = i + 1;
7779
7780                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7781                 if (btf_type_is_ptr(t))
7782                         mark_btf_func_reg_size(env, regno, sizeof(void *));
7783                 else
7784                         /* scalar. ensured by btf_check_kfunc_arg_match() */
7785                         mark_btf_func_reg_size(env, regno, t->size);
7786         }
7787
7788         return 0;
7789 }
7790
7791 static bool signed_add_overflows(s64 a, s64 b)
7792 {
7793         /* Do the add in u64, where overflow is well-defined */
7794         s64 res = (s64)((u64)a + (u64)b);
7795
7796         if (b < 0)
7797                 return res > a;
7798         return res < a;
7799 }
7800
7801 static bool signed_add32_overflows(s32 a, s32 b)
7802 {
7803         /* Do the add in u32, where overflow is well-defined */
7804         s32 res = (s32)((u32)a + (u32)b);
7805
7806         if (b < 0)
7807                 return res > a;
7808         return res < a;
7809 }
7810
7811 static bool signed_sub_overflows(s64 a, s64 b)
7812 {
7813         /* Do the sub in u64, where overflow is well-defined */
7814         s64 res = (s64)((u64)a - (u64)b);
7815
7816         if (b < 0)
7817                 return res < a;
7818         return res > a;
7819 }
7820
7821 static bool signed_sub32_overflows(s32 a, s32 b)
7822 {
7823         /* Do the sub in u32, where overflow is well-defined */
7824         s32 res = (s32)((u32)a - (u32)b);
7825
7826         if (b < 0)
7827                 return res < a;
7828         return res > a;
7829 }
7830
7831 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7832                                   const struct bpf_reg_state *reg,
7833                                   enum bpf_reg_type type)
7834 {
7835         bool known = tnum_is_const(reg->var_off);
7836         s64 val = reg->var_off.value;
7837         s64 smin = reg->smin_value;
7838
7839         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7840                 verbose(env, "math between %s pointer and %lld is not allowed\n",
7841                         reg_type_str(env, type), val);
7842                 return false;
7843         }
7844
7845         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7846                 verbose(env, "%s pointer offset %d is not allowed\n",
7847                         reg_type_str(env, type), reg->off);
7848                 return false;
7849         }
7850
7851         if (smin == S64_MIN) {
7852                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7853                         reg_type_str(env, type));
7854                 return false;
7855         }
7856
7857         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7858                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7859                         smin, reg_type_str(env, type));
7860                 return false;
7861         }
7862
7863         return true;
7864 }
7865
7866 enum {
7867         REASON_BOUNDS   = -1,
7868         REASON_TYPE     = -2,
7869         REASON_PATHS    = -3,
7870         REASON_LIMIT    = -4,
7871         REASON_STACK    = -5,
7872 };
7873
7874 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7875                               u32 *alu_limit, bool mask_to_left)
7876 {
7877         u32 max = 0, ptr_limit = 0;
7878
7879         switch (ptr_reg->type) {
7880         case PTR_TO_STACK:
7881                 /* Offset 0 is out-of-bounds, but acceptable start for the
7882                  * left direction, see BPF_REG_FP. Also, unknown scalar
7883                  * offset where we would need to deal with min/max bounds is
7884                  * currently prohibited for unprivileged.
7885                  */
7886                 max = MAX_BPF_STACK + mask_to_left;
7887                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7888                 break;
7889         case PTR_TO_MAP_VALUE:
7890                 max = ptr_reg->map_ptr->value_size;
7891                 ptr_limit = (mask_to_left ?
7892                              ptr_reg->smin_value :
7893                              ptr_reg->umax_value) + ptr_reg->off;
7894                 break;
7895         default:
7896                 return REASON_TYPE;
7897         }
7898
7899         if (ptr_limit >= max)
7900                 return REASON_LIMIT;
7901         *alu_limit = ptr_limit;
7902         return 0;
7903 }
7904
7905 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7906                                     const struct bpf_insn *insn)
7907 {
7908         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7909 }
7910
7911 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7912                                        u32 alu_state, u32 alu_limit)
7913 {
7914         /* If we arrived here from different branches with different
7915          * state or limits to sanitize, then this won't work.
7916          */
7917         if (aux->alu_state &&
7918             (aux->alu_state != alu_state ||
7919              aux->alu_limit != alu_limit))
7920                 return REASON_PATHS;
7921
7922         /* Corresponding fixup done in do_misc_fixups(). */
7923         aux->alu_state = alu_state;
7924         aux->alu_limit = alu_limit;
7925         return 0;
7926 }
7927
7928 static int sanitize_val_alu(struct bpf_verifier_env *env,
7929                             struct bpf_insn *insn)
7930 {
7931         struct bpf_insn_aux_data *aux = cur_aux(env);
7932
7933         if (can_skip_alu_sanitation(env, insn))
7934                 return 0;
7935
7936         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7937 }
7938
7939 static bool sanitize_needed(u8 opcode)
7940 {
7941         return opcode == BPF_ADD || opcode == BPF_SUB;
7942 }
7943
7944 struct bpf_sanitize_info {
7945         struct bpf_insn_aux_data aux;
7946         bool mask_to_left;
7947 };
7948
7949 static struct bpf_verifier_state *
7950 sanitize_speculative_path(struct bpf_verifier_env *env,
7951                           const struct bpf_insn *insn,
7952                           u32 next_idx, u32 curr_idx)
7953 {
7954         struct bpf_verifier_state *branch;
7955         struct bpf_reg_state *regs;
7956
7957         branch = push_stack(env, next_idx, curr_idx, true);
7958         if (branch && insn) {
7959                 regs = branch->frame[branch->curframe]->regs;
7960                 if (BPF_SRC(insn->code) == BPF_K) {
7961                         mark_reg_unknown(env, regs, insn->dst_reg);
7962                 } else if (BPF_SRC(insn->code) == BPF_X) {
7963                         mark_reg_unknown(env, regs, insn->dst_reg);
7964                         mark_reg_unknown(env, regs, insn->src_reg);
7965                 }
7966         }
7967         return branch;
7968 }
7969
7970 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7971                             struct bpf_insn *insn,
7972                             const struct bpf_reg_state *ptr_reg,
7973                             const struct bpf_reg_state *off_reg,
7974                             struct bpf_reg_state *dst_reg,
7975                             struct bpf_sanitize_info *info,
7976                             const bool commit_window)
7977 {
7978         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7979         struct bpf_verifier_state *vstate = env->cur_state;
7980         bool off_is_imm = tnum_is_const(off_reg->var_off);
7981         bool off_is_neg = off_reg->smin_value < 0;
7982         bool ptr_is_dst_reg = ptr_reg == dst_reg;
7983         u8 opcode = BPF_OP(insn->code);
7984         u32 alu_state, alu_limit;
7985         struct bpf_reg_state tmp;
7986         bool ret;
7987         int err;
7988
7989         if (can_skip_alu_sanitation(env, insn))
7990                 return 0;
7991
7992         /* We already marked aux for masking from non-speculative
7993          * paths, thus we got here in the first place. We only care
7994          * to explore bad access from here.
7995          */
7996         if (vstate->speculative)
7997                 goto do_sim;
7998
7999         if (!commit_window) {
8000                 if (!tnum_is_const(off_reg->var_off) &&
8001                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8002                         return REASON_BOUNDS;
8003
8004                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
8005                                      (opcode == BPF_SUB && !off_is_neg);
8006         }
8007
8008         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8009         if (err < 0)
8010                 return err;
8011
8012         if (commit_window) {
8013                 /* In commit phase we narrow the masking window based on
8014                  * the observed pointer move after the simulated operation.
8015                  */
8016                 alu_state = info->aux.alu_state;
8017                 alu_limit = abs(info->aux.alu_limit - alu_limit);
8018         } else {
8019                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8020                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8021                 alu_state |= ptr_is_dst_reg ?
8022                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8023
8024                 /* Limit pruning on unknown scalars to enable deep search for
8025                  * potential masking differences from other program paths.
8026                  */
8027                 if (!off_is_imm)
8028                         env->explore_alu_limits = true;
8029         }
8030
8031         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8032         if (err < 0)
8033                 return err;
8034 do_sim:
8035         /* If we're in commit phase, we're done here given we already
8036          * pushed the truncated dst_reg into the speculative verification
8037          * stack.
8038          *
8039          * Also, when register is a known constant, we rewrite register-based
8040          * operation to immediate-based, and thus do not need masking (and as
8041          * a consequence, do not need to simulate the zero-truncation either).
8042          */
8043         if (commit_window || off_is_imm)
8044                 return 0;
8045
8046         /* Simulate and find potential out-of-bounds access under
8047          * speculative execution from truncation as a result of
8048          * masking when off was not within expected range. If off
8049          * sits in dst, then we temporarily need to move ptr there
8050          * to simulate dst (== 0) +/-= ptr. Needed, for example,
8051          * for cases where we use K-based arithmetic in one direction
8052          * and truncated reg-based in the other in order to explore
8053          * bad access.
8054          */
8055         if (!ptr_is_dst_reg) {
8056                 tmp = *dst_reg;
8057                 *dst_reg = *ptr_reg;
8058         }
8059         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8060                                         env->insn_idx);
8061         if (!ptr_is_dst_reg && ret)
8062                 *dst_reg = tmp;
8063         return !ret ? REASON_STACK : 0;
8064 }
8065
8066 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8067 {
8068         struct bpf_verifier_state *vstate = env->cur_state;
8069
8070         /* If we simulate paths under speculation, we don't update the
8071          * insn as 'seen' such that when we verify unreachable paths in
8072          * the non-speculative domain, sanitize_dead_code() can still
8073          * rewrite/sanitize them.
8074          */
8075         if (!vstate->speculative)
8076                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8077 }
8078
8079 static int sanitize_err(struct bpf_verifier_env *env,
8080                         const struct bpf_insn *insn, int reason,
8081                         const struct bpf_reg_state *off_reg,
8082                         const struct bpf_reg_state *dst_reg)
8083 {
8084         static const char *err = "pointer arithmetic with it prohibited for !root";
8085         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8086         u32 dst = insn->dst_reg, src = insn->src_reg;
8087
8088         switch (reason) {
8089         case REASON_BOUNDS:
8090                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8091                         off_reg == dst_reg ? dst : src, err);
8092                 break;
8093         case REASON_TYPE:
8094                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8095                         off_reg == dst_reg ? src : dst, err);
8096                 break;
8097         case REASON_PATHS:
8098                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8099                         dst, op, err);
8100                 break;
8101         case REASON_LIMIT:
8102                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8103                         dst, op, err);
8104                 break;
8105         case REASON_STACK:
8106                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8107                         dst, err);
8108                 break;
8109         default:
8110                 verbose(env, "verifier internal error: unknown reason (%d)\n",
8111                         reason);
8112                 break;
8113         }
8114
8115         return -EACCES;
8116 }
8117
8118 /* check that stack access falls within stack limits and that 'reg' doesn't
8119  * have a variable offset.
8120  *
8121  * Variable offset is prohibited for unprivileged mode for simplicity since it
8122  * requires corresponding support in Spectre masking for stack ALU.  See also
8123  * retrieve_ptr_limit().
8124  *
8125  *
8126  * 'off' includes 'reg->off'.
8127  */
8128 static int check_stack_access_for_ptr_arithmetic(
8129                                 struct bpf_verifier_env *env,
8130                                 int regno,
8131                                 const struct bpf_reg_state *reg,
8132                                 int off)
8133 {
8134         if (!tnum_is_const(reg->var_off)) {
8135                 char tn_buf[48];
8136
8137                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8138                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8139                         regno, tn_buf, off);
8140                 return -EACCES;
8141         }
8142
8143         if (off >= 0 || off < -MAX_BPF_STACK) {
8144                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8145                         "prohibited for !root; off=%d\n", regno, off);
8146                 return -EACCES;
8147         }
8148
8149         return 0;
8150 }
8151
8152 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8153                                  const struct bpf_insn *insn,
8154                                  const struct bpf_reg_state *dst_reg)
8155 {
8156         u32 dst = insn->dst_reg;
8157
8158         /* For unprivileged we require that resulting offset must be in bounds
8159          * in order to be able to sanitize access later on.
8160          */
8161         if (env->bypass_spec_v1)
8162                 return 0;
8163
8164         switch (dst_reg->type) {
8165         case PTR_TO_STACK:
8166                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8167                                         dst_reg->off + dst_reg->var_off.value))
8168                         return -EACCES;
8169                 break;
8170         case PTR_TO_MAP_VALUE:
8171                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8172                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8173                                 "prohibited for !root\n", dst);
8174                         return -EACCES;
8175                 }
8176                 break;
8177         default:
8178                 break;
8179         }
8180
8181         return 0;
8182 }
8183
8184 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8185  * Caller should also handle BPF_MOV case separately.
8186  * If we return -EACCES, caller may want to try again treating pointer as a
8187  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8188  */
8189 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8190                                    struct bpf_insn *insn,
8191                                    const struct bpf_reg_state *ptr_reg,
8192                                    const struct bpf_reg_state *off_reg)
8193 {
8194         struct bpf_verifier_state *vstate = env->cur_state;
8195         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8196         struct bpf_reg_state *regs = state->regs, *dst_reg;
8197         bool known = tnum_is_const(off_reg->var_off);
8198         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8199             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8200         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8201             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8202         struct bpf_sanitize_info info = {};
8203         u8 opcode = BPF_OP(insn->code);
8204         u32 dst = insn->dst_reg;
8205         int ret;
8206
8207         dst_reg = &regs[dst];
8208
8209         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8210             smin_val > smax_val || umin_val > umax_val) {
8211                 /* Taint dst register if offset had invalid bounds derived from
8212                  * e.g. dead branches.
8213                  */
8214                 __mark_reg_unknown(env, dst_reg);
8215                 return 0;
8216         }
8217
8218         if (BPF_CLASS(insn->code) != BPF_ALU64) {
8219                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8220                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8221                         __mark_reg_unknown(env, dst_reg);
8222                         return 0;
8223                 }
8224
8225                 verbose(env,
8226                         "R%d 32-bit pointer arithmetic prohibited\n",
8227                         dst);
8228                 return -EACCES;
8229         }
8230
8231         if (ptr_reg->type & PTR_MAYBE_NULL) {
8232                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8233                         dst, reg_type_str(env, ptr_reg->type));
8234                 return -EACCES;
8235         }
8236
8237         switch (base_type(ptr_reg->type)) {
8238         case CONST_PTR_TO_MAP:
8239                 /* smin_val represents the known value */
8240                 if (known && smin_val == 0 && opcode == BPF_ADD)
8241                         break;
8242                 fallthrough;
8243         case PTR_TO_PACKET_END:
8244         case PTR_TO_SOCKET:
8245         case PTR_TO_SOCK_COMMON:
8246         case PTR_TO_TCP_SOCK:
8247         case PTR_TO_XDP_SOCK:
8248                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8249                         dst, reg_type_str(env, ptr_reg->type));
8250                 return -EACCES;
8251         default:
8252                 break;
8253         }
8254
8255         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8256          * The id may be overwritten later if we create a new variable offset.
8257          */
8258         dst_reg->type = ptr_reg->type;
8259         dst_reg->id = ptr_reg->id;
8260
8261         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8262             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8263                 return -EINVAL;
8264
8265         /* pointer types do not carry 32-bit bounds at the moment. */
8266         __mark_reg32_unbounded(dst_reg);
8267
8268         if (sanitize_needed(opcode)) {
8269                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8270                                        &info, false);
8271                 if (ret < 0)
8272                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8273         }
8274
8275         switch (opcode) {
8276         case BPF_ADD:
8277                 /* We can take a fixed offset as long as it doesn't overflow
8278                  * the s32 'off' field
8279                  */
8280                 if (known && (ptr_reg->off + smin_val ==
8281                               (s64)(s32)(ptr_reg->off + smin_val))) {
8282                         /* pointer += K.  Accumulate it into fixed offset */
8283                         dst_reg->smin_value = smin_ptr;
8284                         dst_reg->smax_value = smax_ptr;
8285                         dst_reg->umin_value = umin_ptr;
8286                         dst_reg->umax_value = umax_ptr;
8287                         dst_reg->var_off = ptr_reg->var_off;
8288                         dst_reg->off = ptr_reg->off + smin_val;
8289                         dst_reg->raw = ptr_reg->raw;
8290                         break;
8291                 }
8292                 /* A new variable offset is created.  Note that off_reg->off
8293                  * == 0, since it's a scalar.
8294                  * dst_reg gets the pointer type and since some positive
8295                  * integer value was added to the pointer, give it a new 'id'
8296                  * if it's a PTR_TO_PACKET.
8297                  * this creates a new 'base' pointer, off_reg (variable) gets
8298                  * added into the variable offset, and we copy the fixed offset
8299                  * from ptr_reg.
8300                  */
8301                 if (signed_add_overflows(smin_ptr, smin_val) ||
8302                     signed_add_overflows(smax_ptr, smax_val)) {
8303                         dst_reg->smin_value = S64_MIN;
8304                         dst_reg->smax_value = S64_MAX;
8305                 } else {
8306                         dst_reg->smin_value = smin_ptr + smin_val;
8307                         dst_reg->smax_value = smax_ptr + smax_val;
8308                 }
8309                 if (umin_ptr + umin_val < umin_ptr ||
8310                     umax_ptr + umax_val < umax_ptr) {
8311                         dst_reg->umin_value = 0;
8312                         dst_reg->umax_value = U64_MAX;
8313                 } else {
8314                         dst_reg->umin_value = umin_ptr + umin_val;
8315                         dst_reg->umax_value = umax_ptr + umax_val;
8316                 }
8317                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8318                 dst_reg->off = ptr_reg->off;
8319                 dst_reg->raw = ptr_reg->raw;
8320                 if (reg_is_pkt_pointer(ptr_reg)) {
8321                         dst_reg->id = ++env->id_gen;
8322                         /* something was added to pkt_ptr, set range to zero */
8323                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8324                 }
8325                 break;
8326         case BPF_SUB:
8327                 if (dst_reg == off_reg) {
8328                         /* scalar -= pointer.  Creates an unknown scalar */
8329                         verbose(env, "R%d tried to subtract pointer from scalar\n",
8330                                 dst);
8331                         return -EACCES;
8332                 }
8333                 /* We don't allow subtraction from FP, because (according to
8334                  * test_verifier.c test "invalid fp arithmetic", JITs might not
8335                  * be able to deal with it.
8336                  */
8337                 if (ptr_reg->type == PTR_TO_STACK) {
8338                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
8339                                 dst);
8340                         return -EACCES;
8341                 }
8342                 if (known && (ptr_reg->off - smin_val ==
8343                               (s64)(s32)(ptr_reg->off - smin_val))) {
8344                         /* pointer -= K.  Subtract it from fixed offset */
8345                         dst_reg->smin_value = smin_ptr;
8346                         dst_reg->smax_value = smax_ptr;
8347                         dst_reg->umin_value = umin_ptr;
8348                         dst_reg->umax_value = umax_ptr;
8349                         dst_reg->var_off = ptr_reg->var_off;
8350                         dst_reg->id = ptr_reg->id;
8351                         dst_reg->off = ptr_reg->off - smin_val;
8352                         dst_reg->raw = ptr_reg->raw;
8353                         break;
8354                 }
8355                 /* A new variable offset is created.  If the subtrahend is known
8356                  * nonnegative, then any reg->range we had before is still good.
8357                  */
8358                 if (signed_sub_overflows(smin_ptr, smax_val) ||
8359                     signed_sub_overflows(smax_ptr, smin_val)) {
8360                         /* Overflow possible, we know nothing */
8361                         dst_reg->smin_value = S64_MIN;
8362                         dst_reg->smax_value = S64_MAX;
8363                 } else {
8364                         dst_reg->smin_value = smin_ptr - smax_val;
8365                         dst_reg->smax_value = smax_ptr - smin_val;
8366                 }
8367                 if (umin_ptr < umax_val) {
8368                         /* Overflow possible, we know nothing */
8369                         dst_reg->umin_value = 0;
8370                         dst_reg->umax_value = U64_MAX;
8371                 } else {
8372                         /* Cannot overflow (as long as bounds are consistent) */
8373                         dst_reg->umin_value = umin_ptr - umax_val;
8374                         dst_reg->umax_value = umax_ptr - umin_val;
8375                 }
8376                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8377                 dst_reg->off = ptr_reg->off;
8378                 dst_reg->raw = ptr_reg->raw;
8379                 if (reg_is_pkt_pointer(ptr_reg)) {
8380                         dst_reg->id = ++env->id_gen;
8381                         /* something was added to pkt_ptr, set range to zero */
8382                         if (smin_val < 0)
8383                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8384                 }
8385                 break;
8386         case BPF_AND:
8387         case BPF_OR:
8388         case BPF_XOR:
8389                 /* bitwise ops on pointers are troublesome, prohibit. */
8390                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8391                         dst, bpf_alu_string[opcode >> 4]);
8392                 return -EACCES;
8393         default:
8394                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8395                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8396                         dst, bpf_alu_string[opcode >> 4]);
8397                 return -EACCES;
8398         }
8399
8400         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8401                 return -EINVAL;
8402         reg_bounds_sync(dst_reg);
8403         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8404                 return -EACCES;
8405         if (sanitize_needed(opcode)) {
8406                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8407                                        &info, true);
8408                 if (ret < 0)
8409                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8410         }
8411
8412         return 0;
8413 }
8414
8415 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8416                                  struct bpf_reg_state *src_reg)
8417 {
8418         s32 smin_val = src_reg->s32_min_value;
8419         s32 smax_val = src_reg->s32_max_value;
8420         u32 umin_val = src_reg->u32_min_value;
8421         u32 umax_val = src_reg->u32_max_value;
8422
8423         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8424             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8425                 dst_reg->s32_min_value = S32_MIN;
8426                 dst_reg->s32_max_value = S32_MAX;
8427         } else {
8428                 dst_reg->s32_min_value += smin_val;
8429                 dst_reg->s32_max_value += smax_val;
8430         }
8431         if (dst_reg->u32_min_value + umin_val < umin_val ||
8432             dst_reg->u32_max_value + umax_val < umax_val) {
8433                 dst_reg->u32_min_value = 0;
8434                 dst_reg->u32_max_value = U32_MAX;
8435         } else {
8436                 dst_reg->u32_min_value += umin_val;
8437                 dst_reg->u32_max_value += umax_val;
8438         }
8439 }
8440
8441 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8442                                struct bpf_reg_state *src_reg)
8443 {
8444         s64 smin_val = src_reg->smin_value;
8445         s64 smax_val = src_reg->smax_value;
8446         u64 umin_val = src_reg->umin_value;
8447         u64 umax_val = src_reg->umax_value;
8448
8449         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8450             signed_add_overflows(dst_reg->smax_value, smax_val)) {
8451                 dst_reg->smin_value = S64_MIN;
8452                 dst_reg->smax_value = S64_MAX;
8453         } else {
8454                 dst_reg->smin_value += smin_val;
8455                 dst_reg->smax_value += smax_val;
8456         }
8457         if (dst_reg->umin_value + umin_val < umin_val ||
8458             dst_reg->umax_value + umax_val < umax_val) {
8459                 dst_reg->umin_value = 0;
8460                 dst_reg->umax_value = U64_MAX;
8461         } else {
8462                 dst_reg->umin_value += umin_val;
8463                 dst_reg->umax_value += umax_val;
8464         }
8465 }
8466
8467 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8468                                  struct bpf_reg_state *src_reg)
8469 {
8470         s32 smin_val = src_reg->s32_min_value;
8471         s32 smax_val = src_reg->s32_max_value;
8472         u32 umin_val = src_reg->u32_min_value;
8473         u32 umax_val = src_reg->u32_max_value;
8474
8475         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8476             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8477                 /* Overflow possible, we know nothing */
8478                 dst_reg->s32_min_value = S32_MIN;
8479                 dst_reg->s32_max_value = S32_MAX;
8480         } else {
8481                 dst_reg->s32_min_value -= smax_val;
8482                 dst_reg->s32_max_value -= smin_val;
8483         }
8484         if (dst_reg->u32_min_value < umax_val) {
8485                 /* Overflow possible, we know nothing */
8486                 dst_reg->u32_min_value = 0;
8487                 dst_reg->u32_max_value = U32_MAX;
8488         } else {
8489                 /* Cannot overflow (as long as bounds are consistent) */
8490                 dst_reg->u32_min_value -= umax_val;
8491                 dst_reg->u32_max_value -= umin_val;
8492         }
8493 }
8494
8495 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8496                                struct bpf_reg_state *src_reg)
8497 {
8498         s64 smin_val = src_reg->smin_value;
8499         s64 smax_val = src_reg->smax_value;
8500         u64 umin_val = src_reg->umin_value;
8501         u64 umax_val = src_reg->umax_value;
8502
8503         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8504             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8505                 /* Overflow possible, we know nothing */
8506                 dst_reg->smin_value = S64_MIN;
8507                 dst_reg->smax_value = S64_MAX;
8508         } else {
8509                 dst_reg->smin_value -= smax_val;
8510                 dst_reg->smax_value -= smin_val;
8511         }
8512         if (dst_reg->umin_value < umax_val) {
8513                 /* Overflow possible, we know nothing */
8514                 dst_reg->umin_value = 0;
8515                 dst_reg->umax_value = U64_MAX;
8516         } else {
8517                 /* Cannot overflow (as long as bounds are consistent) */
8518                 dst_reg->umin_value -= umax_val;
8519                 dst_reg->umax_value -= umin_val;
8520         }
8521 }
8522
8523 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8524                                  struct bpf_reg_state *src_reg)
8525 {
8526         s32 smin_val = src_reg->s32_min_value;
8527         u32 umin_val = src_reg->u32_min_value;
8528         u32 umax_val = src_reg->u32_max_value;
8529
8530         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8531                 /* Ain't nobody got time to multiply that sign */
8532                 __mark_reg32_unbounded(dst_reg);
8533                 return;
8534         }
8535         /* Both values are positive, so we can work with unsigned and
8536          * copy the result to signed (unless it exceeds S32_MAX).
8537          */
8538         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8539                 /* Potential overflow, we know nothing */
8540                 __mark_reg32_unbounded(dst_reg);
8541                 return;
8542         }
8543         dst_reg->u32_min_value *= umin_val;
8544         dst_reg->u32_max_value *= umax_val;
8545         if (dst_reg->u32_max_value > S32_MAX) {
8546                 /* Overflow possible, we know nothing */
8547                 dst_reg->s32_min_value = S32_MIN;
8548                 dst_reg->s32_max_value = S32_MAX;
8549         } else {
8550                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8551                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8552         }
8553 }
8554
8555 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8556                                struct bpf_reg_state *src_reg)
8557 {
8558         s64 smin_val = src_reg->smin_value;
8559         u64 umin_val = src_reg->umin_value;
8560         u64 umax_val = src_reg->umax_value;
8561
8562         if (smin_val < 0 || dst_reg->smin_value < 0) {
8563                 /* Ain't nobody got time to multiply that sign */
8564                 __mark_reg64_unbounded(dst_reg);
8565                 return;
8566         }
8567         /* Both values are positive, so we can work with unsigned and
8568          * copy the result to signed (unless it exceeds S64_MAX).
8569          */
8570         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8571                 /* Potential overflow, we know nothing */
8572                 __mark_reg64_unbounded(dst_reg);
8573                 return;
8574         }
8575         dst_reg->umin_value *= umin_val;
8576         dst_reg->umax_value *= umax_val;
8577         if (dst_reg->umax_value > S64_MAX) {
8578                 /* Overflow possible, we know nothing */
8579                 dst_reg->smin_value = S64_MIN;
8580                 dst_reg->smax_value = S64_MAX;
8581         } else {
8582                 dst_reg->smin_value = dst_reg->umin_value;
8583                 dst_reg->smax_value = dst_reg->umax_value;
8584         }
8585 }
8586
8587 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8588                                  struct bpf_reg_state *src_reg)
8589 {
8590         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8591         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8592         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8593         s32 smin_val = src_reg->s32_min_value;
8594         u32 umax_val = src_reg->u32_max_value;
8595
8596         if (src_known && dst_known) {
8597                 __mark_reg32_known(dst_reg, var32_off.value);
8598                 return;
8599         }
8600
8601         /* We get our minimum from the var_off, since that's inherently
8602          * bitwise.  Our maximum is the minimum of the operands' maxima.
8603          */
8604         dst_reg->u32_min_value = var32_off.value;
8605         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8606         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8607                 /* Lose signed bounds when ANDing negative numbers,
8608                  * ain't nobody got time for that.
8609                  */
8610                 dst_reg->s32_min_value = S32_MIN;
8611                 dst_reg->s32_max_value = S32_MAX;
8612         } else {
8613                 /* ANDing two positives gives a positive, so safe to
8614                  * cast result into s64.
8615                  */
8616                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8617                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8618         }
8619 }
8620
8621 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8622                                struct bpf_reg_state *src_reg)
8623 {
8624         bool src_known = tnum_is_const(src_reg->var_off);
8625         bool dst_known = tnum_is_const(dst_reg->var_off);
8626         s64 smin_val = src_reg->smin_value;
8627         u64 umax_val = src_reg->umax_value;
8628
8629         if (src_known && dst_known) {
8630                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8631                 return;
8632         }
8633
8634         /* We get our minimum from the var_off, since that's inherently
8635          * bitwise.  Our maximum is the minimum of the operands' maxima.
8636          */
8637         dst_reg->umin_value = dst_reg->var_off.value;
8638         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8639         if (dst_reg->smin_value < 0 || smin_val < 0) {
8640                 /* Lose signed bounds when ANDing negative numbers,
8641                  * ain't nobody got time for that.
8642                  */
8643                 dst_reg->smin_value = S64_MIN;
8644                 dst_reg->smax_value = S64_MAX;
8645         } else {
8646                 /* ANDing two positives gives a positive, so safe to
8647                  * cast result into s64.
8648                  */
8649                 dst_reg->smin_value = dst_reg->umin_value;
8650                 dst_reg->smax_value = dst_reg->umax_value;
8651         }
8652         /* We may learn something more from the var_off */
8653         __update_reg_bounds(dst_reg);
8654 }
8655
8656 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8657                                 struct bpf_reg_state *src_reg)
8658 {
8659         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8660         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8661         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8662         s32 smin_val = src_reg->s32_min_value;
8663         u32 umin_val = src_reg->u32_min_value;
8664
8665         if (src_known && dst_known) {
8666                 __mark_reg32_known(dst_reg, var32_off.value);
8667                 return;
8668         }
8669
8670         /* We get our maximum from the var_off, and our minimum is the
8671          * maximum of the operands' minima
8672          */
8673         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8674         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8675         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8676                 /* Lose signed bounds when ORing negative numbers,
8677                  * ain't nobody got time for that.
8678                  */
8679                 dst_reg->s32_min_value = S32_MIN;
8680                 dst_reg->s32_max_value = S32_MAX;
8681         } else {
8682                 /* ORing two positives gives a positive, so safe to
8683                  * cast result into s64.
8684                  */
8685                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8686                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8687         }
8688 }
8689
8690 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8691                               struct bpf_reg_state *src_reg)
8692 {
8693         bool src_known = tnum_is_const(src_reg->var_off);
8694         bool dst_known = tnum_is_const(dst_reg->var_off);
8695         s64 smin_val = src_reg->smin_value;
8696         u64 umin_val = src_reg->umin_value;
8697
8698         if (src_known && dst_known) {
8699                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8700                 return;
8701         }
8702
8703         /* We get our maximum from the var_off, and our minimum is the
8704          * maximum of the operands' minima
8705          */
8706         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8707         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8708         if (dst_reg->smin_value < 0 || smin_val < 0) {
8709                 /* Lose signed bounds when ORing negative numbers,
8710                  * ain't nobody got time for that.
8711                  */
8712                 dst_reg->smin_value = S64_MIN;
8713                 dst_reg->smax_value = S64_MAX;
8714         } else {
8715                 /* ORing two positives gives a positive, so safe to
8716                  * cast result into s64.
8717                  */
8718                 dst_reg->smin_value = dst_reg->umin_value;
8719                 dst_reg->smax_value = dst_reg->umax_value;
8720         }
8721         /* We may learn something more from the var_off */
8722         __update_reg_bounds(dst_reg);
8723 }
8724
8725 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8726                                  struct bpf_reg_state *src_reg)
8727 {
8728         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8729         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8730         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8731         s32 smin_val = src_reg->s32_min_value;
8732
8733         if (src_known && dst_known) {
8734                 __mark_reg32_known(dst_reg, var32_off.value);
8735                 return;
8736         }
8737
8738         /* We get both minimum and maximum from the var32_off. */
8739         dst_reg->u32_min_value = var32_off.value;
8740         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8741
8742         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8743                 /* XORing two positive sign numbers gives a positive,
8744                  * so safe to cast u32 result into s32.
8745                  */
8746                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8747                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8748         } else {
8749                 dst_reg->s32_min_value = S32_MIN;
8750                 dst_reg->s32_max_value = S32_MAX;
8751         }
8752 }
8753
8754 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8755                                struct bpf_reg_state *src_reg)
8756 {
8757         bool src_known = tnum_is_const(src_reg->var_off);
8758         bool dst_known = tnum_is_const(dst_reg->var_off);
8759         s64 smin_val = src_reg->smin_value;
8760
8761         if (src_known && dst_known) {
8762                 /* dst_reg->var_off.value has been updated earlier */
8763                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8764                 return;
8765         }
8766
8767         /* We get both minimum and maximum from the var_off. */
8768         dst_reg->umin_value = dst_reg->var_off.value;
8769         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8770
8771         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8772                 /* XORing two positive sign numbers gives a positive,
8773                  * so safe to cast u64 result into s64.
8774                  */
8775                 dst_reg->smin_value = dst_reg->umin_value;
8776                 dst_reg->smax_value = dst_reg->umax_value;
8777         } else {
8778                 dst_reg->smin_value = S64_MIN;
8779                 dst_reg->smax_value = S64_MAX;
8780         }
8781
8782         __update_reg_bounds(dst_reg);
8783 }
8784
8785 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8786                                    u64 umin_val, u64 umax_val)
8787 {
8788         /* We lose all sign bit information (except what we can pick
8789          * up from var_off)
8790          */
8791         dst_reg->s32_min_value = S32_MIN;
8792         dst_reg->s32_max_value = S32_MAX;
8793         /* If we might shift our top bit out, then we know nothing */
8794         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8795                 dst_reg->u32_min_value = 0;
8796                 dst_reg->u32_max_value = U32_MAX;
8797         } else {
8798                 dst_reg->u32_min_value <<= umin_val;
8799                 dst_reg->u32_max_value <<= umax_val;
8800         }
8801 }
8802
8803 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8804                                  struct bpf_reg_state *src_reg)
8805 {
8806         u32 umax_val = src_reg->u32_max_value;
8807         u32 umin_val = src_reg->u32_min_value;
8808         /* u32 alu operation will zext upper bits */
8809         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8810
8811         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8812         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8813         /* Not required but being careful mark reg64 bounds as unknown so
8814          * that we are forced to pick them up from tnum and zext later and
8815          * if some path skips this step we are still safe.
8816          */
8817         __mark_reg64_unbounded(dst_reg);
8818         __update_reg32_bounds(dst_reg);
8819 }
8820
8821 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8822                                    u64 umin_val, u64 umax_val)
8823 {
8824         /* Special case <<32 because it is a common compiler pattern to sign
8825          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8826          * positive we know this shift will also be positive so we can track
8827          * bounds correctly. Otherwise we lose all sign bit information except
8828          * what we can pick up from var_off. Perhaps we can generalize this
8829          * later to shifts of any length.
8830          */
8831         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8832                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8833         else
8834                 dst_reg->smax_value = S64_MAX;
8835
8836         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8837                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8838         else
8839                 dst_reg->smin_value = S64_MIN;
8840
8841         /* If we might shift our top bit out, then we know nothing */
8842         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8843                 dst_reg->umin_value = 0;
8844                 dst_reg->umax_value = U64_MAX;
8845         } else {
8846                 dst_reg->umin_value <<= umin_val;
8847                 dst_reg->umax_value <<= umax_val;
8848         }
8849 }
8850
8851 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8852                                struct bpf_reg_state *src_reg)
8853 {
8854         u64 umax_val = src_reg->umax_value;
8855         u64 umin_val = src_reg->umin_value;
8856
8857         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8858         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8859         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8860
8861         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8862         /* We may learn something more from the var_off */
8863         __update_reg_bounds(dst_reg);
8864 }
8865
8866 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8867                                  struct bpf_reg_state *src_reg)
8868 {
8869         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8870         u32 umax_val = src_reg->u32_max_value;
8871         u32 umin_val = src_reg->u32_min_value;
8872
8873         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8874          * be negative, then either:
8875          * 1) src_reg might be zero, so the sign bit of the result is
8876          *    unknown, so we lose our signed bounds
8877          * 2) it's known negative, thus the unsigned bounds capture the
8878          *    signed bounds
8879          * 3) the signed bounds cross zero, so they tell us nothing
8880          *    about the result
8881          * If the value in dst_reg is known nonnegative, then again the
8882          * unsigned bounds capture the signed bounds.
8883          * Thus, in all cases it suffices to blow away our signed bounds
8884          * and rely on inferring new ones from the unsigned bounds and
8885          * var_off of the result.
8886          */
8887         dst_reg->s32_min_value = S32_MIN;
8888         dst_reg->s32_max_value = S32_MAX;
8889
8890         dst_reg->var_off = tnum_rshift(subreg, umin_val);
8891         dst_reg->u32_min_value >>= umax_val;
8892         dst_reg->u32_max_value >>= umin_val;
8893
8894         __mark_reg64_unbounded(dst_reg);
8895         __update_reg32_bounds(dst_reg);
8896 }
8897
8898 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8899                                struct bpf_reg_state *src_reg)
8900 {
8901         u64 umax_val = src_reg->umax_value;
8902         u64 umin_val = src_reg->umin_value;
8903
8904         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8905          * be negative, then either:
8906          * 1) src_reg might be zero, so the sign bit of the result is
8907          *    unknown, so we lose our signed bounds
8908          * 2) it's known negative, thus the unsigned bounds capture the
8909          *    signed bounds
8910          * 3) the signed bounds cross zero, so they tell us nothing
8911          *    about the result
8912          * If the value in dst_reg is known nonnegative, then again the
8913          * unsigned bounds capture the signed bounds.
8914          * Thus, in all cases it suffices to blow away our signed bounds
8915          * and rely on inferring new ones from the unsigned bounds and
8916          * var_off of the result.
8917          */
8918         dst_reg->smin_value = S64_MIN;
8919         dst_reg->smax_value = S64_MAX;
8920         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8921         dst_reg->umin_value >>= umax_val;
8922         dst_reg->umax_value >>= umin_val;
8923
8924         /* Its not easy to operate on alu32 bounds here because it depends
8925          * on bits being shifted in. Take easy way out and mark unbounded
8926          * so we can recalculate later from tnum.
8927          */
8928         __mark_reg32_unbounded(dst_reg);
8929         __update_reg_bounds(dst_reg);
8930 }
8931
8932 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8933                                   struct bpf_reg_state *src_reg)
8934 {
8935         u64 umin_val = src_reg->u32_min_value;
8936
8937         /* Upon reaching here, src_known is true and
8938          * umax_val is equal to umin_val.
8939          */
8940         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8941         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8942
8943         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8944
8945         /* blow away the dst_reg umin_value/umax_value and rely on
8946          * dst_reg var_off to refine the result.
8947          */
8948         dst_reg->u32_min_value = 0;
8949         dst_reg->u32_max_value = U32_MAX;
8950
8951         __mark_reg64_unbounded(dst_reg);
8952         __update_reg32_bounds(dst_reg);
8953 }
8954
8955 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8956                                 struct bpf_reg_state *src_reg)
8957 {
8958         u64 umin_val = src_reg->umin_value;
8959
8960         /* Upon reaching here, src_known is true and umax_val is equal
8961          * to umin_val.
8962          */
8963         dst_reg->smin_value >>= umin_val;
8964         dst_reg->smax_value >>= umin_val;
8965
8966         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8967
8968         /* blow away the dst_reg umin_value/umax_value and rely on
8969          * dst_reg var_off to refine the result.
8970          */
8971         dst_reg->umin_value = 0;
8972         dst_reg->umax_value = U64_MAX;
8973
8974         /* Its not easy to operate on alu32 bounds here because it depends
8975          * on bits being shifted in from upper 32-bits. Take easy way out
8976          * and mark unbounded so we can recalculate later from tnum.
8977          */
8978         __mark_reg32_unbounded(dst_reg);
8979         __update_reg_bounds(dst_reg);
8980 }
8981
8982 /* WARNING: This function does calculations on 64-bit values, but the actual
8983  * execution may occur on 32-bit values. Therefore, things like bitshifts
8984  * need extra checks in the 32-bit case.
8985  */
8986 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8987                                       struct bpf_insn *insn,
8988                                       struct bpf_reg_state *dst_reg,
8989                                       struct bpf_reg_state src_reg)
8990 {
8991         struct bpf_reg_state *regs = cur_regs(env);
8992         u8 opcode = BPF_OP(insn->code);
8993         bool src_known;
8994         s64 smin_val, smax_val;
8995         u64 umin_val, umax_val;
8996         s32 s32_min_val, s32_max_val;
8997         u32 u32_min_val, u32_max_val;
8998         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8999         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9000         int ret;
9001
9002         smin_val = src_reg.smin_value;
9003         smax_val = src_reg.smax_value;
9004         umin_val = src_reg.umin_value;
9005         umax_val = src_reg.umax_value;
9006
9007         s32_min_val = src_reg.s32_min_value;
9008         s32_max_val = src_reg.s32_max_value;
9009         u32_min_val = src_reg.u32_min_value;
9010         u32_max_val = src_reg.u32_max_value;
9011
9012         if (alu32) {
9013                 src_known = tnum_subreg_is_const(src_reg.var_off);
9014                 if ((src_known &&
9015                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9016                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9017                         /* Taint dst register if offset had invalid bounds
9018                          * derived from e.g. dead branches.
9019                          */
9020                         __mark_reg_unknown(env, dst_reg);
9021                         return 0;
9022                 }
9023         } else {
9024                 src_known = tnum_is_const(src_reg.var_off);
9025                 if ((src_known &&
9026                      (smin_val != smax_val || umin_val != umax_val)) ||
9027                     smin_val > smax_val || umin_val > umax_val) {
9028                         /* Taint dst register if offset had invalid bounds
9029                          * derived from e.g. dead branches.
9030                          */
9031                         __mark_reg_unknown(env, dst_reg);
9032                         return 0;
9033                 }
9034         }
9035
9036         if (!src_known &&
9037             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9038                 __mark_reg_unknown(env, dst_reg);
9039                 return 0;
9040         }
9041
9042         if (sanitize_needed(opcode)) {
9043                 ret = sanitize_val_alu(env, insn);
9044                 if (ret < 0)
9045                         return sanitize_err(env, insn, ret, NULL, NULL);
9046         }
9047
9048         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9049          * There are two classes of instructions: The first class we track both
9050          * alu32 and alu64 sign/unsigned bounds independently this provides the
9051          * greatest amount of precision when alu operations are mixed with jmp32
9052          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9053          * and BPF_OR. This is possible because these ops have fairly easy to
9054          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9055          * See alu32 verifier tests for examples. The second class of
9056          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9057          * with regards to tracking sign/unsigned bounds because the bits may
9058          * cross subreg boundaries in the alu64 case. When this happens we mark
9059          * the reg unbounded in the subreg bound space and use the resulting
9060          * tnum to calculate an approximation of the sign/unsigned bounds.
9061          */
9062         switch (opcode) {
9063         case BPF_ADD:
9064                 scalar32_min_max_add(dst_reg, &src_reg);
9065                 scalar_min_max_add(dst_reg, &src_reg);
9066                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9067                 break;
9068         case BPF_SUB:
9069                 scalar32_min_max_sub(dst_reg, &src_reg);
9070                 scalar_min_max_sub(dst_reg, &src_reg);
9071                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9072                 break;
9073         case BPF_MUL:
9074                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9075                 scalar32_min_max_mul(dst_reg, &src_reg);
9076                 scalar_min_max_mul(dst_reg, &src_reg);
9077                 break;
9078         case BPF_AND:
9079                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9080                 scalar32_min_max_and(dst_reg, &src_reg);
9081                 scalar_min_max_and(dst_reg, &src_reg);
9082                 break;
9083         case BPF_OR:
9084                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9085                 scalar32_min_max_or(dst_reg, &src_reg);
9086                 scalar_min_max_or(dst_reg, &src_reg);
9087                 break;
9088         case BPF_XOR:
9089                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9090                 scalar32_min_max_xor(dst_reg, &src_reg);
9091                 scalar_min_max_xor(dst_reg, &src_reg);
9092                 break;
9093         case BPF_LSH:
9094                 if (umax_val >= insn_bitness) {
9095                         /* Shifts greater than 31 or 63 are undefined.
9096                          * This includes shifts by a negative number.
9097                          */
9098                         mark_reg_unknown(env, regs, insn->dst_reg);
9099                         break;
9100                 }
9101                 if (alu32)
9102                         scalar32_min_max_lsh(dst_reg, &src_reg);
9103                 else
9104                         scalar_min_max_lsh(dst_reg, &src_reg);
9105                 break;
9106         case BPF_RSH:
9107                 if (umax_val >= insn_bitness) {
9108                         /* Shifts greater than 31 or 63 are undefined.
9109                          * This includes shifts by a negative number.
9110                          */
9111                         mark_reg_unknown(env, regs, insn->dst_reg);
9112                         break;
9113                 }
9114                 if (alu32)
9115                         scalar32_min_max_rsh(dst_reg, &src_reg);
9116                 else
9117                         scalar_min_max_rsh(dst_reg, &src_reg);
9118                 break;
9119         case BPF_ARSH:
9120                 if (umax_val >= insn_bitness) {
9121                         /* Shifts greater than 31 or 63 are undefined.
9122                          * This includes shifts by a negative number.
9123                          */
9124                         mark_reg_unknown(env, regs, insn->dst_reg);
9125                         break;
9126                 }
9127                 if (alu32)
9128                         scalar32_min_max_arsh(dst_reg, &src_reg);
9129                 else
9130                         scalar_min_max_arsh(dst_reg, &src_reg);
9131                 break;
9132         default:
9133                 mark_reg_unknown(env, regs, insn->dst_reg);
9134                 break;
9135         }
9136
9137         /* ALU32 ops are zero extended into 64bit register */
9138         if (alu32)
9139                 zext_32_to_64(dst_reg);
9140         reg_bounds_sync(dst_reg);
9141         return 0;
9142 }
9143
9144 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9145  * and var_off.
9146  */
9147 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9148                                    struct bpf_insn *insn)
9149 {
9150         struct bpf_verifier_state *vstate = env->cur_state;
9151         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9152         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9153         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9154         u8 opcode = BPF_OP(insn->code);
9155         int err;
9156
9157         dst_reg = &regs[insn->dst_reg];
9158         src_reg = NULL;
9159         if (dst_reg->type != SCALAR_VALUE)
9160                 ptr_reg = dst_reg;
9161         else
9162                 /* Make sure ID is cleared otherwise dst_reg min/max could be
9163                  * incorrectly propagated into other registers by find_equal_scalars()
9164                  */
9165                 dst_reg->id = 0;
9166         if (BPF_SRC(insn->code) == BPF_X) {
9167                 src_reg = &regs[insn->src_reg];
9168                 if (src_reg->type != SCALAR_VALUE) {
9169                         if (dst_reg->type != SCALAR_VALUE) {
9170                                 /* Combining two pointers by any ALU op yields
9171                                  * an arbitrary scalar. Disallow all math except
9172                                  * pointer subtraction
9173                                  */
9174                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9175                                         mark_reg_unknown(env, regs, insn->dst_reg);
9176                                         return 0;
9177                                 }
9178                                 verbose(env, "R%d pointer %s pointer prohibited\n",
9179                                         insn->dst_reg,
9180                                         bpf_alu_string[opcode >> 4]);
9181                                 return -EACCES;
9182                         } else {
9183                                 /* scalar += pointer
9184                                  * This is legal, but we have to reverse our
9185                                  * src/dest handling in computing the range
9186                                  */
9187                                 err = mark_chain_precision(env, insn->dst_reg);
9188                                 if (err)
9189                                         return err;
9190                                 return adjust_ptr_min_max_vals(env, insn,
9191                                                                src_reg, dst_reg);
9192                         }
9193                 } else if (ptr_reg) {
9194                         /* pointer += scalar */
9195                         err = mark_chain_precision(env, insn->src_reg);
9196                         if (err)
9197                                 return err;
9198                         return adjust_ptr_min_max_vals(env, insn,
9199                                                        dst_reg, src_reg);
9200                 }
9201         } else {
9202                 /* Pretend the src is a reg with a known value, since we only
9203                  * need to be able to read from this state.
9204                  */
9205                 off_reg.type = SCALAR_VALUE;
9206                 __mark_reg_known(&off_reg, insn->imm);
9207                 src_reg = &off_reg;
9208                 if (ptr_reg) /* pointer += K */
9209                         return adjust_ptr_min_max_vals(env, insn,
9210                                                        ptr_reg, src_reg);
9211         }
9212
9213         /* Got here implies adding two SCALAR_VALUEs */
9214         if (WARN_ON_ONCE(ptr_reg)) {
9215                 print_verifier_state(env, state, true);
9216                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9217                 return -EINVAL;
9218         }
9219         if (WARN_ON(!src_reg)) {
9220                 print_verifier_state(env, state, true);
9221                 verbose(env, "verifier internal error: no src_reg\n");
9222                 return -EINVAL;
9223         }
9224         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9225 }
9226
9227 /* check validity of 32-bit and 64-bit arithmetic operations */
9228 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9229 {
9230         struct bpf_reg_state *regs = cur_regs(env);
9231         u8 opcode = BPF_OP(insn->code);
9232         int err;
9233
9234         if (opcode == BPF_END || opcode == BPF_NEG) {
9235                 if (opcode == BPF_NEG) {
9236                         if (BPF_SRC(insn->code) != BPF_K ||
9237                             insn->src_reg != BPF_REG_0 ||
9238                             insn->off != 0 || insn->imm != 0) {
9239                                 verbose(env, "BPF_NEG uses reserved fields\n");
9240                                 return -EINVAL;
9241                         }
9242                 } else {
9243                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9244                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9245                             BPF_CLASS(insn->code) == BPF_ALU64) {
9246                                 verbose(env, "BPF_END uses reserved fields\n");
9247                                 return -EINVAL;
9248                         }
9249                 }
9250
9251                 /* check src operand */
9252                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9253                 if (err)
9254                         return err;
9255
9256                 if (is_pointer_value(env, insn->dst_reg)) {
9257                         verbose(env, "R%d pointer arithmetic prohibited\n",
9258                                 insn->dst_reg);
9259                         return -EACCES;
9260                 }
9261
9262                 /* check dest operand */
9263                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9264                 if (err)
9265                         return err;
9266
9267         } else if (opcode == BPF_MOV) {
9268
9269                 if (BPF_SRC(insn->code) == BPF_X) {
9270                         if (insn->imm != 0 || insn->off != 0) {
9271                                 verbose(env, "BPF_MOV uses reserved fields\n");
9272                                 return -EINVAL;
9273                         }
9274
9275                         /* check src operand */
9276                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9277                         if (err)
9278                                 return err;
9279                 } else {
9280                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9281                                 verbose(env, "BPF_MOV uses reserved fields\n");
9282                                 return -EINVAL;
9283                         }
9284                 }
9285
9286                 /* check dest operand, mark as required later */
9287                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9288                 if (err)
9289                         return err;
9290
9291                 if (BPF_SRC(insn->code) == BPF_X) {
9292                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
9293                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9294
9295                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9296                                 /* case: R1 = R2
9297                                  * copy register state to dest reg
9298                                  */
9299                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9300                                         /* Assign src and dst registers the same ID
9301                                          * that will be used by find_equal_scalars()
9302                                          * to propagate min/max range.
9303                                          */
9304                                         src_reg->id = ++env->id_gen;
9305                                 *dst_reg = *src_reg;
9306                                 dst_reg->live |= REG_LIVE_WRITTEN;
9307                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
9308                         } else {
9309                                 /* R1 = (u32) R2 */
9310                                 if (is_pointer_value(env, insn->src_reg)) {
9311                                         verbose(env,
9312                                                 "R%d partial copy of pointer\n",
9313                                                 insn->src_reg);
9314                                         return -EACCES;
9315                                 } else if (src_reg->type == SCALAR_VALUE) {
9316                                         *dst_reg = *src_reg;
9317                                         /* Make sure ID is cleared otherwise
9318                                          * dst_reg min/max could be incorrectly
9319                                          * propagated into src_reg by find_equal_scalars()
9320                                          */
9321                                         dst_reg->id = 0;
9322                                         dst_reg->live |= REG_LIVE_WRITTEN;
9323                                         dst_reg->subreg_def = env->insn_idx + 1;
9324                                 } else {
9325                                         mark_reg_unknown(env, regs,
9326                                                          insn->dst_reg);
9327                                 }
9328                                 zext_32_to_64(dst_reg);
9329                                 reg_bounds_sync(dst_reg);
9330                         }
9331                 } else {
9332                         /* case: R = imm
9333                          * remember the value we stored into this reg
9334                          */
9335                         /* clear any state __mark_reg_known doesn't set */
9336                         mark_reg_unknown(env, regs, insn->dst_reg);
9337                         regs[insn->dst_reg].type = SCALAR_VALUE;
9338                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9339                                 __mark_reg_known(regs + insn->dst_reg,
9340                                                  insn->imm);
9341                         } else {
9342                                 __mark_reg_known(regs + insn->dst_reg,
9343                                                  (u32)insn->imm);
9344                         }
9345                 }
9346
9347         } else if (opcode > BPF_END) {
9348                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9349                 return -EINVAL;
9350
9351         } else {        /* all other ALU ops: and, sub, xor, add, ... */
9352
9353                 if (BPF_SRC(insn->code) == BPF_X) {
9354                         if (insn->imm != 0 || insn->off != 0) {
9355                                 verbose(env, "BPF_ALU uses reserved fields\n");
9356                                 return -EINVAL;
9357                         }
9358                         /* check src1 operand */
9359                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9360                         if (err)
9361                                 return err;
9362                 } else {
9363                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9364                                 verbose(env, "BPF_ALU uses reserved fields\n");
9365                                 return -EINVAL;
9366                         }
9367                 }
9368
9369                 /* check src2 operand */
9370                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9371                 if (err)
9372                         return err;
9373
9374                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9375                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9376                         verbose(env, "div by zero\n");
9377                         return -EINVAL;
9378                 }
9379
9380                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9381                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9382                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9383
9384                         if (insn->imm < 0 || insn->imm >= size) {
9385                                 verbose(env, "invalid shift %d\n", insn->imm);
9386                                 return -EINVAL;
9387                         }
9388                 }
9389
9390                 /* check dest operand */
9391                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9392                 if (err)
9393                         return err;
9394
9395                 return adjust_reg_min_max_vals(env, insn);
9396         }
9397
9398         return 0;
9399 }
9400
9401 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9402                                    struct bpf_reg_state *dst_reg,
9403                                    enum bpf_reg_type type,
9404                                    bool range_right_open)
9405 {
9406         struct bpf_func_state *state;
9407         struct bpf_reg_state *reg;
9408         int new_range;
9409
9410         if (dst_reg->off < 0 ||
9411             (dst_reg->off == 0 && range_right_open))
9412                 /* This doesn't give us any range */
9413                 return;
9414
9415         if (dst_reg->umax_value > MAX_PACKET_OFF ||
9416             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9417                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
9418                  * than pkt_end, but that's because it's also less than pkt.
9419                  */
9420                 return;
9421
9422         new_range = dst_reg->off;
9423         if (range_right_open)
9424                 new_range++;
9425
9426         /* Examples for register markings:
9427          *
9428          * pkt_data in dst register:
9429          *
9430          *   r2 = r3;
9431          *   r2 += 8;
9432          *   if (r2 > pkt_end) goto <handle exception>
9433          *   <access okay>
9434          *
9435          *   r2 = r3;
9436          *   r2 += 8;
9437          *   if (r2 < pkt_end) goto <access okay>
9438          *   <handle exception>
9439          *
9440          *   Where:
9441          *     r2 == dst_reg, pkt_end == src_reg
9442          *     r2=pkt(id=n,off=8,r=0)
9443          *     r3=pkt(id=n,off=0,r=0)
9444          *
9445          * pkt_data in src register:
9446          *
9447          *   r2 = r3;
9448          *   r2 += 8;
9449          *   if (pkt_end >= r2) goto <access okay>
9450          *   <handle exception>
9451          *
9452          *   r2 = r3;
9453          *   r2 += 8;
9454          *   if (pkt_end <= r2) goto <handle exception>
9455          *   <access okay>
9456          *
9457          *   Where:
9458          *     pkt_end == dst_reg, r2 == src_reg
9459          *     r2=pkt(id=n,off=8,r=0)
9460          *     r3=pkt(id=n,off=0,r=0)
9461          *
9462          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9463          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9464          * and [r3, r3 + 8-1) respectively is safe to access depending on
9465          * the check.
9466          */
9467
9468         /* If our ids match, then we must have the same max_value.  And we
9469          * don't care about the other reg's fixed offset, since if it's too big
9470          * the range won't allow anything.
9471          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9472          */
9473         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9474                 if (reg->type == type && reg->id == dst_reg->id)
9475                         /* keep the maximum range already checked */
9476                         reg->range = max(reg->range, new_range);
9477         }));
9478 }
9479
9480 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9481 {
9482         struct tnum subreg = tnum_subreg(reg->var_off);
9483         s32 sval = (s32)val;
9484
9485         switch (opcode) {
9486         case BPF_JEQ:
9487                 if (tnum_is_const(subreg))
9488                         return !!tnum_equals_const(subreg, val);
9489                 break;
9490         case BPF_JNE:
9491                 if (tnum_is_const(subreg))
9492                         return !tnum_equals_const(subreg, val);
9493                 break;
9494         case BPF_JSET:
9495                 if ((~subreg.mask & subreg.value) & val)
9496                         return 1;
9497                 if (!((subreg.mask | subreg.value) & val))
9498                         return 0;
9499                 break;
9500         case BPF_JGT:
9501                 if (reg->u32_min_value > val)
9502                         return 1;
9503                 else if (reg->u32_max_value <= val)
9504                         return 0;
9505                 break;
9506         case BPF_JSGT:
9507                 if (reg->s32_min_value > sval)
9508                         return 1;
9509                 else if (reg->s32_max_value <= sval)
9510                         return 0;
9511                 break;
9512         case BPF_JLT:
9513                 if (reg->u32_max_value < val)
9514                         return 1;
9515                 else if (reg->u32_min_value >= val)
9516                         return 0;
9517                 break;
9518         case BPF_JSLT:
9519                 if (reg->s32_max_value < sval)
9520                         return 1;
9521                 else if (reg->s32_min_value >= sval)
9522                         return 0;
9523                 break;
9524         case BPF_JGE:
9525                 if (reg->u32_min_value >= val)
9526                         return 1;
9527                 else if (reg->u32_max_value < val)
9528                         return 0;
9529                 break;
9530         case BPF_JSGE:
9531                 if (reg->s32_min_value >= sval)
9532                         return 1;
9533                 else if (reg->s32_max_value < sval)
9534                         return 0;
9535                 break;
9536         case BPF_JLE:
9537                 if (reg->u32_max_value <= val)
9538                         return 1;
9539                 else if (reg->u32_min_value > val)
9540                         return 0;
9541                 break;
9542         case BPF_JSLE:
9543                 if (reg->s32_max_value <= sval)
9544                         return 1;
9545                 else if (reg->s32_min_value > sval)
9546                         return 0;
9547                 break;
9548         }
9549
9550         return -1;
9551 }
9552
9553
9554 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9555 {
9556         s64 sval = (s64)val;
9557
9558         switch (opcode) {
9559         case BPF_JEQ:
9560                 if (tnum_is_const(reg->var_off))
9561                         return !!tnum_equals_const(reg->var_off, val);
9562                 break;
9563         case BPF_JNE:
9564                 if (tnum_is_const(reg->var_off))
9565                         return !tnum_equals_const(reg->var_off, val);
9566                 break;
9567         case BPF_JSET:
9568                 if ((~reg->var_off.mask & reg->var_off.value) & val)
9569                         return 1;
9570                 if (!((reg->var_off.mask | reg->var_off.value) & val))
9571                         return 0;
9572                 break;
9573         case BPF_JGT:
9574                 if (reg->umin_value > val)
9575                         return 1;
9576                 else if (reg->umax_value <= val)
9577                         return 0;
9578                 break;
9579         case BPF_JSGT:
9580                 if (reg->smin_value > sval)
9581                         return 1;
9582                 else if (reg->smax_value <= sval)
9583                         return 0;
9584                 break;
9585         case BPF_JLT:
9586                 if (reg->umax_value < val)
9587                         return 1;
9588                 else if (reg->umin_value >= val)
9589                         return 0;
9590                 break;
9591         case BPF_JSLT:
9592                 if (reg->smax_value < sval)
9593                         return 1;
9594                 else if (reg->smin_value >= sval)
9595                         return 0;
9596                 break;
9597         case BPF_JGE:
9598                 if (reg->umin_value >= val)
9599                         return 1;
9600                 else if (reg->umax_value < val)
9601                         return 0;
9602                 break;
9603         case BPF_JSGE:
9604                 if (reg->smin_value >= sval)
9605                         return 1;
9606                 else if (reg->smax_value < sval)
9607                         return 0;
9608                 break;
9609         case BPF_JLE:
9610                 if (reg->umax_value <= val)
9611                         return 1;
9612                 else if (reg->umin_value > val)
9613                         return 0;
9614                 break;
9615         case BPF_JSLE:
9616                 if (reg->smax_value <= sval)
9617                         return 1;
9618                 else if (reg->smin_value > sval)
9619                         return 0;
9620                 break;
9621         }
9622
9623         return -1;
9624 }
9625
9626 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9627  * and return:
9628  *  1 - branch will be taken and "goto target" will be executed
9629  *  0 - branch will not be taken and fall-through to next insn
9630  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9631  *      range [0,10]
9632  */
9633 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9634                            bool is_jmp32)
9635 {
9636         if (__is_pointer_value(false, reg)) {
9637                 if (!reg_type_not_null(reg->type))
9638                         return -1;
9639
9640                 /* If pointer is valid tests against zero will fail so we can
9641                  * use this to direct branch taken.
9642                  */
9643                 if (val != 0)
9644                         return -1;
9645
9646                 switch (opcode) {
9647                 case BPF_JEQ:
9648                         return 0;
9649                 case BPF_JNE:
9650                         return 1;
9651                 default:
9652                         return -1;
9653                 }
9654         }
9655
9656         if (is_jmp32)
9657                 return is_branch32_taken(reg, val, opcode);
9658         return is_branch64_taken(reg, val, opcode);
9659 }
9660
9661 static int flip_opcode(u32 opcode)
9662 {
9663         /* How can we transform "a <op> b" into "b <op> a"? */
9664         static const u8 opcode_flip[16] = {
9665                 /* these stay the same */
9666                 [BPF_JEQ  >> 4] = BPF_JEQ,
9667                 [BPF_JNE  >> 4] = BPF_JNE,
9668                 [BPF_JSET >> 4] = BPF_JSET,
9669                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9670                 [BPF_JGE  >> 4] = BPF_JLE,
9671                 [BPF_JGT  >> 4] = BPF_JLT,
9672                 [BPF_JLE  >> 4] = BPF_JGE,
9673                 [BPF_JLT  >> 4] = BPF_JGT,
9674                 [BPF_JSGE >> 4] = BPF_JSLE,
9675                 [BPF_JSGT >> 4] = BPF_JSLT,
9676                 [BPF_JSLE >> 4] = BPF_JSGE,
9677                 [BPF_JSLT >> 4] = BPF_JSGT
9678         };
9679         return opcode_flip[opcode >> 4];
9680 }
9681
9682 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9683                                    struct bpf_reg_state *src_reg,
9684                                    u8 opcode)
9685 {
9686         struct bpf_reg_state *pkt;
9687
9688         if (src_reg->type == PTR_TO_PACKET_END) {
9689                 pkt = dst_reg;
9690         } else if (dst_reg->type == PTR_TO_PACKET_END) {
9691                 pkt = src_reg;
9692                 opcode = flip_opcode(opcode);
9693         } else {
9694                 return -1;
9695         }
9696
9697         if (pkt->range >= 0)
9698                 return -1;
9699
9700         switch (opcode) {
9701         case BPF_JLE:
9702                 /* pkt <= pkt_end */
9703                 fallthrough;
9704         case BPF_JGT:
9705                 /* pkt > pkt_end */
9706                 if (pkt->range == BEYOND_PKT_END)
9707                         /* pkt has at last one extra byte beyond pkt_end */
9708                         return opcode == BPF_JGT;
9709                 break;
9710         case BPF_JLT:
9711                 /* pkt < pkt_end */
9712                 fallthrough;
9713         case BPF_JGE:
9714                 /* pkt >= pkt_end */
9715                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9716                         return opcode == BPF_JGE;
9717                 break;
9718         }
9719         return -1;
9720 }
9721
9722 /* Adjusts the register min/max values in the case that the dst_reg is the
9723  * variable register that we are working on, and src_reg is a constant or we're
9724  * simply doing a BPF_K check.
9725  * In JEQ/JNE cases we also adjust the var_off values.
9726  */
9727 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9728                             struct bpf_reg_state *false_reg,
9729                             u64 val, u32 val32,
9730                             u8 opcode, bool is_jmp32)
9731 {
9732         struct tnum false_32off = tnum_subreg(false_reg->var_off);
9733         struct tnum false_64off = false_reg->var_off;
9734         struct tnum true_32off = tnum_subreg(true_reg->var_off);
9735         struct tnum true_64off = true_reg->var_off;
9736         s64 sval = (s64)val;
9737         s32 sval32 = (s32)val32;
9738
9739         /* If the dst_reg is a pointer, we can't learn anything about its
9740          * variable offset from the compare (unless src_reg were a pointer into
9741          * the same object, but we don't bother with that.
9742          * Since false_reg and true_reg have the same type by construction, we
9743          * only need to check one of them for pointerness.
9744          */
9745         if (__is_pointer_value(false, false_reg))
9746                 return;
9747
9748         switch (opcode) {
9749         /* JEQ/JNE comparison doesn't change the register equivalence.
9750          *
9751          * r1 = r2;
9752          * if (r1 == 42) goto label;
9753          * ...
9754          * label: // here both r1 and r2 are known to be 42.
9755          *
9756          * Hence when marking register as known preserve it's ID.
9757          */
9758         case BPF_JEQ:
9759                 if (is_jmp32) {
9760                         __mark_reg32_known(true_reg, val32);
9761                         true_32off = tnum_subreg(true_reg->var_off);
9762                 } else {
9763                         ___mark_reg_known(true_reg, val);
9764                         true_64off = true_reg->var_off;
9765                 }
9766                 break;
9767         case BPF_JNE:
9768                 if (is_jmp32) {
9769                         __mark_reg32_known(false_reg, val32);
9770                         false_32off = tnum_subreg(false_reg->var_off);
9771                 } else {
9772                         ___mark_reg_known(false_reg, val);
9773                         false_64off = false_reg->var_off;
9774                 }
9775                 break;
9776         case BPF_JSET:
9777                 if (is_jmp32) {
9778                         false_32off = tnum_and(false_32off, tnum_const(~val32));
9779                         if (is_power_of_2(val32))
9780                                 true_32off = tnum_or(true_32off,
9781                                                      tnum_const(val32));
9782                 } else {
9783                         false_64off = tnum_and(false_64off, tnum_const(~val));
9784                         if (is_power_of_2(val))
9785                                 true_64off = tnum_or(true_64off,
9786                                                      tnum_const(val));
9787                 }
9788                 break;
9789         case BPF_JGE:
9790         case BPF_JGT:
9791         {
9792                 if (is_jmp32) {
9793                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9794                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9795
9796                         false_reg->u32_max_value = min(false_reg->u32_max_value,
9797                                                        false_umax);
9798                         true_reg->u32_min_value = max(true_reg->u32_min_value,
9799                                                       true_umin);
9800                 } else {
9801                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9802                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9803
9804                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
9805                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
9806                 }
9807                 break;
9808         }
9809         case BPF_JSGE:
9810         case BPF_JSGT:
9811         {
9812                 if (is_jmp32) {
9813                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9814                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9815
9816                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9817                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9818                 } else {
9819                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9820                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9821
9822                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
9823                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
9824                 }
9825                 break;
9826         }
9827         case BPF_JLE:
9828         case BPF_JLT:
9829         {
9830                 if (is_jmp32) {
9831                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9832                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9833
9834                         false_reg->u32_min_value = max(false_reg->u32_min_value,
9835                                                        false_umin);
9836                         true_reg->u32_max_value = min(true_reg->u32_max_value,
9837                                                       true_umax);
9838                 } else {
9839                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9840                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9841
9842                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
9843                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
9844                 }
9845                 break;
9846         }
9847         case BPF_JSLE:
9848         case BPF_JSLT:
9849         {
9850                 if (is_jmp32) {
9851                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9852                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9853
9854                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9855                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9856                 } else {
9857                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9858                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9859
9860                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
9861                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
9862                 }
9863                 break;
9864         }
9865         default:
9866                 return;
9867         }
9868
9869         if (is_jmp32) {
9870                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9871                                              tnum_subreg(false_32off));
9872                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9873                                             tnum_subreg(true_32off));
9874                 __reg_combine_32_into_64(false_reg);
9875                 __reg_combine_32_into_64(true_reg);
9876         } else {
9877                 false_reg->var_off = false_64off;
9878                 true_reg->var_off = true_64off;
9879                 __reg_combine_64_into_32(false_reg);
9880                 __reg_combine_64_into_32(true_reg);
9881         }
9882 }
9883
9884 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9885  * the variable reg.
9886  */
9887 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9888                                 struct bpf_reg_state *false_reg,
9889                                 u64 val, u32 val32,
9890                                 u8 opcode, bool is_jmp32)
9891 {
9892         opcode = flip_opcode(opcode);
9893         /* This uses zero as "not present in table"; luckily the zero opcode,
9894          * BPF_JA, can't get here.
9895          */
9896         if (opcode)
9897                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9898 }
9899
9900 /* Regs are known to be equal, so intersect their min/max/var_off */
9901 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9902                                   struct bpf_reg_state *dst_reg)
9903 {
9904         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9905                                                         dst_reg->umin_value);
9906         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9907                                                         dst_reg->umax_value);
9908         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9909                                                         dst_reg->smin_value);
9910         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9911                                                         dst_reg->smax_value);
9912         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9913                                                              dst_reg->var_off);
9914         reg_bounds_sync(src_reg);
9915         reg_bounds_sync(dst_reg);
9916 }
9917
9918 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9919                                 struct bpf_reg_state *true_dst,
9920                                 struct bpf_reg_state *false_src,
9921                                 struct bpf_reg_state *false_dst,
9922                                 u8 opcode)
9923 {
9924         switch (opcode) {
9925         case BPF_JEQ:
9926                 __reg_combine_min_max(true_src, true_dst);
9927                 break;
9928         case BPF_JNE:
9929                 __reg_combine_min_max(false_src, false_dst);
9930                 break;
9931         }
9932 }
9933
9934 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9935                                  struct bpf_reg_state *reg, u32 id,
9936                                  bool is_null)
9937 {
9938         if (type_may_be_null(reg->type) && reg->id == id &&
9939             !WARN_ON_ONCE(!reg->id)) {
9940                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9941                                  !tnum_equals_const(reg->var_off, 0) ||
9942                                  reg->off)) {
9943                         /* Old offset (both fixed and variable parts) should
9944                          * have been known-zero, because we don't allow pointer
9945                          * arithmetic on pointers that might be NULL. If we
9946                          * see this happening, don't convert the register.
9947                          */
9948                         return;
9949                 }
9950                 if (is_null) {
9951                         reg->type = SCALAR_VALUE;
9952                         /* We don't need id and ref_obj_id from this point
9953                          * onwards anymore, thus we should better reset it,
9954                          * so that state pruning has chances to take effect.
9955                          */
9956                         reg->id = 0;
9957                         reg->ref_obj_id = 0;
9958
9959                         return;
9960                 }
9961
9962                 mark_ptr_not_null_reg(reg);
9963
9964                 if (!reg_may_point_to_spin_lock(reg)) {
9965                         /* For not-NULL ptr, reg->ref_obj_id will be reset
9966                          * in release_reference().
9967                          *
9968                          * reg->id is still used by spin_lock ptr. Other
9969                          * than spin_lock ptr type, reg->id can be reset.
9970                          */
9971                         reg->id = 0;
9972                 }
9973         }
9974 }
9975
9976 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9977  * be folded together at some point.
9978  */
9979 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9980                                   bool is_null)
9981 {
9982         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9983         struct bpf_reg_state *regs = state->regs, *reg;
9984         u32 ref_obj_id = regs[regno].ref_obj_id;
9985         u32 id = regs[regno].id;
9986
9987         if (ref_obj_id && ref_obj_id == id && is_null)
9988                 /* regs[regno] is in the " == NULL" branch.
9989                  * No one could have freed the reference state before
9990                  * doing the NULL check.
9991                  */
9992                 WARN_ON_ONCE(release_reference_state(state, id));
9993
9994         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9995                 mark_ptr_or_null_reg(state, reg, id, is_null);
9996         }));
9997 }
9998
9999 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10000                                    struct bpf_reg_state *dst_reg,
10001                                    struct bpf_reg_state *src_reg,
10002                                    struct bpf_verifier_state *this_branch,
10003                                    struct bpf_verifier_state *other_branch)
10004 {
10005         if (BPF_SRC(insn->code) != BPF_X)
10006                 return false;
10007
10008         /* Pointers are always 64-bit. */
10009         if (BPF_CLASS(insn->code) == BPF_JMP32)
10010                 return false;
10011
10012         switch (BPF_OP(insn->code)) {
10013         case BPF_JGT:
10014                 if ((dst_reg->type == PTR_TO_PACKET &&
10015                      src_reg->type == PTR_TO_PACKET_END) ||
10016                     (dst_reg->type == PTR_TO_PACKET_META &&
10017                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10018                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10019                         find_good_pkt_pointers(this_branch, dst_reg,
10020                                                dst_reg->type, false);
10021                         mark_pkt_end(other_branch, insn->dst_reg, true);
10022                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10023                             src_reg->type == PTR_TO_PACKET) ||
10024                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10025                             src_reg->type == PTR_TO_PACKET_META)) {
10026                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10027                         find_good_pkt_pointers(other_branch, src_reg,
10028                                                src_reg->type, true);
10029                         mark_pkt_end(this_branch, insn->src_reg, false);
10030                 } else {
10031                         return false;
10032                 }
10033                 break;
10034         case BPF_JLT:
10035                 if ((dst_reg->type == PTR_TO_PACKET &&
10036                      src_reg->type == PTR_TO_PACKET_END) ||
10037                     (dst_reg->type == PTR_TO_PACKET_META &&
10038                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10039                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10040                         find_good_pkt_pointers(other_branch, dst_reg,
10041                                                dst_reg->type, true);
10042                         mark_pkt_end(this_branch, insn->dst_reg, false);
10043                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10044                             src_reg->type == PTR_TO_PACKET) ||
10045                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10046                             src_reg->type == PTR_TO_PACKET_META)) {
10047                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10048                         find_good_pkt_pointers(this_branch, src_reg,
10049                                                src_reg->type, false);
10050                         mark_pkt_end(other_branch, insn->src_reg, true);
10051                 } else {
10052                         return false;
10053                 }
10054                 break;
10055         case BPF_JGE:
10056                 if ((dst_reg->type == PTR_TO_PACKET &&
10057                      src_reg->type == PTR_TO_PACKET_END) ||
10058                     (dst_reg->type == PTR_TO_PACKET_META &&
10059                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10060                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10061                         find_good_pkt_pointers(this_branch, dst_reg,
10062                                                dst_reg->type, true);
10063                         mark_pkt_end(other_branch, insn->dst_reg, false);
10064                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10065                             src_reg->type == PTR_TO_PACKET) ||
10066                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10067                             src_reg->type == PTR_TO_PACKET_META)) {
10068                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10069                         find_good_pkt_pointers(other_branch, src_reg,
10070                                                src_reg->type, false);
10071                         mark_pkt_end(this_branch, insn->src_reg, true);
10072                 } else {
10073                         return false;
10074                 }
10075                 break;
10076         case BPF_JLE:
10077                 if ((dst_reg->type == PTR_TO_PACKET &&
10078                      src_reg->type == PTR_TO_PACKET_END) ||
10079                     (dst_reg->type == PTR_TO_PACKET_META &&
10080                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10081                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10082                         find_good_pkt_pointers(other_branch, dst_reg,
10083                                                dst_reg->type, false);
10084                         mark_pkt_end(this_branch, insn->dst_reg, true);
10085                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10086                             src_reg->type == PTR_TO_PACKET) ||
10087                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10088                             src_reg->type == PTR_TO_PACKET_META)) {
10089                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10090                         find_good_pkt_pointers(this_branch, src_reg,
10091                                                src_reg->type, true);
10092                         mark_pkt_end(other_branch, insn->src_reg, false);
10093                 } else {
10094                         return false;
10095                 }
10096                 break;
10097         default:
10098                 return false;
10099         }
10100
10101         return true;
10102 }
10103
10104 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10105                                struct bpf_reg_state *known_reg)
10106 {
10107         struct bpf_func_state *state;
10108         struct bpf_reg_state *reg;
10109
10110         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10111                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10112                         *reg = *known_reg;
10113         }));
10114 }
10115
10116 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10117                              struct bpf_insn *insn, int *insn_idx)
10118 {
10119         struct bpf_verifier_state *this_branch = env->cur_state;
10120         struct bpf_verifier_state *other_branch;
10121         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10122         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10123         u8 opcode = BPF_OP(insn->code);
10124         bool is_jmp32;
10125         int pred = -1;
10126         int err;
10127
10128         /* Only conditional jumps are expected to reach here. */
10129         if (opcode == BPF_JA || opcode > BPF_JSLE) {
10130                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10131                 return -EINVAL;
10132         }
10133
10134         if (BPF_SRC(insn->code) == BPF_X) {
10135                 if (insn->imm != 0) {
10136                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10137                         return -EINVAL;
10138                 }
10139
10140                 /* check src1 operand */
10141                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10142                 if (err)
10143                         return err;
10144
10145                 if (is_pointer_value(env, insn->src_reg)) {
10146                         verbose(env, "R%d pointer comparison prohibited\n",
10147                                 insn->src_reg);
10148                         return -EACCES;
10149                 }
10150                 src_reg = &regs[insn->src_reg];
10151         } else {
10152                 if (insn->src_reg != BPF_REG_0) {
10153                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10154                         return -EINVAL;
10155                 }
10156         }
10157
10158         /* check src2 operand */
10159         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10160         if (err)
10161                 return err;
10162
10163         dst_reg = &regs[insn->dst_reg];
10164         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10165
10166         if (BPF_SRC(insn->code) == BPF_K) {
10167                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10168         } else if (src_reg->type == SCALAR_VALUE &&
10169                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10170                 pred = is_branch_taken(dst_reg,
10171                                        tnum_subreg(src_reg->var_off).value,
10172                                        opcode,
10173                                        is_jmp32);
10174         } else if (src_reg->type == SCALAR_VALUE &&
10175                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10176                 pred = is_branch_taken(dst_reg,
10177                                        src_reg->var_off.value,
10178                                        opcode,
10179                                        is_jmp32);
10180         } else if (reg_is_pkt_pointer_any(dst_reg) &&
10181                    reg_is_pkt_pointer_any(src_reg) &&
10182                    !is_jmp32) {
10183                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10184         }
10185
10186         if (pred >= 0) {
10187                 /* If we get here with a dst_reg pointer type it is because
10188                  * above is_branch_taken() special cased the 0 comparison.
10189                  */
10190                 if (!__is_pointer_value(false, dst_reg))
10191                         err = mark_chain_precision(env, insn->dst_reg);
10192                 if (BPF_SRC(insn->code) == BPF_X && !err &&
10193                     !__is_pointer_value(false, src_reg))
10194                         err = mark_chain_precision(env, insn->src_reg);
10195                 if (err)
10196                         return err;
10197         }
10198
10199         if (pred == 1) {
10200                 /* Only follow the goto, ignore fall-through. If needed, push
10201                  * the fall-through branch for simulation under speculative
10202                  * execution.
10203                  */
10204                 if (!env->bypass_spec_v1 &&
10205                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
10206                                                *insn_idx))
10207                         return -EFAULT;
10208                 *insn_idx += insn->off;
10209                 return 0;
10210         } else if (pred == 0) {
10211                 /* Only follow the fall-through branch, since that's where the
10212                  * program will go. If needed, push the goto branch for
10213                  * simulation under speculative execution.
10214                  */
10215                 if (!env->bypass_spec_v1 &&
10216                     !sanitize_speculative_path(env, insn,
10217                                                *insn_idx + insn->off + 1,
10218                                                *insn_idx))
10219                         return -EFAULT;
10220                 return 0;
10221         }
10222
10223         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10224                                   false);
10225         if (!other_branch)
10226                 return -EFAULT;
10227         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10228
10229         /* detect if we are comparing against a constant value so we can adjust
10230          * our min/max values for our dst register.
10231          * this is only legit if both are scalars (or pointers to the same
10232          * object, I suppose, but we don't support that right now), because
10233          * otherwise the different base pointers mean the offsets aren't
10234          * comparable.
10235          */
10236         if (BPF_SRC(insn->code) == BPF_X) {
10237                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10238
10239                 if (dst_reg->type == SCALAR_VALUE &&
10240                     src_reg->type == SCALAR_VALUE) {
10241                         if (tnum_is_const(src_reg->var_off) ||
10242                             (is_jmp32 &&
10243                              tnum_is_const(tnum_subreg(src_reg->var_off))))
10244                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10245                                                 dst_reg,
10246                                                 src_reg->var_off.value,
10247                                                 tnum_subreg(src_reg->var_off).value,
10248                                                 opcode, is_jmp32);
10249                         else if (tnum_is_const(dst_reg->var_off) ||
10250                                  (is_jmp32 &&
10251                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
10252                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10253                                                     src_reg,
10254                                                     dst_reg->var_off.value,
10255                                                     tnum_subreg(dst_reg->var_off).value,
10256                                                     opcode, is_jmp32);
10257                         else if (!is_jmp32 &&
10258                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
10259                                 /* Comparing for equality, we can combine knowledge */
10260                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10261                                                     &other_branch_regs[insn->dst_reg],
10262                                                     src_reg, dst_reg, opcode);
10263                         if (src_reg->id &&
10264                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10265                                 find_equal_scalars(this_branch, src_reg);
10266                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10267                         }
10268
10269                 }
10270         } else if (dst_reg->type == SCALAR_VALUE) {
10271                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10272                                         dst_reg, insn->imm, (u32)insn->imm,
10273                                         opcode, is_jmp32);
10274         }
10275
10276         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10277             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10278                 find_equal_scalars(this_branch, dst_reg);
10279                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10280         }
10281
10282         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10283          * NOTE: these optimizations below are related with pointer comparison
10284          *       which will never be JMP32.
10285          */
10286         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10287             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10288             type_may_be_null(dst_reg->type)) {
10289                 /* Mark all identical registers in each branch as either
10290                  * safe or unknown depending R == 0 or R != 0 conditional.
10291                  */
10292                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10293                                       opcode == BPF_JNE);
10294                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10295                                       opcode == BPF_JEQ);
10296         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10297                                            this_branch, other_branch) &&
10298                    is_pointer_value(env, insn->dst_reg)) {
10299                 verbose(env, "R%d pointer comparison prohibited\n",
10300                         insn->dst_reg);
10301                 return -EACCES;
10302         }
10303         if (env->log.level & BPF_LOG_LEVEL)
10304                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10305         return 0;
10306 }
10307
10308 /* verify BPF_LD_IMM64 instruction */
10309 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10310 {
10311         struct bpf_insn_aux_data *aux = cur_aux(env);
10312         struct bpf_reg_state *regs = cur_regs(env);
10313         struct bpf_reg_state *dst_reg;
10314         struct bpf_map *map;
10315         int err;
10316
10317         if (BPF_SIZE(insn->code) != BPF_DW) {
10318                 verbose(env, "invalid BPF_LD_IMM insn\n");
10319                 return -EINVAL;
10320         }
10321         if (insn->off != 0) {
10322                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10323                 return -EINVAL;
10324         }
10325
10326         err = check_reg_arg(env, insn->dst_reg, DST_OP);
10327         if (err)
10328                 return err;
10329
10330         dst_reg = &regs[insn->dst_reg];
10331         if (insn->src_reg == 0) {
10332                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10333
10334                 dst_reg->type = SCALAR_VALUE;
10335                 __mark_reg_known(&regs[insn->dst_reg], imm);
10336                 return 0;
10337         }
10338
10339         /* All special src_reg cases are listed below. From this point onwards
10340          * we either succeed and assign a corresponding dst_reg->type after
10341          * zeroing the offset, or fail and reject the program.
10342          */
10343         mark_reg_known_zero(env, regs, insn->dst_reg);
10344
10345         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10346                 dst_reg->type = aux->btf_var.reg_type;
10347                 switch (base_type(dst_reg->type)) {
10348                 case PTR_TO_MEM:
10349                         dst_reg->mem_size = aux->btf_var.mem_size;
10350                         break;
10351                 case PTR_TO_BTF_ID:
10352                         dst_reg->btf = aux->btf_var.btf;
10353                         dst_reg->btf_id = aux->btf_var.btf_id;
10354                         break;
10355                 default:
10356                         verbose(env, "bpf verifier is misconfigured\n");
10357                         return -EFAULT;
10358                 }
10359                 return 0;
10360         }
10361
10362         if (insn->src_reg == BPF_PSEUDO_FUNC) {
10363                 struct bpf_prog_aux *aux = env->prog->aux;
10364                 u32 subprogno = find_subprog(env,
10365                                              env->insn_idx + insn->imm + 1);
10366
10367                 if (!aux->func_info) {
10368                         verbose(env, "missing btf func_info\n");
10369                         return -EINVAL;
10370                 }
10371                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10372                         verbose(env, "callback function not static\n");
10373                         return -EINVAL;
10374                 }
10375
10376                 dst_reg->type = PTR_TO_FUNC;
10377                 dst_reg->subprogno = subprogno;
10378                 return 0;
10379         }
10380
10381         map = env->used_maps[aux->map_index];
10382         dst_reg->map_ptr = map;
10383
10384         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10385             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10386                 dst_reg->type = PTR_TO_MAP_VALUE;
10387                 dst_reg->off = aux->map_off;
10388                 if (map_value_has_spin_lock(map))
10389                         dst_reg->id = ++env->id_gen;
10390         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10391                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10392                 dst_reg->type = CONST_PTR_TO_MAP;
10393         } else {
10394                 verbose(env, "bpf verifier is misconfigured\n");
10395                 return -EINVAL;
10396         }
10397
10398         return 0;
10399 }
10400
10401 static bool may_access_skb(enum bpf_prog_type type)
10402 {
10403         switch (type) {
10404         case BPF_PROG_TYPE_SOCKET_FILTER:
10405         case BPF_PROG_TYPE_SCHED_CLS:
10406         case BPF_PROG_TYPE_SCHED_ACT:
10407                 return true;
10408         default:
10409                 return false;
10410         }
10411 }
10412
10413 /* verify safety of LD_ABS|LD_IND instructions:
10414  * - they can only appear in the programs where ctx == skb
10415  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10416  *   preserve R6-R9, and store return value into R0
10417  *
10418  * Implicit input:
10419  *   ctx == skb == R6 == CTX
10420  *
10421  * Explicit input:
10422  *   SRC == any register
10423  *   IMM == 32-bit immediate
10424  *
10425  * Output:
10426  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10427  */
10428 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10429 {
10430         struct bpf_reg_state *regs = cur_regs(env);
10431         static const int ctx_reg = BPF_REG_6;
10432         u8 mode = BPF_MODE(insn->code);
10433         int i, err;
10434
10435         if (!may_access_skb(resolve_prog_type(env->prog))) {
10436                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10437                 return -EINVAL;
10438         }
10439
10440         if (!env->ops->gen_ld_abs) {
10441                 verbose(env, "bpf verifier is misconfigured\n");
10442                 return -EINVAL;
10443         }
10444
10445         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10446             BPF_SIZE(insn->code) == BPF_DW ||
10447             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10448                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10449                 return -EINVAL;
10450         }
10451
10452         /* check whether implicit source operand (register R6) is readable */
10453         err = check_reg_arg(env, ctx_reg, SRC_OP);
10454         if (err)
10455                 return err;
10456
10457         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10458          * gen_ld_abs() may terminate the program at runtime, leading to
10459          * reference leak.
10460          */
10461         err = check_reference_leak(env);
10462         if (err) {
10463                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10464                 return err;
10465         }
10466
10467         if (env->cur_state->active_spin_lock) {
10468                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10469                 return -EINVAL;
10470         }
10471
10472         if (regs[ctx_reg].type != PTR_TO_CTX) {
10473                 verbose(env,
10474                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10475                 return -EINVAL;
10476         }
10477
10478         if (mode == BPF_IND) {
10479                 /* check explicit source operand */
10480                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10481                 if (err)
10482                         return err;
10483         }
10484
10485         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10486         if (err < 0)
10487                 return err;
10488
10489         /* reset caller saved regs to unreadable */
10490         for (i = 0; i < CALLER_SAVED_REGS; i++) {
10491                 mark_reg_not_init(env, regs, caller_saved[i]);
10492                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10493         }
10494
10495         /* mark destination R0 register as readable, since it contains
10496          * the value fetched from the packet.
10497          * Already marked as written above.
10498          */
10499         mark_reg_unknown(env, regs, BPF_REG_0);
10500         /* ld_abs load up to 32-bit skb data. */
10501         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10502         return 0;
10503 }
10504
10505 static int check_return_code(struct bpf_verifier_env *env)
10506 {
10507         struct tnum enforce_attach_type_range = tnum_unknown;
10508         const struct bpf_prog *prog = env->prog;
10509         struct bpf_reg_state *reg;
10510         struct tnum range = tnum_range(0, 1);
10511         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10512         int err;
10513         struct bpf_func_state *frame = env->cur_state->frame[0];
10514         const bool is_subprog = frame->subprogno;
10515
10516         /* LSM and struct_ops func-ptr's return type could be "void" */
10517         if (!is_subprog) {
10518                 switch (prog_type) {
10519                 case BPF_PROG_TYPE_LSM:
10520                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
10521                                 /* See below, can be 0 or 0-1 depending on hook. */
10522                                 break;
10523                         fallthrough;
10524                 case BPF_PROG_TYPE_STRUCT_OPS:
10525                         if (!prog->aux->attach_func_proto->type)
10526                                 return 0;
10527                         break;
10528                 default:
10529                         break;
10530                 }
10531         }
10532
10533         /* eBPF calling convention is such that R0 is used
10534          * to return the value from eBPF program.
10535          * Make sure that it's readable at this time
10536          * of bpf_exit, which means that program wrote
10537          * something into it earlier
10538          */
10539         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10540         if (err)
10541                 return err;
10542
10543         if (is_pointer_value(env, BPF_REG_0)) {
10544                 verbose(env, "R0 leaks addr as return value\n");
10545                 return -EACCES;
10546         }
10547
10548         reg = cur_regs(env) + BPF_REG_0;
10549
10550         if (frame->in_async_callback_fn) {
10551                 /* enforce return zero from async callbacks like timer */
10552                 if (reg->type != SCALAR_VALUE) {
10553                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10554                                 reg_type_str(env, reg->type));
10555                         return -EINVAL;
10556                 }
10557
10558                 if (!tnum_in(tnum_const(0), reg->var_off)) {
10559                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10560                         return -EINVAL;
10561                 }
10562                 return 0;
10563         }
10564
10565         if (is_subprog) {
10566                 if (reg->type != SCALAR_VALUE) {
10567                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10568                                 reg_type_str(env, reg->type));
10569                         return -EINVAL;
10570                 }
10571                 return 0;
10572         }
10573
10574         switch (prog_type) {
10575         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10576                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10577                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10578                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10579                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10580                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10581                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10582                         range = tnum_range(1, 1);
10583                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10584                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10585                         range = tnum_range(0, 3);
10586                 break;
10587         case BPF_PROG_TYPE_CGROUP_SKB:
10588                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10589                         range = tnum_range(0, 3);
10590                         enforce_attach_type_range = tnum_range(2, 3);
10591                 }
10592                 break;
10593         case BPF_PROG_TYPE_CGROUP_SOCK:
10594         case BPF_PROG_TYPE_SOCK_OPS:
10595         case BPF_PROG_TYPE_CGROUP_DEVICE:
10596         case BPF_PROG_TYPE_CGROUP_SYSCTL:
10597         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10598                 break;
10599         case BPF_PROG_TYPE_RAW_TRACEPOINT:
10600                 if (!env->prog->aux->attach_btf_id)
10601                         return 0;
10602                 range = tnum_const(0);
10603                 break;
10604         case BPF_PROG_TYPE_TRACING:
10605                 switch (env->prog->expected_attach_type) {
10606                 case BPF_TRACE_FENTRY:
10607                 case BPF_TRACE_FEXIT:
10608                         range = tnum_const(0);
10609                         break;
10610                 case BPF_TRACE_RAW_TP:
10611                 case BPF_MODIFY_RETURN:
10612                         return 0;
10613                 case BPF_TRACE_ITER:
10614                         break;
10615                 default:
10616                         return -ENOTSUPP;
10617                 }
10618                 break;
10619         case BPF_PROG_TYPE_SK_LOOKUP:
10620                 range = tnum_range(SK_DROP, SK_PASS);
10621                 break;
10622
10623         case BPF_PROG_TYPE_LSM:
10624                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10625                         /* Regular BPF_PROG_TYPE_LSM programs can return
10626                          * any value.
10627                          */
10628                         return 0;
10629                 }
10630                 if (!env->prog->aux->attach_func_proto->type) {
10631                         /* Make sure programs that attach to void
10632                          * hooks don't try to modify return value.
10633                          */
10634                         range = tnum_range(1, 1);
10635                 }
10636                 break;
10637
10638         case BPF_PROG_TYPE_EXT:
10639                 /* freplace program can return anything as its return value
10640                  * depends on the to-be-replaced kernel func or bpf program.
10641                  */
10642         default:
10643                 return 0;
10644         }
10645
10646         if (reg->type != SCALAR_VALUE) {
10647                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10648                         reg_type_str(env, reg->type));
10649                 return -EINVAL;
10650         }
10651
10652         if (!tnum_in(range, reg->var_off)) {
10653                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10654                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10655                     prog_type == BPF_PROG_TYPE_LSM &&
10656                     !prog->aux->attach_func_proto->type)
10657                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10658                 return -EINVAL;
10659         }
10660
10661         if (!tnum_is_unknown(enforce_attach_type_range) &&
10662             tnum_in(enforce_attach_type_range, reg->var_off))
10663                 env->prog->enforce_expected_attach_type = 1;
10664         return 0;
10665 }
10666
10667 /* non-recursive DFS pseudo code
10668  * 1  procedure DFS-iterative(G,v):
10669  * 2      label v as discovered
10670  * 3      let S be a stack
10671  * 4      S.push(v)
10672  * 5      while S is not empty
10673  * 6            t <- S.pop()
10674  * 7            if t is what we're looking for:
10675  * 8                return t
10676  * 9            for all edges e in G.adjacentEdges(t) do
10677  * 10               if edge e is already labelled
10678  * 11                   continue with the next edge
10679  * 12               w <- G.adjacentVertex(t,e)
10680  * 13               if vertex w is not discovered and not explored
10681  * 14                   label e as tree-edge
10682  * 15                   label w as discovered
10683  * 16                   S.push(w)
10684  * 17                   continue at 5
10685  * 18               else if vertex w is discovered
10686  * 19                   label e as back-edge
10687  * 20               else
10688  * 21                   // vertex w is explored
10689  * 22                   label e as forward- or cross-edge
10690  * 23           label t as explored
10691  * 24           S.pop()
10692  *
10693  * convention:
10694  * 0x10 - discovered
10695  * 0x11 - discovered and fall-through edge labelled
10696  * 0x12 - discovered and fall-through and branch edges labelled
10697  * 0x20 - explored
10698  */
10699
10700 enum {
10701         DISCOVERED = 0x10,
10702         EXPLORED = 0x20,
10703         FALLTHROUGH = 1,
10704         BRANCH = 2,
10705 };
10706
10707 static u32 state_htab_size(struct bpf_verifier_env *env)
10708 {
10709         return env->prog->len;
10710 }
10711
10712 static struct bpf_verifier_state_list **explored_state(
10713                                         struct bpf_verifier_env *env,
10714                                         int idx)
10715 {
10716         struct bpf_verifier_state *cur = env->cur_state;
10717         struct bpf_func_state *state = cur->frame[cur->curframe];
10718
10719         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10720 }
10721
10722 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10723 {
10724         env->insn_aux_data[idx].prune_point = true;
10725 }
10726
10727 enum {
10728         DONE_EXPLORING = 0,
10729         KEEP_EXPLORING = 1,
10730 };
10731
10732 /* t, w, e - match pseudo-code above:
10733  * t - index of current instruction
10734  * w - next instruction
10735  * e - edge
10736  */
10737 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10738                      bool loop_ok)
10739 {
10740         int *insn_stack = env->cfg.insn_stack;
10741         int *insn_state = env->cfg.insn_state;
10742
10743         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10744                 return DONE_EXPLORING;
10745
10746         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10747                 return DONE_EXPLORING;
10748
10749         if (w < 0 || w >= env->prog->len) {
10750                 verbose_linfo(env, t, "%d: ", t);
10751                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10752                 return -EINVAL;
10753         }
10754
10755         if (e == BRANCH)
10756                 /* mark branch target for state pruning */
10757                 init_explored_state(env, w);
10758
10759         if (insn_state[w] == 0) {
10760                 /* tree-edge */
10761                 insn_state[t] = DISCOVERED | e;
10762                 insn_state[w] = DISCOVERED;
10763                 if (env->cfg.cur_stack >= env->prog->len)
10764                         return -E2BIG;
10765                 insn_stack[env->cfg.cur_stack++] = w;
10766                 return KEEP_EXPLORING;
10767         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10768                 if (loop_ok && env->bpf_capable)
10769                         return DONE_EXPLORING;
10770                 verbose_linfo(env, t, "%d: ", t);
10771                 verbose_linfo(env, w, "%d: ", w);
10772                 verbose(env, "back-edge from insn %d to %d\n", t, w);
10773                 return -EINVAL;
10774         } else if (insn_state[w] == EXPLORED) {
10775                 /* forward- or cross-edge */
10776                 insn_state[t] = DISCOVERED | e;
10777         } else {
10778                 verbose(env, "insn state internal bug\n");
10779                 return -EFAULT;
10780         }
10781         return DONE_EXPLORING;
10782 }
10783
10784 static int visit_func_call_insn(int t, int insn_cnt,
10785                                 struct bpf_insn *insns,
10786                                 struct bpf_verifier_env *env,
10787                                 bool visit_callee)
10788 {
10789         int ret;
10790
10791         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10792         if (ret)
10793                 return ret;
10794
10795         if (t + 1 < insn_cnt)
10796                 init_explored_state(env, t + 1);
10797         if (visit_callee) {
10798                 init_explored_state(env, t);
10799                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10800                                 /* It's ok to allow recursion from CFG point of
10801                                  * view. __check_func_call() will do the actual
10802                                  * check.
10803                                  */
10804                                 bpf_pseudo_func(insns + t));
10805         }
10806         return ret;
10807 }
10808
10809 /* Visits the instruction at index t and returns one of the following:
10810  *  < 0 - an error occurred
10811  *  DONE_EXPLORING - the instruction was fully explored
10812  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10813  */
10814 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10815 {
10816         struct bpf_insn *insns = env->prog->insnsi;
10817         int ret;
10818
10819         if (bpf_pseudo_func(insns + t))
10820                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10821
10822         /* All non-branch instructions have a single fall-through edge. */
10823         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10824             BPF_CLASS(insns[t].code) != BPF_JMP32)
10825                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10826
10827         switch (BPF_OP(insns[t].code)) {
10828         case BPF_EXIT:
10829                 return DONE_EXPLORING;
10830
10831         case BPF_CALL:
10832                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10833                         /* Mark this call insn to trigger is_state_visited() check
10834                          * before call itself is processed by __check_func_call().
10835                          * Otherwise new async state will be pushed for further
10836                          * exploration.
10837                          */
10838                         init_explored_state(env, t);
10839                 return visit_func_call_insn(t, insn_cnt, insns, env,
10840                                             insns[t].src_reg == BPF_PSEUDO_CALL);
10841
10842         case BPF_JA:
10843                 if (BPF_SRC(insns[t].code) != BPF_K)
10844                         return -EINVAL;
10845
10846                 /* unconditional jump with single edge */
10847                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10848                                 true);
10849                 if (ret)
10850                         return ret;
10851
10852                 /* unconditional jmp is not a good pruning point,
10853                  * but it's marked, since backtracking needs
10854                  * to record jmp history in is_state_visited().
10855                  */
10856                 init_explored_state(env, t + insns[t].off + 1);
10857                 /* tell verifier to check for equivalent states
10858                  * after every call and jump
10859                  */
10860                 if (t + 1 < insn_cnt)
10861                         init_explored_state(env, t + 1);
10862
10863                 return ret;
10864
10865         default:
10866                 /* conditional jump with two edges */
10867                 init_explored_state(env, t);
10868                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10869                 if (ret)
10870                         return ret;
10871
10872                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10873         }
10874 }
10875
10876 /* non-recursive depth-first-search to detect loops in BPF program
10877  * loop == back-edge in directed graph
10878  */
10879 static int check_cfg(struct bpf_verifier_env *env)
10880 {
10881         int insn_cnt = env->prog->len;
10882         int *insn_stack, *insn_state;
10883         int ret = 0;
10884         int i;
10885
10886         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10887         if (!insn_state)
10888                 return -ENOMEM;
10889
10890         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10891         if (!insn_stack) {
10892                 kvfree(insn_state);
10893                 return -ENOMEM;
10894         }
10895
10896         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10897         insn_stack[0] = 0; /* 0 is the first instruction */
10898         env->cfg.cur_stack = 1;
10899
10900         while (env->cfg.cur_stack > 0) {
10901                 int t = insn_stack[env->cfg.cur_stack - 1];
10902
10903                 ret = visit_insn(t, insn_cnt, env);
10904                 switch (ret) {
10905                 case DONE_EXPLORING:
10906                         insn_state[t] = EXPLORED;
10907                         env->cfg.cur_stack--;
10908                         break;
10909                 case KEEP_EXPLORING:
10910                         break;
10911                 default:
10912                         if (ret > 0) {
10913                                 verbose(env, "visit_insn internal bug\n");
10914                                 ret = -EFAULT;
10915                         }
10916                         goto err_free;
10917                 }
10918         }
10919
10920         if (env->cfg.cur_stack < 0) {
10921                 verbose(env, "pop stack internal bug\n");
10922                 ret = -EFAULT;
10923                 goto err_free;
10924         }
10925
10926         for (i = 0; i < insn_cnt; i++) {
10927                 if (insn_state[i] != EXPLORED) {
10928                         verbose(env, "unreachable insn %d\n", i);
10929                         ret = -EINVAL;
10930                         goto err_free;
10931                 }
10932         }
10933         ret = 0; /* cfg looks good */
10934
10935 err_free:
10936         kvfree(insn_state);
10937         kvfree(insn_stack);
10938         env->cfg.insn_state = env->cfg.insn_stack = NULL;
10939         return ret;
10940 }
10941
10942 static int check_abnormal_return(struct bpf_verifier_env *env)
10943 {
10944         int i;
10945
10946         for (i = 1; i < env->subprog_cnt; i++) {
10947                 if (env->subprog_info[i].has_ld_abs) {
10948                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10949                         return -EINVAL;
10950                 }
10951                 if (env->subprog_info[i].has_tail_call) {
10952                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10953                         return -EINVAL;
10954                 }
10955         }
10956         return 0;
10957 }
10958
10959 /* The minimum supported BTF func info size */
10960 #define MIN_BPF_FUNCINFO_SIZE   8
10961 #define MAX_FUNCINFO_REC_SIZE   252
10962
10963 static int check_btf_func(struct bpf_verifier_env *env,
10964                           const union bpf_attr *attr,
10965                           bpfptr_t uattr)
10966 {
10967         const struct btf_type *type, *func_proto, *ret_type;
10968         u32 i, nfuncs, urec_size, min_size;
10969         u32 krec_size = sizeof(struct bpf_func_info);
10970         struct bpf_func_info *krecord;
10971         struct bpf_func_info_aux *info_aux = NULL;
10972         struct bpf_prog *prog;
10973         const struct btf *btf;
10974         bpfptr_t urecord;
10975         u32 prev_offset = 0;
10976         bool scalar_return;
10977         int ret = -ENOMEM;
10978
10979         nfuncs = attr->func_info_cnt;
10980         if (!nfuncs) {
10981                 if (check_abnormal_return(env))
10982                         return -EINVAL;
10983                 return 0;
10984         }
10985
10986         if (nfuncs != env->subprog_cnt) {
10987                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10988                 return -EINVAL;
10989         }
10990
10991         urec_size = attr->func_info_rec_size;
10992         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10993             urec_size > MAX_FUNCINFO_REC_SIZE ||
10994             urec_size % sizeof(u32)) {
10995                 verbose(env, "invalid func info rec size %u\n", urec_size);
10996                 return -EINVAL;
10997         }
10998
10999         prog = env->prog;
11000         btf = prog->aux->btf;
11001
11002         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11003         min_size = min_t(u32, krec_size, urec_size);
11004
11005         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11006         if (!krecord)
11007                 return -ENOMEM;
11008         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11009         if (!info_aux)
11010                 goto err_free;
11011
11012         for (i = 0; i < nfuncs; i++) {
11013                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11014                 if (ret) {
11015                         if (ret == -E2BIG) {
11016                                 verbose(env, "nonzero tailing record in func info");
11017                                 /* set the size kernel expects so loader can zero
11018                                  * out the rest of the record.
11019                                  */
11020                                 if (copy_to_bpfptr_offset(uattr,
11021                                                           offsetof(union bpf_attr, func_info_rec_size),
11022                                                           &min_size, sizeof(min_size)))
11023                                         ret = -EFAULT;
11024                         }
11025                         goto err_free;
11026                 }
11027
11028                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11029                         ret = -EFAULT;
11030                         goto err_free;
11031                 }
11032
11033                 /* check insn_off */
11034                 ret = -EINVAL;
11035                 if (i == 0) {
11036                         if (krecord[i].insn_off) {
11037                                 verbose(env,
11038                                         "nonzero insn_off %u for the first func info record",
11039                                         krecord[i].insn_off);
11040                                 goto err_free;
11041                         }
11042                 } else if (krecord[i].insn_off <= prev_offset) {
11043                         verbose(env,
11044                                 "same or smaller insn offset (%u) than previous func info record (%u)",
11045                                 krecord[i].insn_off, prev_offset);
11046                         goto err_free;
11047                 }
11048
11049                 if (env->subprog_info[i].start != krecord[i].insn_off) {
11050                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11051                         goto err_free;
11052                 }
11053
11054                 /* check type_id */
11055                 type = btf_type_by_id(btf, krecord[i].type_id);
11056                 if (!type || !btf_type_is_func(type)) {
11057                         verbose(env, "invalid type id %d in func info",
11058                                 krecord[i].type_id);
11059                         goto err_free;
11060                 }
11061                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11062
11063                 func_proto = btf_type_by_id(btf, type->type);
11064                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11065                         /* btf_func_check() already verified it during BTF load */
11066                         goto err_free;
11067                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11068                 scalar_return =
11069                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11070                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11071                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11072                         goto err_free;
11073                 }
11074                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11075                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11076                         goto err_free;
11077                 }
11078
11079                 prev_offset = krecord[i].insn_off;
11080                 bpfptr_add(&urecord, urec_size);
11081         }
11082
11083         prog->aux->func_info = krecord;
11084         prog->aux->func_info_cnt = nfuncs;
11085         prog->aux->func_info_aux = info_aux;
11086         return 0;
11087
11088 err_free:
11089         kvfree(krecord);
11090         kfree(info_aux);
11091         return ret;
11092 }
11093
11094 static void adjust_btf_func(struct bpf_verifier_env *env)
11095 {
11096         struct bpf_prog_aux *aux = env->prog->aux;
11097         int i;
11098
11099         if (!aux->func_info)
11100                 return;
11101
11102         for (i = 0; i < env->subprog_cnt; i++)
11103                 aux->func_info[i].insn_off = env->subprog_info[i].start;
11104 }
11105
11106 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
11107 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
11108
11109 static int check_btf_line(struct bpf_verifier_env *env,
11110                           const union bpf_attr *attr,
11111                           bpfptr_t uattr)
11112 {
11113         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11114         struct bpf_subprog_info *sub;
11115         struct bpf_line_info *linfo;
11116         struct bpf_prog *prog;
11117         const struct btf *btf;
11118         bpfptr_t ulinfo;
11119         int err;
11120
11121         nr_linfo = attr->line_info_cnt;
11122         if (!nr_linfo)
11123                 return 0;
11124         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11125                 return -EINVAL;
11126
11127         rec_size = attr->line_info_rec_size;
11128         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11129             rec_size > MAX_LINEINFO_REC_SIZE ||
11130             rec_size & (sizeof(u32) - 1))
11131                 return -EINVAL;
11132
11133         /* Need to zero it in case the userspace may
11134          * pass in a smaller bpf_line_info object.
11135          */
11136         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11137                          GFP_KERNEL | __GFP_NOWARN);
11138         if (!linfo)
11139                 return -ENOMEM;
11140
11141         prog = env->prog;
11142         btf = prog->aux->btf;
11143
11144         s = 0;
11145         sub = env->subprog_info;
11146         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11147         expected_size = sizeof(struct bpf_line_info);
11148         ncopy = min_t(u32, expected_size, rec_size);
11149         for (i = 0; i < nr_linfo; i++) {
11150                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11151                 if (err) {
11152                         if (err == -E2BIG) {
11153                                 verbose(env, "nonzero tailing record in line_info");
11154                                 if (copy_to_bpfptr_offset(uattr,
11155                                                           offsetof(union bpf_attr, line_info_rec_size),
11156                                                           &expected_size, sizeof(expected_size)))
11157                                         err = -EFAULT;
11158                         }
11159                         goto err_free;
11160                 }
11161
11162                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11163                         err = -EFAULT;
11164                         goto err_free;
11165                 }
11166
11167                 /*
11168                  * Check insn_off to ensure
11169                  * 1) strictly increasing AND
11170                  * 2) bounded by prog->len
11171                  *
11172                  * The linfo[0].insn_off == 0 check logically falls into
11173                  * the later "missing bpf_line_info for func..." case
11174                  * because the first linfo[0].insn_off must be the
11175                  * first sub also and the first sub must have
11176                  * subprog_info[0].start == 0.
11177                  */
11178                 if ((i && linfo[i].insn_off <= prev_offset) ||
11179                     linfo[i].insn_off >= prog->len) {
11180                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11181                                 i, linfo[i].insn_off, prev_offset,
11182                                 prog->len);
11183                         err = -EINVAL;
11184                         goto err_free;
11185                 }
11186
11187                 if (!prog->insnsi[linfo[i].insn_off].code) {
11188                         verbose(env,
11189                                 "Invalid insn code at line_info[%u].insn_off\n",
11190                                 i);
11191                         err = -EINVAL;
11192                         goto err_free;
11193                 }
11194
11195                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11196                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11197                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11198                         err = -EINVAL;
11199                         goto err_free;
11200                 }
11201
11202                 if (s != env->subprog_cnt) {
11203                         if (linfo[i].insn_off == sub[s].start) {
11204                                 sub[s].linfo_idx = i;
11205                                 s++;
11206                         } else if (sub[s].start < linfo[i].insn_off) {
11207                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
11208                                 err = -EINVAL;
11209                                 goto err_free;
11210                         }
11211                 }
11212
11213                 prev_offset = linfo[i].insn_off;
11214                 bpfptr_add(&ulinfo, rec_size);
11215         }
11216
11217         if (s != env->subprog_cnt) {
11218                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11219                         env->subprog_cnt - s, s);
11220                 err = -EINVAL;
11221                 goto err_free;
11222         }
11223
11224         prog->aux->linfo = linfo;
11225         prog->aux->nr_linfo = nr_linfo;
11226
11227         return 0;
11228
11229 err_free:
11230         kvfree(linfo);
11231         return err;
11232 }
11233
11234 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
11235 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
11236
11237 static int check_core_relo(struct bpf_verifier_env *env,
11238                            const union bpf_attr *attr,
11239                            bpfptr_t uattr)
11240 {
11241         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11242         struct bpf_core_relo core_relo = {};
11243         struct bpf_prog *prog = env->prog;
11244         const struct btf *btf = prog->aux->btf;
11245         struct bpf_core_ctx ctx = {
11246                 .log = &env->log,
11247                 .btf = btf,
11248         };
11249         bpfptr_t u_core_relo;
11250         int err;
11251
11252         nr_core_relo = attr->core_relo_cnt;
11253         if (!nr_core_relo)
11254                 return 0;
11255         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11256                 return -EINVAL;
11257
11258         rec_size = attr->core_relo_rec_size;
11259         if (rec_size < MIN_CORE_RELO_SIZE ||
11260             rec_size > MAX_CORE_RELO_SIZE ||
11261             rec_size % sizeof(u32))
11262                 return -EINVAL;
11263
11264         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11265         expected_size = sizeof(struct bpf_core_relo);
11266         ncopy = min_t(u32, expected_size, rec_size);
11267
11268         /* Unlike func_info and line_info, copy and apply each CO-RE
11269          * relocation record one at a time.
11270          */
11271         for (i = 0; i < nr_core_relo; i++) {
11272                 /* future proofing when sizeof(bpf_core_relo) changes */
11273                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11274                 if (err) {
11275                         if (err == -E2BIG) {
11276                                 verbose(env, "nonzero tailing record in core_relo");
11277                                 if (copy_to_bpfptr_offset(uattr,
11278                                                           offsetof(union bpf_attr, core_relo_rec_size),
11279                                                           &expected_size, sizeof(expected_size)))
11280                                         err = -EFAULT;
11281                         }
11282                         break;
11283                 }
11284
11285                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11286                         err = -EFAULT;
11287                         break;
11288                 }
11289
11290                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11291                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11292                                 i, core_relo.insn_off, prog->len);
11293                         err = -EINVAL;
11294                         break;
11295                 }
11296
11297                 err = bpf_core_apply(&ctx, &core_relo, i,
11298                                      &prog->insnsi[core_relo.insn_off / 8]);
11299                 if (err)
11300                         break;
11301                 bpfptr_add(&u_core_relo, rec_size);
11302         }
11303         return err;
11304 }
11305
11306 static int check_btf_info(struct bpf_verifier_env *env,
11307                           const union bpf_attr *attr,
11308                           bpfptr_t uattr)
11309 {
11310         struct btf *btf;
11311         int err;
11312
11313         if (!attr->func_info_cnt && !attr->line_info_cnt) {
11314                 if (check_abnormal_return(env))
11315                         return -EINVAL;
11316                 return 0;
11317         }
11318
11319         btf = btf_get_by_fd(attr->prog_btf_fd);
11320         if (IS_ERR(btf))
11321                 return PTR_ERR(btf);
11322         if (btf_is_kernel(btf)) {
11323                 btf_put(btf);
11324                 return -EACCES;
11325         }
11326         env->prog->aux->btf = btf;
11327
11328         err = check_btf_func(env, attr, uattr);
11329         if (err)
11330                 return err;
11331
11332         err = check_btf_line(env, attr, uattr);
11333         if (err)
11334                 return err;
11335
11336         err = check_core_relo(env, attr, uattr);
11337         if (err)
11338                 return err;
11339
11340         return 0;
11341 }
11342
11343 /* check %cur's range satisfies %old's */
11344 static bool range_within(struct bpf_reg_state *old,
11345                          struct bpf_reg_state *cur)
11346 {
11347         return old->umin_value <= cur->umin_value &&
11348                old->umax_value >= cur->umax_value &&
11349                old->smin_value <= cur->smin_value &&
11350                old->smax_value >= cur->smax_value &&
11351                old->u32_min_value <= cur->u32_min_value &&
11352                old->u32_max_value >= cur->u32_max_value &&
11353                old->s32_min_value <= cur->s32_min_value &&
11354                old->s32_max_value >= cur->s32_max_value;
11355 }
11356
11357 /* If in the old state two registers had the same id, then they need to have
11358  * the same id in the new state as well.  But that id could be different from
11359  * the old state, so we need to track the mapping from old to new ids.
11360  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11361  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11362  * regs with a different old id could still have new id 9, we don't care about
11363  * that.
11364  * So we look through our idmap to see if this old id has been seen before.  If
11365  * so, we require the new id to match; otherwise, we add the id pair to the map.
11366  */
11367 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11368 {
11369         unsigned int i;
11370
11371         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11372                 if (!idmap[i].old) {
11373                         /* Reached an empty slot; haven't seen this id before */
11374                         idmap[i].old = old_id;
11375                         idmap[i].cur = cur_id;
11376                         return true;
11377                 }
11378                 if (idmap[i].old == old_id)
11379                         return idmap[i].cur == cur_id;
11380         }
11381         /* We ran out of idmap slots, which should be impossible */
11382         WARN_ON_ONCE(1);
11383         return false;
11384 }
11385
11386 static void clean_func_state(struct bpf_verifier_env *env,
11387                              struct bpf_func_state *st)
11388 {
11389         enum bpf_reg_liveness live;
11390         int i, j;
11391
11392         for (i = 0; i < BPF_REG_FP; i++) {
11393                 live = st->regs[i].live;
11394                 /* liveness must not touch this register anymore */
11395                 st->regs[i].live |= REG_LIVE_DONE;
11396                 if (!(live & REG_LIVE_READ))
11397                         /* since the register is unused, clear its state
11398                          * to make further comparison simpler
11399                          */
11400                         __mark_reg_not_init(env, &st->regs[i]);
11401         }
11402
11403         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11404                 live = st->stack[i].spilled_ptr.live;
11405                 /* liveness must not touch this stack slot anymore */
11406                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11407                 if (!(live & REG_LIVE_READ)) {
11408                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11409                         for (j = 0; j < BPF_REG_SIZE; j++)
11410                                 st->stack[i].slot_type[j] = STACK_INVALID;
11411                 }
11412         }
11413 }
11414
11415 static void clean_verifier_state(struct bpf_verifier_env *env,
11416                                  struct bpf_verifier_state *st)
11417 {
11418         int i;
11419
11420         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11421                 /* all regs in this state in all frames were already marked */
11422                 return;
11423
11424         for (i = 0; i <= st->curframe; i++)
11425                 clean_func_state(env, st->frame[i]);
11426 }
11427
11428 /* the parentage chains form a tree.
11429  * the verifier states are added to state lists at given insn and
11430  * pushed into state stack for future exploration.
11431  * when the verifier reaches bpf_exit insn some of the verifer states
11432  * stored in the state lists have their final liveness state already,
11433  * but a lot of states will get revised from liveness point of view when
11434  * the verifier explores other branches.
11435  * Example:
11436  * 1: r0 = 1
11437  * 2: if r1 == 100 goto pc+1
11438  * 3: r0 = 2
11439  * 4: exit
11440  * when the verifier reaches exit insn the register r0 in the state list of
11441  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11442  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11443  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11444  *
11445  * Since the verifier pushes the branch states as it sees them while exploring
11446  * the program the condition of walking the branch instruction for the second
11447  * time means that all states below this branch were already explored and
11448  * their final liveness marks are already propagated.
11449  * Hence when the verifier completes the search of state list in is_state_visited()
11450  * we can call this clean_live_states() function to mark all liveness states
11451  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11452  * will not be used.
11453  * This function also clears the registers and stack for states that !READ
11454  * to simplify state merging.
11455  *
11456  * Important note here that walking the same branch instruction in the callee
11457  * doesn't meant that the states are DONE. The verifier has to compare
11458  * the callsites
11459  */
11460 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11461                               struct bpf_verifier_state *cur)
11462 {
11463         struct bpf_verifier_state_list *sl;
11464         int i;
11465
11466         sl = *explored_state(env, insn);
11467         while (sl) {
11468                 if (sl->state.branches)
11469                         goto next;
11470                 if (sl->state.insn_idx != insn ||
11471                     sl->state.curframe != cur->curframe)
11472                         goto next;
11473                 for (i = 0; i <= cur->curframe; i++)
11474                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11475                                 goto next;
11476                 clean_verifier_state(env, &sl->state);
11477 next:
11478                 sl = sl->next;
11479         }
11480 }
11481
11482 /* Returns true if (rold safe implies rcur safe) */
11483 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11484                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11485 {
11486         bool equal;
11487
11488         if (!(rold->live & REG_LIVE_READ))
11489                 /* explored state didn't use this */
11490                 return true;
11491
11492         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11493
11494         if (rold->type == PTR_TO_STACK)
11495                 /* two stack pointers are equal only if they're pointing to
11496                  * the same stack frame, since fp-8 in foo != fp-8 in bar
11497                  */
11498                 return equal && rold->frameno == rcur->frameno;
11499
11500         if (equal)
11501                 return true;
11502
11503         if (rold->type == NOT_INIT)
11504                 /* explored state can't have used this */
11505                 return true;
11506         if (rcur->type == NOT_INIT)
11507                 return false;
11508         switch (base_type(rold->type)) {
11509         case SCALAR_VALUE:
11510                 if (env->explore_alu_limits)
11511                         return false;
11512                 if (rcur->type == SCALAR_VALUE) {
11513                         if (!rold->precise && !rcur->precise)
11514                                 return true;
11515                         /* new val must satisfy old val knowledge */
11516                         return range_within(rold, rcur) &&
11517                                tnum_in(rold->var_off, rcur->var_off);
11518                 } else {
11519                         /* We're trying to use a pointer in place of a scalar.
11520                          * Even if the scalar was unbounded, this could lead to
11521                          * pointer leaks because scalars are allowed to leak
11522                          * while pointers are not. We could make this safe in
11523                          * special cases if root is calling us, but it's
11524                          * probably not worth the hassle.
11525                          */
11526                         return false;
11527                 }
11528         case PTR_TO_MAP_KEY:
11529         case PTR_TO_MAP_VALUE:
11530                 /* a PTR_TO_MAP_VALUE could be safe to use as a
11531                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11532                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11533                  * checked, doing so could have affected others with the same
11534                  * id, and we can't check for that because we lost the id when
11535                  * we converted to a PTR_TO_MAP_VALUE.
11536                  */
11537                 if (type_may_be_null(rold->type)) {
11538                         if (!type_may_be_null(rcur->type))
11539                                 return false;
11540                         if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11541                                 return false;
11542                         /* Check our ids match any regs they're supposed to */
11543                         return check_ids(rold->id, rcur->id, idmap);
11544                 }
11545
11546                 /* If the new min/max/var_off satisfy the old ones and
11547                  * everything else matches, we are OK.
11548                  * 'id' is not compared, since it's only used for maps with
11549                  * bpf_spin_lock inside map element and in such cases if
11550                  * the rest of the prog is valid for one map element then
11551                  * it's valid for all map elements regardless of the key
11552                  * used in bpf_map_lookup()
11553                  */
11554                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11555                        range_within(rold, rcur) &&
11556                        tnum_in(rold->var_off, rcur->var_off);
11557         case PTR_TO_PACKET_META:
11558         case PTR_TO_PACKET:
11559                 if (rcur->type != rold->type)
11560                         return false;
11561                 /* We must have at least as much range as the old ptr
11562                  * did, so that any accesses which were safe before are
11563                  * still safe.  This is true even if old range < old off,
11564                  * since someone could have accessed through (ptr - k), or
11565                  * even done ptr -= k in a register, to get a safe access.
11566                  */
11567                 if (rold->range > rcur->range)
11568                         return false;
11569                 /* If the offsets don't match, we can't trust our alignment;
11570                  * nor can we be sure that we won't fall out of range.
11571                  */
11572                 if (rold->off != rcur->off)
11573                         return false;
11574                 /* id relations must be preserved */
11575                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11576                         return false;
11577                 /* new val must satisfy old val knowledge */
11578                 return range_within(rold, rcur) &&
11579                        tnum_in(rold->var_off, rcur->var_off);
11580         case PTR_TO_CTX:
11581         case CONST_PTR_TO_MAP:
11582         case PTR_TO_PACKET_END:
11583         case PTR_TO_FLOW_KEYS:
11584         case PTR_TO_SOCKET:
11585         case PTR_TO_SOCK_COMMON:
11586         case PTR_TO_TCP_SOCK:
11587         case PTR_TO_XDP_SOCK:
11588                 /* Only valid matches are exact, which memcmp() above
11589                  * would have accepted
11590                  */
11591         default:
11592                 /* Don't know what's going on, just say it's not safe */
11593                 return false;
11594         }
11595
11596         /* Shouldn't get here; if we do, say it's not safe */
11597         WARN_ON_ONCE(1);
11598         return false;
11599 }
11600
11601 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11602                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11603 {
11604         int i, spi;
11605
11606         /* walk slots of the explored stack and ignore any additional
11607          * slots in the current stack, since explored(safe) state
11608          * didn't use them
11609          */
11610         for (i = 0; i < old->allocated_stack; i++) {
11611                 spi = i / BPF_REG_SIZE;
11612
11613                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11614                         i += BPF_REG_SIZE - 1;
11615                         /* explored state didn't use this */
11616                         continue;
11617                 }
11618
11619                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11620                         continue;
11621
11622                 /* explored stack has more populated slots than current stack
11623                  * and these slots were used
11624                  */
11625                 if (i >= cur->allocated_stack)
11626                         return false;
11627
11628                 /* if old state was safe with misc data in the stack
11629                  * it will be safe with zero-initialized stack.
11630                  * The opposite is not true
11631                  */
11632                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11633                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11634                         continue;
11635                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11636                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11637                         /* Ex: old explored (safe) state has STACK_SPILL in
11638                          * this stack slot, but current has STACK_MISC ->
11639                          * this verifier states are not equivalent,
11640                          * return false to continue verification of this path
11641                          */
11642                         return false;
11643                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11644                         continue;
11645                 if (!is_spilled_reg(&old->stack[spi]))
11646                         continue;
11647                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11648                              &cur->stack[spi].spilled_ptr, idmap))
11649                         /* when explored and current stack slot are both storing
11650                          * spilled registers, check that stored pointers types
11651                          * are the same as well.
11652                          * Ex: explored safe path could have stored
11653                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11654                          * but current path has stored:
11655                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11656                          * such verifier states are not equivalent.
11657                          * return false to continue verification of this path
11658                          */
11659                         return false;
11660         }
11661         return true;
11662 }
11663
11664 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11665 {
11666         if (old->acquired_refs != cur->acquired_refs)
11667                 return false;
11668         return !memcmp(old->refs, cur->refs,
11669                        sizeof(*old->refs) * old->acquired_refs);
11670 }
11671
11672 /* compare two verifier states
11673  *
11674  * all states stored in state_list are known to be valid, since
11675  * verifier reached 'bpf_exit' instruction through them
11676  *
11677  * this function is called when verifier exploring different branches of
11678  * execution popped from the state stack. If it sees an old state that has
11679  * more strict register state and more strict stack state then this execution
11680  * branch doesn't need to be explored further, since verifier already
11681  * concluded that more strict state leads to valid finish.
11682  *
11683  * Therefore two states are equivalent if register state is more conservative
11684  * and explored stack state is more conservative than the current one.
11685  * Example:
11686  *       explored                   current
11687  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11688  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11689  *
11690  * In other words if current stack state (one being explored) has more
11691  * valid slots than old one that already passed validation, it means
11692  * the verifier can stop exploring and conclude that current state is valid too
11693  *
11694  * Similarly with registers. If explored state has register type as invalid
11695  * whereas register type in current state is meaningful, it means that
11696  * the current state will reach 'bpf_exit' instruction safely
11697  */
11698 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11699                               struct bpf_func_state *cur)
11700 {
11701         int i;
11702
11703         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11704         for (i = 0; i < MAX_BPF_REG; i++)
11705                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11706                              env->idmap_scratch))
11707                         return false;
11708
11709         if (!stacksafe(env, old, cur, env->idmap_scratch))
11710                 return false;
11711
11712         if (!refsafe(old, cur))
11713                 return false;
11714
11715         return true;
11716 }
11717
11718 static bool states_equal(struct bpf_verifier_env *env,
11719                          struct bpf_verifier_state *old,
11720                          struct bpf_verifier_state *cur)
11721 {
11722         int i;
11723
11724         if (old->curframe != cur->curframe)
11725                 return false;
11726
11727         /* Verification state from speculative execution simulation
11728          * must never prune a non-speculative execution one.
11729          */
11730         if (old->speculative && !cur->speculative)
11731                 return false;
11732
11733         if (old->active_spin_lock != cur->active_spin_lock)
11734                 return false;
11735
11736         /* for states to be equal callsites have to be the same
11737          * and all frame states need to be equivalent
11738          */
11739         for (i = 0; i <= old->curframe; i++) {
11740                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11741                         return false;
11742                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11743                         return false;
11744         }
11745         return true;
11746 }
11747
11748 /* Return 0 if no propagation happened. Return negative error code if error
11749  * happened. Otherwise, return the propagated bit.
11750  */
11751 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11752                                   struct bpf_reg_state *reg,
11753                                   struct bpf_reg_state *parent_reg)
11754 {
11755         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11756         u8 flag = reg->live & REG_LIVE_READ;
11757         int err;
11758
11759         /* When comes here, read flags of PARENT_REG or REG could be any of
11760          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11761          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11762          */
11763         if (parent_flag == REG_LIVE_READ64 ||
11764             /* Or if there is no read flag from REG. */
11765             !flag ||
11766             /* Or if the read flag from REG is the same as PARENT_REG. */
11767             parent_flag == flag)
11768                 return 0;
11769
11770         err = mark_reg_read(env, reg, parent_reg, flag);
11771         if (err)
11772                 return err;
11773
11774         return flag;
11775 }
11776
11777 /* A write screens off any subsequent reads; but write marks come from the
11778  * straight-line code between a state and its parent.  When we arrive at an
11779  * equivalent state (jump target or such) we didn't arrive by the straight-line
11780  * code, so read marks in the state must propagate to the parent regardless
11781  * of the state's write marks. That's what 'parent == state->parent' comparison
11782  * in mark_reg_read() is for.
11783  */
11784 static int propagate_liveness(struct bpf_verifier_env *env,
11785                               const struct bpf_verifier_state *vstate,
11786                               struct bpf_verifier_state *vparent)
11787 {
11788         struct bpf_reg_state *state_reg, *parent_reg;
11789         struct bpf_func_state *state, *parent;
11790         int i, frame, err = 0;
11791
11792         if (vparent->curframe != vstate->curframe) {
11793                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11794                      vparent->curframe, vstate->curframe);
11795                 return -EFAULT;
11796         }
11797         /* Propagate read liveness of registers... */
11798         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11799         for (frame = 0; frame <= vstate->curframe; frame++) {
11800                 parent = vparent->frame[frame];
11801                 state = vstate->frame[frame];
11802                 parent_reg = parent->regs;
11803                 state_reg = state->regs;
11804                 /* We don't need to worry about FP liveness, it's read-only */
11805                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11806                         err = propagate_liveness_reg(env, &state_reg[i],
11807                                                      &parent_reg[i]);
11808                         if (err < 0)
11809                                 return err;
11810                         if (err == REG_LIVE_READ64)
11811                                 mark_insn_zext(env, &parent_reg[i]);
11812                 }
11813
11814                 /* Propagate stack slots. */
11815                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11816                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11817                         parent_reg = &parent->stack[i].spilled_ptr;
11818                         state_reg = &state->stack[i].spilled_ptr;
11819                         err = propagate_liveness_reg(env, state_reg,
11820                                                      parent_reg);
11821                         if (err < 0)
11822                                 return err;
11823                 }
11824         }
11825         return 0;
11826 }
11827
11828 /* find precise scalars in the previous equivalent state and
11829  * propagate them into the current state
11830  */
11831 static int propagate_precision(struct bpf_verifier_env *env,
11832                                const struct bpf_verifier_state *old)
11833 {
11834         struct bpf_reg_state *state_reg;
11835         struct bpf_func_state *state;
11836         int i, err = 0;
11837
11838         state = old->frame[old->curframe];
11839         state_reg = state->regs;
11840         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11841                 if (state_reg->type != SCALAR_VALUE ||
11842                     !state_reg->precise)
11843                         continue;
11844                 if (env->log.level & BPF_LOG_LEVEL2)
11845                         verbose(env, "propagating r%d\n", i);
11846                 err = mark_chain_precision(env, i);
11847                 if (err < 0)
11848                         return err;
11849         }
11850
11851         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11852                 if (!is_spilled_reg(&state->stack[i]))
11853                         continue;
11854                 state_reg = &state->stack[i].spilled_ptr;
11855                 if (state_reg->type != SCALAR_VALUE ||
11856                     !state_reg->precise)
11857                         continue;
11858                 if (env->log.level & BPF_LOG_LEVEL2)
11859                         verbose(env, "propagating fp%d\n",
11860                                 (-i - 1) * BPF_REG_SIZE);
11861                 err = mark_chain_precision_stack(env, i);
11862                 if (err < 0)
11863                         return err;
11864         }
11865         return 0;
11866 }
11867
11868 static bool states_maybe_looping(struct bpf_verifier_state *old,
11869                                  struct bpf_verifier_state *cur)
11870 {
11871         struct bpf_func_state *fold, *fcur;
11872         int i, fr = cur->curframe;
11873
11874         if (old->curframe != fr)
11875                 return false;
11876
11877         fold = old->frame[fr];
11878         fcur = cur->frame[fr];
11879         for (i = 0; i < MAX_BPF_REG; i++)
11880                 if (memcmp(&fold->regs[i], &fcur->regs[i],
11881                            offsetof(struct bpf_reg_state, parent)))
11882                         return false;
11883         return true;
11884 }
11885
11886
11887 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11888 {
11889         struct bpf_verifier_state_list *new_sl;
11890         struct bpf_verifier_state_list *sl, **pprev;
11891         struct bpf_verifier_state *cur = env->cur_state, *new;
11892         int i, j, err, states_cnt = 0;
11893         bool add_new_state = env->test_state_freq ? true : false;
11894
11895         cur->last_insn_idx = env->prev_insn_idx;
11896         if (!env->insn_aux_data[insn_idx].prune_point)
11897                 /* this 'insn_idx' instruction wasn't marked, so we will not
11898                  * be doing state search here
11899                  */
11900                 return 0;
11901
11902         /* bpf progs typically have pruning point every 4 instructions
11903          * http://vger.kernel.org/bpfconf2019.html#session-1
11904          * Do not add new state for future pruning if the verifier hasn't seen
11905          * at least 2 jumps and at least 8 instructions.
11906          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11907          * In tests that amounts to up to 50% reduction into total verifier
11908          * memory consumption and 20% verifier time speedup.
11909          */
11910         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11911             env->insn_processed - env->prev_insn_processed >= 8)
11912                 add_new_state = true;
11913
11914         pprev = explored_state(env, insn_idx);
11915         sl = *pprev;
11916
11917         clean_live_states(env, insn_idx, cur);
11918
11919         while (sl) {
11920                 states_cnt++;
11921                 if (sl->state.insn_idx != insn_idx)
11922                         goto next;
11923
11924                 if (sl->state.branches) {
11925                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11926
11927                         if (frame->in_async_callback_fn &&
11928                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11929                                 /* Different async_entry_cnt means that the verifier is
11930                                  * processing another entry into async callback.
11931                                  * Seeing the same state is not an indication of infinite
11932                                  * loop or infinite recursion.
11933                                  * But finding the same state doesn't mean that it's safe
11934                                  * to stop processing the current state. The previous state
11935                                  * hasn't yet reached bpf_exit, since state.branches > 0.
11936                                  * Checking in_async_callback_fn alone is not enough either.
11937                                  * Since the verifier still needs to catch infinite loops
11938                                  * inside async callbacks.
11939                                  */
11940                         } else if (states_maybe_looping(&sl->state, cur) &&
11941                                    states_equal(env, &sl->state, cur)) {
11942                                 verbose_linfo(env, insn_idx, "; ");
11943                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11944                                 return -EINVAL;
11945                         }
11946                         /* if the verifier is processing a loop, avoid adding new state
11947                          * too often, since different loop iterations have distinct
11948                          * states and may not help future pruning.
11949                          * This threshold shouldn't be too low to make sure that
11950                          * a loop with large bound will be rejected quickly.
11951                          * The most abusive loop will be:
11952                          * r1 += 1
11953                          * if r1 < 1000000 goto pc-2
11954                          * 1M insn_procssed limit / 100 == 10k peak states.
11955                          * This threshold shouldn't be too high either, since states
11956                          * at the end of the loop are likely to be useful in pruning.
11957                          */
11958                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11959                             env->insn_processed - env->prev_insn_processed < 100)
11960                                 add_new_state = false;
11961                         goto miss;
11962                 }
11963                 if (states_equal(env, &sl->state, cur)) {
11964                         sl->hit_cnt++;
11965                         /* reached equivalent register/stack state,
11966                          * prune the search.
11967                          * Registers read by the continuation are read by us.
11968                          * If we have any write marks in env->cur_state, they
11969                          * will prevent corresponding reads in the continuation
11970                          * from reaching our parent (an explored_state).  Our
11971                          * own state will get the read marks recorded, but
11972                          * they'll be immediately forgotten as we're pruning
11973                          * this state and will pop a new one.
11974                          */
11975                         err = propagate_liveness(env, &sl->state, cur);
11976
11977                         /* if previous state reached the exit with precision and
11978                          * current state is equivalent to it (except precsion marks)
11979                          * the precision needs to be propagated back in
11980                          * the current state.
11981                          */
11982                         err = err ? : push_jmp_history(env, cur);
11983                         err = err ? : propagate_precision(env, &sl->state);
11984                         if (err)
11985                                 return err;
11986                         return 1;
11987                 }
11988 miss:
11989                 /* when new state is not going to be added do not increase miss count.
11990                  * Otherwise several loop iterations will remove the state
11991                  * recorded earlier. The goal of these heuristics is to have
11992                  * states from some iterations of the loop (some in the beginning
11993                  * and some at the end) to help pruning.
11994                  */
11995                 if (add_new_state)
11996                         sl->miss_cnt++;
11997                 /* heuristic to determine whether this state is beneficial
11998                  * to keep checking from state equivalence point of view.
11999                  * Higher numbers increase max_states_per_insn and verification time,
12000                  * but do not meaningfully decrease insn_processed.
12001                  */
12002                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12003                         /* the state is unlikely to be useful. Remove it to
12004                          * speed up verification
12005                          */
12006                         *pprev = sl->next;
12007                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12008                                 u32 br = sl->state.branches;
12009
12010                                 WARN_ONCE(br,
12011                                           "BUG live_done but branches_to_explore %d\n",
12012                                           br);
12013                                 free_verifier_state(&sl->state, false);
12014                                 kfree(sl);
12015                                 env->peak_states--;
12016                         } else {
12017                                 /* cannot free this state, since parentage chain may
12018                                  * walk it later. Add it for free_list instead to
12019                                  * be freed at the end of verification
12020                                  */
12021                                 sl->next = env->free_list;
12022                                 env->free_list = sl;
12023                         }
12024                         sl = *pprev;
12025                         continue;
12026                 }
12027 next:
12028                 pprev = &sl->next;
12029                 sl = *pprev;
12030         }
12031
12032         if (env->max_states_per_insn < states_cnt)
12033                 env->max_states_per_insn = states_cnt;
12034
12035         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12036                 return push_jmp_history(env, cur);
12037
12038         if (!add_new_state)
12039                 return push_jmp_history(env, cur);
12040
12041         /* There were no equivalent states, remember the current one.
12042          * Technically the current state is not proven to be safe yet,
12043          * but it will either reach outer most bpf_exit (which means it's safe)
12044          * or it will be rejected. When there are no loops the verifier won't be
12045          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12046          * again on the way to bpf_exit.
12047          * When looping the sl->state.branches will be > 0 and this state
12048          * will not be considered for equivalence until branches == 0.
12049          */
12050         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12051         if (!new_sl)
12052                 return -ENOMEM;
12053         env->total_states++;
12054         env->peak_states++;
12055         env->prev_jmps_processed = env->jmps_processed;
12056         env->prev_insn_processed = env->insn_processed;
12057
12058         /* add new state to the head of linked list */
12059         new = &new_sl->state;
12060         err = copy_verifier_state(new, cur);
12061         if (err) {
12062                 free_verifier_state(new, false);
12063                 kfree(new_sl);
12064                 return err;
12065         }
12066         new->insn_idx = insn_idx;
12067         WARN_ONCE(new->branches != 1,
12068                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12069
12070         cur->parent = new;
12071         cur->first_insn_idx = insn_idx;
12072         clear_jmp_history(cur);
12073         new_sl->next = *explored_state(env, insn_idx);
12074         *explored_state(env, insn_idx) = new_sl;
12075         /* connect new state to parentage chain. Current frame needs all
12076          * registers connected. Only r6 - r9 of the callers are alive (pushed
12077          * to the stack implicitly by JITs) so in callers' frames connect just
12078          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12079          * the state of the call instruction (with WRITTEN set), and r0 comes
12080          * from callee with its full parentage chain, anyway.
12081          */
12082         /* clear write marks in current state: the writes we did are not writes
12083          * our child did, so they don't screen off its reads from us.
12084          * (There are no read marks in current state, because reads always mark
12085          * their parent and current state never has children yet.  Only
12086          * explored_states can get read marks.)
12087          */
12088         for (j = 0; j <= cur->curframe; j++) {
12089                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12090                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12091                 for (i = 0; i < BPF_REG_FP; i++)
12092                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12093         }
12094
12095         /* all stack frames are accessible from callee, clear them all */
12096         for (j = 0; j <= cur->curframe; j++) {
12097                 struct bpf_func_state *frame = cur->frame[j];
12098                 struct bpf_func_state *newframe = new->frame[j];
12099
12100                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12101                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12102                         frame->stack[i].spilled_ptr.parent =
12103                                                 &newframe->stack[i].spilled_ptr;
12104                 }
12105         }
12106         return 0;
12107 }
12108
12109 /* Return true if it's OK to have the same insn return a different type. */
12110 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12111 {
12112         switch (base_type(type)) {
12113         case PTR_TO_CTX:
12114         case PTR_TO_SOCKET:
12115         case PTR_TO_SOCK_COMMON:
12116         case PTR_TO_TCP_SOCK:
12117         case PTR_TO_XDP_SOCK:
12118         case PTR_TO_BTF_ID:
12119                 return false;
12120         default:
12121                 return true;
12122         }
12123 }
12124
12125 /* If an instruction was previously used with particular pointer types, then we
12126  * need to be careful to avoid cases such as the below, where it may be ok
12127  * for one branch accessing the pointer, but not ok for the other branch:
12128  *
12129  * R1 = sock_ptr
12130  * goto X;
12131  * ...
12132  * R1 = some_other_valid_ptr;
12133  * goto X;
12134  * ...
12135  * R2 = *(u32 *)(R1 + 0);
12136  */
12137 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12138 {
12139         return src != prev && (!reg_type_mismatch_ok(src) ||
12140                                !reg_type_mismatch_ok(prev));
12141 }
12142
12143 static int do_check(struct bpf_verifier_env *env)
12144 {
12145         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12146         struct bpf_verifier_state *state = env->cur_state;
12147         struct bpf_insn *insns = env->prog->insnsi;
12148         struct bpf_reg_state *regs;
12149         int insn_cnt = env->prog->len;
12150         bool do_print_state = false;
12151         int prev_insn_idx = -1;
12152
12153         for (;;) {
12154                 struct bpf_insn *insn;
12155                 u8 class;
12156                 int err;
12157
12158                 env->prev_insn_idx = prev_insn_idx;
12159                 if (env->insn_idx >= insn_cnt) {
12160                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
12161                                 env->insn_idx, insn_cnt);
12162                         return -EFAULT;
12163                 }
12164
12165                 insn = &insns[env->insn_idx];
12166                 class = BPF_CLASS(insn->code);
12167
12168                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12169                         verbose(env,
12170                                 "BPF program is too large. Processed %d insn\n",
12171                                 env->insn_processed);
12172                         return -E2BIG;
12173                 }
12174
12175                 err = is_state_visited(env, env->insn_idx);
12176                 if (err < 0)
12177                         return err;
12178                 if (err == 1) {
12179                         /* found equivalent state, can prune the search */
12180                         if (env->log.level & BPF_LOG_LEVEL) {
12181                                 if (do_print_state)
12182                                         verbose(env, "\nfrom %d to %d%s: safe\n",
12183                                                 env->prev_insn_idx, env->insn_idx,
12184                                                 env->cur_state->speculative ?
12185                                                 " (speculative execution)" : "");
12186                                 else
12187                                         verbose(env, "%d: safe\n", env->insn_idx);
12188                         }
12189                         goto process_bpf_exit;
12190                 }
12191
12192                 if (signal_pending(current))
12193                         return -EAGAIN;
12194
12195                 if (need_resched())
12196                         cond_resched();
12197
12198                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12199                         verbose(env, "\nfrom %d to %d%s:",
12200                                 env->prev_insn_idx, env->insn_idx,
12201                                 env->cur_state->speculative ?
12202                                 " (speculative execution)" : "");
12203                         print_verifier_state(env, state->frame[state->curframe], true);
12204                         do_print_state = false;
12205                 }
12206
12207                 if (env->log.level & BPF_LOG_LEVEL) {
12208                         const struct bpf_insn_cbs cbs = {
12209                                 .cb_call        = disasm_kfunc_name,
12210                                 .cb_print       = verbose,
12211                                 .private_data   = env,
12212                         };
12213
12214                         if (verifier_state_scratched(env))
12215                                 print_insn_state(env, state->frame[state->curframe]);
12216
12217                         verbose_linfo(env, env->insn_idx, "; ");
12218                         env->prev_log_len = env->log.len_used;
12219                         verbose(env, "%d: ", env->insn_idx);
12220                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12221                         env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12222                         env->prev_log_len = env->log.len_used;
12223                 }
12224
12225                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12226                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12227                                                            env->prev_insn_idx);
12228                         if (err)
12229                                 return err;
12230                 }
12231
12232                 regs = cur_regs(env);
12233                 sanitize_mark_insn_seen(env);
12234                 prev_insn_idx = env->insn_idx;
12235
12236                 if (class == BPF_ALU || class == BPF_ALU64) {
12237                         err = check_alu_op(env, insn);
12238                         if (err)
12239                                 return err;
12240
12241                 } else if (class == BPF_LDX) {
12242                         enum bpf_reg_type *prev_src_type, src_reg_type;
12243
12244                         /* check for reserved fields is already done */
12245
12246                         /* check src operand */
12247                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12248                         if (err)
12249                                 return err;
12250
12251                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12252                         if (err)
12253                                 return err;
12254
12255                         src_reg_type = regs[insn->src_reg].type;
12256
12257                         /* check that memory (src_reg + off) is readable,
12258                          * the state of dst_reg will be updated by this func
12259                          */
12260                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
12261                                                insn->off, BPF_SIZE(insn->code),
12262                                                BPF_READ, insn->dst_reg, false);
12263                         if (err)
12264                                 return err;
12265
12266                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12267
12268                         if (*prev_src_type == NOT_INIT) {
12269                                 /* saw a valid insn
12270                                  * dst_reg = *(u32 *)(src_reg + off)
12271                                  * save type to validate intersecting paths
12272                                  */
12273                                 *prev_src_type = src_reg_type;
12274
12275                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12276                                 /* ABuser program is trying to use the same insn
12277                                  * dst_reg = *(u32*) (src_reg + off)
12278                                  * with different pointer types:
12279                                  * src_reg == ctx in one branch and
12280                                  * src_reg == stack|map in some other branch.
12281                                  * Reject it.
12282                                  */
12283                                 verbose(env, "same insn cannot be used with different pointers\n");
12284                                 return -EINVAL;
12285                         }
12286
12287                 } else if (class == BPF_STX) {
12288                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
12289
12290                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12291                                 err = check_atomic(env, env->insn_idx, insn);
12292                                 if (err)
12293                                         return err;
12294                                 env->insn_idx++;
12295                                 continue;
12296                         }
12297
12298                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12299                                 verbose(env, "BPF_STX uses reserved fields\n");
12300                                 return -EINVAL;
12301                         }
12302
12303                         /* check src1 operand */
12304                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12305                         if (err)
12306                                 return err;
12307                         /* check src2 operand */
12308                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12309                         if (err)
12310                                 return err;
12311
12312                         dst_reg_type = regs[insn->dst_reg].type;
12313
12314                         /* check that memory (dst_reg + off) is writeable */
12315                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12316                                                insn->off, BPF_SIZE(insn->code),
12317                                                BPF_WRITE, insn->src_reg, false);
12318                         if (err)
12319                                 return err;
12320
12321                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12322
12323                         if (*prev_dst_type == NOT_INIT) {
12324                                 *prev_dst_type = dst_reg_type;
12325                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12326                                 verbose(env, "same insn cannot be used with different pointers\n");
12327                                 return -EINVAL;
12328                         }
12329
12330                 } else if (class == BPF_ST) {
12331                         if (BPF_MODE(insn->code) != BPF_MEM ||
12332                             insn->src_reg != BPF_REG_0) {
12333                                 verbose(env, "BPF_ST uses reserved fields\n");
12334                                 return -EINVAL;
12335                         }
12336                         /* check src operand */
12337                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12338                         if (err)
12339                                 return err;
12340
12341                         if (is_ctx_reg(env, insn->dst_reg)) {
12342                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12343                                         insn->dst_reg,
12344                                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12345                                 return -EACCES;
12346                         }
12347
12348                         /* check that memory (dst_reg + off) is writeable */
12349                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12350                                                insn->off, BPF_SIZE(insn->code),
12351                                                BPF_WRITE, -1, false);
12352                         if (err)
12353                                 return err;
12354
12355                 } else if (class == BPF_JMP || class == BPF_JMP32) {
12356                         u8 opcode = BPF_OP(insn->code);
12357
12358                         env->jmps_processed++;
12359                         if (opcode == BPF_CALL) {
12360                                 if (BPF_SRC(insn->code) != BPF_K ||
12361                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12362                                      && insn->off != 0) ||
12363                                     (insn->src_reg != BPF_REG_0 &&
12364                                      insn->src_reg != BPF_PSEUDO_CALL &&
12365                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12366                                     insn->dst_reg != BPF_REG_0 ||
12367                                     class == BPF_JMP32) {
12368                                         verbose(env, "BPF_CALL uses reserved fields\n");
12369                                         return -EINVAL;
12370                                 }
12371
12372                                 if (env->cur_state->active_spin_lock &&
12373                                     (insn->src_reg == BPF_PSEUDO_CALL ||
12374                                      insn->imm != BPF_FUNC_spin_unlock)) {
12375                                         verbose(env, "function calls are not allowed while holding a lock\n");
12376                                         return -EINVAL;
12377                                 }
12378                                 if (insn->src_reg == BPF_PSEUDO_CALL)
12379                                         err = check_func_call(env, insn, &env->insn_idx);
12380                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12381                                         err = check_kfunc_call(env, insn, &env->insn_idx);
12382                                 else
12383                                         err = check_helper_call(env, insn, &env->insn_idx);
12384                                 if (err)
12385                                         return err;
12386                         } else if (opcode == BPF_JA) {
12387                                 if (BPF_SRC(insn->code) != BPF_K ||
12388                                     insn->imm != 0 ||
12389                                     insn->src_reg != BPF_REG_0 ||
12390                                     insn->dst_reg != BPF_REG_0 ||
12391                                     class == BPF_JMP32) {
12392                                         verbose(env, "BPF_JA uses reserved fields\n");
12393                                         return -EINVAL;
12394                                 }
12395
12396                                 env->insn_idx += insn->off + 1;
12397                                 continue;
12398
12399                         } else if (opcode == BPF_EXIT) {
12400                                 if (BPF_SRC(insn->code) != BPF_K ||
12401                                     insn->imm != 0 ||
12402                                     insn->src_reg != BPF_REG_0 ||
12403                                     insn->dst_reg != BPF_REG_0 ||
12404                                     class == BPF_JMP32) {
12405                                         verbose(env, "BPF_EXIT uses reserved fields\n");
12406                                         return -EINVAL;
12407                                 }
12408
12409                                 if (env->cur_state->active_spin_lock) {
12410                                         verbose(env, "bpf_spin_unlock is missing\n");
12411                                         return -EINVAL;
12412                                 }
12413
12414                                 /* We must do check_reference_leak here before
12415                                  * prepare_func_exit to handle the case when
12416                                  * state->curframe > 0, it may be a callback
12417                                  * function, for which reference_state must
12418                                  * match caller reference state when it exits.
12419                                  */
12420                                 err = check_reference_leak(env);
12421                                 if (err)
12422                                         return err;
12423
12424                                 if (state->curframe) {
12425                                         /* exit from nested function */
12426                                         err = prepare_func_exit(env, &env->insn_idx);
12427                                         if (err)
12428                                                 return err;
12429                                         do_print_state = true;
12430                                         continue;
12431                                 }
12432
12433                                 err = check_return_code(env);
12434                                 if (err)
12435                                         return err;
12436 process_bpf_exit:
12437                                 mark_verifier_state_scratched(env);
12438                                 update_branch_counts(env, env->cur_state);
12439                                 err = pop_stack(env, &prev_insn_idx,
12440                                                 &env->insn_idx, pop_log);
12441                                 if (err < 0) {
12442                                         if (err != -ENOENT)
12443                                                 return err;
12444                                         break;
12445                                 } else {
12446                                         do_print_state = true;
12447                                         continue;
12448                                 }
12449                         } else {
12450                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12451                                 if (err)
12452                                         return err;
12453                         }
12454                 } else if (class == BPF_LD) {
12455                         u8 mode = BPF_MODE(insn->code);
12456
12457                         if (mode == BPF_ABS || mode == BPF_IND) {
12458                                 err = check_ld_abs(env, insn);
12459                                 if (err)
12460                                         return err;
12461
12462                         } else if (mode == BPF_IMM) {
12463                                 err = check_ld_imm(env, insn);
12464                                 if (err)
12465                                         return err;
12466
12467                                 env->insn_idx++;
12468                                 sanitize_mark_insn_seen(env);
12469                         } else {
12470                                 verbose(env, "invalid BPF_LD mode\n");
12471                                 return -EINVAL;
12472                         }
12473                 } else {
12474                         verbose(env, "unknown insn class %d\n", class);
12475                         return -EINVAL;
12476                 }
12477
12478                 env->insn_idx++;
12479         }
12480
12481         return 0;
12482 }
12483
12484 static int find_btf_percpu_datasec(struct btf *btf)
12485 {
12486         const struct btf_type *t;
12487         const char *tname;
12488         int i, n;
12489
12490         /*
12491          * Both vmlinux and module each have their own ".data..percpu"
12492          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12493          * types to look at only module's own BTF types.
12494          */
12495         n = btf_nr_types(btf);
12496         if (btf_is_module(btf))
12497                 i = btf_nr_types(btf_vmlinux);
12498         else
12499                 i = 1;
12500
12501         for(; i < n; i++) {
12502                 t = btf_type_by_id(btf, i);
12503                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12504                         continue;
12505
12506                 tname = btf_name_by_offset(btf, t->name_off);
12507                 if (!strcmp(tname, ".data..percpu"))
12508                         return i;
12509         }
12510
12511         return -ENOENT;
12512 }
12513
12514 /* replace pseudo btf_id with kernel symbol address */
12515 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12516                                struct bpf_insn *insn,
12517                                struct bpf_insn_aux_data *aux)
12518 {
12519         const struct btf_var_secinfo *vsi;
12520         const struct btf_type *datasec;
12521         struct btf_mod_pair *btf_mod;
12522         const struct btf_type *t;
12523         const char *sym_name;
12524         bool percpu = false;
12525         u32 type, id = insn->imm;
12526         struct btf *btf;
12527         s32 datasec_id;
12528         u64 addr;
12529         int i, btf_fd, err;
12530
12531         btf_fd = insn[1].imm;
12532         if (btf_fd) {
12533                 btf = btf_get_by_fd(btf_fd);
12534                 if (IS_ERR(btf)) {
12535                         verbose(env, "invalid module BTF object FD specified.\n");
12536                         return -EINVAL;
12537                 }
12538         } else {
12539                 if (!btf_vmlinux) {
12540                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12541                         return -EINVAL;
12542                 }
12543                 btf = btf_vmlinux;
12544                 btf_get(btf);
12545         }
12546
12547         t = btf_type_by_id(btf, id);
12548         if (!t) {
12549                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12550                 err = -ENOENT;
12551                 goto err_put;
12552         }
12553
12554         if (!btf_type_is_var(t)) {
12555                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12556                 err = -EINVAL;
12557                 goto err_put;
12558         }
12559
12560         sym_name = btf_name_by_offset(btf, t->name_off);
12561         addr = kallsyms_lookup_name(sym_name);
12562         if (!addr) {
12563                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12564                         sym_name);
12565                 err = -ENOENT;
12566                 goto err_put;
12567         }
12568
12569         datasec_id = find_btf_percpu_datasec(btf);
12570         if (datasec_id > 0) {
12571                 datasec = btf_type_by_id(btf, datasec_id);
12572                 for_each_vsi(i, datasec, vsi) {
12573                         if (vsi->type == id) {
12574                                 percpu = true;
12575                                 break;
12576                         }
12577                 }
12578         }
12579
12580         insn[0].imm = (u32)addr;
12581         insn[1].imm = addr >> 32;
12582
12583         type = t->type;
12584         t = btf_type_skip_modifiers(btf, type, NULL);
12585         if (percpu) {
12586                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12587                 aux->btf_var.btf = btf;
12588                 aux->btf_var.btf_id = type;
12589         } else if (!btf_type_is_struct(t)) {
12590                 const struct btf_type *ret;
12591                 const char *tname;
12592                 u32 tsize;
12593
12594                 /* resolve the type size of ksym. */
12595                 ret = btf_resolve_size(btf, t, &tsize);
12596                 if (IS_ERR(ret)) {
12597                         tname = btf_name_by_offset(btf, t->name_off);
12598                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12599                                 tname, PTR_ERR(ret));
12600                         err = -EINVAL;
12601                         goto err_put;
12602                 }
12603                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12604                 aux->btf_var.mem_size = tsize;
12605         } else {
12606                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12607                 aux->btf_var.btf = btf;
12608                 aux->btf_var.btf_id = type;
12609         }
12610
12611         /* check whether we recorded this BTF (and maybe module) already */
12612         for (i = 0; i < env->used_btf_cnt; i++) {
12613                 if (env->used_btfs[i].btf == btf) {
12614                         btf_put(btf);
12615                         return 0;
12616                 }
12617         }
12618
12619         if (env->used_btf_cnt >= MAX_USED_BTFS) {
12620                 err = -E2BIG;
12621                 goto err_put;
12622         }
12623
12624         btf_mod = &env->used_btfs[env->used_btf_cnt];
12625         btf_mod->btf = btf;
12626         btf_mod->module = NULL;
12627
12628         /* if we reference variables from kernel module, bump its refcount */
12629         if (btf_is_module(btf)) {
12630                 btf_mod->module = btf_try_get_module(btf);
12631                 if (!btf_mod->module) {
12632                         err = -ENXIO;
12633                         goto err_put;
12634                 }
12635         }
12636
12637         env->used_btf_cnt++;
12638
12639         return 0;
12640 err_put:
12641         btf_put(btf);
12642         return err;
12643 }
12644
12645 static bool is_tracing_prog_type(enum bpf_prog_type type)
12646 {
12647         switch (type) {
12648         case BPF_PROG_TYPE_KPROBE:
12649         case BPF_PROG_TYPE_TRACEPOINT:
12650         case BPF_PROG_TYPE_PERF_EVENT:
12651         case BPF_PROG_TYPE_RAW_TRACEPOINT:
12652         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12653                 return true;
12654         default:
12655                 return false;
12656         }
12657 }
12658
12659 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12660                                         struct bpf_map *map,
12661                                         struct bpf_prog *prog)
12662
12663 {
12664         enum bpf_prog_type prog_type = resolve_prog_type(prog);
12665
12666         if (map_value_has_spin_lock(map)) {
12667                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12668                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12669                         return -EINVAL;
12670                 }
12671
12672                 if (is_tracing_prog_type(prog_type)) {
12673                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12674                         return -EINVAL;
12675                 }
12676
12677                 if (prog->aux->sleepable) {
12678                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12679                         return -EINVAL;
12680                 }
12681         }
12682
12683         if (map_value_has_timer(map)) {
12684                 if (is_tracing_prog_type(prog_type)) {
12685                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
12686                         return -EINVAL;
12687                 }
12688         }
12689
12690         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12691             !bpf_offload_prog_map_match(prog, map)) {
12692                 verbose(env, "offload device mismatch between prog and map\n");
12693                 return -EINVAL;
12694         }
12695
12696         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12697                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12698                 return -EINVAL;
12699         }
12700
12701         if (prog->aux->sleepable)
12702                 switch (map->map_type) {
12703                 case BPF_MAP_TYPE_HASH:
12704                 case BPF_MAP_TYPE_LRU_HASH:
12705                 case BPF_MAP_TYPE_ARRAY:
12706                 case BPF_MAP_TYPE_PERCPU_HASH:
12707                 case BPF_MAP_TYPE_PERCPU_ARRAY:
12708                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12709                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12710                 case BPF_MAP_TYPE_HASH_OF_MAPS:
12711                 case BPF_MAP_TYPE_RINGBUF:
12712                 case BPF_MAP_TYPE_USER_RINGBUF:
12713                 case BPF_MAP_TYPE_INODE_STORAGE:
12714                 case BPF_MAP_TYPE_SK_STORAGE:
12715                 case BPF_MAP_TYPE_TASK_STORAGE:
12716                         break;
12717                 default:
12718                         verbose(env,
12719                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12720                         return -EINVAL;
12721                 }
12722
12723         return 0;
12724 }
12725
12726 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12727 {
12728         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12729                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12730 }
12731
12732 /* find and rewrite pseudo imm in ld_imm64 instructions:
12733  *
12734  * 1. if it accesses map FD, replace it with actual map pointer.
12735  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12736  *
12737  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12738  */
12739 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12740 {
12741         struct bpf_insn *insn = env->prog->insnsi;
12742         int insn_cnt = env->prog->len;
12743         int i, j, err;
12744
12745         err = bpf_prog_calc_tag(env->prog);
12746         if (err)
12747                 return err;
12748
12749         for (i = 0; i < insn_cnt; i++, insn++) {
12750                 if (BPF_CLASS(insn->code) == BPF_LDX &&
12751                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12752                         verbose(env, "BPF_LDX uses reserved fields\n");
12753                         return -EINVAL;
12754                 }
12755
12756                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12757                         struct bpf_insn_aux_data *aux;
12758                         struct bpf_map *map;
12759                         struct fd f;
12760                         u64 addr;
12761                         u32 fd;
12762
12763                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
12764                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12765                             insn[1].off != 0) {
12766                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
12767                                 return -EINVAL;
12768                         }
12769
12770                         if (insn[0].src_reg == 0)
12771                                 /* valid generic load 64-bit imm */
12772                                 goto next_insn;
12773
12774                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12775                                 aux = &env->insn_aux_data[i];
12776                                 err = check_pseudo_btf_id(env, insn, aux);
12777                                 if (err)
12778                                         return err;
12779                                 goto next_insn;
12780                         }
12781
12782                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12783                                 aux = &env->insn_aux_data[i];
12784                                 aux->ptr_type = PTR_TO_FUNC;
12785                                 goto next_insn;
12786                         }
12787
12788                         /* In final convert_pseudo_ld_imm64() step, this is
12789                          * converted into regular 64-bit imm load insn.
12790                          */
12791                         switch (insn[0].src_reg) {
12792                         case BPF_PSEUDO_MAP_VALUE:
12793                         case BPF_PSEUDO_MAP_IDX_VALUE:
12794                                 break;
12795                         case BPF_PSEUDO_MAP_FD:
12796                         case BPF_PSEUDO_MAP_IDX:
12797                                 if (insn[1].imm == 0)
12798                                         break;
12799                                 fallthrough;
12800                         default:
12801                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12802                                 return -EINVAL;
12803                         }
12804
12805                         switch (insn[0].src_reg) {
12806                         case BPF_PSEUDO_MAP_IDX_VALUE:
12807                         case BPF_PSEUDO_MAP_IDX:
12808                                 if (bpfptr_is_null(env->fd_array)) {
12809                                         verbose(env, "fd_idx without fd_array is invalid\n");
12810                                         return -EPROTO;
12811                                 }
12812                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12813                                                             insn[0].imm * sizeof(fd),
12814                                                             sizeof(fd)))
12815                                         return -EFAULT;
12816                                 break;
12817                         default:
12818                                 fd = insn[0].imm;
12819                                 break;
12820                         }
12821
12822                         f = fdget(fd);
12823                         map = __bpf_map_get(f);
12824                         if (IS_ERR(map)) {
12825                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12826                                         insn[0].imm);
12827                                 return PTR_ERR(map);
12828                         }
12829
12830                         err = check_map_prog_compatibility(env, map, env->prog);
12831                         if (err) {
12832                                 fdput(f);
12833                                 return err;
12834                         }
12835
12836                         aux = &env->insn_aux_data[i];
12837                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12838                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12839                                 addr = (unsigned long)map;
12840                         } else {
12841                                 u32 off = insn[1].imm;
12842
12843                                 if (off >= BPF_MAX_VAR_OFF) {
12844                                         verbose(env, "direct value offset of %u is not allowed\n", off);
12845                                         fdput(f);
12846                                         return -EINVAL;
12847                                 }
12848
12849                                 if (!map->ops->map_direct_value_addr) {
12850                                         verbose(env, "no direct value access support for this map type\n");
12851                                         fdput(f);
12852                                         return -EINVAL;
12853                                 }
12854
12855                                 err = map->ops->map_direct_value_addr(map, &addr, off);
12856                                 if (err) {
12857                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12858                                                 map->value_size, off);
12859                                         fdput(f);
12860                                         return err;
12861                                 }
12862
12863                                 aux->map_off = off;
12864                                 addr += off;
12865                         }
12866
12867                         insn[0].imm = (u32)addr;
12868                         insn[1].imm = addr >> 32;
12869
12870                         /* check whether we recorded this map already */
12871                         for (j = 0; j < env->used_map_cnt; j++) {
12872                                 if (env->used_maps[j] == map) {
12873                                         aux->map_index = j;
12874                                         fdput(f);
12875                                         goto next_insn;
12876                                 }
12877                         }
12878
12879                         if (env->used_map_cnt >= MAX_USED_MAPS) {
12880                                 fdput(f);
12881                                 return -E2BIG;
12882                         }
12883
12884                         /* hold the map. If the program is rejected by verifier,
12885                          * the map will be released by release_maps() or it
12886                          * will be used by the valid program until it's unloaded
12887                          * and all maps are released in free_used_maps()
12888                          */
12889                         bpf_map_inc(map);
12890
12891                         aux->map_index = env->used_map_cnt;
12892                         env->used_maps[env->used_map_cnt++] = map;
12893
12894                         if (bpf_map_is_cgroup_storage(map) &&
12895                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
12896                                 verbose(env, "only one cgroup storage of each type is allowed\n");
12897                                 fdput(f);
12898                                 return -EBUSY;
12899                         }
12900
12901                         fdput(f);
12902 next_insn:
12903                         insn++;
12904                         i++;
12905                         continue;
12906                 }
12907
12908                 /* Basic sanity check before we invest more work here. */
12909                 if (!bpf_opcode_in_insntable(insn->code)) {
12910                         verbose(env, "unknown opcode %02x\n", insn->code);
12911                         return -EINVAL;
12912                 }
12913         }
12914
12915         /* now all pseudo BPF_LD_IMM64 instructions load valid
12916          * 'struct bpf_map *' into a register instead of user map_fd.
12917          * These pointers will be used later by verifier to validate map access.
12918          */
12919         return 0;
12920 }
12921
12922 /* drop refcnt of maps used by the rejected program */
12923 static void release_maps(struct bpf_verifier_env *env)
12924 {
12925         __bpf_free_used_maps(env->prog->aux, env->used_maps,
12926                              env->used_map_cnt);
12927 }
12928
12929 /* drop refcnt of maps used by the rejected program */
12930 static void release_btfs(struct bpf_verifier_env *env)
12931 {
12932         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12933                              env->used_btf_cnt);
12934 }
12935
12936 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12937 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12938 {
12939         struct bpf_insn *insn = env->prog->insnsi;
12940         int insn_cnt = env->prog->len;
12941         int i;
12942
12943         for (i = 0; i < insn_cnt; i++, insn++) {
12944                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12945                         continue;
12946                 if (insn->src_reg == BPF_PSEUDO_FUNC)
12947                         continue;
12948                 insn->src_reg = 0;
12949         }
12950 }
12951
12952 /* single env->prog->insni[off] instruction was replaced with the range
12953  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
12954  * [0, off) and [off, end) to new locations, so the patched range stays zero
12955  */
12956 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12957                                  struct bpf_insn_aux_data *new_data,
12958                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
12959 {
12960         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12961         struct bpf_insn *insn = new_prog->insnsi;
12962         u32 old_seen = old_data[off].seen;
12963         u32 prog_len;
12964         int i;
12965
12966         /* aux info at OFF always needs adjustment, no matter fast path
12967          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12968          * original insn at old prog.
12969          */
12970         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12971
12972         if (cnt == 1)
12973                 return;
12974         prog_len = new_prog->len;
12975
12976         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12977         memcpy(new_data + off + cnt - 1, old_data + off,
12978                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12979         for (i = off; i < off + cnt - 1; i++) {
12980                 /* Expand insni[off]'s seen count to the patched range. */
12981                 new_data[i].seen = old_seen;
12982                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
12983         }
12984         env->insn_aux_data = new_data;
12985         vfree(old_data);
12986 }
12987
12988 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12989 {
12990         int i;
12991
12992         if (len == 1)
12993                 return;
12994         /* NOTE: fake 'exit' subprog should be updated as well. */
12995         for (i = 0; i <= env->subprog_cnt; i++) {
12996                 if (env->subprog_info[i].start <= off)
12997                         continue;
12998                 env->subprog_info[i].start += len - 1;
12999         }
13000 }
13001
13002 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13003 {
13004         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13005         int i, sz = prog->aux->size_poke_tab;
13006         struct bpf_jit_poke_descriptor *desc;
13007
13008         for (i = 0; i < sz; i++) {
13009                 desc = &tab[i];
13010                 if (desc->insn_idx <= off)
13011                         continue;
13012                 desc->insn_idx += len - 1;
13013         }
13014 }
13015
13016 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13017                                             const struct bpf_insn *patch, u32 len)
13018 {
13019         struct bpf_prog *new_prog;
13020         struct bpf_insn_aux_data *new_data = NULL;
13021
13022         if (len > 1) {
13023                 new_data = vzalloc(array_size(env->prog->len + len - 1,
13024                                               sizeof(struct bpf_insn_aux_data)));
13025                 if (!new_data)
13026                         return NULL;
13027         }
13028
13029         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13030         if (IS_ERR(new_prog)) {
13031                 if (PTR_ERR(new_prog) == -ERANGE)
13032                         verbose(env,
13033                                 "insn %d cannot be patched due to 16-bit range\n",
13034                                 env->insn_aux_data[off].orig_idx);
13035                 vfree(new_data);
13036                 return NULL;
13037         }
13038         adjust_insn_aux_data(env, new_data, new_prog, off, len);
13039         adjust_subprog_starts(env, off, len);
13040         adjust_poke_descs(new_prog, off, len);
13041         return new_prog;
13042 }
13043
13044 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13045                                               u32 off, u32 cnt)
13046 {
13047         int i, j;
13048
13049         /* find first prog starting at or after off (first to remove) */
13050         for (i = 0; i < env->subprog_cnt; i++)
13051                 if (env->subprog_info[i].start >= off)
13052                         break;
13053         /* find first prog starting at or after off + cnt (first to stay) */
13054         for (j = i; j < env->subprog_cnt; j++)
13055                 if (env->subprog_info[j].start >= off + cnt)
13056                         break;
13057         /* if j doesn't start exactly at off + cnt, we are just removing
13058          * the front of previous prog
13059          */
13060         if (env->subprog_info[j].start != off + cnt)
13061                 j--;
13062
13063         if (j > i) {
13064                 struct bpf_prog_aux *aux = env->prog->aux;
13065                 int move;
13066
13067                 /* move fake 'exit' subprog as well */
13068                 move = env->subprog_cnt + 1 - j;
13069
13070                 memmove(env->subprog_info + i,
13071                         env->subprog_info + j,
13072                         sizeof(*env->subprog_info) * move);
13073                 env->subprog_cnt -= j - i;
13074
13075                 /* remove func_info */
13076                 if (aux->func_info) {
13077                         move = aux->func_info_cnt - j;
13078
13079                         memmove(aux->func_info + i,
13080                                 aux->func_info + j,
13081                                 sizeof(*aux->func_info) * move);
13082                         aux->func_info_cnt -= j - i;
13083                         /* func_info->insn_off is set after all code rewrites,
13084                          * in adjust_btf_func() - no need to adjust
13085                          */
13086                 }
13087         } else {
13088                 /* convert i from "first prog to remove" to "first to adjust" */
13089                 if (env->subprog_info[i].start == off)
13090                         i++;
13091         }
13092
13093         /* update fake 'exit' subprog as well */
13094         for (; i <= env->subprog_cnt; i++)
13095                 env->subprog_info[i].start -= cnt;
13096
13097         return 0;
13098 }
13099
13100 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13101                                       u32 cnt)
13102 {
13103         struct bpf_prog *prog = env->prog;
13104         u32 i, l_off, l_cnt, nr_linfo;
13105         struct bpf_line_info *linfo;
13106
13107         nr_linfo = prog->aux->nr_linfo;
13108         if (!nr_linfo)
13109                 return 0;
13110
13111         linfo = prog->aux->linfo;
13112
13113         /* find first line info to remove, count lines to be removed */
13114         for (i = 0; i < nr_linfo; i++)
13115                 if (linfo[i].insn_off >= off)
13116                         break;
13117
13118         l_off = i;
13119         l_cnt = 0;
13120         for (; i < nr_linfo; i++)
13121                 if (linfo[i].insn_off < off + cnt)
13122                         l_cnt++;
13123                 else
13124                         break;
13125
13126         /* First live insn doesn't match first live linfo, it needs to "inherit"
13127          * last removed linfo.  prog is already modified, so prog->len == off
13128          * means no live instructions after (tail of the program was removed).
13129          */
13130         if (prog->len != off && l_cnt &&
13131             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13132                 l_cnt--;
13133                 linfo[--i].insn_off = off + cnt;
13134         }
13135
13136         /* remove the line info which refer to the removed instructions */
13137         if (l_cnt) {
13138                 memmove(linfo + l_off, linfo + i,
13139                         sizeof(*linfo) * (nr_linfo - i));
13140
13141                 prog->aux->nr_linfo -= l_cnt;
13142                 nr_linfo = prog->aux->nr_linfo;
13143         }
13144
13145         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13146         for (i = l_off; i < nr_linfo; i++)
13147                 linfo[i].insn_off -= cnt;
13148
13149         /* fix up all subprogs (incl. 'exit') which start >= off */
13150         for (i = 0; i <= env->subprog_cnt; i++)
13151                 if (env->subprog_info[i].linfo_idx > l_off) {
13152                         /* program may have started in the removed region but
13153                          * may not be fully removed
13154                          */
13155                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13156                                 env->subprog_info[i].linfo_idx -= l_cnt;
13157                         else
13158                                 env->subprog_info[i].linfo_idx = l_off;
13159                 }
13160
13161         return 0;
13162 }
13163
13164 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13165 {
13166         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13167         unsigned int orig_prog_len = env->prog->len;
13168         int err;
13169
13170         if (bpf_prog_is_dev_bound(env->prog->aux))
13171                 bpf_prog_offload_remove_insns(env, off, cnt);
13172
13173         err = bpf_remove_insns(env->prog, off, cnt);
13174         if (err)
13175                 return err;
13176
13177         err = adjust_subprog_starts_after_remove(env, off, cnt);
13178         if (err)
13179                 return err;
13180
13181         err = bpf_adj_linfo_after_remove(env, off, cnt);
13182         if (err)
13183                 return err;
13184
13185         memmove(aux_data + off, aux_data + off + cnt,
13186                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13187
13188         return 0;
13189 }
13190
13191 /* The verifier does more data flow analysis than llvm and will not
13192  * explore branches that are dead at run time. Malicious programs can
13193  * have dead code too. Therefore replace all dead at-run-time code
13194  * with 'ja -1'.
13195  *
13196  * Just nops are not optimal, e.g. if they would sit at the end of the
13197  * program and through another bug we would manage to jump there, then
13198  * we'd execute beyond program memory otherwise. Returning exception
13199  * code also wouldn't work since we can have subprogs where the dead
13200  * code could be located.
13201  */
13202 static void sanitize_dead_code(struct bpf_verifier_env *env)
13203 {
13204         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13205         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13206         struct bpf_insn *insn = env->prog->insnsi;
13207         const int insn_cnt = env->prog->len;
13208         int i;
13209
13210         for (i = 0; i < insn_cnt; i++) {
13211                 if (aux_data[i].seen)
13212                         continue;
13213                 memcpy(insn + i, &trap, sizeof(trap));
13214                 aux_data[i].zext_dst = false;
13215         }
13216 }
13217
13218 static bool insn_is_cond_jump(u8 code)
13219 {
13220         u8 op;
13221
13222         if (BPF_CLASS(code) == BPF_JMP32)
13223                 return true;
13224
13225         if (BPF_CLASS(code) != BPF_JMP)
13226                 return false;
13227
13228         op = BPF_OP(code);
13229         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13230 }
13231
13232 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13233 {
13234         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13235         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13236         struct bpf_insn *insn = env->prog->insnsi;
13237         const int insn_cnt = env->prog->len;
13238         int i;
13239
13240         for (i = 0; i < insn_cnt; i++, insn++) {
13241                 if (!insn_is_cond_jump(insn->code))
13242                         continue;
13243
13244                 if (!aux_data[i + 1].seen)
13245                         ja.off = insn->off;
13246                 else if (!aux_data[i + 1 + insn->off].seen)
13247                         ja.off = 0;
13248                 else
13249                         continue;
13250
13251                 if (bpf_prog_is_dev_bound(env->prog->aux))
13252                         bpf_prog_offload_replace_insn(env, i, &ja);
13253
13254                 memcpy(insn, &ja, sizeof(ja));
13255         }
13256 }
13257
13258 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13259 {
13260         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13261         int insn_cnt = env->prog->len;
13262         int i, err;
13263
13264         for (i = 0; i < insn_cnt; i++) {
13265                 int j;
13266
13267                 j = 0;
13268                 while (i + j < insn_cnt && !aux_data[i + j].seen)
13269                         j++;
13270                 if (!j)
13271                         continue;
13272
13273                 err = verifier_remove_insns(env, i, j);
13274                 if (err)
13275                         return err;
13276                 insn_cnt = env->prog->len;
13277         }
13278
13279         return 0;
13280 }
13281
13282 static int opt_remove_nops(struct bpf_verifier_env *env)
13283 {
13284         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13285         struct bpf_insn *insn = env->prog->insnsi;
13286         int insn_cnt = env->prog->len;
13287         int i, err;
13288
13289         for (i = 0; i < insn_cnt; i++) {
13290                 if (memcmp(&insn[i], &ja, sizeof(ja)))
13291                         continue;
13292
13293                 err = verifier_remove_insns(env, i, 1);
13294                 if (err)
13295                         return err;
13296                 insn_cnt--;
13297                 i--;
13298         }
13299
13300         return 0;
13301 }
13302
13303 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13304                                          const union bpf_attr *attr)
13305 {
13306         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13307         struct bpf_insn_aux_data *aux = env->insn_aux_data;
13308         int i, patch_len, delta = 0, len = env->prog->len;
13309         struct bpf_insn *insns = env->prog->insnsi;
13310         struct bpf_prog *new_prog;
13311         bool rnd_hi32;
13312
13313         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13314         zext_patch[1] = BPF_ZEXT_REG(0);
13315         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13316         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13317         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13318         for (i = 0; i < len; i++) {
13319                 int adj_idx = i + delta;
13320                 struct bpf_insn insn;
13321                 int load_reg;
13322
13323                 insn = insns[adj_idx];
13324                 load_reg = insn_def_regno(&insn);
13325                 if (!aux[adj_idx].zext_dst) {
13326                         u8 code, class;
13327                         u32 imm_rnd;
13328
13329                         if (!rnd_hi32)
13330                                 continue;
13331
13332                         code = insn.code;
13333                         class = BPF_CLASS(code);
13334                         if (load_reg == -1)
13335                                 continue;
13336
13337                         /* NOTE: arg "reg" (the fourth one) is only used for
13338                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
13339                          *       here.
13340                          */
13341                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13342                                 if (class == BPF_LD &&
13343                                     BPF_MODE(code) == BPF_IMM)
13344                                         i++;
13345                                 continue;
13346                         }
13347
13348                         /* ctx load could be transformed into wider load. */
13349                         if (class == BPF_LDX &&
13350                             aux[adj_idx].ptr_type == PTR_TO_CTX)
13351                                 continue;
13352
13353                         imm_rnd = get_random_u32();
13354                         rnd_hi32_patch[0] = insn;
13355                         rnd_hi32_patch[1].imm = imm_rnd;
13356                         rnd_hi32_patch[3].dst_reg = load_reg;
13357                         patch = rnd_hi32_patch;
13358                         patch_len = 4;
13359                         goto apply_patch_buffer;
13360                 }
13361
13362                 /* Add in an zero-extend instruction if a) the JIT has requested
13363                  * it or b) it's a CMPXCHG.
13364                  *
13365                  * The latter is because: BPF_CMPXCHG always loads a value into
13366                  * R0, therefore always zero-extends. However some archs'
13367                  * equivalent instruction only does this load when the
13368                  * comparison is successful. This detail of CMPXCHG is
13369                  * orthogonal to the general zero-extension behaviour of the
13370                  * CPU, so it's treated independently of bpf_jit_needs_zext.
13371                  */
13372                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13373                         continue;
13374
13375                 if (WARN_ON(load_reg == -1)) {
13376                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13377                         return -EFAULT;
13378                 }
13379
13380                 zext_patch[0] = insn;
13381                 zext_patch[1].dst_reg = load_reg;
13382                 zext_patch[1].src_reg = load_reg;
13383                 patch = zext_patch;
13384                 patch_len = 2;
13385 apply_patch_buffer:
13386                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13387                 if (!new_prog)
13388                         return -ENOMEM;
13389                 env->prog = new_prog;
13390                 insns = new_prog->insnsi;
13391                 aux = env->insn_aux_data;
13392                 delta += patch_len - 1;
13393         }
13394
13395         return 0;
13396 }
13397
13398 /* convert load instructions that access fields of a context type into a
13399  * sequence of instructions that access fields of the underlying structure:
13400  *     struct __sk_buff    -> struct sk_buff
13401  *     struct bpf_sock_ops -> struct sock
13402  */
13403 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13404 {
13405         const struct bpf_verifier_ops *ops = env->ops;
13406         int i, cnt, size, ctx_field_size, delta = 0;
13407         const int insn_cnt = env->prog->len;
13408         struct bpf_insn insn_buf[16], *insn;
13409         u32 target_size, size_default, off;
13410         struct bpf_prog *new_prog;
13411         enum bpf_access_type type;
13412         bool is_narrower_load;
13413
13414         if (ops->gen_prologue || env->seen_direct_write) {
13415                 if (!ops->gen_prologue) {
13416                         verbose(env, "bpf verifier is misconfigured\n");
13417                         return -EINVAL;
13418                 }
13419                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13420                                         env->prog);
13421                 if (cnt >= ARRAY_SIZE(insn_buf)) {
13422                         verbose(env, "bpf verifier is misconfigured\n");
13423                         return -EINVAL;
13424                 } else if (cnt) {
13425                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13426                         if (!new_prog)
13427                                 return -ENOMEM;
13428
13429                         env->prog = new_prog;
13430                         delta += cnt - 1;
13431                 }
13432         }
13433
13434         if (bpf_prog_is_dev_bound(env->prog->aux))
13435                 return 0;
13436
13437         insn = env->prog->insnsi + delta;
13438
13439         for (i = 0; i < insn_cnt; i++, insn++) {
13440                 bpf_convert_ctx_access_t convert_ctx_access;
13441                 bool ctx_access;
13442
13443                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13444                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13445                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13446                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13447                         type = BPF_READ;
13448                         ctx_access = true;
13449                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13450                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13451                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13452                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13453                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13454                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13455                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13456                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13457                         type = BPF_WRITE;
13458                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13459                 } else {
13460                         continue;
13461                 }
13462
13463                 if (type == BPF_WRITE &&
13464                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
13465                         struct bpf_insn patch[] = {
13466                                 *insn,
13467                                 BPF_ST_NOSPEC(),
13468                         };
13469
13470                         cnt = ARRAY_SIZE(patch);
13471                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13472                         if (!new_prog)
13473                                 return -ENOMEM;
13474
13475                         delta    += cnt - 1;
13476                         env->prog = new_prog;
13477                         insn      = new_prog->insnsi + i + delta;
13478                         continue;
13479                 }
13480
13481                 if (!ctx_access)
13482                         continue;
13483
13484                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13485                 case PTR_TO_CTX:
13486                         if (!ops->convert_ctx_access)
13487                                 continue;
13488                         convert_ctx_access = ops->convert_ctx_access;
13489                         break;
13490                 case PTR_TO_SOCKET:
13491                 case PTR_TO_SOCK_COMMON:
13492                         convert_ctx_access = bpf_sock_convert_ctx_access;
13493                         break;
13494                 case PTR_TO_TCP_SOCK:
13495                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13496                         break;
13497                 case PTR_TO_XDP_SOCK:
13498                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13499                         break;
13500                 case PTR_TO_BTF_ID:
13501                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13502                         if (type == BPF_READ) {
13503                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
13504                                         BPF_SIZE((insn)->code);
13505                                 env->prog->aux->num_exentries++;
13506                         }
13507                         continue;
13508                 default:
13509                         continue;
13510                 }
13511
13512                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13513                 size = BPF_LDST_BYTES(insn);
13514
13515                 /* If the read access is a narrower load of the field,
13516                  * convert to a 4/8-byte load, to minimum program type specific
13517                  * convert_ctx_access changes. If conversion is successful,
13518                  * we will apply proper mask to the result.
13519                  */
13520                 is_narrower_load = size < ctx_field_size;
13521                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13522                 off = insn->off;
13523                 if (is_narrower_load) {
13524                         u8 size_code;
13525
13526                         if (type == BPF_WRITE) {
13527                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13528                                 return -EINVAL;
13529                         }
13530
13531                         size_code = BPF_H;
13532                         if (ctx_field_size == 4)
13533                                 size_code = BPF_W;
13534                         else if (ctx_field_size == 8)
13535                                 size_code = BPF_DW;
13536
13537                         insn->off = off & ~(size_default - 1);
13538                         insn->code = BPF_LDX | BPF_MEM | size_code;
13539                 }
13540
13541                 target_size = 0;
13542                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13543                                          &target_size);
13544                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13545                     (ctx_field_size && !target_size)) {
13546                         verbose(env, "bpf verifier is misconfigured\n");
13547                         return -EINVAL;
13548                 }
13549
13550                 if (is_narrower_load && size < target_size) {
13551                         u8 shift = bpf_ctx_narrow_access_offset(
13552                                 off, size, size_default) * 8;
13553                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13554                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13555                                 return -EINVAL;
13556                         }
13557                         if (ctx_field_size <= 4) {
13558                                 if (shift)
13559                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13560                                                                         insn->dst_reg,
13561                                                                         shift);
13562                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13563                                                                 (1 << size * 8) - 1);
13564                         } else {
13565                                 if (shift)
13566                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13567                                                                         insn->dst_reg,
13568                                                                         shift);
13569                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13570                                                                 (1ULL << size * 8) - 1);
13571                         }
13572                 }
13573
13574                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13575                 if (!new_prog)
13576                         return -ENOMEM;
13577
13578                 delta += cnt - 1;
13579
13580                 /* keep walking new program and skip insns we just inserted */
13581                 env->prog = new_prog;
13582                 insn      = new_prog->insnsi + i + delta;
13583         }
13584
13585         return 0;
13586 }
13587
13588 static int jit_subprogs(struct bpf_verifier_env *env)
13589 {
13590         struct bpf_prog *prog = env->prog, **func, *tmp;
13591         int i, j, subprog_start, subprog_end = 0, len, subprog;
13592         struct bpf_map *map_ptr;
13593         struct bpf_insn *insn;
13594         void *old_bpf_func;
13595         int err, num_exentries;
13596
13597         if (env->subprog_cnt <= 1)
13598                 return 0;
13599
13600         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13601                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13602                         continue;
13603
13604                 /* Upon error here we cannot fall back to interpreter but
13605                  * need a hard reject of the program. Thus -EFAULT is
13606                  * propagated in any case.
13607                  */
13608                 subprog = find_subprog(env, i + insn->imm + 1);
13609                 if (subprog < 0) {
13610                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13611                                   i + insn->imm + 1);
13612                         return -EFAULT;
13613                 }
13614                 /* temporarily remember subprog id inside insn instead of
13615                  * aux_data, since next loop will split up all insns into funcs
13616                  */
13617                 insn->off = subprog;
13618                 /* remember original imm in case JIT fails and fallback
13619                  * to interpreter will be needed
13620                  */
13621                 env->insn_aux_data[i].call_imm = insn->imm;
13622                 /* point imm to __bpf_call_base+1 from JITs point of view */
13623                 insn->imm = 1;
13624                 if (bpf_pseudo_func(insn))
13625                         /* jit (e.g. x86_64) may emit fewer instructions
13626                          * if it learns a u32 imm is the same as a u64 imm.
13627                          * Force a non zero here.
13628                          */
13629                         insn[1].imm = 1;
13630         }
13631
13632         err = bpf_prog_alloc_jited_linfo(prog);
13633         if (err)
13634                 goto out_undo_insn;
13635
13636         err = -ENOMEM;
13637         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13638         if (!func)
13639                 goto out_undo_insn;
13640
13641         for (i = 0; i < env->subprog_cnt; i++) {
13642                 subprog_start = subprog_end;
13643                 subprog_end = env->subprog_info[i + 1].start;
13644
13645                 len = subprog_end - subprog_start;
13646                 /* bpf_prog_run() doesn't call subprogs directly,
13647                  * hence main prog stats include the runtime of subprogs.
13648                  * subprogs don't have IDs and not reachable via prog_get_next_id
13649                  * func[i]->stats will never be accessed and stays NULL
13650                  */
13651                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13652                 if (!func[i])
13653                         goto out_free;
13654                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13655                        len * sizeof(struct bpf_insn));
13656                 func[i]->type = prog->type;
13657                 func[i]->len = len;
13658                 if (bpf_prog_calc_tag(func[i]))
13659                         goto out_free;
13660                 func[i]->is_func = 1;
13661                 func[i]->aux->func_idx = i;
13662                 /* Below members will be freed only at prog->aux */
13663                 func[i]->aux->btf = prog->aux->btf;
13664                 func[i]->aux->func_info = prog->aux->func_info;
13665                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13666                 func[i]->aux->poke_tab = prog->aux->poke_tab;
13667                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13668
13669                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13670                         struct bpf_jit_poke_descriptor *poke;
13671
13672                         poke = &prog->aux->poke_tab[j];
13673                         if (poke->insn_idx < subprog_end &&
13674                             poke->insn_idx >= subprog_start)
13675                                 poke->aux = func[i]->aux;
13676                 }
13677
13678                 func[i]->aux->name[0] = 'F';
13679                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13680                 func[i]->jit_requested = 1;
13681                 func[i]->blinding_requested = prog->blinding_requested;
13682                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13683                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13684                 func[i]->aux->linfo = prog->aux->linfo;
13685                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13686                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13687                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13688                 num_exentries = 0;
13689                 insn = func[i]->insnsi;
13690                 for (j = 0; j < func[i]->len; j++, insn++) {
13691                         if (BPF_CLASS(insn->code) == BPF_LDX &&
13692                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
13693                                 num_exentries++;
13694                 }
13695                 func[i]->aux->num_exentries = num_exentries;
13696                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13697                 func[i] = bpf_int_jit_compile(func[i]);
13698                 if (!func[i]->jited) {
13699                         err = -ENOTSUPP;
13700                         goto out_free;
13701                 }
13702                 cond_resched();
13703         }
13704
13705         /* at this point all bpf functions were successfully JITed
13706          * now populate all bpf_calls with correct addresses and
13707          * run last pass of JIT
13708          */
13709         for (i = 0; i < env->subprog_cnt; i++) {
13710                 insn = func[i]->insnsi;
13711                 for (j = 0; j < func[i]->len; j++, insn++) {
13712                         if (bpf_pseudo_func(insn)) {
13713                                 subprog = insn->off;
13714                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13715                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13716                                 continue;
13717                         }
13718                         if (!bpf_pseudo_call(insn))
13719                                 continue;
13720                         subprog = insn->off;
13721                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13722                 }
13723
13724                 /* we use the aux data to keep a list of the start addresses
13725                  * of the JITed images for each function in the program
13726                  *
13727                  * for some architectures, such as powerpc64, the imm field
13728                  * might not be large enough to hold the offset of the start
13729                  * address of the callee's JITed image from __bpf_call_base
13730                  *
13731                  * in such cases, we can lookup the start address of a callee
13732                  * by using its subprog id, available from the off field of
13733                  * the call instruction, as an index for this list
13734                  */
13735                 func[i]->aux->func = func;
13736                 func[i]->aux->func_cnt = env->subprog_cnt;
13737         }
13738         for (i = 0; i < env->subprog_cnt; i++) {
13739                 old_bpf_func = func[i]->bpf_func;
13740                 tmp = bpf_int_jit_compile(func[i]);
13741                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13742                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13743                         err = -ENOTSUPP;
13744                         goto out_free;
13745                 }
13746                 cond_resched();
13747         }
13748
13749         /* finally lock prog and jit images for all functions and
13750          * populate kallsysm
13751          */
13752         for (i = 0; i < env->subprog_cnt; i++) {
13753                 bpf_prog_lock_ro(func[i]);
13754                 bpf_prog_kallsyms_add(func[i]);
13755         }
13756
13757         /* Last step: make now unused interpreter insns from main
13758          * prog consistent for later dump requests, so they can
13759          * later look the same as if they were interpreted only.
13760          */
13761         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13762                 if (bpf_pseudo_func(insn)) {
13763                         insn[0].imm = env->insn_aux_data[i].call_imm;
13764                         insn[1].imm = insn->off;
13765                         insn->off = 0;
13766                         continue;
13767                 }
13768                 if (!bpf_pseudo_call(insn))
13769                         continue;
13770                 insn->off = env->insn_aux_data[i].call_imm;
13771                 subprog = find_subprog(env, i + insn->off + 1);
13772                 insn->imm = subprog;
13773         }
13774
13775         prog->jited = 1;
13776         prog->bpf_func = func[0]->bpf_func;
13777         prog->jited_len = func[0]->jited_len;
13778         prog->aux->func = func;
13779         prog->aux->func_cnt = env->subprog_cnt;
13780         bpf_prog_jit_attempt_done(prog);
13781         return 0;
13782 out_free:
13783         /* We failed JIT'ing, so at this point we need to unregister poke
13784          * descriptors from subprogs, so that kernel is not attempting to
13785          * patch it anymore as we're freeing the subprog JIT memory.
13786          */
13787         for (i = 0; i < prog->aux->size_poke_tab; i++) {
13788                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13789                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13790         }
13791         /* At this point we're guaranteed that poke descriptors are not
13792          * live anymore. We can just unlink its descriptor table as it's
13793          * released with the main prog.
13794          */
13795         for (i = 0; i < env->subprog_cnt; i++) {
13796                 if (!func[i])
13797                         continue;
13798                 func[i]->aux->poke_tab = NULL;
13799                 bpf_jit_free(func[i]);
13800         }
13801         kfree(func);
13802 out_undo_insn:
13803         /* cleanup main prog to be interpreted */
13804         prog->jit_requested = 0;
13805         prog->blinding_requested = 0;
13806         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13807                 if (!bpf_pseudo_call(insn))
13808                         continue;
13809                 insn->off = 0;
13810                 insn->imm = env->insn_aux_data[i].call_imm;
13811         }
13812         bpf_prog_jit_attempt_done(prog);
13813         return err;
13814 }
13815
13816 static int fixup_call_args(struct bpf_verifier_env *env)
13817 {
13818 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13819         struct bpf_prog *prog = env->prog;
13820         struct bpf_insn *insn = prog->insnsi;
13821         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13822         int i, depth;
13823 #endif
13824         int err = 0;
13825
13826         if (env->prog->jit_requested &&
13827             !bpf_prog_is_dev_bound(env->prog->aux)) {
13828                 err = jit_subprogs(env);
13829                 if (err == 0)
13830                         return 0;
13831                 if (err == -EFAULT)
13832                         return err;
13833         }
13834 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13835         if (has_kfunc_call) {
13836                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13837                 return -EINVAL;
13838         }
13839         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13840                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13841                  * have to be rejected, since interpreter doesn't support them yet.
13842                  */
13843                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13844                 return -EINVAL;
13845         }
13846         for (i = 0; i < prog->len; i++, insn++) {
13847                 if (bpf_pseudo_func(insn)) {
13848                         /* When JIT fails the progs with callback calls
13849                          * have to be rejected, since interpreter doesn't support them yet.
13850                          */
13851                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
13852                         return -EINVAL;
13853                 }
13854
13855                 if (!bpf_pseudo_call(insn))
13856                         continue;
13857                 depth = get_callee_stack_depth(env, insn, i);
13858                 if (depth < 0)
13859                         return depth;
13860                 bpf_patch_call_args(insn, depth);
13861         }
13862         err = 0;
13863 #endif
13864         return err;
13865 }
13866
13867 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13868                             struct bpf_insn *insn)
13869 {
13870         const struct bpf_kfunc_desc *desc;
13871
13872         if (!insn->imm) {
13873                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13874                 return -EINVAL;
13875         }
13876
13877         /* insn->imm has the btf func_id. Replace it with
13878          * an address (relative to __bpf_base_call).
13879          */
13880         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13881         if (!desc) {
13882                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13883                         insn->imm);
13884                 return -EFAULT;
13885         }
13886
13887         insn->imm = desc->imm;
13888
13889         return 0;
13890 }
13891
13892 /* Do various post-verification rewrites in a single program pass.
13893  * These rewrites simplify JIT and interpreter implementations.
13894  */
13895 static int do_misc_fixups(struct bpf_verifier_env *env)
13896 {
13897         struct bpf_prog *prog = env->prog;
13898         enum bpf_attach_type eatype = prog->expected_attach_type;
13899         enum bpf_prog_type prog_type = resolve_prog_type(prog);
13900         struct bpf_insn *insn = prog->insnsi;
13901         const struct bpf_func_proto *fn;
13902         const int insn_cnt = prog->len;
13903         const struct bpf_map_ops *ops;
13904         struct bpf_insn_aux_data *aux;
13905         struct bpf_insn insn_buf[16];
13906         struct bpf_prog *new_prog;
13907         struct bpf_map *map_ptr;
13908         int i, ret, cnt, delta = 0;
13909
13910         for (i = 0; i < insn_cnt; i++, insn++) {
13911                 /* Make divide-by-zero exceptions impossible. */
13912                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13913                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13914                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13915                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13916                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13917                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13918                         struct bpf_insn *patchlet;
13919                         struct bpf_insn chk_and_div[] = {
13920                                 /* [R,W]x div 0 -> 0 */
13921                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13922                                              BPF_JNE | BPF_K, insn->src_reg,
13923                                              0, 2, 0),
13924                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13925                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13926                                 *insn,
13927                         };
13928                         struct bpf_insn chk_and_mod[] = {
13929                                 /* [R,W]x mod 0 -> [R,W]x */
13930                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13931                                              BPF_JEQ | BPF_K, insn->src_reg,
13932                                              0, 1 + (is64 ? 0 : 1), 0),
13933                                 *insn,
13934                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13935                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13936                         };
13937
13938                         patchlet = isdiv ? chk_and_div : chk_and_mod;
13939                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13940                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13941
13942                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13943                         if (!new_prog)
13944                                 return -ENOMEM;
13945
13946                         delta    += cnt - 1;
13947                         env->prog = prog = new_prog;
13948                         insn      = new_prog->insnsi + i + delta;
13949                         continue;
13950                 }
13951
13952                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13953                 if (BPF_CLASS(insn->code) == BPF_LD &&
13954                     (BPF_MODE(insn->code) == BPF_ABS ||
13955                      BPF_MODE(insn->code) == BPF_IND)) {
13956                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
13957                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13958                                 verbose(env, "bpf verifier is misconfigured\n");
13959                                 return -EINVAL;
13960                         }
13961
13962                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13963                         if (!new_prog)
13964                                 return -ENOMEM;
13965
13966                         delta    += cnt - 1;
13967                         env->prog = prog = new_prog;
13968                         insn      = new_prog->insnsi + i + delta;
13969                         continue;
13970                 }
13971
13972                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
13973                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13974                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13975                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13976                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13977                         struct bpf_insn *patch = &insn_buf[0];
13978                         bool issrc, isneg, isimm;
13979                         u32 off_reg;
13980
13981                         aux = &env->insn_aux_data[i + delta];
13982                         if (!aux->alu_state ||
13983                             aux->alu_state == BPF_ALU_NON_POINTER)
13984                                 continue;
13985
13986                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13987                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13988                                 BPF_ALU_SANITIZE_SRC;
13989                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
13990
13991                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
13992                         if (isimm) {
13993                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13994                         } else {
13995                                 if (isneg)
13996                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13997                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13998                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13999                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14000                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14001                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14002                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14003                         }
14004                         if (!issrc)
14005                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14006                         insn->src_reg = BPF_REG_AX;
14007                         if (isneg)
14008                                 insn->code = insn->code == code_add ?
14009                                              code_sub : code_add;
14010                         *patch++ = *insn;
14011                         if (issrc && isneg && !isimm)
14012                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14013                         cnt = patch - insn_buf;
14014
14015                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14016                         if (!new_prog)
14017                                 return -ENOMEM;
14018
14019                         delta    += cnt - 1;
14020                         env->prog = prog = new_prog;
14021                         insn      = new_prog->insnsi + i + delta;
14022                         continue;
14023                 }
14024
14025                 if (insn->code != (BPF_JMP | BPF_CALL))
14026                         continue;
14027                 if (insn->src_reg == BPF_PSEUDO_CALL)
14028                         continue;
14029                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14030                         ret = fixup_kfunc_call(env, insn);
14031                         if (ret)
14032                                 return ret;
14033                         continue;
14034                 }
14035
14036                 if (insn->imm == BPF_FUNC_get_route_realm)
14037                         prog->dst_needed = 1;
14038                 if (insn->imm == BPF_FUNC_get_prandom_u32)
14039                         bpf_user_rnd_init_once();
14040                 if (insn->imm == BPF_FUNC_override_return)
14041                         prog->kprobe_override = 1;
14042                 if (insn->imm == BPF_FUNC_tail_call) {
14043                         /* If we tail call into other programs, we
14044                          * cannot make any assumptions since they can
14045                          * be replaced dynamically during runtime in
14046                          * the program array.
14047                          */
14048                         prog->cb_access = 1;
14049                         if (!allow_tail_call_in_subprogs(env))
14050                                 prog->aux->stack_depth = MAX_BPF_STACK;
14051                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14052
14053                         /* mark bpf_tail_call as different opcode to avoid
14054                          * conditional branch in the interpreter for every normal
14055                          * call and to prevent accidental JITing by JIT compiler
14056                          * that doesn't support bpf_tail_call yet
14057                          */
14058                         insn->imm = 0;
14059                         insn->code = BPF_JMP | BPF_TAIL_CALL;
14060
14061                         aux = &env->insn_aux_data[i + delta];
14062                         if (env->bpf_capable && !prog->blinding_requested &&
14063                             prog->jit_requested &&
14064                             !bpf_map_key_poisoned(aux) &&
14065                             !bpf_map_ptr_poisoned(aux) &&
14066                             !bpf_map_ptr_unpriv(aux)) {
14067                                 struct bpf_jit_poke_descriptor desc = {
14068                                         .reason = BPF_POKE_REASON_TAIL_CALL,
14069                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14070                                         .tail_call.key = bpf_map_key_immediate(aux),
14071                                         .insn_idx = i + delta,
14072                                 };
14073
14074                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14075                                 if (ret < 0) {
14076                                         verbose(env, "adding tail call poke descriptor failed\n");
14077                                         return ret;
14078                                 }
14079
14080                                 insn->imm = ret + 1;
14081                                 continue;
14082                         }
14083
14084                         if (!bpf_map_ptr_unpriv(aux))
14085                                 continue;
14086
14087                         /* instead of changing every JIT dealing with tail_call
14088                          * emit two extra insns:
14089                          * if (index >= max_entries) goto out;
14090                          * index &= array->index_mask;
14091                          * to avoid out-of-bounds cpu speculation
14092                          */
14093                         if (bpf_map_ptr_poisoned(aux)) {
14094                                 verbose(env, "tail_call abusing map_ptr\n");
14095                                 return -EINVAL;
14096                         }
14097
14098                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14099                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14100                                                   map_ptr->max_entries, 2);
14101                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14102                                                     container_of(map_ptr,
14103                                                                  struct bpf_array,
14104                                                                  map)->index_mask);
14105                         insn_buf[2] = *insn;
14106                         cnt = 3;
14107                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14108                         if (!new_prog)
14109                                 return -ENOMEM;
14110
14111                         delta    += cnt - 1;
14112                         env->prog = prog = new_prog;
14113                         insn      = new_prog->insnsi + i + delta;
14114                         continue;
14115                 }
14116
14117                 if (insn->imm == BPF_FUNC_timer_set_callback) {
14118                         /* The verifier will process callback_fn as many times as necessary
14119                          * with different maps and the register states prepared by
14120                          * set_timer_callback_state will be accurate.
14121                          *
14122                          * The following use case is valid:
14123                          *   map1 is shared by prog1, prog2, prog3.
14124                          *   prog1 calls bpf_timer_init for some map1 elements
14125                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
14126                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
14127                          *   prog3 calls bpf_timer_start for some map1 elements.
14128                          *     Those that were not both bpf_timer_init-ed and
14129                          *     bpf_timer_set_callback-ed will return -EINVAL.
14130                          */
14131                         struct bpf_insn ld_addrs[2] = {
14132                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14133                         };
14134
14135                         insn_buf[0] = ld_addrs[0];
14136                         insn_buf[1] = ld_addrs[1];
14137                         insn_buf[2] = *insn;
14138                         cnt = 3;
14139
14140                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14141                         if (!new_prog)
14142                                 return -ENOMEM;
14143
14144                         delta    += cnt - 1;
14145                         env->prog = prog = new_prog;
14146                         insn      = new_prog->insnsi + i + delta;
14147                         goto patch_call_imm;
14148                 }
14149
14150                 if (insn->imm == BPF_FUNC_task_storage_get ||
14151                     insn->imm == BPF_FUNC_sk_storage_get ||
14152                     insn->imm == BPF_FUNC_inode_storage_get) {
14153                         if (env->prog->aux->sleepable)
14154                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14155                         else
14156                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14157                         insn_buf[1] = *insn;
14158                         cnt = 2;
14159
14160                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14161                         if (!new_prog)
14162                                 return -ENOMEM;
14163
14164                         delta += cnt - 1;
14165                         env->prog = prog = new_prog;
14166                         insn = new_prog->insnsi + i + delta;
14167                         goto patch_call_imm;
14168                 }
14169
14170                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14171                  * and other inlining handlers are currently limited to 64 bit
14172                  * only.
14173                  */
14174                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14175                     (insn->imm == BPF_FUNC_map_lookup_elem ||
14176                      insn->imm == BPF_FUNC_map_update_elem ||
14177                      insn->imm == BPF_FUNC_map_delete_elem ||
14178                      insn->imm == BPF_FUNC_map_push_elem   ||
14179                      insn->imm == BPF_FUNC_map_pop_elem    ||
14180                      insn->imm == BPF_FUNC_map_peek_elem   ||
14181                      insn->imm == BPF_FUNC_redirect_map    ||
14182                      insn->imm == BPF_FUNC_for_each_map_elem ||
14183                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14184                         aux = &env->insn_aux_data[i + delta];
14185                         if (bpf_map_ptr_poisoned(aux))
14186                                 goto patch_call_imm;
14187
14188                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14189                         ops = map_ptr->ops;
14190                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
14191                             ops->map_gen_lookup) {
14192                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14193                                 if (cnt == -EOPNOTSUPP)
14194                                         goto patch_map_ops_generic;
14195                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14196                                         verbose(env, "bpf verifier is misconfigured\n");
14197                                         return -EINVAL;
14198                                 }
14199
14200                                 new_prog = bpf_patch_insn_data(env, i + delta,
14201                                                                insn_buf, cnt);
14202                                 if (!new_prog)
14203                                         return -ENOMEM;
14204
14205                                 delta    += cnt - 1;
14206                                 env->prog = prog = new_prog;
14207                                 insn      = new_prog->insnsi + i + delta;
14208                                 continue;
14209                         }
14210
14211                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14212                                      (void *(*)(struct bpf_map *map, void *key))NULL));
14213                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14214                                      (int (*)(struct bpf_map *map, void *key))NULL));
14215                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14216                                      (int (*)(struct bpf_map *map, void *key, void *value,
14217                                               u64 flags))NULL));
14218                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14219                                      (int (*)(struct bpf_map *map, void *value,
14220                                               u64 flags))NULL));
14221                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14222                                      (int (*)(struct bpf_map *map, void *value))NULL));
14223                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14224                                      (int (*)(struct bpf_map *map, void *value))NULL));
14225                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
14226                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14227                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14228                                      (int (*)(struct bpf_map *map,
14229                                               bpf_callback_t callback_fn,
14230                                               void *callback_ctx,
14231                                               u64 flags))NULL));
14232                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14233                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14234
14235 patch_map_ops_generic:
14236                         switch (insn->imm) {
14237                         case BPF_FUNC_map_lookup_elem:
14238                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14239                                 continue;
14240                         case BPF_FUNC_map_update_elem:
14241                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14242                                 continue;
14243                         case BPF_FUNC_map_delete_elem:
14244                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14245                                 continue;
14246                         case BPF_FUNC_map_push_elem:
14247                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14248                                 continue;
14249                         case BPF_FUNC_map_pop_elem:
14250                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14251                                 continue;
14252                         case BPF_FUNC_map_peek_elem:
14253                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14254                                 continue;
14255                         case BPF_FUNC_redirect_map:
14256                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14257                                 continue;
14258                         case BPF_FUNC_for_each_map_elem:
14259                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14260                                 continue;
14261                         case BPF_FUNC_map_lookup_percpu_elem:
14262                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14263                                 continue;
14264                         }
14265
14266                         goto patch_call_imm;
14267                 }
14268
14269                 /* Implement bpf_jiffies64 inline. */
14270                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14271                     insn->imm == BPF_FUNC_jiffies64) {
14272                         struct bpf_insn ld_jiffies_addr[2] = {
14273                                 BPF_LD_IMM64(BPF_REG_0,
14274                                              (unsigned long)&jiffies),
14275                         };
14276
14277                         insn_buf[0] = ld_jiffies_addr[0];
14278                         insn_buf[1] = ld_jiffies_addr[1];
14279                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14280                                                   BPF_REG_0, 0);
14281                         cnt = 3;
14282
14283                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14284                                                        cnt);
14285                         if (!new_prog)
14286                                 return -ENOMEM;
14287
14288                         delta    += cnt - 1;
14289                         env->prog = prog = new_prog;
14290                         insn      = new_prog->insnsi + i + delta;
14291                         continue;
14292                 }
14293
14294                 /* Implement bpf_get_func_arg inline. */
14295                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14296                     insn->imm == BPF_FUNC_get_func_arg) {
14297                         /* Load nr_args from ctx - 8 */
14298                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14299                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14300                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14301                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14302                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14303                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14304                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14305                         insn_buf[7] = BPF_JMP_A(1);
14306                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14307                         cnt = 9;
14308
14309                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14310                         if (!new_prog)
14311                                 return -ENOMEM;
14312
14313                         delta    += cnt - 1;
14314                         env->prog = prog = new_prog;
14315                         insn      = new_prog->insnsi + i + delta;
14316                         continue;
14317                 }
14318
14319                 /* Implement bpf_get_func_ret inline. */
14320                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14321                     insn->imm == BPF_FUNC_get_func_ret) {
14322                         if (eatype == BPF_TRACE_FEXIT ||
14323                             eatype == BPF_MODIFY_RETURN) {
14324                                 /* Load nr_args from ctx - 8 */
14325                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14326                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14327                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14328                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14329                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14330                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14331                                 cnt = 6;
14332                         } else {
14333                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14334                                 cnt = 1;
14335                         }
14336
14337                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14338                         if (!new_prog)
14339                                 return -ENOMEM;
14340
14341                         delta    += cnt - 1;
14342                         env->prog = prog = new_prog;
14343                         insn      = new_prog->insnsi + i + delta;
14344                         continue;
14345                 }
14346
14347                 /* Implement get_func_arg_cnt inline. */
14348                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14349                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
14350                         /* Load nr_args from ctx - 8 */
14351                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14352
14353                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14354                         if (!new_prog)
14355                                 return -ENOMEM;
14356
14357                         env->prog = prog = new_prog;
14358                         insn      = new_prog->insnsi + i + delta;
14359                         continue;
14360                 }
14361
14362                 /* Implement bpf_get_func_ip inline. */
14363                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14364                     insn->imm == BPF_FUNC_get_func_ip) {
14365                         /* Load IP address from ctx - 16 */
14366                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14367
14368                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14369                         if (!new_prog)
14370                                 return -ENOMEM;
14371
14372                         env->prog = prog = new_prog;
14373                         insn      = new_prog->insnsi + i + delta;
14374                         continue;
14375                 }
14376
14377 patch_call_imm:
14378                 fn = env->ops->get_func_proto(insn->imm, env->prog);
14379                 /* all functions that have prototype and verifier allowed
14380                  * programs to call them, must be real in-kernel functions
14381                  */
14382                 if (!fn->func) {
14383                         verbose(env,
14384                                 "kernel subsystem misconfigured func %s#%d\n",
14385                                 func_id_name(insn->imm), insn->imm);
14386                         return -EFAULT;
14387                 }
14388                 insn->imm = fn->func - __bpf_call_base;
14389         }
14390
14391         /* Since poke tab is now finalized, publish aux to tracker. */
14392         for (i = 0; i < prog->aux->size_poke_tab; i++) {
14393                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14394                 if (!map_ptr->ops->map_poke_track ||
14395                     !map_ptr->ops->map_poke_untrack ||
14396                     !map_ptr->ops->map_poke_run) {
14397                         verbose(env, "bpf verifier is misconfigured\n");
14398                         return -EINVAL;
14399                 }
14400
14401                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14402                 if (ret < 0) {
14403                         verbose(env, "tracking tail call prog failed\n");
14404                         return ret;
14405                 }
14406         }
14407
14408         sort_kfunc_descs_by_imm(env->prog);
14409
14410         return 0;
14411 }
14412
14413 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14414                                         int position,
14415                                         s32 stack_base,
14416                                         u32 callback_subprogno,
14417                                         u32 *cnt)
14418 {
14419         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14420         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14421         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14422         int reg_loop_max = BPF_REG_6;
14423         int reg_loop_cnt = BPF_REG_7;
14424         int reg_loop_ctx = BPF_REG_8;
14425
14426         struct bpf_prog *new_prog;
14427         u32 callback_start;
14428         u32 call_insn_offset;
14429         s32 callback_offset;
14430
14431         /* This represents an inlined version of bpf_iter.c:bpf_loop,
14432          * be careful to modify this code in sync.
14433          */
14434         struct bpf_insn insn_buf[] = {
14435                 /* Return error and jump to the end of the patch if
14436                  * expected number of iterations is too big.
14437                  */
14438                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14439                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14440                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14441                 /* spill R6, R7, R8 to use these as loop vars */
14442                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14443                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14444                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14445                 /* initialize loop vars */
14446                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14447                 BPF_MOV32_IMM(reg_loop_cnt, 0),
14448                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14449                 /* loop header,
14450                  * if reg_loop_cnt >= reg_loop_max skip the loop body
14451                  */
14452                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14453                 /* callback call,
14454                  * correct callback offset would be set after patching
14455                  */
14456                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14457                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14458                 BPF_CALL_REL(0),
14459                 /* increment loop counter */
14460                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14461                 /* jump to loop header if callback returned 0 */
14462                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14463                 /* return value of bpf_loop,
14464                  * set R0 to the number of iterations
14465                  */
14466                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14467                 /* restore original values of R6, R7, R8 */
14468                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14469                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14470                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14471         };
14472
14473         *cnt = ARRAY_SIZE(insn_buf);
14474         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14475         if (!new_prog)
14476                 return new_prog;
14477
14478         /* callback start is known only after patching */
14479         callback_start = env->subprog_info[callback_subprogno].start;
14480         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14481         call_insn_offset = position + 12;
14482         callback_offset = callback_start - call_insn_offset - 1;
14483         new_prog->insnsi[call_insn_offset].imm = callback_offset;
14484
14485         return new_prog;
14486 }
14487
14488 static bool is_bpf_loop_call(struct bpf_insn *insn)
14489 {
14490         return insn->code == (BPF_JMP | BPF_CALL) &&
14491                 insn->src_reg == 0 &&
14492                 insn->imm == BPF_FUNC_loop;
14493 }
14494
14495 /* For all sub-programs in the program (including main) check
14496  * insn_aux_data to see if there are bpf_loop calls that require
14497  * inlining. If such calls are found the calls are replaced with a
14498  * sequence of instructions produced by `inline_bpf_loop` function and
14499  * subprog stack_depth is increased by the size of 3 registers.
14500  * This stack space is used to spill values of the R6, R7, R8.  These
14501  * registers are used to store the loop bound, counter and context
14502  * variables.
14503  */
14504 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14505 {
14506         struct bpf_subprog_info *subprogs = env->subprog_info;
14507         int i, cur_subprog = 0, cnt, delta = 0;
14508         struct bpf_insn *insn = env->prog->insnsi;
14509         int insn_cnt = env->prog->len;
14510         u16 stack_depth = subprogs[cur_subprog].stack_depth;
14511         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14512         u16 stack_depth_extra = 0;
14513
14514         for (i = 0; i < insn_cnt; i++, insn++) {
14515                 struct bpf_loop_inline_state *inline_state =
14516                         &env->insn_aux_data[i + delta].loop_inline_state;
14517
14518                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14519                         struct bpf_prog *new_prog;
14520
14521                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14522                         new_prog = inline_bpf_loop(env,
14523                                                    i + delta,
14524                                                    -(stack_depth + stack_depth_extra),
14525                                                    inline_state->callback_subprogno,
14526                                                    &cnt);
14527                         if (!new_prog)
14528                                 return -ENOMEM;
14529
14530                         delta     += cnt - 1;
14531                         env->prog  = new_prog;
14532                         insn       = new_prog->insnsi + i + delta;
14533                 }
14534
14535                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14536                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
14537                         cur_subprog++;
14538                         stack_depth = subprogs[cur_subprog].stack_depth;
14539                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14540                         stack_depth_extra = 0;
14541                 }
14542         }
14543
14544         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14545
14546         return 0;
14547 }
14548
14549 static void free_states(struct bpf_verifier_env *env)
14550 {
14551         struct bpf_verifier_state_list *sl, *sln;
14552         int i;
14553
14554         sl = env->free_list;
14555         while (sl) {
14556                 sln = sl->next;
14557                 free_verifier_state(&sl->state, false);
14558                 kfree(sl);
14559                 sl = sln;
14560         }
14561         env->free_list = NULL;
14562
14563         if (!env->explored_states)
14564                 return;
14565
14566         for (i = 0; i < state_htab_size(env); i++) {
14567                 sl = env->explored_states[i];
14568
14569                 while (sl) {
14570                         sln = sl->next;
14571                         free_verifier_state(&sl->state, false);
14572                         kfree(sl);
14573                         sl = sln;
14574                 }
14575                 env->explored_states[i] = NULL;
14576         }
14577 }
14578
14579 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14580 {
14581         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14582         struct bpf_verifier_state *state;
14583         struct bpf_reg_state *regs;
14584         int ret, i;
14585
14586         env->prev_linfo = NULL;
14587         env->pass_cnt++;
14588
14589         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14590         if (!state)
14591                 return -ENOMEM;
14592         state->curframe = 0;
14593         state->speculative = false;
14594         state->branches = 1;
14595         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14596         if (!state->frame[0]) {
14597                 kfree(state);
14598                 return -ENOMEM;
14599         }
14600         env->cur_state = state;
14601         init_func_state(env, state->frame[0],
14602                         BPF_MAIN_FUNC /* callsite */,
14603                         0 /* frameno */,
14604                         subprog);
14605
14606         regs = state->frame[state->curframe]->regs;
14607         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14608                 ret = btf_prepare_func_args(env, subprog, regs);
14609                 if (ret)
14610                         goto out;
14611                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14612                         if (regs[i].type == PTR_TO_CTX)
14613                                 mark_reg_known_zero(env, regs, i);
14614                         else if (regs[i].type == SCALAR_VALUE)
14615                                 mark_reg_unknown(env, regs, i);
14616                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
14617                                 const u32 mem_size = regs[i].mem_size;
14618
14619                                 mark_reg_known_zero(env, regs, i);
14620                                 regs[i].mem_size = mem_size;
14621                                 regs[i].id = ++env->id_gen;
14622                         }
14623                 }
14624         } else {
14625                 /* 1st arg to a function */
14626                 regs[BPF_REG_1].type = PTR_TO_CTX;
14627                 mark_reg_known_zero(env, regs, BPF_REG_1);
14628                 ret = btf_check_subprog_arg_match(env, subprog, regs);
14629                 if (ret == -EFAULT)
14630                         /* unlikely verifier bug. abort.
14631                          * ret == 0 and ret < 0 are sadly acceptable for
14632                          * main() function due to backward compatibility.
14633                          * Like socket filter program may be written as:
14634                          * int bpf_prog(struct pt_regs *ctx)
14635                          * and never dereference that ctx in the program.
14636                          * 'struct pt_regs' is a type mismatch for socket
14637                          * filter that should be using 'struct __sk_buff'.
14638                          */
14639                         goto out;
14640         }
14641
14642         ret = do_check(env);
14643 out:
14644         /* check for NULL is necessary, since cur_state can be freed inside
14645          * do_check() under memory pressure.
14646          */
14647         if (env->cur_state) {
14648                 free_verifier_state(env->cur_state, true);
14649                 env->cur_state = NULL;
14650         }
14651         while (!pop_stack(env, NULL, NULL, false));
14652         if (!ret && pop_log)
14653                 bpf_vlog_reset(&env->log, 0);
14654         free_states(env);
14655         return ret;
14656 }
14657
14658 /* Verify all global functions in a BPF program one by one based on their BTF.
14659  * All global functions must pass verification. Otherwise the whole program is rejected.
14660  * Consider:
14661  * int bar(int);
14662  * int foo(int f)
14663  * {
14664  *    return bar(f);
14665  * }
14666  * int bar(int b)
14667  * {
14668  *    ...
14669  * }
14670  * foo() will be verified first for R1=any_scalar_value. During verification it
14671  * will be assumed that bar() already verified successfully and call to bar()
14672  * from foo() will be checked for type match only. Later bar() will be verified
14673  * independently to check that it's safe for R1=any_scalar_value.
14674  */
14675 static int do_check_subprogs(struct bpf_verifier_env *env)
14676 {
14677         struct bpf_prog_aux *aux = env->prog->aux;
14678         int i, ret;
14679
14680         if (!aux->func_info)
14681                 return 0;
14682
14683         for (i = 1; i < env->subprog_cnt; i++) {
14684                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14685                         continue;
14686                 env->insn_idx = env->subprog_info[i].start;
14687                 WARN_ON_ONCE(env->insn_idx == 0);
14688                 ret = do_check_common(env, i);
14689                 if (ret) {
14690                         return ret;
14691                 } else if (env->log.level & BPF_LOG_LEVEL) {
14692                         verbose(env,
14693                                 "Func#%d is safe for any args that match its prototype\n",
14694                                 i);
14695                 }
14696         }
14697         return 0;
14698 }
14699
14700 static int do_check_main(struct bpf_verifier_env *env)
14701 {
14702         int ret;
14703
14704         env->insn_idx = 0;
14705         ret = do_check_common(env, 0);
14706         if (!ret)
14707                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14708         return ret;
14709 }
14710
14711
14712 static void print_verification_stats(struct bpf_verifier_env *env)
14713 {
14714         int i;
14715
14716         if (env->log.level & BPF_LOG_STATS) {
14717                 verbose(env, "verification time %lld usec\n",
14718                         div_u64(env->verification_time, 1000));
14719                 verbose(env, "stack depth ");
14720                 for (i = 0; i < env->subprog_cnt; i++) {
14721                         u32 depth = env->subprog_info[i].stack_depth;
14722
14723                         verbose(env, "%d", depth);
14724                         if (i + 1 < env->subprog_cnt)
14725                                 verbose(env, "+");
14726                 }
14727                 verbose(env, "\n");
14728         }
14729         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14730                 "total_states %d peak_states %d mark_read %d\n",
14731                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14732                 env->max_states_per_insn, env->total_states,
14733                 env->peak_states, env->longest_mark_read_walk);
14734 }
14735
14736 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14737 {
14738         const struct btf_type *t, *func_proto;
14739         const struct bpf_struct_ops *st_ops;
14740         const struct btf_member *member;
14741         struct bpf_prog *prog = env->prog;
14742         u32 btf_id, member_idx;
14743         const char *mname;
14744
14745         if (!prog->gpl_compatible) {
14746                 verbose(env, "struct ops programs must have a GPL compatible license\n");
14747                 return -EINVAL;
14748         }
14749
14750         btf_id = prog->aux->attach_btf_id;
14751         st_ops = bpf_struct_ops_find(btf_id);
14752         if (!st_ops) {
14753                 verbose(env, "attach_btf_id %u is not a supported struct\n",
14754                         btf_id);
14755                 return -ENOTSUPP;
14756         }
14757
14758         t = st_ops->type;
14759         member_idx = prog->expected_attach_type;
14760         if (member_idx >= btf_type_vlen(t)) {
14761                 verbose(env, "attach to invalid member idx %u of struct %s\n",
14762                         member_idx, st_ops->name);
14763                 return -EINVAL;
14764         }
14765
14766         member = &btf_type_member(t)[member_idx];
14767         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14768         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14769                                                NULL);
14770         if (!func_proto) {
14771                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14772                         mname, member_idx, st_ops->name);
14773                 return -EINVAL;
14774         }
14775
14776         if (st_ops->check_member) {
14777                 int err = st_ops->check_member(t, member);
14778
14779                 if (err) {
14780                         verbose(env, "attach to unsupported member %s of struct %s\n",
14781                                 mname, st_ops->name);
14782                         return err;
14783                 }
14784         }
14785
14786         prog->aux->attach_func_proto = func_proto;
14787         prog->aux->attach_func_name = mname;
14788         env->ops = st_ops->verifier_ops;
14789
14790         return 0;
14791 }
14792 #define SECURITY_PREFIX "security_"
14793
14794 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14795 {
14796         if (within_error_injection_list(addr) ||
14797             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14798                 return 0;
14799
14800         return -EINVAL;
14801 }
14802
14803 /* list of non-sleepable functions that are otherwise on
14804  * ALLOW_ERROR_INJECTION list
14805  */
14806 BTF_SET_START(btf_non_sleepable_error_inject)
14807 /* Three functions below can be called from sleepable and non-sleepable context.
14808  * Assume non-sleepable from bpf safety point of view.
14809  */
14810 BTF_ID(func, __filemap_add_folio)
14811 BTF_ID(func, should_fail_alloc_page)
14812 BTF_ID(func, should_failslab)
14813 BTF_SET_END(btf_non_sleepable_error_inject)
14814
14815 static int check_non_sleepable_error_inject(u32 btf_id)
14816 {
14817         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14818 }
14819
14820 int bpf_check_attach_target(struct bpf_verifier_log *log,
14821                             const struct bpf_prog *prog,
14822                             const struct bpf_prog *tgt_prog,
14823                             u32 btf_id,
14824                             struct bpf_attach_target_info *tgt_info)
14825 {
14826         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14827         const char prefix[] = "btf_trace_";
14828         int ret = 0, subprog = -1, i;
14829         const struct btf_type *t;
14830         bool conservative = true;
14831         const char *tname;
14832         struct btf *btf;
14833         long addr = 0;
14834
14835         if (!btf_id) {
14836                 bpf_log(log, "Tracing programs must provide btf_id\n");
14837                 return -EINVAL;
14838         }
14839         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14840         if (!btf) {
14841                 bpf_log(log,
14842                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14843                 return -EINVAL;
14844         }
14845         t = btf_type_by_id(btf, btf_id);
14846         if (!t) {
14847                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14848                 return -EINVAL;
14849         }
14850         tname = btf_name_by_offset(btf, t->name_off);
14851         if (!tname) {
14852                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14853                 return -EINVAL;
14854         }
14855         if (tgt_prog) {
14856                 struct bpf_prog_aux *aux = tgt_prog->aux;
14857
14858                 for (i = 0; i < aux->func_info_cnt; i++)
14859                         if (aux->func_info[i].type_id == btf_id) {
14860                                 subprog = i;
14861                                 break;
14862                         }
14863                 if (subprog == -1) {
14864                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
14865                         return -EINVAL;
14866                 }
14867                 conservative = aux->func_info_aux[subprog].unreliable;
14868                 if (prog_extension) {
14869                         if (conservative) {
14870                                 bpf_log(log,
14871                                         "Cannot replace static functions\n");
14872                                 return -EINVAL;
14873                         }
14874                         if (!prog->jit_requested) {
14875                                 bpf_log(log,
14876                                         "Extension programs should be JITed\n");
14877                                 return -EINVAL;
14878                         }
14879                 }
14880                 if (!tgt_prog->jited) {
14881                         bpf_log(log, "Can attach to only JITed progs\n");
14882                         return -EINVAL;
14883                 }
14884                 if (tgt_prog->type == prog->type) {
14885                         /* Cannot fentry/fexit another fentry/fexit program.
14886                          * Cannot attach program extension to another extension.
14887                          * It's ok to attach fentry/fexit to extension program.
14888                          */
14889                         bpf_log(log, "Cannot recursively attach\n");
14890                         return -EINVAL;
14891                 }
14892                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14893                     prog_extension &&
14894                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14895                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14896                         /* Program extensions can extend all program types
14897                          * except fentry/fexit. The reason is the following.
14898                          * The fentry/fexit programs are used for performance
14899                          * analysis, stats and can be attached to any program
14900                          * type except themselves. When extension program is
14901                          * replacing XDP function it is necessary to allow
14902                          * performance analysis of all functions. Both original
14903                          * XDP program and its program extension. Hence
14904                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14905                          * allowed. If extending of fentry/fexit was allowed it
14906                          * would be possible to create long call chain
14907                          * fentry->extension->fentry->extension beyond
14908                          * reasonable stack size. Hence extending fentry is not
14909                          * allowed.
14910                          */
14911                         bpf_log(log, "Cannot extend fentry/fexit\n");
14912                         return -EINVAL;
14913                 }
14914         } else {
14915                 if (prog_extension) {
14916                         bpf_log(log, "Cannot replace kernel functions\n");
14917                         return -EINVAL;
14918                 }
14919         }
14920
14921         switch (prog->expected_attach_type) {
14922         case BPF_TRACE_RAW_TP:
14923                 if (tgt_prog) {
14924                         bpf_log(log,
14925                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14926                         return -EINVAL;
14927                 }
14928                 if (!btf_type_is_typedef(t)) {
14929                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
14930                                 btf_id);
14931                         return -EINVAL;
14932                 }
14933                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14934                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14935                                 btf_id, tname);
14936                         return -EINVAL;
14937                 }
14938                 tname += sizeof(prefix) - 1;
14939                 t = btf_type_by_id(btf, t->type);
14940                 if (!btf_type_is_ptr(t))
14941                         /* should never happen in valid vmlinux build */
14942                         return -EINVAL;
14943                 t = btf_type_by_id(btf, t->type);
14944                 if (!btf_type_is_func_proto(t))
14945                         /* should never happen in valid vmlinux build */
14946                         return -EINVAL;
14947
14948                 break;
14949         case BPF_TRACE_ITER:
14950                 if (!btf_type_is_func(t)) {
14951                         bpf_log(log, "attach_btf_id %u is not a function\n",
14952                                 btf_id);
14953                         return -EINVAL;
14954                 }
14955                 t = btf_type_by_id(btf, t->type);
14956                 if (!btf_type_is_func_proto(t))
14957                         return -EINVAL;
14958                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14959                 if (ret)
14960                         return ret;
14961                 break;
14962         default:
14963                 if (!prog_extension)
14964                         return -EINVAL;
14965                 fallthrough;
14966         case BPF_MODIFY_RETURN:
14967         case BPF_LSM_MAC:
14968         case BPF_LSM_CGROUP:
14969         case BPF_TRACE_FENTRY:
14970         case BPF_TRACE_FEXIT:
14971                 if (!btf_type_is_func(t)) {
14972                         bpf_log(log, "attach_btf_id %u is not a function\n",
14973                                 btf_id);
14974                         return -EINVAL;
14975                 }
14976                 if (prog_extension &&
14977                     btf_check_type_match(log, prog, btf, t))
14978                         return -EINVAL;
14979                 t = btf_type_by_id(btf, t->type);
14980                 if (!btf_type_is_func_proto(t))
14981                         return -EINVAL;
14982
14983                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
14984                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
14985                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
14986                         return -EINVAL;
14987
14988                 if (tgt_prog && conservative)
14989                         t = NULL;
14990
14991                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14992                 if (ret < 0)
14993                         return ret;
14994
14995                 if (tgt_prog) {
14996                         if (subprog == 0)
14997                                 addr = (long) tgt_prog->bpf_func;
14998                         else
14999                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15000                 } else {
15001                         addr = kallsyms_lookup_name(tname);
15002                         if (!addr) {
15003                                 bpf_log(log,
15004                                         "The address of function %s cannot be found\n",
15005                                         tname);
15006                                 return -ENOENT;
15007                         }
15008                 }
15009
15010                 if (prog->aux->sleepable) {
15011                         ret = -EINVAL;
15012                         switch (prog->type) {
15013                         case BPF_PROG_TYPE_TRACING:
15014                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15015                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15016                                  */
15017                                 if (!check_non_sleepable_error_inject(btf_id) &&
15018                                     within_error_injection_list(addr))
15019                                         ret = 0;
15020                                 break;
15021                         case BPF_PROG_TYPE_LSM:
15022                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15023                                  * Only some of them are sleepable.
15024                                  */
15025                                 if (bpf_lsm_is_sleepable_hook(btf_id))
15026                                         ret = 0;
15027                                 break;
15028                         default:
15029                                 break;
15030                         }
15031                         if (ret) {
15032                                 bpf_log(log, "%s is not sleepable\n", tname);
15033                                 return ret;
15034                         }
15035                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15036                         if (tgt_prog) {
15037                                 bpf_log(log, "can't modify return codes of BPF programs\n");
15038                                 return -EINVAL;
15039                         }
15040                         ret = check_attach_modify_return(addr, tname);
15041                         if (ret) {
15042                                 bpf_log(log, "%s() is not modifiable\n", tname);
15043                                 return ret;
15044                         }
15045                 }
15046
15047                 break;
15048         }
15049         tgt_info->tgt_addr = addr;
15050         tgt_info->tgt_name = tname;
15051         tgt_info->tgt_type = t;
15052         return 0;
15053 }
15054
15055 BTF_SET_START(btf_id_deny)
15056 BTF_ID_UNUSED
15057 #ifdef CONFIG_SMP
15058 BTF_ID(func, migrate_disable)
15059 BTF_ID(func, migrate_enable)
15060 #endif
15061 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15062 BTF_ID(func, rcu_read_unlock_strict)
15063 #endif
15064 BTF_SET_END(btf_id_deny)
15065
15066 static int check_attach_btf_id(struct bpf_verifier_env *env)
15067 {
15068         struct bpf_prog *prog = env->prog;
15069         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15070         struct bpf_attach_target_info tgt_info = {};
15071         u32 btf_id = prog->aux->attach_btf_id;
15072         struct bpf_trampoline *tr;
15073         int ret;
15074         u64 key;
15075
15076         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15077                 if (prog->aux->sleepable)
15078                         /* attach_btf_id checked to be zero already */
15079                         return 0;
15080                 verbose(env, "Syscall programs can only be sleepable\n");
15081                 return -EINVAL;
15082         }
15083
15084         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15085             prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15086                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15087                 return -EINVAL;
15088         }
15089
15090         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15091                 return check_struct_ops_btf_id(env);
15092
15093         if (prog->type != BPF_PROG_TYPE_TRACING &&
15094             prog->type != BPF_PROG_TYPE_LSM &&
15095             prog->type != BPF_PROG_TYPE_EXT)
15096                 return 0;
15097
15098         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15099         if (ret)
15100                 return ret;
15101
15102         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15103                 /* to make freplace equivalent to their targets, they need to
15104                  * inherit env->ops and expected_attach_type for the rest of the
15105                  * verification
15106                  */
15107                 env->ops = bpf_verifier_ops[tgt_prog->type];
15108                 prog->expected_attach_type = tgt_prog->expected_attach_type;
15109         }
15110
15111         /* store info about the attachment target that will be used later */
15112         prog->aux->attach_func_proto = tgt_info.tgt_type;
15113         prog->aux->attach_func_name = tgt_info.tgt_name;
15114
15115         if (tgt_prog) {
15116                 prog->aux->saved_dst_prog_type = tgt_prog->type;
15117                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15118         }
15119
15120         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15121                 prog->aux->attach_btf_trace = true;
15122                 return 0;
15123         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15124                 if (!bpf_iter_prog_supported(prog))
15125                         return -EINVAL;
15126                 return 0;
15127         }
15128
15129         if (prog->type == BPF_PROG_TYPE_LSM) {
15130                 ret = bpf_lsm_verify_prog(&env->log, prog);
15131                 if (ret < 0)
15132                         return ret;
15133         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15134                    btf_id_set_contains(&btf_id_deny, btf_id)) {
15135                 return -EINVAL;
15136         }
15137
15138         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15139         tr = bpf_trampoline_get(key, &tgt_info);
15140         if (!tr)
15141                 return -ENOMEM;
15142
15143         prog->aux->dst_trampoline = tr;
15144         return 0;
15145 }
15146
15147 struct btf *bpf_get_btf_vmlinux(void)
15148 {
15149         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15150                 mutex_lock(&bpf_verifier_lock);
15151                 if (!btf_vmlinux)
15152                         btf_vmlinux = btf_parse_vmlinux();
15153                 mutex_unlock(&bpf_verifier_lock);
15154         }
15155         return btf_vmlinux;
15156 }
15157
15158 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15159 {
15160         u64 start_time = ktime_get_ns();
15161         struct bpf_verifier_env *env;
15162         struct bpf_verifier_log *log;
15163         int i, len, ret = -EINVAL;
15164         bool is_priv;
15165
15166         /* no program is valid */
15167         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15168                 return -EINVAL;
15169
15170         /* 'struct bpf_verifier_env' can be global, but since it's not small,
15171          * allocate/free it every time bpf_check() is called
15172          */
15173         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15174         if (!env)
15175                 return -ENOMEM;
15176         log = &env->log;
15177
15178         len = (*prog)->len;
15179         env->insn_aux_data =
15180                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15181         ret = -ENOMEM;
15182         if (!env->insn_aux_data)
15183                 goto err_free_env;
15184         for (i = 0; i < len; i++)
15185                 env->insn_aux_data[i].orig_idx = i;
15186         env->prog = *prog;
15187         env->ops = bpf_verifier_ops[env->prog->type];
15188         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15189         is_priv = bpf_capable();
15190
15191         bpf_get_btf_vmlinux();
15192
15193         /* grab the mutex to protect few globals used by verifier */
15194         if (!is_priv)
15195                 mutex_lock(&bpf_verifier_lock);
15196
15197         if (attr->log_level || attr->log_buf || attr->log_size) {
15198                 /* user requested verbose verifier output
15199                  * and supplied buffer to store the verification trace
15200                  */
15201                 log->level = attr->log_level;
15202                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15203                 log->len_total = attr->log_size;
15204
15205                 /* log attributes have to be sane */
15206                 if (!bpf_verifier_log_attr_valid(log)) {
15207                         ret = -EINVAL;
15208                         goto err_unlock;
15209                 }
15210         }
15211
15212         mark_verifier_state_clean(env);
15213
15214         if (IS_ERR(btf_vmlinux)) {
15215                 /* Either gcc or pahole or kernel are broken. */
15216                 verbose(env, "in-kernel BTF is malformed\n");
15217                 ret = PTR_ERR(btf_vmlinux);
15218                 goto skip_full_check;
15219         }
15220
15221         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15222         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15223                 env->strict_alignment = true;
15224         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15225                 env->strict_alignment = false;
15226
15227         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15228         env->allow_uninit_stack = bpf_allow_uninit_stack();
15229         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15230         env->bypass_spec_v1 = bpf_bypass_spec_v1();
15231         env->bypass_spec_v4 = bpf_bypass_spec_v4();
15232         env->bpf_capable = bpf_capable();
15233
15234         if (is_priv)
15235                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15236
15237         env->explored_states = kvcalloc(state_htab_size(env),
15238                                        sizeof(struct bpf_verifier_state_list *),
15239                                        GFP_USER);
15240         ret = -ENOMEM;
15241         if (!env->explored_states)
15242                 goto skip_full_check;
15243
15244         ret = add_subprog_and_kfunc(env);
15245         if (ret < 0)
15246                 goto skip_full_check;
15247
15248         ret = check_subprogs(env);
15249         if (ret < 0)
15250                 goto skip_full_check;
15251
15252         ret = check_btf_info(env, attr, uattr);
15253         if (ret < 0)
15254                 goto skip_full_check;
15255
15256         ret = check_attach_btf_id(env);
15257         if (ret)
15258                 goto skip_full_check;
15259
15260         ret = resolve_pseudo_ldimm64(env);
15261         if (ret < 0)
15262                 goto skip_full_check;
15263
15264         if (bpf_prog_is_dev_bound(env->prog->aux)) {
15265                 ret = bpf_prog_offload_verifier_prep(env->prog);
15266                 if (ret)
15267                         goto skip_full_check;
15268         }
15269
15270         ret = check_cfg(env);
15271         if (ret < 0)
15272                 goto skip_full_check;
15273
15274         ret = do_check_subprogs(env);
15275         ret = ret ?: do_check_main(env);
15276
15277         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15278                 ret = bpf_prog_offload_finalize(env);
15279
15280 skip_full_check:
15281         kvfree(env->explored_states);
15282
15283         if (ret == 0)
15284                 ret = check_max_stack_depth(env);
15285
15286         /* instruction rewrites happen after this point */
15287         if (ret == 0)
15288                 ret = optimize_bpf_loop(env);
15289
15290         if (is_priv) {
15291                 if (ret == 0)
15292                         opt_hard_wire_dead_code_branches(env);
15293                 if (ret == 0)
15294                         ret = opt_remove_dead_code(env);
15295                 if (ret == 0)
15296                         ret = opt_remove_nops(env);
15297         } else {
15298                 if (ret == 0)
15299                         sanitize_dead_code(env);
15300         }
15301
15302         if (ret == 0)
15303                 /* program is valid, convert *(u32*)(ctx + off) accesses */
15304                 ret = convert_ctx_accesses(env);
15305
15306         if (ret == 0)
15307                 ret = do_misc_fixups(env);
15308
15309         /* do 32-bit optimization after insn patching has done so those patched
15310          * insns could be handled correctly.
15311          */
15312         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15313                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15314                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15315                                                                      : false;
15316         }
15317
15318         if (ret == 0)
15319                 ret = fixup_call_args(env);
15320
15321         env->verification_time = ktime_get_ns() - start_time;
15322         print_verification_stats(env);
15323         env->prog->aux->verified_insns = env->insn_processed;
15324
15325         if (log->level && bpf_verifier_log_full(log))
15326                 ret = -ENOSPC;
15327         if (log->level && !log->ubuf) {
15328                 ret = -EFAULT;
15329                 goto err_release_maps;
15330         }
15331
15332         if (ret)
15333                 goto err_release_maps;
15334
15335         if (env->used_map_cnt) {
15336                 /* if program passed verifier, update used_maps in bpf_prog_info */
15337                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15338                                                           sizeof(env->used_maps[0]),
15339                                                           GFP_KERNEL);
15340
15341                 if (!env->prog->aux->used_maps) {
15342                         ret = -ENOMEM;
15343                         goto err_release_maps;
15344                 }
15345
15346                 memcpy(env->prog->aux->used_maps, env->used_maps,
15347                        sizeof(env->used_maps[0]) * env->used_map_cnt);
15348                 env->prog->aux->used_map_cnt = env->used_map_cnt;
15349         }
15350         if (env->used_btf_cnt) {
15351                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15352                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15353                                                           sizeof(env->used_btfs[0]),
15354                                                           GFP_KERNEL);
15355                 if (!env->prog->aux->used_btfs) {
15356                         ret = -ENOMEM;
15357                         goto err_release_maps;
15358                 }
15359
15360                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15361                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15362                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15363         }
15364         if (env->used_map_cnt || env->used_btf_cnt) {
15365                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15366                  * bpf_ld_imm64 instructions
15367                  */
15368                 convert_pseudo_ld_imm64(env);
15369         }
15370
15371         adjust_btf_func(env);
15372
15373 err_release_maps:
15374         if (!env->prog->aux->used_maps)
15375                 /* if we didn't copy map pointers into bpf_prog_info, release
15376                  * them now. Otherwise free_used_maps() will release them.
15377                  */
15378                 release_maps(env);
15379         if (!env->prog->aux->used_btfs)
15380                 release_btfs(env);
15381
15382         /* extension progs temporarily inherit the attach_type of their targets
15383            for verification purposes, so set it back to zero before returning
15384          */
15385         if (env->prog->type == BPF_PROG_TYPE_EXT)
15386                 env->prog->expected_attach_type = 0;
15387
15388         *prog = env->prog;
15389 err_unlock:
15390         if (!is_priv)
15391                 mutex_unlock(&bpf_verifier_lock);
15392         vfree(env->insn_aux_data);
15393 err_free_env:
15394         kfree(env);
15395         return ret;
15396 }