rcuscale: Move shutdown from wait_event() to wait_event_idle()
[platform/kernel/linux-starfive.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27
28 #include "disasm.h"
29
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32         [_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168         /* verifer state is 'st'
169          * before processing instruction 'insn_idx'
170          * and after processing instruction 'prev_insn_idx'
171          */
172         struct bpf_verifier_state st;
173         int insn_idx;
174         int prev_insn_idx;
175         struct bpf_verifier_stack_elem *next;
176         /* length of verifier log at the time this state was pushed on stack */
177         u32 log_pos;
178 };
179
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
181 #define BPF_COMPLEXITY_LIMIT_STATES     64
182
183 #define BPF_MAP_KEY_POISON      (1ULL << 63)
184 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
185
186 #define BPF_MAP_PTR_UNPRIV      1UL
187 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
188                                           POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193
194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 {
196         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
197 }
198
199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 {
201         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
202 }
203
204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205                               const struct bpf_map *map, bool unpriv)
206 {
207         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208         unpriv |= bpf_map_ptr_unpriv(aux);
209         aux->map_ptr_state = (unsigned long)map |
210                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211 }
212
213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 {
215         return aux->map_key_state & BPF_MAP_KEY_POISON;
216 }
217
218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 {
220         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221 }
222
223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 {
225         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226 }
227
228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 {
230         bool poisoned = bpf_map_key_poisoned(aux);
231
232         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
234 }
235
236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 {
238         return insn->code == (BPF_JMP | BPF_CALL) &&
239                insn->src_reg == BPF_PSEUDO_CALL;
240 }
241
242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 {
244         return insn->code == (BPF_JMP | BPF_CALL) &&
245                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246 }
247
248 struct bpf_call_arg_meta {
249         struct bpf_map *map_ptr;
250         bool raw_mode;
251         bool pkt_access;
252         u8 release_regno;
253         int regno;
254         int access_size;
255         int mem_size;
256         u64 msize_max_value;
257         int ref_obj_id;
258         int map_uid;
259         int func_id;
260         struct btf *btf;
261         u32 btf_id;
262         struct btf *ret_btf;
263         u32 ret_btf_id;
264         u32 subprogno;
265         struct bpf_map_value_off_desc *kptr_off_desc;
266         u8 uninit_dynptr_regno;
267 };
268
269 struct btf *btf_vmlinux;
270
271 static DEFINE_MUTEX(bpf_verifier_lock);
272
273 static const struct bpf_line_info *
274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 {
276         const struct bpf_line_info *linfo;
277         const struct bpf_prog *prog;
278         u32 i, nr_linfo;
279
280         prog = env->prog;
281         nr_linfo = prog->aux->nr_linfo;
282
283         if (!nr_linfo || insn_off >= prog->len)
284                 return NULL;
285
286         linfo = prog->aux->linfo;
287         for (i = 1; i < nr_linfo; i++)
288                 if (insn_off < linfo[i].insn_off)
289                         break;
290
291         return &linfo[i - 1];
292 }
293
294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295                        va_list args)
296 {
297         unsigned int n;
298
299         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300
301         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302                   "verifier log line truncated - local buffer too short\n");
303
304         if (log->level == BPF_LOG_KERNEL) {
305                 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306
307                 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
308                 return;
309         }
310
311         n = min(log->len_total - log->len_used - 1, n);
312         log->kbuf[n] = '\0';
313         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314                 log->len_used += n;
315         else
316                 log->ubuf = NULL;
317 }
318
319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320 {
321         char zero = 0;
322
323         if (!bpf_verifier_log_needed(log))
324                 return;
325
326         log->len_used = new_pos;
327         if (put_user(zero, log->ubuf + new_pos))
328                 log->ubuf = NULL;
329 }
330
331 /* log_level controls verbosity level of eBPF verifier.
332  * bpf_verifier_log_write() is used to dump the verification trace to the log,
333  * so the user can figure out what's wrong with the program
334  */
335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336                                            const char *fmt, ...)
337 {
338         va_list args;
339
340         if (!bpf_verifier_log_needed(&env->log))
341                 return;
342
343         va_start(args, fmt);
344         bpf_verifier_vlog(&env->log, fmt, args);
345         va_end(args);
346 }
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348
349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 {
351         struct bpf_verifier_env *env = private_data;
352         va_list args;
353
354         if (!bpf_verifier_log_needed(&env->log))
355                 return;
356
357         va_start(args, fmt);
358         bpf_verifier_vlog(&env->log, fmt, args);
359         va_end(args);
360 }
361
362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363                             const char *fmt, ...)
364 {
365         va_list args;
366
367         if (!bpf_verifier_log_needed(log))
368                 return;
369
370         va_start(args, fmt);
371         bpf_verifier_vlog(log, fmt, args);
372         va_end(args);
373 }
374 EXPORT_SYMBOL_GPL(bpf_log);
375
376 static const char *ltrim(const char *s)
377 {
378         while (isspace(*s))
379                 s++;
380
381         return s;
382 }
383
384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385                                          u32 insn_off,
386                                          const char *prefix_fmt, ...)
387 {
388         const struct bpf_line_info *linfo;
389
390         if (!bpf_verifier_log_needed(&env->log))
391                 return;
392
393         linfo = find_linfo(env, insn_off);
394         if (!linfo || linfo == env->prev_linfo)
395                 return;
396
397         if (prefix_fmt) {
398                 va_list args;
399
400                 va_start(args, prefix_fmt);
401                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
402                 va_end(args);
403         }
404
405         verbose(env, "%s\n",
406                 ltrim(btf_name_by_offset(env->prog->aux->btf,
407                                          linfo->line_off)));
408
409         env->prev_linfo = linfo;
410 }
411
412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413                                    struct bpf_reg_state *reg,
414                                    struct tnum *range, const char *ctx,
415                                    const char *reg_name)
416 {
417         char tn_buf[48];
418
419         verbose(env, "At %s the register %s ", ctx, reg_name);
420         if (!tnum_is_unknown(reg->var_off)) {
421                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422                 verbose(env, "has value %s", tn_buf);
423         } else {
424                 verbose(env, "has unknown scalar value");
425         }
426         tnum_strn(tn_buf, sizeof(tn_buf), *range);
427         verbose(env, " should have been in %s\n", tn_buf);
428 }
429
430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
431 {
432         type = base_type(type);
433         return type == PTR_TO_PACKET ||
434                type == PTR_TO_PACKET_META;
435 }
436
437 static bool type_is_sk_pointer(enum bpf_reg_type type)
438 {
439         return type == PTR_TO_SOCKET ||
440                 type == PTR_TO_SOCK_COMMON ||
441                 type == PTR_TO_TCP_SOCK ||
442                 type == PTR_TO_XDP_SOCK;
443 }
444
445 static bool reg_type_not_null(enum bpf_reg_type type)
446 {
447         return type == PTR_TO_SOCKET ||
448                 type == PTR_TO_TCP_SOCK ||
449                 type == PTR_TO_MAP_VALUE ||
450                 type == PTR_TO_MAP_KEY ||
451                 type == PTR_TO_SOCK_COMMON;
452 }
453
454 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
455 {
456         return reg->type == PTR_TO_MAP_VALUE &&
457                 map_value_has_spin_lock(reg->map_ptr);
458 }
459
460 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
461 {
462         type = base_type(type);
463         return type == PTR_TO_SOCKET || type == PTR_TO_TCP_SOCK ||
464                 type == PTR_TO_MEM || type == PTR_TO_BTF_ID;
465 }
466
467 static bool type_is_rdonly_mem(u32 type)
468 {
469         return type & MEM_RDONLY;
470 }
471
472 static bool type_may_be_null(u32 type)
473 {
474         return type & PTR_MAYBE_NULL;
475 }
476
477 static bool is_acquire_function(enum bpf_func_id func_id,
478                                 const struct bpf_map *map)
479 {
480         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
481
482         if (func_id == BPF_FUNC_sk_lookup_tcp ||
483             func_id == BPF_FUNC_sk_lookup_udp ||
484             func_id == BPF_FUNC_skc_lookup_tcp ||
485             func_id == BPF_FUNC_ringbuf_reserve ||
486             func_id == BPF_FUNC_kptr_xchg)
487                 return true;
488
489         if (func_id == BPF_FUNC_map_lookup_elem &&
490             (map_type == BPF_MAP_TYPE_SOCKMAP ||
491              map_type == BPF_MAP_TYPE_SOCKHASH))
492                 return true;
493
494         return false;
495 }
496
497 static bool is_ptr_cast_function(enum bpf_func_id func_id)
498 {
499         return func_id == BPF_FUNC_tcp_sock ||
500                 func_id == BPF_FUNC_sk_fullsock ||
501                 func_id == BPF_FUNC_skc_to_tcp_sock ||
502                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
503                 func_id == BPF_FUNC_skc_to_udp6_sock ||
504                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
505                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
506                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
507 }
508
509 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
510 {
511         return func_id == BPF_FUNC_dynptr_data;
512 }
513
514 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
515                                         const struct bpf_map *map)
516 {
517         int ref_obj_uses = 0;
518
519         if (is_ptr_cast_function(func_id))
520                 ref_obj_uses++;
521         if (is_acquire_function(func_id, map))
522                 ref_obj_uses++;
523         if (is_dynptr_ref_function(func_id))
524                 ref_obj_uses++;
525
526         return ref_obj_uses > 1;
527 }
528
529 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
530 {
531         return BPF_CLASS(insn->code) == BPF_STX &&
532                BPF_MODE(insn->code) == BPF_ATOMIC &&
533                insn->imm == BPF_CMPXCHG;
534 }
535
536 /* string representation of 'enum bpf_reg_type'
537  *
538  * Note that reg_type_str() can not appear more than once in a single verbose()
539  * statement.
540  */
541 static const char *reg_type_str(struct bpf_verifier_env *env,
542                                 enum bpf_reg_type type)
543 {
544         char postfix[16] = {0}, prefix[32] = {0};
545         static const char * const str[] = {
546                 [NOT_INIT]              = "?",
547                 [SCALAR_VALUE]          = "scalar",
548                 [PTR_TO_CTX]            = "ctx",
549                 [CONST_PTR_TO_MAP]      = "map_ptr",
550                 [PTR_TO_MAP_VALUE]      = "map_value",
551                 [PTR_TO_STACK]          = "fp",
552                 [PTR_TO_PACKET]         = "pkt",
553                 [PTR_TO_PACKET_META]    = "pkt_meta",
554                 [PTR_TO_PACKET_END]     = "pkt_end",
555                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
556                 [PTR_TO_SOCKET]         = "sock",
557                 [PTR_TO_SOCK_COMMON]    = "sock_common",
558                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
559                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
560                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
561                 [PTR_TO_BTF_ID]         = "ptr_",
562                 [PTR_TO_MEM]            = "mem",
563                 [PTR_TO_BUF]            = "buf",
564                 [PTR_TO_FUNC]           = "func",
565                 [PTR_TO_MAP_KEY]        = "map_key",
566                 [PTR_TO_DYNPTR]         = "dynptr_ptr",
567         };
568
569         if (type & PTR_MAYBE_NULL) {
570                 if (base_type(type) == PTR_TO_BTF_ID)
571                         strncpy(postfix, "or_null_", 16);
572                 else
573                         strncpy(postfix, "_or_null", 16);
574         }
575
576         if (type & MEM_RDONLY)
577                 strncpy(prefix, "rdonly_", 32);
578         if (type & MEM_ALLOC)
579                 strncpy(prefix, "alloc_", 32);
580         if (type & MEM_USER)
581                 strncpy(prefix, "user_", 32);
582         if (type & MEM_PERCPU)
583                 strncpy(prefix, "percpu_", 32);
584         if (type & PTR_UNTRUSTED)
585                 strncpy(prefix, "untrusted_", 32);
586
587         snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
588                  prefix, str[base_type(type)], postfix);
589         return env->type_str_buf;
590 }
591
592 static char slot_type_char[] = {
593         [STACK_INVALID] = '?',
594         [STACK_SPILL]   = 'r',
595         [STACK_MISC]    = 'm',
596         [STACK_ZERO]    = '0',
597         [STACK_DYNPTR]  = 'd',
598 };
599
600 static void print_liveness(struct bpf_verifier_env *env,
601                            enum bpf_reg_liveness live)
602 {
603         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
604             verbose(env, "_");
605         if (live & REG_LIVE_READ)
606                 verbose(env, "r");
607         if (live & REG_LIVE_WRITTEN)
608                 verbose(env, "w");
609         if (live & REG_LIVE_DONE)
610                 verbose(env, "D");
611 }
612
613 static int get_spi(s32 off)
614 {
615         return (-off - 1) / BPF_REG_SIZE;
616 }
617
618 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
619 {
620         int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
621
622         /* We need to check that slots between [spi - nr_slots + 1, spi] are
623          * within [0, allocated_stack).
624          *
625          * Please note that the spi grows downwards. For example, a dynptr
626          * takes the size of two stack slots; the first slot will be at
627          * spi and the second slot will be at spi - 1.
628          */
629         return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
630 }
631
632 static struct bpf_func_state *func(struct bpf_verifier_env *env,
633                                    const struct bpf_reg_state *reg)
634 {
635         struct bpf_verifier_state *cur = env->cur_state;
636
637         return cur->frame[reg->frameno];
638 }
639
640 static const char *kernel_type_name(const struct btf* btf, u32 id)
641 {
642         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
643 }
644
645 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
646 {
647         env->scratched_regs |= 1U << regno;
648 }
649
650 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
651 {
652         env->scratched_stack_slots |= 1ULL << spi;
653 }
654
655 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
656 {
657         return (env->scratched_regs >> regno) & 1;
658 }
659
660 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
661 {
662         return (env->scratched_stack_slots >> regno) & 1;
663 }
664
665 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
666 {
667         return env->scratched_regs || env->scratched_stack_slots;
668 }
669
670 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
671 {
672         env->scratched_regs = 0U;
673         env->scratched_stack_slots = 0ULL;
674 }
675
676 /* Used for printing the entire verifier state. */
677 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
678 {
679         env->scratched_regs = ~0U;
680         env->scratched_stack_slots = ~0ULL;
681 }
682
683 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
684 {
685         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
686         case DYNPTR_TYPE_LOCAL:
687                 return BPF_DYNPTR_TYPE_LOCAL;
688         case DYNPTR_TYPE_RINGBUF:
689                 return BPF_DYNPTR_TYPE_RINGBUF;
690         default:
691                 return BPF_DYNPTR_TYPE_INVALID;
692         }
693 }
694
695 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
696 {
697         return type == BPF_DYNPTR_TYPE_RINGBUF;
698 }
699
700 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
701                                    enum bpf_arg_type arg_type, int insn_idx)
702 {
703         struct bpf_func_state *state = func(env, reg);
704         enum bpf_dynptr_type type;
705         int spi, i, id;
706
707         spi = get_spi(reg->off);
708
709         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
710                 return -EINVAL;
711
712         for (i = 0; i < BPF_REG_SIZE; i++) {
713                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
714                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
715         }
716
717         type = arg_to_dynptr_type(arg_type);
718         if (type == BPF_DYNPTR_TYPE_INVALID)
719                 return -EINVAL;
720
721         state->stack[spi].spilled_ptr.dynptr.first_slot = true;
722         state->stack[spi].spilled_ptr.dynptr.type = type;
723         state->stack[spi - 1].spilled_ptr.dynptr.type = type;
724
725         if (dynptr_type_refcounted(type)) {
726                 /* The id is used to track proper releasing */
727                 id = acquire_reference_state(env, insn_idx);
728                 if (id < 0)
729                         return id;
730
731                 state->stack[spi].spilled_ptr.id = id;
732                 state->stack[spi - 1].spilled_ptr.id = id;
733         }
734
735         return 0;
736 }
737
738 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
739 {
740         struct bpf_func_state *state = func(env, reg);
741         int spi, i;
742
743         spi = get_spi(reg->off);
744
745         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
746                 return -EINVAL;
747
748         for (i = 0; i < BPF_REG_SIZE; i++) {
749                 state->stack[spi].slot_type[i] = STACK_INVALID;
750                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
751         }
752
753         /* Invalidate any slices associated with this dynptr */
754         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
755                 release_reference(env, state->stack[spi].spilled_ptr.id);
756                 state->stack[spi].spilled_ptr.id = 0;
757                 state->stack[spi - 1].spilled_ptr.id = 0;
758         }
759
760         state->stack[spi].spilled_ptr.dynptr.first_slot = false;
761         state->stack[spi].spilled_ptr.dynptr.type = 0;
762         state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
763
764         return 0;
765 }
766
767 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
768 {
769         struct bpf_func_state *state = func(env, reg);
770         int spi = get_spi(reg->off);
771         int i;
772
773         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
774                 return true;
775
776         for (i = 0; i < BPF_REG_SIZE; i++) {
777                 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
778                     state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
779                         return false;
780         }
781
782         return true;
783 }
784
785 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
786                               struct bpf_reg_state *reg)
787 {
788         struct bpf_func_state *state = func(env, reg);
789         int spi = get_spi(reg->off);
790         int i;
791
792         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
793             !state->stack[spi].spilled_ptr.dynptr.first_slot)
794                 return false;
795
796         for (i = 0; i < BPF_REG_SIZE; i++) {
797                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
798                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
799                         return false;
800         }
801
802         return true;
803 }
804
805 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
806                              struct bpf_reg_state *reg,
807                              enum bpf_arg_type arg_type)
808 {
809         struct bpf_func_state *state = func(env, reg);
810         enum bpf_dynptr_type dynptr_type;
811         int spi = get_spi(reg->off);
812
813         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
814         if (arg_type == ARG_PTR_TO_DYNPTR)
815                 return true;
816
817         dynptr_type = arg_to_dynptr_type(arg_type);
818
819         return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
820 }
821
822 /* The reg state of a pointer or a bounded scalar was saved when
823  * it was spilled to the stack.
824  */
825 static bool is_spilled_reg(const struct bpf_stack_state *stack)
826 {
827         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
828 }
829
830 static void scrub_spilled_slot(u8 *stype)
831 {
832         if (*stype != STACK_INVALID)
833                 *stype = STACK_MISC;
834 }
835
836 static void print_verifier_state(struct bpf_verifier_env *env,
837                                  const struct bpf_func_state *state,
838                                  bool print_all)
839 {
840         const struct bpf_reg_state *reg;
841         enum bpf_reg_type t;
842         int i;
843
844         if (state->frameno)
845                 verbose(env, " frame%d:", state->frameno);
846         for (i = 0; i < MAX_BPF_REG; i++) {
847                 reg = &state->regs[i];
848                 t = reg->type;
849                 if (t == NOT_INIT)
850                         continue;
851                 if (!print_all && !reg_scratched(env, i))
852                         continue;
853                 verbose(env, " R%d", i);
854                 print_liveness(env, reg->live);
855                 verbose(env, "=");
856                 if (t == SCALAR_VALUE && reg->precise)
857                         verbose(env, "P");
858                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
859                     tnum_is_const(reg->var_off)) {
860                         /* reg->off should be 0 for SCALAR_VALUE */
861                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
862                         verbose(env, "%lld", reg->var_off.value + reg->off);
863                 } else {
864                         const char *sep = "";
865
866                         verbose(env, "%s", reg_type_str(env, t));
867                         if (base_type(t) == PTR_TO_BTF_ID)
868                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
869                         verbose(env, "(");
870 /*
871  * _a stands for append, was shortened to avoid multiline statements below.
872  * This macro is used to output a comma separated list of attributes.
873  */
874 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
875
876                         if (reg->id)
877                                 verbose_a("id=%d", reg->id);
878                         if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
879                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
880                         if (t != SCALAR_VALUE)
881                                 verbose_a("off=%d", reg->off);
882                         if (type_is_pkt_pointer(t))
883                                 verbose_a("r=%d", reg->range);
884                         else if (base_type(t) == CONST_PTR_TO_MAP ||
885                                  base_type(t) == PTR_TO_MAP_KEY ||
886                                  base_type(t) == PTR_TO_MAP_VALUE)
887                                 verbose_a("ks=%d,vs=%d",
888                                           reg->map_ptr->key_size,
889                                           reg->map_ptr->value_size);
890                         if (tnum_is_const(reg->var_off)) {
891                                 /* Typically an immediate SCALAR_VALUE, but
892                                  * could be a pointer whose offset is too big
893                                  * for reg->off
894                                  */
895                                 verbose_a("imm=%llx", reg->var_off.value);
896                         } else {
897                                 if (reg->smin_value != reg->umin_value &&
898                                     reg->smin_value != S64_MIN)
899                                         verbose_a("smin=%lld", (long long)reg->smin_value);
900                                 if (reg->smax_value != reg->umax_value &&
901                                     reg->smax_value != S64_MAX)
902                                         verbose_a("smax=%lld", (long long)reg->smax_value);
903                                 if (reg->umin_value != 0)
904                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
905                                 if (reg->umax_value != U64_MAX)
906                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
907                                 if (!tnum_is_unknown(reg->var_off)) {
908                                         char tn_buf[48];
909
910                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
911                                         verbose_a("var_off=%s", tn_buf);
912                                 }
913                                 if (reg->s32_min_value != reg->smin_value &&
914                                     reg->s32_min_value != S32_MIN)
915                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
916                                 if (reg->s32_max_value != reg->smax_value &&
917                                     reg->s32_max_value != S32_MAX)
918                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
919                                 if (reg->u32_min_value != reg->umin_value &&
920                                     reg->u32_min_value != U32_MIN)
921                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
922                                 if (reg->u32_max_value != reg->umax_value &&
923                                     reg->u32_max_value != U32_MAX)
924                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
925                         }
926 #undef verbose_a
927
928                         verbose(env, ")");
929                 }
930         }
931         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
932                 char types_buf[BPF_REG_SIZE + 1];
933                 bool valid = false;
934                 int j;
935
936                 for (j = 0; j < BPF_REG_SIZE; j++) {
937                         if (state->stack[i].slot_type[j] != STACK_INVALID)
938                                 valid = true;
939                         types_buf[j] = slot_type_char[
940                                         state->stack[i].slot_type[j]];
941                 }
942                 types_buf[BPF_REG_SIZE] = 0;
943                 if (!valid)
944                         continue;
945                 if (!print_all && !stack_slot_scratched(env, i))
946                         continue;
947                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
948                 print_liveness(env, state->stack[i].spilled_ptr.live);
949                 if (is_spilled_reg(&state->stack[i])) {
950                         reg = &state->stack[i].spilled_ptr;
951                         t = reg->type;
952                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
953                         if (t == SCALAR_VALUE && reg->precise)
954                                 verbose(env, "P");
955                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
956                                 verbose(env, "%lld", reg->var_off.value + reg->off);
957                 } else {
958                         verbose(env, "=%s", types_buf);
959                 }
960         }
961         if (state->acquired_refs && state->refs[0].id) {
962                 verbose(env, " refs=%d", state->refs[0].id);
963                 for (i = 1; i < state->acquired_refs; i++)
964                         if (state->refs[i].id)
965                                 verbose(env, ",%d", state->refs[i].id);
966         }
967         if (state->in_callback_fn)
968                 verbose(env, " cb");
969         if (state->in_async_callback_fn)
970                 verbose(env, " async_cb");
971         verbose(env, "\n");
972         mark_verifier_state_clean(env);
973 }
974
975 static inline u32 vlog_alignment(u32 pos)
976 {
977         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
978                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
979 }
980
981 static void print_insn_state(struct bpf_verifier_env *env,
982                              const struct bpf_func_state *state)
983 {
984         if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
985                 /* remove new line character */
986                 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
987                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
988         } else {
989                 verbose(env, "%d:", env->insn_idx);
990         }
991         print_verifier_state(env, state, false);
992 }
993
994 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
995  * small to hold src. This is different from krealloc since we don't want to preserve
996  * the contents of dst.
997  *
998  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
999  * not be allocated.
1000  */
1001 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1002 {
1003         size_t alloc_bytes;
1004         void *orig = dst;
1005         size_t bytes;
1006
1007         if (ZERO_OR_NULL_PTR(src))
1008                 goto out;
1009
1010         if (unlikely(check_mul_overflow(n, size, &bytes)))
1011                 return NULL;
1012
1013         alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1014         dst = krealloc(orig, alloc_bytes, flags);
1015         if (!dst) {
1016                 kfree(orig);
1017                 return NULL;
1018         }
1019
1020         memcpy(dst, src, bytes);
1021 out:
1022         return dst ? dst : ZERO_SIZE_PTR;
1023 }
1024
1025 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1026  * small to hold new_n items. new items are zeroed out if the array grows.
1027  *
1028  * Contrary to krealloc_array, does not free arr if new_n is zero.
1029  */
1030 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1031 {
1032         size_t alloc_size;
1033         void *new_arr;
1034
1035         if (!new_n || old_n == new_n)
1036                 goto out;
1037
1038         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1039         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1040         if (!new_arr) {
1041                 kfree(arr);
1042                 return NULL;
1043         }
1044         arr = new_arr;
1045
1046         if (new_n > old_n)
1047                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1048
1049 out:
1050         return arr ? arr : ZERO_SIZE_PTR;
1051 }
1052
1053 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1054 {
1055         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1056                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1057         if (!dst->refs)
1058                 return -ENOMEM;
1059
1060         dst->acquired_refs = src->acquired_refs;
1061         return 0;
1062 }
1063
1064 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1065 {
1066         size_t n = src->allocated_stack / BPF_REG_SIZE;
1067
1068         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1069                                 GFP_KERNEL);
1070         if (!dst->stack)
1071                 return -ENOMEM;
1072
1073         dst->allocated_stack = src->allocated_stack;
1074         return 0;
1075 }
1076
1077 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1078 {
1079         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1080                                     sizeof(struct bpf_reference_state));
1081         if (!state->refs)
1082                 return -ENOMEM;
1083
1084         state->acquired_refs = n;
1085         return 0;
1086 }
1087
1088 static int grow_stack_state(struct bpf_func_state *state, int size)
1089 {
1090         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1091
1092         if (old_n >= n)
1093                 return 0;
1094
1095         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1096         if (!state->stack)
1097                 return -ENOMEM;
1098
1099         state->allocated_stack = size;
1100         return 0;
1101 }
1102
1103 /* Acquire a pointer id from the env and update the state->refs to include
1104  * this new pointer reference.
1105  * On success, returns a valid pointer id to associate with the register
1106  * On failure, returns a negative errno.
1107  */
1108 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1109 {
1110         struct bpf_func_state *state = cur_func(env);
1111         int new_ofs = state->acquired_refs;
1112         int id, err;
1113
1114         err = resize_reference_state(state, state->acquired_refs + 1);
1115         if (err)
1116                 return err;
1117         id = ++env->id_gen;
1118         state->refs[new_ofs].id = id;
1119         state->refs[new_ofs].insn_idx = insn_idx;
1120         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1121
1122         return id;
1123 }
1124
1125 /* release function corresponding to acquire_reference_state(). Idempotent. */
1126 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1127 {
1128         int i, last_idx;
1129
1130         last_idx = state->acquired_refs - 1;
1131         for (i = 0; i < state->acquired_refs; i++) {
1132                 if (state->refs[i].id == ptr_id) {
1133                         /* Cannot release caller references in callbacks */
1134                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1135                                 return -EINVAL;
1136                         if (last_idx && i != last_idx)
1137                                 memcpy(&state->refs[i], &state->refs[last_idx],
1138                                        sizeof(*state->refs));
1139                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1140                         state->acquired_refs--;
1141                         return 0;
1142                 }
1143         }
1144         return -EINVAL;
1145 }
1146
1147 static void free_func_state(struct bpf_func_state *state)
1148 {
1149         if (!state)
1150                 return;
1151         kfree(state->refs);
1152         kfree(state->stack);
1153         kfree(state);
1154 }
1155
1156 static void clear_jmp_history(struct bpf_verifier_state *state)
1157 {
1158         kfree(state->jmp_history);
1159         state->jmp_history = NULL;
1160         state->jmp_history_cnt = 0;
1161 }
1162
1163 static void free_verifier_state(struct bpf_verifier_state *state,
1164                                 bool free_self)
1165 {
1166         int i;
1167
1168         for (i = 0; i <= state->curframe; i++) {
1169                 free_func_state(state->frame[i]);
1170                 state->frame[i] = NULL;
1171         }
1172         clear_jmp_history(state);
1173         if (free_self)
1174                 kfree(state);
1175 }
1176
1177 /* copy verifier state from src to dst growing dst stack space
1178  * when necessary to accommodate larger src stack
1179  */
1180 static int copy_func_state(struct bpf_func_state *dst,
1181                            const struct bpf_func_state *src)
1182 {
1183         int err;
1184
1185         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1186         err = copy_reference_state(dst, src);
1187         if (err)
1188                 return err;
1189         return copy_stack_state(dst, src);
1190 }
1191
1192 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1193                                const struct bpf_verifier_state *src)
1194 {
1195         struct bpf_func_state *dst;
1196         int i, err;
1197
1198         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1199                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1200                                             GFP_USER);
1201         if (!dst_state->jmp_history)
1202                 return -ENOMEM;
1203         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1204
1205         /* if dst has more stack frames then src frame, free them */
1206         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1207                 free_func_state(dst_state->frame[i]);
1208                 dst_state->frame[i] = NULL;
1209         }
1210         dst_state->speculative = src->speculative;
1211         dst_state->curframe = src->curframe;
1212         dst_state->active_spin_lock = src->active_spin_lock;
1213         dst_state->branches = src->branches;
1214         dst_state->parent = src->parent;
1215         dst_state->first_insn_idx = src->first_insn_idx;
1216         dst_state->last_insn_idx = src->last_insn_idx;
1217         for (i = 0; i <= src->curframe; i++) {
1218                 dst = dst_state->frame[i];
1219                 if (!dst) {
1220                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1221                         if (!dst)
1222                                 return -ENOMEM;
1223                         dst_state->frame[i] = dst;
1224                 }
1225                 err = copy_func_state(dst, src->frame[i]);
1226                 if (err)
1227                         return err;
1228         }
1229         return 0;
1230 }
1231
1232 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1233 {
1234         while (st) {
1235                 u32 br = --st->branches;
1236
1237                 /* WARN_ON(br > 1) technically makes sense here,
1238                  * but see comment in push_stack(), hence:
1239                  */
1240                 WARN_ONCE((int)br < 0,
1241                           "BUG update_branch_counts:branches_to_explore=%d\n",
1242                           br);
1243                 if (br)
1244                         break;
1245                 st = st->parent;
1246         }
1247 }
1248
1249 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1250                      int *insn_idx, bool pop_log)
1251 {
1252         struct bpf_verifier_state *cur = env->cur_state;
1253         struct bpf_verifier_stack_elem *elem, *head = env->head;
1254         int err;
1255
1256         if (env->head == NULL)
1257                 return -ENOENT;
1258
1259         if (cur) {
1260                 err = copy_verifier_state(cur, &head->st);
1261                 if (err)
1262                         return err;
1263         }
1264         if (pop_log)
1265                 bpf_vlog_reset(&env->log, head->log_pos);
1266         if (insn_idx)
1267                 *insn_idx = head->insn_idx;
1268         if (prev_insn_idx)
1269                 *prev_insn_idx = head->prev_insn_idx;
1270         elem = head->next;
1271         free_verifier_state(&head->st, false);
1272         kfree(head);
1273         env->head = elem;
1274         env->stack_size--;
1275         return 0;
1276 }
1277
1278 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1279                                              int insn_idx, int prev_insn_idx,
1280                                              bool speculative)
1281 {
1282         struct bpf_verifier_state *cur = env->cur_state;
1283         struct bpf_verifier_stack_elem *elem;
1284         int err;
1285
1286         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1287         if (!elem)
1288                 goto err;
1289
1290         elem->insn_idx = insn_idx;
1291         elem->prev_insn_idx = prev_insn_idx;
1292         elem->next = env->head;
1293         elem->log_pos = env->log.len_used;
1294         env->head = elem;
1295         env->stack_size++;
1296         err = copy_verifier_state(&elem->st, cur);
1297         if (err)
1298                 goto err;
1299         elem->st.speculative |= speculative;
1300         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1301                 verbose(env, "The sequence of %d jumps is too complex.\n",
1302                         env->stack_size);
1303                 goto err;
1304         }
1305         if (elem->st.parent) {
1306                 ++elem->st.parent->branches;
1307                 /* WARN_ON(branches > 2) technically makes sense here,
1308                  * but
1309                  * 1. speculative states will bump 'branches' for non-branch
1310                  * instructions
1311                  * 2. is_state_visited() heuristics may decide not to create
1312                  * a new state for a sequence of branches and all such current
1313                  * and cloned states will be pointing to a single parent state
1314                  * which might have large 'branches' count.
1315                  */
1316         }
1317         return &elem->st;
1318 err:
1319         free_verifier_state(env->cur_state, true);
1320         env->cur_state = NULL;
1321         /* pop all elements and return */
1322         while (!pop_stack(env, NULL, NULL, false));
1323         return NULL;
1324 }
1325
1326 #define CALLER_SAVED_REGS 6
1327 static const int caller_saved[CALLER_SAVED_REGS] = {
1328         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1329 };
1330
1331 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1332                                 struct bpf_reg_state *reg);
1333
1334 /* This helper doesn't clear reg->id */
1335 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1336 {
1337         reg->var_off = tnum_const(imm);
1338         reg->smin_value = (s64)imm;
1339         reg->smax_value = (s64)imm;
1340         reg->umin_value = imm;
1341         reg->umax_value = imm;
1342
1343         reg->s32_min_value = (s32)imm;
1344         reg->s32_max_value = (s32)imm;
1345         reg->u32_min_value = (u32)imm;
1346         reg->u32_max_value = (u32)imm;
1347 }
1348
1349 /* Mark the unknown part of a register (variable offset or scalar value) as
1350  * known to have the value @imm.
1351  */
1352 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1353 {
1354         /* Clear id, off, and union(map_ptr, range) */
1355         memset(((u8 *)reg) + sizeof(reg->type), 0,
1356                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1357         ___mark_reg_known(reg, imm);
1358 }
1359
1360 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1361 {
1362         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1363         reg->s32_min_value = (s32)imm;
1364         reg->s32_max_value = (s32)imm;
1365         reg->u32_min_value = (u32)imm;
1366         reg->u32_max_value = (u32)imm;
1367 }
1368
1369 /* Mark the 'variable offset' part of a register as zero.  This should be
1370  * used only on registers holding a pointer type.
1371  */
1372 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1373 {
1374         __mark_reg_known(reg, 0);
1375 }
1376
1377 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1378 {
1379         __mark_reg_known(reg, 0);
1380         reg->type = SCALAR_VALUE;
1381 }
1382
1383 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1384                                 struct bpf_reg_state *regs, u32 regno)
1385 {
1386         if (WARN_ON(regno >= MAX_BPF_REG)) {
1387                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1388                 /* Something bad happened, let's kill all regs */
1389                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1390                         __mark_reg_not_init(env, regs + regno);
1391                 return;
1392         }
1393         __mark_reg_known_zero(regs + regno);
1394 }
1395
1396 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1397 {
1398         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1399                 const struct bpf_map *map = reg->map_ptr;
1400
1401                 if (map->inner_map_meta) {
1402                         reg->type = CONST_PTR_TO_MAP;
1403                         reg->map_ptr = map->inner_map_meta;
1404                         /* transfer reg's id which is unique for every map_lookup_elem
1405                          * as UID of the inner map.
1406                          */
1407                         if (map_value_has_timer(map->inner_map_meta))
1408                                 reg->map_uid = reg->id;
1409                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1410                         reg->type = PTR_TO_XDP_SOCK;
1411                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1412                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1413                         reg->type = PTR_TO_SOCKET;
1414                 } else {
1415                         reg->type = PTR_TO_MAP_VALUE;
1416                 }
1417                 return;
1418         }
1419
1420         reg->type &= ~PTR_MAYBE_NULL;
1421 }
1422
1423 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1424 {
1425         return type_is_pkt_pointer(reg->type);
1426 }
1427
1428 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1429 {
1430         return reg_is_pkt_pointer(reg) ||
1431                reg->type == PTR_TO_PACKET_END;
1432 }
1433
1434 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1435 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1436                                     enum bpf_reg_type which)
1437 {
1438         /* The register can already have a range from prior markings.
1439          * This is fine as long as it hasn't been advanced from its
1440          * origin.
1441          */
1442         return reg->type == which &&
1443                reg->id == 0 &&
1444                reg->off == 0 &&
1445                tnum_equals_const(reg->var_off, 0);
1446 }
1447
1448 /* Reset the min/max bounds of a register */
1449 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1450 {
1451         reg->smin_value = S64_MIN;
1452         reg->smax_value = S64_MAX;
1453         reg->umin_value = 0;
1454         reg->umax_value = U64_MAX;
1455
1456         reg->s32_min_value = S32_MIN;
1457         reg->s32_max_value = S32_MAX;
1458         reg->u32_min_value = 0;
1459         reg->u32_max_value = U32_MAX;
1460 }
1461
1462 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1463 {
1464         reg->smin_value = S64_MIN;
1465         reg->smax_value = S64_MAX;
1466         reg->umin_value = 0;
1467         reg->umax_value = U64_MAX;
1468 }
1469
1470 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1471 {
1472         reg->s32_min_value = S32_MIN;
1473         reg->s32_max_value = S32_MAX;
1474         reg->u32_min_value = 0;
1475         reg->u32_max_value = U32_MAX;
1476 }
1477
1478 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1479 {
1480         struct tnum var32_off = tnum_subreg(reg->var_off);
1481
1482         /* min signed is max(sign bit) | min(other bits) */
1483         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1484                         var32_off.value | (var32_off.mask & S32_MIN));
1485         /* max signed is min(sign bit) | max(other bits) */
1486         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1487                         var32_off.value | (var32_off.mask & S32_MAX));
1488         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1489         reg->u32_max_value = min(reg->u32_max_value,
1490                                  (u32)(var32_off.value | var32_off.mask));
1491 }
1492
1493 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1494 {
1495         /* min signed is max(sign bit) | min(other bits) */
1496         reg->smin_value = max_t(s64, reg->smin_value,
1497                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1498         /* max signed is min(sign bit) | max(other bits) */
1499         reg->smax_value = min_t(s64, reg->smax_value,
1500                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1501         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1502         reg->umax_value = min(reg->umax_value,
1503                               reg->var_off.value | reg->var_off.mask);
1504 }
1505
1506 static void __update_reg_bounds(struct bpf_reg_state *reg)
1507 {
1508         __update_reg32_bounds(reg);
1509         __update_reg64_bounds(reg);
1510 }
1511
1512 /* Uses signed min/max values to inform unsigned, and vice-versa */
1513 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1514 {
1515         /* Learn sign from signed bounds.
1516          * If we cannot cross the sign boundary, then signed and unsigned bounds
1517          * are the same, so combine.  This works even in the negative case, e.g.
1518          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1519          */
1520         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1521                 reg->s32_min_value = reg->u32_min_value =
1522                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1523                 reg->s32_max_value = reg->u32_max_value =
1524                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1525                 return;
1526         }
1527         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1528          * boundary, so we must be careful.
1529          */
1530         if ((s32)reg->u32_max_value >= 0) {
1531                 /* Positive.  We can't learn anything from the smin, but smax
1532                  * is positive, hence safe.
1533                  */
1534                 reg->s32_min_value = reg->u32_min_value;
1535                 reg->s32_max_value = reg->u32_max_value =
1536                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1537         } else if ((s32)reg->u32_min_value < 0) {
1538                 /* Negative.  We can't learn anything from the smax, but smin
1539                  * is negative, hence safe.
1540                  */
1541                 reg->s32_min_value = reg->u32_min_value =
1542                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1543                 reg->s32_max_value = reg->u32_max_value;
1544         }
1545 }
1546
1547 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1548 {
1549         /* Learn sign from signed bounds.
1550          * If we cannot cross the sign boundary, then signed and unsigned bounds
1551          * are the same, so combine.  This works even in the negative case, e.g.
1552          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1553          */
1554         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1555                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1556                                                           reg->umin_value);
1557                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1558                                                           reg->umax_value);
1559                 return;
1560         }
1561         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1562          * boundary, so we must be careful.
1563          */
1564         if ((s64)reg->umax_value >= 0) {
1565                 /* Positive.  We can't learn anything from the smin, but smax
1566                  * is positive, hence safe.
1567                  */
1568                 reg->smin_value = reg->umin_value;
1569                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1570                                                           reg->umax_value);
1571         } else if ((s64)reg->umin_value < 0) {
1572                 /* Negative.  We can't learn anything from the smax, but smin
1573                  * is negative, hence safe.
1574                  */
1575                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1576                                                           reg->umin_value);
1577                 reg->smax_value = reg->umax_value;
1578         }
1579 }
1580
1581 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1582 {
1583         __reg32_deduce_bounds(reg);
1584         __reg64_deduce_bounds(reg);
1585 }
1586
1587 /* Attempts to improve var_off based on unsigned min/max information */
1588 static void __reg_bound_offset(struct bpf_reg_state *reg)
1589 {
1590         struct tnum var64_off = tnum_intersect(reg->var_off,
1591                                                tnum_range(reg->umin_value,
1592                                                           reg->umax_value));
1593         struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
1594                                                tnum_range(reg->u32_min_value,
1595                                                           reg->u32_max_value));
1596
1597         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1598 }
1599
1600 static void reg_bounds_sync(struct bpf_reg_state *reg)
1601 {
1602         /* We might have learned new bounds from the var_off. */
1603         __update_reg_bounds(reg);
1604         /* We might have learned something about the sign bit. */
1605         __reg_deduce_bounds(reg);
1606         /* We might have learned some bits from the bounds. */
1607         __reg_bound_offset(reg);
1608         /* Intersecting with the old var_off might have improved our bounds
1609          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1610          * then new var_off is (0; 0x7f...fc) which improves our umax.
1611          */
1612         __update_reg_bounds(reg);
1613 }
1614
1615 static bool __reg32_bound_s64(s32 a)
1616 {
1617         return a >= 0 && a <= S32_MAX;
1618 }
1619
1620 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1621 {
1622         reg->umin_value = reg->u32_min_value;
1623         reg->umax_value = reg->u32_max_value;
1624
1625         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1626          * be positive otherwise set to worse case bounds and refine later
1627          * from tnum.
1628          */
1629         if (__reg32_bound_s64(reg->s32_min_value) &&
1630             __reg32_bound_s64(reg->s32_max_value)) {
1631                 reg->smin_value = reg->s32_min_value;
1632                 reg->smax_value = reg->s32_max_value;
1633         } else {
1634                 reg->smin_value = 0;
1635                 reg->smax_value = U32_MAX;
1636         }
1637 }
1638
1639 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1640 {
1641         /* special case when 64-bit register has upper 32-bit register
1642          * zeroed. Typically happens after zext or <<32, >>32 sequence
1643          * allowing us to use 32-bit bounds directly,
1644          */
1645         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1646                 __reg_assign_32_into_64(reg);
1647         } else {
1648                 /* Otherwise the best we can do is push lower 32bit known and
1649                  * unknown bits into register (var_off set from jmp logic)
1650                  * then learn as much as possible from the 64-bit tnum
1651                  * known and unknown bits. The previous smin/smax bounds are
1652                  * invalid here because of jmp32 compare so mark them unknown
1653                  * so they do not impact tnum bounds calculation.
1654                  */
1655                 __mark_reg64_unbounded(reg);
1656         }
1657         reg_bounds_sync(reg);
1658 }
1659
1660 static bool __reg64_bound_s32(s64 a)
1661 {
1662         return a >= S32_MIN && a <= S32_MAX;
1663 }
1664
1665 static bool __reg64_bound_u32(u64 a)
1666 {
1667         return a >= U32_MIN && a <= U32_MAX;
1668 }
1669
1670 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1671 {
1672         __mark_reg32_unbounded(reg);
1673         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1674                 reg->s32_min_value = (s32)reg->smin_value;
1675                 reg->s32_max_value = (s32)reg->smax_value;
1676         }
1677         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1678                 reg->u32_min_value = (u32)reg->umin_value;
1679                 reg->u32_max_value = (u32)reg->umax_value;
1680         }
1681         reg_bounds_sync(reg);
1682 }
1683
1684 /* Mark a register as having a completely unknown (scalar) value. */
1685 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1686                                struct bpf_reg_state *reg)
1687 {
1688         /*
1689          * Clear type, id, off, and union(map_ptr, range) and
1690          * padding between 'type' and union
1691          */
1692         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1693         reg->type = SCALAR_VALUE;
1694         reg->var_off = tnum_unknown;
1695         reg->frameno = 0;
1696         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1697         __mark_reg_unbounded(reg);
1698 }
1699
1700 static void mark_reg_unknown(struct bpf_verifier_env *env,
1701                              struct bpf_reg_state *regs, u32 regno)
1702 {
1703         if (WARN_ON(regno >= MAX_BPF_REG)) {
1704                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1705                 /* Something bad happened, let's kill all regs except FP */
1706                 for (regno = 0; regno < BPF_REG_FP; regno++)
1707                         __mark_reg_not_init(env, regs + regno);
1708                 return;
1709         }
1710         __mark_reg_unknown(env, regs + regno);
1711 }
1712
1713 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1714                                 struct bpf_reg_state *reg)
1715 {
1716         __mark_reg_unknown(env, reg);
1717         reg->type = NOT_INIT;
1718 }
1719
1720 static void mark_reg_not_init(struct bpf_verifier_env *env,
1721                               struct bpf_reg_state *regs, u32 regno)
1722 {
1723         if (WARN_ON(regno >= MAX_BPF_REG)) {
1724                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1725                 /* Something bad happened, let's kill all regs except FP */
1726                 for (regno = 0; regno < BPF_REG_FP; regno++)
1727                         __mark_reg_not_init(env, regs + regno);
1728                 return;
1729         }
1730         __mark_reg_not_init(env, regs + regno);
1731 }
1732
1733 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1734                             struct bpf_reg_state *regs, u32 regno,
1735                             enum bpf_reg_type reg_type,
1736                             struct btf *btf, u32 btf_id,
1737                             enum bpf_type_flag flag)
1738 {
1739         if (reg_type == SCALAR_VALUE) {
1740                 mark_reg_unknown(env, regs, regno);
1741                 return;
1742         }
1743         mark_reg_known_zero(env, regs, regno);
1744         regs[regno].type = PTR_TO_BTF_ID | flag;
1745         regs[regno].btf = btf;
1746         regs[regno].btf_id = btf_id;
1747 }
1748
1749 #define DEF_NOT_SUBREG  (0)
1750 static void init_reg_state(struct bpf_verifier_env *env,
1751                            struct bpf_func_state *state)
1752 {
1753         struct bpf_reg_state *regs = state->regs;
1754         int i;
1755
1756         for (i = 0; i < MAX_BPF_REG; i++) {
1757                 mark_reg_not_init(env, regs, i);
1758                 regs[i].live = REG_LIVE_NONE;
1759                 regs[i].parent = NULL;
1760                 regs[i].subreg_def = DEF_NOT_SUBREG;
1761         }
1762
1763         /* frame pointer */
1764         regs[BPF_REG_FP].type = PTR_TO_STACK;
1765         mark_reg_known_zero(env, regs, BPF_REG_FP);
1766         regs[BPF_REG_FP].frameno = state->frameno;
1767 }
1768
1769 #define BPF_MAIN_FUNC (-1)
1770 static void init_func_state(struct bpf_verifier_env *env,
1771                             struct bpf_func_state *state,
1772                             int callsite, int frameno, int subprogno)
1773 {
1774         state->callsite = callsite;
1775         state->frameno = frameno;
1776         state->subprogno = subprogno;
1777         state->callback_ret_range = tnum_range(0, 0);
1778         init_reg_state(env, state);
1779         mark_verifier_state_scratched(env);
1780 }
1781
1782 /* Similar to push_stack(), but for async callbacks */
1783 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1784                                                 int insn_idx, int prev_insn_idx,
1785                                                 int subprog)
1786 {
1787         struct bpf_verifier_stack_elem *elem;
1788         struct bpf_func_state *frame;
1789
1790         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1791         if (!elem)
1792                 goto err;
1793
1794         elem->insn_idx = insn_idx;
1795         elem->prev_insn_idx = prev_insn_idx;
1796         elem->next = env->head;
1797         elem->log_pos = env->log.len_used;
1798         env->head = elem;
1799         env->stack_size++;
1800         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1801                 verbose(env,
1802                         "The sequence of %d jumps is too complex for async cb.\n",
1803                         env->stack_size);
1804                 goto err;
1805         }
1806         /* Unlike push_stack() do not copy_verifier_state().
1807          * The caller state doesn't matter.
1808          * This is async callback. It starts in a fresh stack.
1809          * Initialize it similar to do_check_common().
1810          */
1811         elem->st.branches = 1;
1812         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1813         if (!frame)
1814                 goto err;
1815         init_func_state(env, frame,
1816                         BPF_MAIN_FUNC /* callsite */,
1817                         0 /* frameno within this callchain */,
1818                         subprog /* subprog number within this prog */);
1819         elem->st.frame[0] = frame;
1820         return &elem->st;
1821 err:
1822         free_verifier_state(env->cur_state, true);
1823         env->cur_state = NULL;
1824         /* pop all elements and return */
1825         while (!pop_stack(env, NULL, NULL, false));
1826         return NULL;
1827 }
1828
1829
1830 enum reg_arg_type {
1831         SRC_OP,         /* register is used as source operand */
1832         DST_OP,         /* register is used as destination operand */
1833         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1834 };
1835
1836 static int cmp_subprogs(const void *a, const void *b)
1837 {
1838         return ((struct bpf_subprog_info *)a)->start -
1839                ((struct bpf_subprog_info *)b)->start;
1840 }
1841
1842 static int find_subprog(struct bpf_verifier_env *env, int off)
1843 {
1844         struct bpf_subprog_info *p;
1845
1846         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1847                     sizeof(env->subprog_info[0]), cmp_subprogs);
1848         if (!p)
1849                 return -ENOENT;
1850         return p - env->subprog_info;
1851
1852 }
1853
1854 static int add_subprog(struct bpf_verifier_env *env, int off)
1855 {
1856         int insn_cnt = env->prog->len;
1857         int ret;
1858
1859         if (off >= insn_cnt || off < 0) {
1860                 verbose(env, "call to invalid destination\n");
1861                 return -EINVAL;
1862         }
1863         ret = find_subprog(env, off);
1864         if (ret >= 0)
1865                 return ret;
1866         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1867                 verbose(env, "too many subprograms\n");
1868                 return -E2BIG;
1869         }
1870         /* determine subprog starts. The end is one before the next starts */
1871         env->subprog_info[env->subprog_cnt++].start = off;
1872         sort(env->subprog_info, env->subprog_cnt,
1873              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1874         return env->subprog_cnt - 1;
1875 }
1876
1877 #define MAX_KFUNC_DESCS 256
1878 #define MAX_KFUNC_BTFS  256
1879
1880 struct bpf_kfunc_desc {
1881         struct btf_func_model func_model;
1882         u32 func_id;
1883         s32 imm;
1884         u16 offset;
1885 };
1886
1887 struct bpf_kfunc_btf {
1888         struct btf *btf;
1889         struct module *module;
1890         u16 offset;
1891 };
1892
1893 struct bpf_kfunc_desc_tab {
1894         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1895         u32 nr_descs;
1896 };
1897
1898 struct bpf_kfunc_btf_tab {
1899         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1900         u32 nr_descs;
1901 };
1902
1903 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1904 {
1905         const struct bpf_kfunc_desc *d0 = a;
1906         const struct bpf_kfunc_desc *d1 = b;
1907
1908         /* func_id is not greater than BTF_MAX_TYPE */
1909         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1910 }
1911
1912 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1913 {
1914         const struct bpf_kfunc_btf *d0 = a;
1915         const struct bpf_kfunc_btf *d1 = b;
1916
1917         return d0->offset - d1->offset;
1918 }
1919
1920 static const struct bpf_kfunc_desc *
1921 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1922 {
1923         struct bpf_kfunc_desc desc = {
1924                 .func_id = func_id,
1925                 .offset = offset,
1926         };
1927         struct bpf_kfunc_desc_tab *tab;
1928
1929         tab = prog->aux->kfunc_tab;
1930         return bsearch(&desc, tab->descs, tab->nr_descs,
1931                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1932 }
1933
1934 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1935                                          s16 offset)
1936 {
1937         struct bpf_kfunc_btf kf_btf = { .offset = offset };
1938         struct bpf_kfunc_btf_tab *tab;
1939         struct bpf_kfunc_btf *b;
1940         struct module *mod;
1941         struct btf *btf;
1942         int btf_fd;
1943
1944         tab = env->prog->aux->kfunc_btf_tab;
1945         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1946                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1947         if (!b) {
1948                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1949                         verbose(env, "too many different module BTFs\n");
1950                         return ERR_PTR(-E2BIG);
1951                 }
1952
1953                 if (bpfptr_is_null(env->fd_array)) {
1954                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1955                         return ERR_PTR(-EPROTO);
1956                 }
1957
1958                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1959                                             offset * sizeof(btf_fd),
1960                                             sizeof(btf_fd)))
1961                         return ERR_PTR(-EFAULT);
1962
1963                 btf = btf_get_by_fd(btf_fd);
1964                 if (IS_ERR(btf)) {
1965                         verbose(env, "invalid module BTF fd specified\n");
1966                         return btf;
1967                 }
1968
1969                 if (!btf_is_module(btf)) {
1970                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
1971                         btf_put(btf);
1972                         return ERR_PTR(-EINVAL);
1973                 }
1974
1975                 mod = btf_try_get_module(btf);
1976                 if (!mod) {
1977                         btf_put(btf);
1978                         return ERR_PTR(-ENXIO);
1979                 }
1980
1981                 b = &tab->descs[tab->nr_descs++];
1982                 b->btf = btf;
1983                 b->module = mod;
1984                 b->offset = offset;
1985
1986                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1987                      kfunc_btf_cmp_by_off, NULL);
1988         }
1989         return b->btf;
1990 }
1991
1992 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1993 {
1994         if (!tab)
1995                 return;
1996
1997         while (tab->nr_descs--) {
1998                 module_put(tab->descs[tab->nr_descs].module);
1999                 btf_put(tab->descs[tab->nr_descs].btf);
2000         }
2001         kfree(tab);
2002 }
2003
2004 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2005 {
2006         if (offset) {
2007                 if (offset < 0) {
2008                         /* In the future, this can be allowed to increase limit
2009                          * of fd index into fd_array, interpreted as u16.
2010                          */
2011                         verbose(env, "negative offset disallowed for kernel module function call\n");
2012                         return ERR_PTR(-EINVAL);
2013                 }
2014
2015                 return __find_kfunc_desc_btf(env, offset);
2016         }
2017         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2018 }
2019
2020 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2021 {
2022         const struct btf_type *func, *func_proto;
2023         struct bpf_kfunc_btf_tab *btf_tab;
2024         struct bpf_kfunc_desc_tab *tab;
2025         struct bpf_prog_aux *prog_aux;
2026         struct bpf_kfunc_desc *desc;
2027         const char *func_name;
2028         struct btf *desc_btf;
2029         unsigned long call_imm;
2030         unsigned long addr;
2031         int err;
2032
2033         prog_aux = env->prog->aux;
2034         tab = prog_aux->kfunc_tab;
2035         btf_tab = prog_aux->kfunc_btf_tab;
2036         if (!tab) {
2037                 if (!btf_vmlinux) {
2038                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2039                         return -ENOTSUPP;
2040                 }
2041
2042                 if (!env->prog->jit_requested) {
2043                         verbose(env, "JIT is required for calling kernel function\n");
2044                         return -ENOTSUPP;
2045                 }
2046
2047                 if (!bpf_jit_supports_kfunc_call()) {
2048                         verbose(env, "JIT does not support calling kernel function\n");
2049                         return -ENOTSUPP;
2050                 }
2051
2052                 if (!env->prog->gpl_compatible) {
2053                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2054                         return -EINVAL;
2055                 }
2056
2057                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2058                 if (!tab)
2059                         return -ENOMEM;
2060                 prog_aux->kfunc_tab = tab;
2061         }
2062
2063         /* func_id == 0 is always invalid, but instead of returning an error, be
2064          * conservative and wait until the code elimination pass before returning
2065          * error, so that invalid calls that get pruned out can be in BPF programs
2066          * loaded from userspace.  It is also required that offset be untouched
2067          * for such calls.
2068          */
2069         if (!func_id && !offset)
2070                 return 0;
2071
2072         if (!btf_tab && offset) {
2073                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2074                 if (!btf_tab)
2075                         return -ENOMEM;
2076                 prog_aux->kfunc_btf_tab = btf_tab;
2077         }
2078
2079         desc_btf = find_kfunc_desc_btf(env, offset);
2080         if (IS_ERR(desc_btf)) {
2081                 verbose(env, "failed to find BTF for kernel function\n");
2082                 return PTR_ERR(desc_btf);
2083         }
2084
2085         if (find_kfunc_desc(env->prog, func_id, offset))
2086                 return 0;
2087
2088         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2089                 verbose(env, "too many different kernel function calls\n");
2090                 return -E2BIG;
2091         }
2092
2093         func = btf_type_by_id(desc_btf, func_id);
2094         if (!func || !btf_type_is_func(func)) {
2095                 verbose(env, "kernel btf_id %u is not a function\n",
2096                         func_id);
2097                 return -EINVAL;
2098         }
2099         func_proto = btf_type_by_id(desc_btf, func->type);
2100         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2101                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2102                         func_id);
2103                 return -EINVAL;
2104         }
2105
2106         func_name = btf_name_by_offset(desc_btf, func->name_off);
2107         addr = kallsyms_lookup_name(func_name);
2108         if (!addr) {
2109                 verbose(env, "cannot find address for kernel function %s\n",
2110                         func_name);
2111                 return -EINVAL;
2112         }
2113
2114         call_imm = BPF_CALL_IMM(addr);
2115         /* Check whether or not the relative offset overflows desc->imm */
2116         if ((unsigned long)(s32)call_imm != call_imm) {
2117                 verbose(env, "address of kernel function %s is out of range\n",
2118                         func_name);
2119                 return -EINVAL;
2120         }
2121
2122         desc = &tab->descs[tab->nr_descs++];
2123         desc->func_id = func_id;
2124         desc->imm = call_imm;
2125         desc->offset = offset;
2126         err = btf_distill_func_proto(&env->log, desc_btf,
2127                                      func_proto, func_name,
2128                                      &desc->func_model);
2129         if (!err)
2130                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2131                      kfunc_desc_cmp_by_id_off, NULL);
2132         return err;
2133 }
2134
2135 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2136 {
2137         const struct bpf_kfunc_desc *d0 = a;
2138         const struct bpf_kfunc_desc *d1 = b;
2139
2140         if (d0->imm > d1->imm)
2141                 return 1;
2142         else if (d0->imm < d1->imm)
2143                 return -1;
2144         return 0;
2145 }
2146
2147 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2148 {
2149         struct bpf_kfunc_desc_tab *tab;
2150
2151         tab = prog->aux->kfunc_tab;
2152         if (!tab)
2153                 return;
2154
2155         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2156              kfunc_desc_cmp_by_imm, NULL);
2157 }
2158
2159 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2160 {
2161         return !!prog->aux->kfunc_tab;
2162 }
2163
2164 const struct btf_func_model *
2165 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2166                          const struct bpf_insn *insn)
2167 {
2168         const struct bpf_kfunc_desc desc = {
2169                 .imm = insn->imm,
2170         };
2171         const struct bpf_kfunc_desc *res;
2172         struct bpf_kfunc_desc_tab *tab;
2173
2174         tab = prog->aux->kfunc_tab;
2175         res = bsearch(&desc, tab->descs, tab->nr_descs,
2176                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2177
2178         return res ? &res->func_model : NULL;
2179 }
2180
2181 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2182 {
2183         struct bpf_subprog_info *subprog = env->subprog_info;
2184         struct bpf_insn *insn = env->prog->insnsi;
2185         int i, ret, insn_cnt = env->prog->len;
2186
2187         /* Add entry function. */
2188         ret = add_subprog(env, 0);
2189         if (ret)
2190                 return ret;
2191
2192         for (i = 0; i < insn_cnt; i++, insn++) {
2193                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2194                     !bpf_pseudo_kfunc_call(insn))
2195                         continue;
2196
2197                 if (!env->bpf_capable) {
2198                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2199                         return -EPERM;
2200                 }
2201
2202                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2203                         ret = add_subprog(env, i + insn->imm + 1);
2204                 else
2205                         ret = add_kfunc_call(env, insn->imm, insn->off);
2206
2207                 if (ret < 0)
2208                         return ret;
2209         }
2210
2211         /* Add a fake 'exit' subprog which could simplify subprog iteration
2212          * logic. 'subprog_cnt' should not be increased.
2213          */
2214         subprog[env->subprog_cnt].start = insn_cnt;
2215
2216         if (env->log.level & BPF_LOG_LEVEL2)
2217                 for (i = 0; i < env->subprog_cnt; i++)
2218                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2219
2220         return 0;
2221 }
2222
2223 static int check_subprogs(struct bpf_verifier_env *env)
2224 {
2225         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2226         struct bpf_subprog_info *subprog = env->subprog_info;
2227         struct bpf_insn *insn = env->prog->insnsi;
2228         int insn_cnt = env->prog->len;
2229
2230         /* now check that all jumps are within the same subprog */
2231         subprog_start = subprog[cur_subprog].start;
2232         subprog_end = subprog[cur_subprog + 1].start;
2233         for (i = 0; i < insn_cnt; i++) {
2234                 u8 code = insn[i].code;
2235
2236                 if (code == (BPF_JMP | BPF_CALL) &&
2237                     insn[i].imm == BPF_FUNC_tail_call &&
2238                     insn[i].src_reg != BPF_PSEUDO_CALL)
2239                         subprog[cur_subprog].has_tail_call = true;
2240                 if (BPF_CLASS(code) == BPF_LD &&
2241                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2242                         subprog[cur_subprog].has_ld_abs = true;
2243                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2244                         goto next;
2245                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2246                         goto next;
2247                 off = i + insn[i].off + 1;
2248                 if (off < subprog_start || off >= subprog_end) {
2249                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2250                         return -EINVAL;
2251                 }
2252 next:
2253                 if (i == subprog_end - 1) {
2254                         /* to avoid fall-through from one subprog into another
2255                          * the last insn of the subprog should be either exit
2256                          * or unconditional jump back
2257                          */
2258                         if (code != (BPF_JMP | BPF_EXIT) &&
2259                             code != (BPF_JMP | BPF_JA)) {
2260                                 verbose(env, "last insn is not an exit or jmp\n");
2261                                 return -EINVAL;
2262                         }
2263                         subprog_start = subprog_end;
2264                         cur_subprog++;
2265                         if (cur_subprog < env->subprog_cnt)
2266                                 subprog_end = subprog[cur_subprog + 1].start;
2267                 }
2268         }
2269         return 0;
2270 }
2271
2272 /* Parentage chain of this register (or stack slot) should take care of all
2273  * issues like callee-saved registers, stack slot allocation time, etc.
2274  */
2275 static int mark_reg_read(struct bpf_verifier_env *env,
2276                          const struct bpf_reg_state *state,
2277                          struct bpf_reg_state *parent, u8 flag)
2278 {
2279         bool writes = parent == state->parent; /* Observe write marks */
2280         int cnt = 0;
2281
2282         while (parent) {
2283                 /* if read wasn't screened by an earlier write ... */
2284                 if (writes && state->live & REG_LIVE_WRITTEN)
2285                         break;
2286                 if (parent->live & REG_LIVE_DONE) {
2287                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2288                                 reg_type_str(env, parent->type),
2289                                 parent->var_off.value, parent->off);
2290                         return -EFAULT;
2291                 }
2292                 /* The first condition is more likely to be true than the
2293                  * second, checked it first.
2294                  */
2295                 if ((parent->live & REG_LIVE_READ) == flag ||
2296                     parent->live & REG_LIVE_READ64)
2297                         /* The parentage chain never changes and
2298                          * this parent was already marked as LIVE_READ.
2299                          * There is no need to keep walking the chain again and
2300                          * keep re-marking all parents as LIVE_READ.
2301                          * This case happens when the same register is read
2302                          * multiple times without writes into it in-between.
2303                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2304                          * then no need to set the weak REG_LIVE_READ32.
2305                          */
2306                         break;
2307                 /* ... then we depend on parent's value */
2308                 parent->live |= flag;
2309                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2310                 if (flag == REG_LIVE_READ64)
2311                         parent->live &= ~REG_LIVE_READ32;
2312                 state = parent;
2313                 parent = state->parent;
2314                 writes = true;
2315                 cnt++;
2316         }
2317
2318         if (env->longest_mark_read_walk < cnt)
2319                 env->longest_mark_read_walk = cnt;
2320         return 0;
2321 }
2322
2323 /* This function is supposed to be used by the following 32-bit optimization
2324  * code only. It returns TRUE if the source or destination register operates
2325  * on 64-bit, otherwise return FALSE.
2326  */
2327 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2328                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2329 {
2330         u8 code, class, op;
2331
2332         code = insn->code;
2333         class = BPF_CLASS(code);
2334         op = BPF_OP(code);
2335         if (class == BPF_JMP) {
2336                 /* BPF_EXIT for "main" will reach here. Return TRUE
2337                  * conservatively.
2338                  */
2339                 if (op == BPF_EXIT)
2340                         return true;
2341                 if (op == BPF_CALL) {
2342                         /* BPF to BPF call will reach here because of marking
2343                          * caller saved clobber with DST_OP_NO_MARK for which we
2344                          * don't care the register def because they are anyway
2345                          * marked as NOT_INIT already.
2346                          */
2347                         if (insn->src_reg == BPF_PSEUDO_CALL)
2348                                 return false;
2349                         /* Helper call will reach here because of arg type
2350                          * check, conservatively return TRUE.
2351                          */
2352                         if (t == SRC_OP)
2353                                 return true;
2354
2355                         return false;
2356                 }
2357         }
2358
2359         if (class == BPF_ALU64 || class == BPF_JMP ||
2360             /* BPF_END always use BPF_ALU class. */
2361             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2362                 return true;
2363
2364         if (class == BPF_ALU || class == BPF_JMP32)
2365                 return false;
2366
2367         if (class == BPF_LDX) {
2368                 if (t != SRC_OP)
2369                         return BPF_SIZE(code) == BPF_DW;
2370                 /* LDX source must be ptr. */
2371                 return true;
2372         }
2373
2374         if (class == BPF_STX) {
2375                 /* BPF_STX (including atomic variants) has multiple source
2376                  * operands, one of which is a ptr. Check whether the caller is
2377                  * asking about it.
2378                  */
2379                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2380                         return true;
2381                 return BPF_SIZE(code) == BPF_DW;
2382         }
2383
2384         if (class == BPF_LD) {
2385                 u8 mode = BPF_MODE(code);
2386
2387                 /* LD_IMM64 */
2388                 if (mode == BPF_IMM)
2389                         return true;
2390
2391                 /* Both LD_IND and LD_ABS return 32-bit data. */
2392                 if (t != SRC_OP)
2393                         return  false;
2394
2395                 /* Implicit ctx ptr. */
2396                 if (regno == BPF_REG_6)
2397                         return true;
2398
2399                 /* Explicit source could be any width. */
2400                 return true;
2401         }
2402
2403         if (class == BPF_ST)
2404                 /* The only source register for BPF_ST is a ptr. */
2405                 return true;
2406
2407         /* Conservatively return true at default. */
2408         return true;
2409 }
2410
2411 /* Return the regno defined by the insn, or -1. */
2412 static int insn_def_regno(const struct bpf_insn *insn)
2413 {
2414         switch (BPF_CLASS(insn->code)) {
2415         case BPF_JMP:
2416         case BPF_JMP32:
2417         case BPF_ST:
2418                 return -1;
2419         case BPF_STX:
2420                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2421                     (insn->imm & BPF_FETCH)) {
2422                         if (insn->imm == BPF_CMPXCHG)
2423                                 return BPF_REG_0;
2424                         else
2425                                 return insn->src_reg;
2426                 } else {
2427                         return -1;
2428                 }
2429         default:
2430                 return insn->dst_reg;
2431         }
2432 }
2433
2434 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2435 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2436 {
2437         int dst_reg = insn_def_regno(insn);
2438
2439         if (dst_reg == -1)
2440                 return false;
2441
2442         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2443 }
2444
2445 static void mark_insn_zext(struct bpf_verifier_env *env,
2446                            struct bpf_reg_state *reg)
2447 {
2448         s32 def_idx = reg->subreg_def;
2449
2450         if (def_idx == DEF_NOT_SUBREG)
2451                 return;
2452
2453         env->insn_aux_data[def_idx - 1].zext_dst = true;
2454         /* The dst will be zero extended, so won't be sub-register anymore. */
2455         reg->subreg_def = DEF_NOT_SUBREG;
2456 }
2457
2458 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2459                          enum reg_arg_type t)
2460 {
2461         struct bpf_verifier_state *vstate = env->cur_state;
2462         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2463         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2464         struct bpf_reg_state *reg, *regs = state->regs;
2465         bool rw64;
2466
2467         if (regno >= MAX_BPF_REG) {
2468                 verbose(env, "R%d is invalid\n", regno);
2469                 return -EINVAL;
2470         }
2471
2472         mark_reg_scratched(env, regno);
2473
2474         reg = &regs[regno];
2475         rw64 = is_reg64(env, insn, regno, reg, t);
2476         if (t == SRC_OP) {
2477                 /* check whether register used as source operand can be read */
2478                 if (reg->type == NOT_INIT) {
2479                         verbose(env, "R%d !read_ok\n", regno);
2480                         return -EACCES;
2481                 }
2482                 /* We don't need to worry about FP liveness because it's read-only */
2483                 if (regno == BPF_REG_FP)
2484                         return 0;
2485
2486                 if (rw64)
2487                         mark_insn_zext(env, reg);
2488
2489                 return mark_reg_read(env, reg, reg->parent,
2490                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2491         } else {
2492                 /* check whether register used as dest operand can be written to */
2493                 if (regno == BPF_REG_FP) {
2494                         verbose(env, "frame pointer is read only\n");
2495                         return -EACCES;
2496                 }
2497                 reg->live |= REG_LIVE_WRITTEN;
2498                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2499                 if (t == DST_OP)
2500                         mark_reg_unknown(env, regs, regno);
2501         }
2502         return 0;
2503 }
2504
2505 /* for any branch, call, exit record the history of jmps in the given state */
2506 static int push_jmp_history(struct bpf_verifier_env *env,
2507                             struct bpf_verifier_state *cur)
2508 {
2509         u32 cnt = cur->jmp_history_cnt;
2510         struct bpf_idx_pair *p;
2511         size_t alloc_size;
2512
2513         cnt++;
2514         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2515         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2516         if (!p)
2517                 return -ENOMEM;
2518         p[cnt - 1].idx = env->insn_idx;
2519         p[cnt - 1].prev_idx = env->prev_insn_idx;
2520         cur->jmp_history = p;
2521         cur->jmp_history_cnt = cnt;
2522         return 0;
2523 }
2524
2525 /* Backtrack one insn at a time. If idx is not at the top of recorded
2526  * history then previous instruction came from straight line execution.
2527  */
2528 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2529                              u32 *history)
2530 {
2531         u32 cnt = *history;
2532
2533         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2534                 i = st->jmp_history[cnt - 1].prev_idx;
2535                 (*history)--;
2536         } else {
2537                 i--;
2538         }
2539         return i;
2540 }
2541
2542 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2543 {
2544         const struct btf_type *func;
2545         struct btf *desc_btf;
2546
2547         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2548                 return NULL;
2549
2550         desc_btf = find_kfunc_desc_btf(data, insn->off);
2551         if (IS_ERR(desc_btf))
2552                 return "<error>";
2553
2554         func = btf_type_by_id(desc_btf, insn->imm);
2555         return btf_name_by_offset(desc_btf, func->name_off);
2556 }
2557
2558 /* For given verifier state backtrack_insn() is called from the last insn to
2559  * the first insn. Its purpose is to compute a bitmask of registers and
2560  * stack slots that needs precision in the parent verifier state.
2561  */
2562 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2563                           u32 *reg_mask, u64 *stack_mask)
2564 {
2565         const struct bpf_insn_cbs cbs = {
2566                 .cb_call        = disasm_kfunc_name,
2567                 .cb_print       = verbose,
2568                 .private_data   = env,
2569         };
2570         struct bpf_insn *insn = env->prog->insnsi + idx;
2571         u8 class = BPF_CLASS(insn->code);
2572         u8 opcode = BPF_OP(insn->code);
2573         u8 mode = BPF_MODE(insn->code);
2574         u32 dreg = 1u << insn->dst_reg;
2575         u32 sreg = 1u << insn->src_reg;
2576         u32 spi;
2577
2578         if (insn->code == 0)
2579                 return 0;
2580         if (env->log.level & BPF_LOG_LEVEL2) {
2581                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2582                 verbose(env, "%d: ", idx);
2583                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2584         }
2585
2586         if (class == BPF_ALU || class == BPF_ALU64) {
2587                 if (!(*reg_mask & dreg))
2588                         return 0;
2589                 if (opcode == BPF_MOV) {
2590                         if (BPF_SRC(insn->code) == BPF_X) {
2591                                 /* dreg = sreg
2592                                  * dreg needs precision after this insn
2593                                  * sreg needs precision before this insn
2594                                  */
2595                                 *reg_mask &= ~dreg;
2596                                 *reg_mask |= sreg;
2597                         } else {
2598                                 /* dreg = K
2599                                  * dreg needs precision after this insn.
2600                                  * Corresponding register is already marked
2601                                  * as precise=true in this verifier state.
2602                                  * No further markings in parent are necessary
2603                                  */
2604                                 *reg_mask &= ~dreg;
2605                         }
2606                 } else {
2607                         if (BPF_SRC(insn->code) == BPF_X) {
2608                                 /* dreg += sreg
2609                                  * both dreg and sreg need precision
2610                                  * before this insn
2611                                  */
2612                                 *reg_mask |= sreg;
2613                         } /* else dreg += K
2614                            * dreg still needs precision before this insn
2615                            */
2616                 }
2617         } else if (class == BPF_LDX) {
2618                 if (!(*reg_mask & dreg))
2619                         return 0;
2620                 *reg_mask &= ~dreg;
2621
2622                 /* scalars can only be spilled into stack w/o losing precision.
2623                  * Load from any other memory can be zero extended.
2624                  * The desire to keep that precision is already indicated
2625                  * by 'precise' mark in corresponding register of this state.
2626                  * No further tracking necessary.
2627                  */
2628                 if (insn->src_reg != BPF_REG_FP)
2629                         return 0;
2630
2631                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2632                  * that [fp - off] slot contains scalar that needs to be
2633                  * tracked with precision
2634                  */
2635                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2636                 if (spi >= 64) {
2637                         verbose(env, "BUG spi %d\n", spi);
2638                         WARN_ONCE(1, "verifier backtracking bug");
2639                         return -EFAULT;
2640                 }
2641                 *stack_mask |= 1ull << spi;
2642         } else if (class == BPF_STX || class == BPF_ST) {
2643                 if (*reg_mask & dreg)
2644                         /* stx & st shouldn't be using _scalar_ dst_reg
2645                          * to access memory. It means backtracking
2646                          * encountered a case of pointer subtraction.
2647                          */
2648                         return -ENOTSUPP;
2649                 /* scalars can only be spilled into stack */
2650                 if (insn->dst_reg != BPF_REG_FP)
2651                         return 0;
2652                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2653                 if (spi >= 64) {
2654                         verbose(env, "BUG spi %d\n", spi);
2655                         WARN_ONCE(1, "verifier backtracking bug");
2656                         return -EFAULT;
2657                 }
2658                 if (!(*stack_mask & (1ull << spi)))
2659                         return 0;
2660                 *stack_mask &= ~(1ull << spi);
2661                 if (class == BPF_STX)
2662                         *reg_mask |= sreg;
2663         } else if (class == BPF_JMP || class == BPF_JMP32) {
2664                 if (opcode == BPF_CALL) {
2665                         if (insn->src_reg == BPF_PSEUDO_CALL)
2666                                 return -ENOTSUPP;
2667                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
2668                          * catch this error later. Make backtracking conservative
2669                          * with ENOTSUPP.
2670                          */
2671                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2672                                 return -ENOTSUPP;
2673                         /* regular helper call sets R0 */
2674                         *reg_mask &= ~1;
2675                         if (*reg_mask & 0x3f) {
2676                                 /* if backtracing was looking for registers R1-R5
2677                                  * they should have been found already.
2678                                  */
2679                                 verbose(env, "BUG regs %x\n", *reg_mask);
2680                                 WARN_ONCE(1, "verifier backtracking bug");
2681                                 return -EFAULT;
2682                         }
2683                 } else if (opcode == BPF_EXIT) {
2684                         return -ENOTSUPP;
2685                 } else if (BPF_SRC(insn->code) == BPF_X) {
2686                         if (!(*reg_mask & (dreg | sreg)))
2687                                 return 0;
2688                         /* dreg <cond> sreg
2689                          * Both dreg and sreg need precision before
2690                          * this insn. If only sreg was marked precise
2691                          * before it would be equally necessary to
2692                          * propagate it to dreg.
2693                          */
2694                         *reg_mask |= (sreg | dreg);
2695                          /* else dreg <cond> K
2696                           * Only dreg still needs precision before
2697                           * this insn, so for the K-based conditional
2698                           * there is nothing new to be marked.
2699                           */
2700                 }
2701         } else if (class == BPF_LD) {
2702                 if (!(*reg_mask & dreg))
2703                         return 0;
2704                 *reg_mask &= ~dreg;
2705                 /* It's ld_imm64 or ld_abs or ld_ind.
2706                  * For ld_imm64 no further tracking of precision
2707                  * into parent is necessary
2708                  */
2709                 if (mode == BPF_IND || mode == BPF_ABS)
2710                         /* to be analyzed */
2711                         return -ENOTSUPP;
2712         }
2713         return 0;
2714 }
2715
2716 /* the scalar precision tracking algorithm:
2717  * . at the start all registers have precise=false.
2718  * . scalar ranges are tracked as normal through alu and jmp insns.
2719  * . once precise value of the scalar register is used in:
2720  *   .  ptr + scalar alu
2721  *   . if (scalar cond K|scalar)
2722  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2723  *   backtrack through the verifier states and mark all registers and
2724  *   stack slots with spilled constants that these scalar regisers
2725  *   should be precise.
2726  * . during state pruning two registers (or spilled stack slots)
2727  *   are equivalent if both are not precise.
2728  *
2729  * Note the verifier cannot simply walk register parentage chain,
2730  * since many different registers and stack slots could have been
2731  * used to compute single precise scalar.
2732  *
2733  * The approach of starting with precise=true for all registers and then
2734  * backtrack to mark a register as not precise when the verifier detects
2735  * that program doesn't care about specific value (e.g., when helper
2736  * takes register as ARG_ANYTHING parameter) is not safe.
2737  *
2738  * It's ok to walk single parentage chain of the verifier states.
2739  * It's possible that this backtracking will go all the way till 1st insn.
2740  * All other branches will be explored for needing precision later.
2741  *
2742  * The backtracking needs to deal with cases like:
2743  *   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)
2744  * r9 -= r8
2745  * r5 = r9
2746  * if r5 > 0x79f goto pc+7
2747  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2748  * r5 += 1
2749  * ...
2750  * call bpf_perf_event_output#25
2751  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2752  *
2753  * and this case:
2754  * r6 = 1
2755  * call foo // uses callee's r6 inside to compute r0
2756  * r0 += r6
2757  * if r0 == 0 goto
2758  *
2759  * to track above reg_mask/stack_mask needs to be independent for each frame.
2760  *
2761  * Also if parent's curframe > frame where backtracking started,
2762  * the verifier need to mark registers in both frames, otherwise callees
2763  * may incorrectly prune callers. This is similar to
2764  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2765  *
2766  * For now backtracking falls back into conservative marking.
2767  */
2768 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2769                                      struct bpf_verifier_state *st)
2770 {
2771         struct bpf_func_state *func;
2772         struct bpf_reg_state *reg;
2773         int i, j;
2774
2775         /* big hammer: mark all scalars precise in this path.
2776          * pop_stack may still get !precise scalars.
2777          */
2778         for (; st; st = st->parent)
2779                 for (i = 0; i <= st->curframe; i++) {
2780                         func = st->frame[i];
2781                         for (j = 0; j < BPF_REG_FP; j++) {
2782                                 reg = &func->regs[j];
2783                                 if (reg->type != SCALAR_VALUE)
2784                                         continue;
2785                                 reg->precise = true;
2786                         }
2787                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2788                                 if (!is_spilled_reg(&func->stack[j]))
2789                                         continue;
2790                                 reg = &func->stack[j].spilled_ptr;
2791                                 if (reg->type != SCALAR_VALUE)
2792                                         continue;
2793                                 reg->precise = true;
2794                         }
2795                 }
2796 }
2797
2798 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2799                                   int spi)
2800 {
2801         struct bpf_verifier_state *st = env->cur_state;
2802         int first_idx = st->first_insn_idx;
2803         int last_idx = env->insn_idx;
2804         struct bpf_func_state *func;
2805         struct bpf_reg_state *reg;
2806         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2807         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2808         bool skip_first = true;
2809         bool new_marks = false;
2810         int i, err;
2811
2812         if (!env->bpf_capable)
2813                 return 0;
2814
2815         func = st->frame[frame];
2816         if (regno >= 0) {
2817                 reg = &func->regs[regno];
2818                 if (reg->type != SCALAR_VALUE) {
2819                         WARN_ONCE(1, "backtracing misuse");
2820                         return -EFAULT;
2821                 }
2822                 if (!reg->precise)
2823                         new_marks = true;
2824                 else
2825                         reg_mask = 0;
2826                 reg->precise = true;
2827         }
2828
2829         while (spi >= 0) {
2830                 if (!is_spilled_reg(&func->stack[spi])) {
2831                         stack_mask = 0;
2832                         break;
2833                 }
2834                 reg = &func->stack[spi].spilled_ptr;
2835                 if (reg->type != SCALAR_VALUE) {
2836                         stack_mask = 0;
2837                         break;
2838                 }
2839                 if (!reg->precise)
2840                         new_marks = true;
2841                 else
2842                         stack_mask = 0;
2843                 reg->precise = true;
2844                 break;
2845         }
2846
2847         if (!new_marks)
2848                 return 0;
2849         if (!reg_mask && !stack_mask)
2850                 return 0;
2851         for (;;) {
2852                 DECLARE_BITMAP(mask, 64);
2853                 u32 history = st->jmp_history_cnt;
2854
2855                 if (env->log.level & BPF_LOG_LEVEL2)
2856                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2857                 for (i = last_idx;;) {
2858                         if (skip_first) {
2859                                 err = 0;
2860                                 skip_first = false;
2861                         } else {
2862                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2863                         }
2864                         if (err == -ENOTSUPP) {
2865                                 mark_all_scalars_precise(env, st);
2866                                 return 0;
2867                         } else if (err) {
2868                                 return err;
2869                         }
2870                         if (!reg_mask && !stack_mask)
2871                                 /* Found assignment(s) into tracked register in this state.
2872                                  * Since this state is already marked, just return.
2873                                  * Nothing to be tracked further in the parent state.
2874                                  */
2875                                 return 0;
2876                         if (i == first_idx)
2877                                 break;
2878                         i = get_prev_insn_idx(st, i, &history);
2879                         if (i >= env->prog->len) {
2880                                 /* This can happen if backtracking reached insn 0
2881                                  * and there are still reg_mask or stack_mask
2882                                  * to backtrack.
2883                                  * It means the backtracking missed the spot where
2884                                  * particular register was initialized with a constant.
2885                                  */
2886                                 verbose(env, "BUG backtracking idx %d\n", i);
2887                                 WARN_ONCE(1, "verifier backtracking bug");
2888                                 return -EFAULT;
2889                         }
2890                 }
2891                 st = st->parent;
2892                 if (!st)
2893                         break;
2894
2895                 new_marks = false;
2896                 func = st->frame[frame];
2897                 bitmap_from_u64(mask, reg_mask);
2898                 for_each_set_bit(i, mask, 32) {
2899                         reg = &func->regs[i];
2900                         if (reg->type != SCALAR_VALUE) {
2901                                 reg_mask &= ~(1u << i);
2902                                 continue;
2903                         }
2904                         if (!reg->precise)
2905                                 new_marks = true;
2906                         reg->precise = true;
2907                 }
2908
2909                 bitmap_from_u64(mask, stack_mask);
2910                 for_each_set_bit(i, mask, 64) {
2911                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2912                                 /* the sequence of instructions:
2913                                  * 2: (bf) r3 = r10
2914                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2915                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2916                                  * doesn't contain jmps. It's backtracked
2917                                  * as a single block.
2918                                  * During backtracking insn 3 is not recognized as
2919                                  * stack access, so at the end of backtracking
2920                                  * stack slot fp-8 is still marked in stack_mask.
2921                                  * However the parent state may not have accessed
2922                                  * fp-8 and it's "unallocated" stack space.
2923                                  * In such case fallback to conservative.
2924                                  */
2925                                 mark_all_scalars_precise(env, st);
2926                                 return 0;
2927                         }
2928
2929                         if (!is_spilled_reg(&func->stack[i])) {
2930                                 stack_mask &= ~(1ull << i);
2931                                 continue;
2932                         }
2933                         reg = &func->stack[i].spilled_ptr;
2934                         if (reg->type != SCALAR_VALUE) {
2935                                 stack_mask &= ~(1ull << i);
2936                                 continue;
2937                         }
2938                         if (!reg->precise)
2939                                 new_marks = true;
2940                         reg->precise = true;
2941                 }
2942                 if (env->log.level & BPF_LOG_LEVEL2) {
2943                         verbose(env, "parent %s regs=%x stack=%llx marks:",
2944                                 new_marks ? "didn't have" : "already had",
2945                                 reg_mask, stack_mask);
2946                         print_verifier_state(env, func, true);
2947                 }
2948
2949                 if (!reg_mask && !stack_mask)
2950                         break;
2951                 if (!new_marks)
2952                         break;
2953
2954                 last_idx = st->last_insn_idx;
2955                 first_idx = st->first_insn_idx;
2956         }
2957         return 0;
2958 }
2959
2960 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2961 {
2962         return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2963 }
2964
2965 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2966 {
2967         return __mark_chain_precision(env, frame, regno, -1);
2968 }
2969
2970 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2971 {
2972         return __mark_chain_precision(env, frame, -1, spi);
2973 }
2974
2975 static bool is_spillable_regtype(enum bpf_reg_type type)
2976 {
2977         switch (base_type(type)) {
2978         case PTR_TO_MAP_VALUE:
2979         case PTR_TO_STACK:
2980         case PTR_TO_CTX:
2981         case PTR_TO_PACKET:
2982         case PTR_TO_PACKET_META:
2983         case PTR_TO_PACKET_END:
2984         case PTR_TO_FLOW_KEYS:
2985         case CONST_PTR_TO_MAP:
2986         case PTR_TO_SOCKET:
2987         case PTR_TO_SOCK_COMMON:
2988         case PTR_TO_TCP_SOCK:
2989         case PTR_TO_XDP_SOCK:
2990         case PTR_TO_BTF_ID:
2991         case PTR_TO_BUF:
2992         case PTR_TO_MEM:
2993         case PTR_TO_FUNC:
2994         case PTR_TO_MAP_KEY:
2995                 return true;
2996         default:
2997                 return false;
2998         }
2999 }
3000
3001 /* Does this register contain a constant zero? */
3002 static bool register_is_null(struct bpf_reg_state *reg)
3003 {
3004         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3005 }
3006
3007 static bool register_is_const(struct bpf_reg_state *reg)
3008 {
3009         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3010 }
3011
3012 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3013 {
3014         return tnum_is_unknown(reg->var_off) &&
3015                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3016                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3017                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3018                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3019 }
3020
3021 static bool register_is_bounded(struct bpf_reg_state *reg)
3022 {
3023         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3024 }
3025
3026 static bool __is_pointer_value(bool allow_ptr_leaks,
3027                                const struct bpf_reg_state *reg)
3028 {
3029         if (allow_ptr_leaks)
3030                 return false;
3031
3032         return reg->type != SCALAR_VALUE;
3033 }
3034
3035 /* Copy src state preserving dst->parent and dst->live fields */
3036 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3037 {
3038         struct bpf_reg_state *parent = dst->parent;
3039         enum bpf_reg_liveness live = dst->live;
3040
3041         *dst = *src;
3042         dst->parent = parent;
3043         dst->live = live;
3044 }
3045
3046 static void save_register_state(struct bpf_func_state *state,
3047                                 int spi, struct bpf_reg_state *reg,
3048                                 int size)
3049 {
3050         int i;
3051
3052         copy_register_state(&state->stack[spi].spilled_ptr, reg);
3053         if (size == BPF_REG_SIZE)
3054                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3055
3056         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3057                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3058
3059         /* size < 8 bytes spill */
3060         for (; i; i--)
3061                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3062 }
3063
3064 static bool is_bpf_st_mem(struct bpf_insn *insn)
3065 {
3066         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3067 }
3068
3069 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3070  * stack boundary and alignment are checked in check_mem_access()
3071  */
3072 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3073                                        /* stack frame we're writing to */
3074                                        struct bpf_func_state *state,
3075                                        int off, int size, int value_regno,
3076                                        int insn_idx)
3077 {
3078         struct bpf_func_state *cur; /* state of the current function */
3079         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3080         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3081         struct bpf_reg_state *reg = NULL;
3082         u32 dst_reg = insn->dst_reg;
3083
3084         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3085         if (err)
3086                 return err;
3087         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3088          * so it's aligned access and [off, off + size) are within stack limits
3089          */
3090         if (!env->allow_ptr_leaks &&
3091             state->stack[spi].slot_type[0] == STACK_SPILL &&
3092             size != BPF_REG_SIZE) {
3093                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3094                 return -EACCES;
3095         }
3096
3097         cur = env->cur_state->frame[env->cur_state->curframe];
3098         if (value_regno >= 0)
3099                 reg = &cur->regs[value_regno];
3100         if (!env->bypass_spec_v4) {
3101                 bool sanitize = reg && is_spillable_regtype(reg->type);
3102
3103                 for (i = 0; i < size; i++) {
3104                         u8 type = state->stack[spi].slot_type[i];
3105
3106                         if (type != STACK_MISC && type != STACK_ZERO) {
3107                                 sanitize = true;
3108                                 break;
3109                         }
3110                 }
3111
3112                 if (sanitize)
3113                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3114         }
3115
3116         mark_stack_slot_scratched(env, spi);
3117         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3118             !register_is_null(reg) && env->bpf_capable) {
3119                 if (dst_reg != BPF_REG_FP) {
3120                         /* The backtracking logic can only recognize explicit
3121                          * stack slot address like [fp - 8]. Other spill of
3122                          * scalar via different register has to be conservative.
3123                          * Backtrack from here and mark all registers as precise
3124                          * that contributed into 'reg' being a constant.
3125                          */
3126                         err = mark_chain_precision(env, value_regno);
3127                         if (err)
3128                                 return err;
3129                 }
3130                 save_register_state(state, spi, reg, size);
3131                 /* Break the relation on a narrowing spill. */
3132                 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
3133                         state->stack[spi].spilled_ptr.id = 0;
3134         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3135                    insn->imm != 0 && env->bpf_capable) {
3136                 struct bpf_reg_state fake_reg = {};
3137
3138                 __mark_reg_known(&fake_reg, (u32)insn->imm);
3139                 fake_reg.type = SCALAR_VALUE;
3140                 save_register_state(state, spi, &fake_reg, size);
3141         } else if (reg && is_spillable_regtype(reg->type)) {
3142                 /* register containing pointer is being spilled into stack */
3143                 if (size != BPF_REG_SIZE) {
3144                         verbose_linfo(env, insn_idx, "; ");
3145                         verbose(env, "invalid size of register spill\n");
3146                         return -EACCES;
3147                 }
3148                 if (state != cur && reg->type == PTR_TO_STACK) {
3149                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3150                         return -EINVAL;
3151                 }
3152                 save_register_state(state, spi, reg, size);
3153         } else {
3154                 u8 type = STACK_MISC;
3155
3156                 /* regular write of data into stack destroys any spilled ptr */
3157                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3158                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3159                 if (is_spilled_reg(&state->stack[spi]))
3160                         for (i = 0; i < BPF_REG_SIZE; i++)
3161                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3162
3163                 /* only mark the slot as written if all 8 bytes were written
3164                  * otherwise read propagation may incorrectly stop too soon
3165                  * when stack slots are partially written.
3166                  * This heuristic means that read propagation will be
3167                  * conservative, since it will add reg_live_read marks
3168                  * to stack slots all the way to first state when programs
3169                  * writes+reads less than 8 bytes
3170                  */
3171                 if (size == BPF_REG_SIZE)
3172                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3173
3174                 /* when we zero initialize stack slots mark them as such */
3175                 if ((reg && register_is_null(reg)) ||
3176                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3177                         /* backtracking doesn't work for STACK_ZERO yet. */
3178                         err = mark_chain_precision(env, value_regno);
3179                         if (err)
3180                                 return err;
3181                         type = STACK_ZERO;
3182                 }
3183
3184                 /* Mark slots affected by this stack write. */
3185                 for (i = 0; i < size; i++)
3186                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3187                                 type;
3188         }
3189         return 0;
3190 }
3191
3192 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3193  * known to contain a variable offset.
3194  * This function checks whether the write is permitted and conservatively
3195  * tracks the effects of the write, considering that each stack slot in the
3196  * dynamic range is potentially written to.
3197  *
3198  * 'off' includes 'regno->off'.
3199  * 'value_regno' can be -1, meaning that an unknown value is being written to
3200  * the stack.
3201  *
3202  * Spilled pointers in range are not marked as written because we don't know
3203  * what's going to be actually written. This means that read propagation for
3204  * future reads cannot be terminated by this write.
3205  *
3206  * For privileged programs, uninitialized stack slots are considered
3207  * initialized by this write (even though we don't know exactly what offsets
3208  * are going to be written to). The idea is that we don't want the verifier to
3209  * reject future reads that access slots written to through variable offsets.
3210  */
3211 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3212                                      /* func where register points to */
3213                                      struct bpf_func_state *state,
3214                                      int ptr_regno, int off, int size,
3215                                      int value_regno, int insn_idx)
3216 {
3217         struct bpf_func_state *cur; /* state of the current function */
3218         int min_off, max_off;
3219         int i, err;
3220         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3221         bool writing_zero = false;
3222         /* set if the fact that we're writing a zero is used to let any
3223          * stack slots remain STACK_ZERO
3224          */
3225         bool zero_used = false;
3226
3227         cur = env->cur_state->frame[env->cur_state->curframe];
3228         ptr_reg = &cur->regs[ptr_regno];
3229         min_off = ptr_reg->smin_value + off;
3230         max_off = ptr_reg->smax_value + off + size;
3231         if (value_regno >= 0)
3232                 value_reg = &cur->regs[value_regno];
3233         if (value_reg && register_is_null(value_reg))
3234                 writing_zero = true;
3235
3236         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3237         if (err)
3238                 return err;
3239
3240
3241         /* Variable offset writes destroy any spilled pointers in range. */
3242         for (i = min_off; i < max_off; i++) {
3243                 u8 new_type, *stype;
3244                 int slot, spi;
3245
3246                 slot = -i - 1;
3247                 spi = slot / BPF_REG_SIZE;
3248                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3249                 mark_stack_slot_scratched(env, spi);
3250
3251                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3252                         /* Reject the write if range we may write to has not
3253                          * been initialized beforehand. If we didn't reject
3254                          * here, the ptr status would be erased below (even
3255                          * though not all slots are actually overwritten),
3256                          * possibly opening the door to leaks.
3257                          *
3258                          * We do however catch STACK_INVALID case below, and
3259                          * only allow reading possibly uninitialized memory
3260                          * later for CAP_PERFMON, as the write may not happen to
3261                          * that slot.
3262                          */
3263                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3264                                 insn_idx, i);
3265                         return -EINVAL;
3266                 }
3267
3268                 /* Erase all spilled pointers. */
3269                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3270
3271                 /* Update the slot type. */
3272                 new_type = STACK_MISC;
3273                 if (writing_zero && *stype == STACK_ZERO) {
3274                         new_type = STACK_ZERO;
3275                         zero_used = true;
3276                 }
3277                 /* If the slot is STACK_INVALID, we check whether it's OK to
3278                  * pretend that it will be initialized by this write. The slot
3279                  * might not actually be written to, and so if we mark it as
3280                  * initialized future reads might leak uninitialized memory.
3281                  * For privileged programs, we will accept such reads to slots
3282                  * that may or may not be written because, if we're reject
3283                  * them, the error would be too confusing.
3284                  */
3285                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3286                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3287                                         insn_idx, i);
3288                         return -EINVAL;
3289                 }
3290                 *stype = new_type;
3291         }
3292         if (zero_used) {
3293                 /* backtracking doesn't work for STACK_ZERO yet. */
3294                 err = mark_chain_precision(env, value_regno);
3295                 if (err)
3296                         return err;
3297         }
3298         return 0;
3299 }
3300
3301 /* When register 'dst_regno' is assigned some values from stack[min_off,
3302  * max_off), we set the register's type according to the types of the
3303  * respective stack slots. If all the stack values are known to be zeros, then
3304  * so is the destination reg. Otherwise, the register is considered to be
3305  * SCALAR. This function does not deal with register filling; the caller must
3306  * ensure that all spilled registers in the stack range have been marked as
3307  * read.
3308  */
3309 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3310                                 /* func where src register points to */
3311                                 struct bpf_func_state *ptr_state,
3312                                 int min_off, int max_off, int dst_regno)
3313 {
3314         struct bpf_verifier_state *vstate = env->cur_state;
3315         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3316         int i, slot, spi;
3317         u8 *stype;
3318         int zeros = 0;
3319
3320         for (i = min_off; i < max_off; i++) {
3321                 slot = -i - 1;
3322                 spi = slot / BPF_REG_SIZE;
3323                 stype = ptr_state->stack[spi].slot_type;
3324                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3325                         break;
3326                 zeros++;
3327         }
3328         if (zeros == max_off - min_off) {
3329                 /* any access_size read into register is zero extended,
3330                  * so the whole register == const_zero
3331                  */
3332                 __mark_reg_const_zero(&state->regs[dst_regno]);
3333                 /* backtracking doesn't support STACK_ZERO yet,
3334                  * so mark it precise here, so that later
3335                  * backtracking can stop here.
3336                  * Backtracking may not need this if this register
3337                  * doesn't participate in pointer adjustment.
3338                  * Forward propagation of precise flag is not
3339                  * necessary either. This mark is only to stop
3340                  * backtracking. Any register that contributed
3341                  * to const 0 was marked precise before spill.
3342                  */
3343                 state->regs[dst_regno].precise = true;
3344         } else {
3345                 /* have read misc data from the stack */
3346                 mark_reg_unknown(env, state->regs, dst_regno);
3347         }
3348         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3349 }
3350
3351 /* Read the stack at 'off' and put the results into the register indicated by
3352  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3353  * spilled reg.
3354  *
3355  * 'dst_regno' can be -1, meaning that the read value is not going to a
3356  * register.
3357  *
3358  * The access is assumed to be within the current stack bounds.
3359  */
3360 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3361                                       /* func where src register points to */
3362                                       struct bpf_func_state *reg_state,
3363                                       int off, int size, int dst_regno)
3364 {
3365         struct bpf_verifier_state *vstate = env->cur_state;
3366         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3367         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3368         struct bpf_reg_state *reg;
3369         u8 *stype, type;
3370
3371         stype = reg_state->stack[spi].slot_type;
3372         reg = &reg_state->stack[spi].spilled_ptr;
3373
3374         if (is_spilled_reg(&reg_state->stack[spi])) {
3375                 u8 spill_size = 1;
3376
3377                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3378                         spill_size++;
3379
3380                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3381                         if (reg->type != SCALAR_VALUE) {
3382                                 verbose_linfo(env, env->insn_idx, "; ");
3383                                 verbose(env, "invalid size of register fill\n");
3384                                 return -EACCES;
3385                         }
3386
3387                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3388                         if (dst_regno < 0)
3389                                 return 0;
3390
3391                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
3392                                 /* The earlier check_reg_arg() has decided the
3393                                  * subreg_def for this insn.  Save it first.
3394                                  */
3395                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
3396
3397                                 copy_register_state(&state->regs[dst_regno], reg);
3398                                 state->regs[dst_regno].subreg_def = subreg_def;
3399                         } else {
3400                                 for (i = 0; i < size; i++) {
3401                                         type = stype[(slot - i) % BPF_REG_SIZE];
3402                                         if (type == STACK_SPILL)
3403                                                 continue;
3404                                         if (type == STACK_MISC)
3405                                                 continue;
3406                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3407                                                 off, i, size);
3408                                         return -EACCES;
3409                                 }
3410                                 mark_reg_unknown(env, state->regs, dst_regno);
3411                         }
3412                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3413                         return 0;
3414                 }
3415
3416                 if (dst_regno >= 0) {
3417                         /* restore register state from stack */
3418                         copy_register_state(&state->regs[dst_regno], reg);
3419                         /* mark reg as written since spilled pointer state likely
3420                          * has its liveness marks cleared by is_state_visited()
3421                          * which resets stack/reg liveness for state transitions
3422                          */
3423                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3424                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3425                         /* If dst_regno==-1, the caller is asking us whether
3426                          * it is acceptable to use this value as a SCALAR_VALUE
3427                          * (e.g. for XADD).
3428                          * We must not allow unprivileged callers to do that
3429                          * with spilled pointers.
3430                          */
3431                         verbose(env, "leaking pointer from stack off %d\n",
3432                                 off);
3433                         return -EACCES;
3434                 }
3435                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3436         } else {
3437                 for (i = 0; i < size; i++) {
3438                         type = stype[(slot - i) % BPF_REG_SIZE];
3439                         if (type == STACK_MISC)
3440                                 continue;
3441                         if (type == STACK_ZERO)
3442                                 continue;
3443                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3444                                 off, i, size);
3445                         return -EACCES;
3446                 }
3447                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3448                 if (dst_regno >= 0)
3449                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3450         }
3451         return 0;
3452 }
3453
3454 enum bpf_access_src {
3455         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3456         ACCESS_HELPER = 2,  /* the access is performed by a helper */
3457 };
3458
3459 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3460                                          int regno, int off, int access_size,
3461                                          bool zero_size_allowed,
3462                                          enum bpf_access_src type,
3463                                          struct bpf_call_arg_meta *meta);
3464
3465 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3466 {
3467         return cur_regs(env) + regno;
3468 }
3469
3470 /* Read the stack at 'ptr_regno + off' and put the result into the register
3471  * 'dst_regno'.
3472  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3473  * but not its variable offset.
3474  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3475  *
3476  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3477  * filling registers (i.e. reads of spilled register cannot be detected when
3478  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3479  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3480  * offset; for a fixed offset check_stack_read_fixed_off should be used
3481  * instead.
3482  */
3483 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3484                                     int ptr_regno, int off, int size, int dst_regno)
3485 {
3486         /* The state of the source register. */
3487         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3488         struct bpf_func_state *ptr_state = func(env, reg);
3489         int err;
3490         int min_off, max_off;
3491
3492         /* Note that we pass a NULL meta, so raw access will not be permitted.
3493          */
3494         err = check_stack_range_initialized(env, ptr_regno, off, size,
3495                                             false, ACCESS_DIRECT, NULL);
3496         if (err)
3497                 return err;
3498
3499         min_off = reg->smin_value + off;
3500         max_off = reg->smax_value + off;
3501         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3502         return 0;
3503 }
3504
3505 /* check_stack_read dispatches to check_stack_read_fixed_off or
3506  * check_stack_read_var_off.
3507  *
3508  * The caller must ensure that the offset falls within the allocated stack
3509  * bounds.
3510  *
3511  * 'dst_regno' is a register which will receive the value from the stack. It
3512  * can be -1, meaning that the read value is not going to a register.
3513  */
3514 static int check_stack_read(struct bpf_verifier_env *env,
3515                             int ptr_regno, int off, int size,
3516                             int dst_regno)
3517 {
3518         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3519         struct bpf_func_state *state = func(env, reg);
3520         int err;
3521         /* Some accesses are only permitted with a static offset. */
3522         bool var_off = !tnum_is_const(reg->var_off);
3523
3524         /* The offset is required to be static when reads don't go to a
3525          * register, in order to not leak pointers (see
3526          * check_stack_read_fixed_off).
3527          */
3528         if (dst_regno < 0 && var_off) {
3529                 char tn_buf[48];
3530
3531                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3532                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3533                         tn_buf, off, size);
3534                 return -EACCES;
3535         }
3536         /* Variable offset is prohibited for unprivileged mode for simplicity
3537          * since it requires corresponding support in Spectre masking for stack
3538          * ALU. See also retrieve_ptr_limit(). The check in
3539          * check_stack_access_for_ptr_arithmetic() called by
3540          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
3541          * with variable offsets, therefore no check is required here. Further,
3542          * just checking it here would be insufficient as speculative stack
3543          * writes could still lead to unsafe speculative behaviour.
3544          */
3545         if (!var_off) {
3546                 off += reg->var_off.value;
3547                 err = check_stack_read_fixed_off(env, state, off, size,
3548                                                  dst_regno);
3549         } else {
3550                 /* Variable offset stack reads need more conservative handling
3551                  * than fixed offset ones. Note that dst_regno >= 0 on this
3552                  * branch.
3553                  */
3554                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3555                                                dst_regno);
3556         }
3557         return err;
3558 }
3559
3560
3561 /* check_stack_write dispatches to check_stack_write_fixed_off or
3562  * check_stack_write_var_off.
3563  *
3564  * 'ptr_regno' is the register used as a pointer into the stack.
3565  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3566  * 'value_regno' is the register whose value we're writing to the stack. It can
3567  * be -1, meaning that we're not writing from a register.
3568  *
3569  * The caller must ensure that the offset falls within the maximum stack size.
3570  */
3571 static int check_stack_write(struct bpf_verifier_env *env,
3572                              int ptr_regno, int off, int size,
3573                              int value_regno, int insn_idx)
3574 {
3575         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3576         struct bpf_func_state *state = func(env, reg);
3577         int err;
3578
3579         if (tnum_is_const(reg->var_off)) {
3580                 off += reg->var_off.value;
3581                 err = check_stack_write_fixed_off(env, state, off, size,
3582                                                   value_regno, insn_idx);
3583         } else {
3584                 /* Variable offset stack reads need more conservative handling
3585                  * than fixed offset ones.
3586                  */
3587                 err = check_stack_write_var_off(env, state,
3588                                                 ptr_regno, off, size,
3589                                                 value_regno, insn_idx);
3590         }
3591         return err;
3592 }
3593
3594 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3595                                  int off, int size, enum bpf_access_type type)
3596 {
3597         struct bpf_reg_state *regs = cur_regs(env);
3598         struct bpf_map *map = regs[regno].map_ptr;
3599         u32 cap = bpf_map_flags_to_cap(map);
3600
3601         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3602                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3603                         map->value_size, off, size);
3604                 return -EACCES;
3605         }
3606
3607         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3608                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3609                         map->value_size, off, size);
3610                 return -EACCES;
3611         }
3612
3613         return 0;
3614 }
3615
3616 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3617 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3618                               int off, int size, u32 mem_size,
3619                               bool zero_size_allowed)
3620 {
3621         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3622         struct bpf_reg_state *reg;
3623
3624         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3625                 return 0;
3626
3627         reg = &cur_regs(env)[regno];
3628         switch (reg->type) {
3629         case PTR_TO_MAP_KEY:
3630                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3631                         mem_size, off, size);
3632                 break;
3633         case PTR_TO_MAP_VALUE:
3634                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3635                         mem_size, off, size);
3636                 break;
3637         case PTR_TO_PACKET:
3638         case PTR_TO_PACKET_META:
3639         case PTR_TO_PACKET_END:
3640                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3641                         off, size, regno, reg->id, off, mem_size);
3642                 break;
3643         case PTR_TO_MEM:
3644         default:
3645                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3646                         mem_size, off, size);
3647         }
3648
3649         return -EACCES;
3650 }
3651
3652 /* check read/write into a memory region with possible variable offset */
3653 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3654                                    int off, int size, u32 mem_size,
3655                                    bool zero_size_allowed)
3656 {
3657         struct bpf_verifier_state *vstate = env->cur_state;
3658         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3659         struct bpf_reg_state *reg = &state->regs[regno];
3660         int err;
3661
3662         /* We may have adjusted the register pointing to memory region, so we
3663          * need to try adding each of min_value and max_value to off
3664          * to make sure our theoretical access will be safe.
3665          *
3666          * The minimum value is only important with signed
3667          * comparisons where we can't assume the floor of a
3668          * value is 0.  If we are using signed variables for our
3669          * index'es we need to make sure that whatever we use
3670          * will have a set floor within our range.
3671          */
3672         if (reg->smin_value < 0 &&
3673             (reg->smin_value == S64_MIN ||
3674              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3675               reg->smin_value + off < 0)) {
3676                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3677                         regno);
3678                 return -EACCES;
3679         }
3680         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3681                                  mem_size, zero_size_allowed);
3682         if (err) {
3683                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3684                         regno);
3685                 return err;
3686         }
3687
3688         /* If we haven't set a max value then we need to bail since we can't be
3689          * sure we won't do bad things.
3690          * If reg->umax_value + off could overflow, treat that as unbounded too.
3691          */
3692         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3693                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3694                         regno);
3695                 return -EACCES;
3696         }
3697         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3698                                  mem_size, zero_size_allowed);
3699         if (err) {
3700                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3701                         regno);
3702                 return err;
3703         }
3704
3705         return 0;
3706 }
3707
3708 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3709                                const struct bpf_reg_state *reg, int regno,
3710                                bool fixed_off_ok)
3711 {
3712         /* Access to this pointer-typed register or passing it to a helper
3713          * is only allowed in its original, unmodified form.
3714          */
3715
3716         if (reg->off < 0) {
3717                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3718                         reg_type_str(env, reg->type), regno, reg->off);
3719                 return -EACCES;
3720         }
3721
3722         if (!fixed_off_ok && reg->off) {
3723                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3724                         reg_type_str(env, reg->type), regno, reg->off);
3725                 return -EACCES;
3726         }
3727
3728         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3729                 char tn_buf[48];
3730
3731                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3732                 verbose(env, "variable %s access var_off=%s disallowed\n",
3733                         reg_type_str(env, reg->type), tn_buf);
3734                 return -EACCES;
3735         }
3736
3737         return 0;
3738 }
3739
3740 int check_ptr_off_reg(struct bpf_verifier_env *env,
3741                       const struct bpf_reg_state *reg, int regno)
3742 {
3743         return __check_ptr_off_reg(env, reg, regno, false);
3744 }
3745
3746 static int map_kptr_match_type(struct bpf_verifier_env *env,
3747                                struct bpf_map_value_off_desc *off_desc,
3748                                struct bpf_reg_state *reg, u32 regno)
3749 {
3750         const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3751         int perm_flags = PTR_MAYBE_NULL;
3752         const char *reg_name = "";
3753
3754         /* Only unreferenced case accepts untrusted pointers */
3755         if (off_desc->type == BPF_KPTR_UNREF)
3756                 perm_flags |= PTR_UNTRUSTED;
3757
3758         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3759                 goto bad_type;
3760
3761         if (!btf_is_kernel(reg->btf)) {
3762                 verbose(env, "R%d must point to kernel BTF\n", regno);
3763                 return -EINVAL;
3764         }
3765         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3766         reg_name = kernel_type_name(reg->btf, reg->btf_id);
3767
3768         /* For ref_ptr case, release function check should ensure we get one
3769          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3770          * normal store of unreferenced kptr, we must ensure var_off is zero.
3771          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3772          * reg->off and reg->ref_obj_id are not needed here.
3773          */
3774         if (__check_ptr_off_reg(env, reg, regno, true))
3775                 return -EACCES;
3776
3777         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3778          * we also need to take into account the reg->off.
3779          *
3780          * We want to support cases like:
3781          *
3782          * struct foo {
3783          *         struct bar br;
3784          *         struct baz bz;
3785          * };
3786          *
3787          * struct foo *v;
3788          * v = func();        // PTR_TO_BTF_ID
3789          * val->foo = v;      // reg->off is zero, btf and btf_id match type
3790          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3791          *                    // first member type of struct after comparison fails
3792          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3793          *                    // to match type
3794          *
3795          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3796          * is zero. We must also ensure that btf_struct_ids_match does not walk
3797          * the struct to match type against first member of struct, i.e. reject
3798          * second case from above. Hence, when type is BPF_KPTR_REF, we set
3799          * strict mode to true for type match.
3800          */
3801         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3802                                   off_desc->kptr.btf, off_desc->kptr.btf_id,
3803                                   off_desc->type == BPF_KPTR_REF))
3804                 goto bad_type;
3805         return 0;
3806 bad_type:
3807         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3808                 reg_type_str(env, reg->type), reg_name);
3809         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3810         if (off_desc->type == BPF_KPTR_UNREF)
3811                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3812                         targ_name);
3813         else
3814                 verbose(env, "\n");
3815         return -EINVAL;
3816 }
3817
3818 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3819                                  int value_regno, int insn_idx,
3820                                  struct bpf_map_value_off_desc *off_desc)
3821 {
3822         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3823         int class = BPF_CLASS(insn->code);
3824         struct bpf_reg_state *val_reg;
3825
3826         /* Things we already checked for in check_map_access and caller:
3827          *  - Reject cases where variable offset may touch kptr
3828          *  - size of access (must be BPF_DW)
3829          *  - tnum_is_const(reg->var_off)
3830          *  - off_desc->offset == off + reg->var_off.value
3831          */
3832         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3833         if (BPF_MODE(insn->code) != BPF_MEM) {
3834                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3835                 return -EACCES;
3836         }
3837
3838         /* We only allow loading referenced kptr, since it will be marked as
3839          * untrusted, similar to unreferenced kptr.
3840          */
3841         if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3842                 verbose(env, "store to referenced kptr disallowed\n");
3843                 return -EACCES;
3844         }
3845
3846         if (class == BPF_LDX) {
3847                 val_reg = reg_state(env, value_regno);
3848                 /* We can simply mark the value_regno receiving the pointer
3849                  * value from map as PTR_TO_BTF_ID, with the correct type.
3850                  */
3851                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3852                                 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3853                 /* For mark_ptr_or_null_reg */
3854                 val_reg->id = ++env->id_gen;
3855         } else if (class == BPF_STX) {
3856                 val_reg = reg_state(env, value_regno);
3857                 if (!register_is_null(val_reg) &&
3858                     map_kptr_match_type(env, off_desc, val_reg, value_regno))
3859                         return -EACCES;
3860         } else if (class == BPF_ST) {
3861                 if (insn->imm) {
3862                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3863                                 off_desc->offset);
3864                         return -EACCES;
3865                 }
3866         } else {
3867                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3868                 return -EACCES;
3869         }
3870         return 0;
3871 }
3872
3873 /* check read/write into a map element with possible variable offset */
3874 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3875                             int off, int size, bool zero_size_allowed,
3876                             enum bpf_access_src src)
3877 {
3878         struct bpf_verifier_state *vstate = env->cur_state;
3879         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3880         struct bpf_reg_state *reg = &state->regs[regno];
3881         struct bpf_map *map = reg->map_ptr;
3882         int err;
3883
3884         err = check_mem_region_access(env, regno, off, size, map->value_size,
3885                                       zero_size_allowed);
3886         if (err)
3887                 return err;
3888
3889         if (map_value_has_spin_lock(map)) {
3890                 u32 lock = map->spin_lock_off;
3891
3892                 /* if any part of struct bpf_spin_lock can be touched by
3893                  * load/store reject this program.
3894                  * To check that [x1, x2) overlaps with [y1, y2)
3895                  * it is sufficient to check x1 < y2 && y1 < x2.
3896                  */
3897                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3898                      lock < reg->umax_value + off + size) {
3899                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3900                         return -EACCES;
3901                 }
3902         }
3903         if (map_value_has_timer(map)) {
3904                 u32 t = map->timer_off;
3905
3906                 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3907                      t < reg->umax_value + off + size) {
3908                         verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3909                         return -EACCES;
3910                 }
3911         }
3912         if (map_value_has_kptrs(map)) {
3913                 struct bpf_map_value_off *tab = map->kptr_off_tab;
3914                 int i;
3915
3916                 for (i = 0; i < tab->nr_off; i++) {
3917                         u32 p = tab->off[i].offset;
3918
3919                         if (reg->smin_value + off < p + sizeof(u64) &&
3920                             p < reg->umax_value + off + size) {
3921                                 if (src != ACCESS_DIRECT) {
3922                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
3923                                         return -EACCES;
3924                                 }
3925                                 if (!tnum_is_const(reg->var_off)) {
3926                                         verbose(env, "kptr access cannot have variable offset\n");
3927                                         return -EACCES;
3928                                 }
3929                                 if (p != off + reg->var_off.value) {
3930                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3931                                                 p, off + reg->var_off.value);
3932                                         return -EACCES;
3933                                 }
3934                                 if (size != bpf_size_to_bytes(BPF_DW)) {
3935                                         verbose(env, "kptr access size must be BPF_DW\n");
3936                                         return -EACCES;
3937                                 }
3938                                 break;
3939                         }
3940                 }
3941         }
3942         return err;
3943 }
3944
3945 #define MAX_PACKET_OFF 0xffff
3946
3947 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3948                                        const struct bpf_call_arg_meta *meta,
3949                                        enum bpf_access_type t)
3950 {
3951         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3952
3953         switch (prog_type) {
3954         /* Program types only with direct read access go here! */
3955         case BPF_PROG_TYPE_LWT_IN:
3956         case BPF_PROG_TYPE_LWT_OUT:
3957         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3958         case BPF_PROG_TYPE_SK_REUSEPORT:
3959         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3960         case BPF_PROG_TYPE_CGROUP_SKB:
3961                 if (t == BPF_WRITE)
3962                         return false;
3963                 fallthrough;
3964
3965         /* Program types with direct read + write access go here! */
3966         case BPF_PROG_TYPE_SCHED_CLS:
3967         case BPF_PROG_TYPE_SCHED_ACT:
3968         case BPF_PROG_TYPE_XDP:
3969         case BPF_PROG_TYPE_LWT_XMIT:
3970         case BPF_PROG_TYPE_SK_SKB:
3971         case BPF_PROG_TYPE_SK_MSG:
3972                 if (meta)
3973                         return meta->pkt_access;
3974
3975                 env->seen_direct_write = true;
3976                 return true;
3977
3978         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3979                 if (t == BPF_WRITE)
3980                         env->seen_direct_write = true;
3981
3982                 return true;
3983
3984         default:
3985                 return false;
3986         }
3987 }
3988
3989 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3990                                int size, bool zero_size_allowed)
3991 {
3992         struct bpf_reg_state *regs = cur_regs(env);
3993         struct bpf_reg_state *reg = &regs[regno];
3994         int err;
3995
3996         /* We may have added a variable offset to the packet pointer; but any
3997          * reg->range we have comes after that.  We are only checking the fixed
3998          * offset.
3999          */
4000
4001         /* We don't allow negative numbers, because we aren't tracking enough
4002          * detail to prove they're safe.
4003          */
4004         if (reg->smin_value < 0) {
4005                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4006                         regno);
4007                 return -EACCES;
4008         }
4009
4010         err = reg->range < 0 ? -EINVAL :
4011               __check_mem_access(env, regno, off, size, reg->range,
4012                                  zero_size_allowed);
4013         if (err) {
4014                 verbose(env, "R%d offset is outside of the packet\n", regno);
4015                 return err;
4016         }
4017
4018         /* __check_mem_access has made sure "off + size - 1" is within u16.
4019          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4020          * otherwise find_good_pkt_pointers would have refused to set range info
4021          * that __check_mem_access would have rejected this pkt access.
4022          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4023          */
4024         env->prog->aux->max_pkt_offset =
4025                 max_t(u32, env->prog->aux->max_pkt_offset,
4026                       off + reg->umax_value + size - 1);
4027
4028         return err;
4029 }
4030
4031 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4032 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4033                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
4034                             struct btf **btf, u32 *btf_id)
4035 {
4036         struct bpf_insn_access_aux info = {
4037                 .reg_type = *reg_type,
4038                 .log = &env->log,
4039         };
4040
4041         if (env->ops->is_valid_access &&
4042             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4043                 /* A non zero info.ctx_field_size indicates that this field is a
4044                  * candidate for later verifier transformation to load the whole
4045                  * field and then apply a mask when accessed with a narrower
4046                  * access than actual ctx access size. A zero info.ctx_field_size
4047                  * will only allow for whole field access and rejects any other
4048                  * type of narrower access.
4049                  */
4050                 *reg_type = info.reg_type;
4051
4052                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4053                         *btf = info.btf;
4054                         *btf_id = info.btf_id;
4055                 } else {
4056                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4057                 }
4058                 /* remember the offset of last byte accessed in ctx */
4059                 if (env->prog->aux->max_ctx_offset < off + size)
4060                         env->prog->aux->max_ctx_offset = off + size;
4061                 return 0;
4062         }
4063
4064         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4065         return -EACCES;
4066 }
4067
4068 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4069                                   int size)
4070 {
4071         if (size < 0 || off < 0 ||
4072             (u64)off + size > sizeof(struct bpf_flow_keys)) {
4073                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4074                         off, size);
4075                 return -EACCES;
4076         }
4077         return 0;
4078 }
4079
4080 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4081                              u32 regno, int off, int size,
4082                              enum bpf_access_type t)
4083 {
4084         struct bpf_reg_state *regs = cur_regs(env);
4085         struct bpf_reg_state *reg = &regs[regno];
4086         struct bpf_insn_access_aux info = {};
4087         bool valid;
4088
4089         if (reg->smin_value < 0) {
4090                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4091                         regno);
4092                 return -EACCES;
4093         }
4094
4095         switch (reg->type) {
4096         case PTR_TO_SOCK_COMMON:
4097                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4098                 break;
4099         case PTR_TO_SOCKET:
4100                 valid = bpf_sock_is_valid_access(off, size, t, &info);
4101                 break;
4102         case PTR_TO_TCP_SOCK:
4103                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4104                 break;
4105         case PTR_TO_XDP_SOCK:
4106                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4107                 break;
4108         default:
4109                 valid = false;
4110         }
4111
4112
4113         if (valid) {
4114                 env->insn_aux_data[insn_idx].ctx_field_size =
4115                         info.ctx_field_size;
4116                 return 0;
4117         }
4118
4119         verbose(env, "R%d invalid %s access off=%d size=%d\n",
4120                 regno, reg_type_str(env, reg->type), off, size);
4121
4122         return -EACCES;
4123 }
4124
4125 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4126 {
4127         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4128 }
4129
4130 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4131 {
4132         const struct bpf_reg_state *reg = reg_state(env, regno);
4133
4134         return reg->type == PTR_TO_CTX;
4135 }
4136
4137 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4138 {
4139         const struct bpf_reg_state *reg = reg_state(env, regno);
4140
4141         return type_is_sk_pointer(reg->type);
4142 }
4143
4144 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4145 {
4146         const struct bpf_reg_state *reg = reg_state(env, regno);
4147
4148         return type_is_pkt_pointer(reg->type);
4149 }
4150
4151 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4152 {
4153         const struct bpf_reg_state *reg = reg_state(env, regno);
4154
4155         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4156         return reg->type == PTR_TO_FLOW_KEYS;
4157 }
4158
4159 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4160                                    const struct bpf_reg_state *reg,
4161                                    int off, int size, bool strict)
4162 {
4163         struct tnum reg_off;
4164         int ip_align;
4165
4166         /* Byte size accesses are always allowed. */
4167         if (!strict || size == 1)
4168                 return 0;
4169
4170         /* For platforms that do not have a Kconfig enabling
4171          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4172          * NET_IP_ALIGN is universally set to '2'.  And on platforms
4173          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4174          * to this code only in strict mode where we want to emulate
4175          * the NET_IP_ALIGN==2 checking.  Therefore use an
4176          * unconditional IP align value of '2'.
4177          */
4178         ip_align = 2;
4179
4180         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4181         if (!tnum_is_aligned(reg_off, size)) {
4182                 char tn_buf[48];
4183
4184                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4185                 verbose(env,
4186                         "misaligned packet access off %d+%s+%d+%d size %d\n",
4187                         ip_align, tn_buf, reg->off, off, size);
4188                 return -EACCES;
4189         }
4190
4191         return 0;
4192 }
4193
4194 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4195                                        const struct bpf_reg_state *reg,
4196                                        const char *pointer_desc,
4197                                        int off, int size, bool strict)
4198 {
4199         struct tnum reg_off;
4200
4201         /* Byte size accesses are always allowed. */
4202         if (!strict || size == 1)
4203                 return 0;
4204
4205         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4206         if (!tnum_is_aligned(reg_off, size)) {
4207                 char tn_buf[48];
4208
4209                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4210                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4211                         pointer_desc, tn_buf, reg->off, off, size);
4212                 return -EACCES;
4213         }
4214
4215         return 0;
4216 }
4217
4218 static int check_ptr_alignment(struct bpf_verifier_env *env,
4219                                const struct bpf_reg_state *reg, int off,
4220                                int size, bool strict_alignment_once)
4221 {
4222         bool strict = env->strict_alignment || strict_alignment_once;
4223         const char *pointer_desc = "";
4224
4225         switch (reg->type) {
4226         case PTR_TO_PACKET:
4227         case PTR_TO_PACKET_META:
4228                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4229                  * right in front, treat it the very same way.
4230                  */
4231                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4232         case PTR_TO_FLOW_KEYS:
4233                 pointer_desc = "flow keys ";
4234                 break;
4235         case PTR_TO_MAP_KEY:
4236                 pointer_desc = "key ";
4237                 break;
4238         case PTR_TO_MAP_VALUE:
4239                 pointer_desc = "value ";
4240                 break;
4241         case PTR_TO_CTX:
4242                 pointer_desc = "context ";
4243                 break;
4244         case PTR_TO_STACK:
4245                 pointer_desc = "stack ";
4246                 /* The stack spill tracking logic in check_stack_write_fixed_off()
4247                  * and check_stack_read_fixed_off() relies on stack accesses being
4248                  * aligned.
4249                  */
4250                 strict = true;
4251                 break;
4252         case PTR_TO_SOCKET:
4253                 pointer_desc = "sock ";
4254                 break;
4255         case PTR_TO_SOCK_COMMON:
4256                 pointer_desc = "sock_common ";
4257                 break;
4258         case PTR_TO_TCP_SOCK:
4259                 pointer_desc = "tcp_sock ";
4260                 break;
4261         case PTR_TO_XDP_SOCK:
4262                 pointer_desc = "xdp_sock ";
4263                 break;
4264         default:
4265                 break;
4266         }
4267         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4268                                            strict);
4269 }
4270
4271 static int update_stack_depth(struct bpf_verifier_env *env,
4272                               const struct bpf_func_state *func,
4273                               int off)
4274 {
4275         u16 stack = env->subprog_info[func->subprogno].stack_depth;
4276
4277         if (stack >= -off)
4278                 return 0;
4279
4280         /* update known max for given subprogram */
4281         env->subprog_info[func->subprogno].stack_depth = -off;
4282         return 0;
4283 }
4284
4285 /* starting from main bpf function walk all instructions of the function
4286  * and recursively walk all callees that given function can call.
4287  * Ignore jump and exit insns.
4288  * Since recursion is prevented by check_cfg() this algorithm
4289  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4290  */
4291 static int check_max_stack_depth(struct bpf_verifier_env *env)
4292 {
4293         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4294         struct bpf_subprog_info *subprog = env->subprog_info;
4295         struct bpf_insn *insn = env->prog->insnsi;
4296         bool tail_call_reachable = false;
4297         int ret_insn[MAX_CALL_FRAMES];
4298         int ret_prog[MAX_CALL_FRAMES];
4299         int j;
4300
4301 process_func:
4302         /* protect against potential stack overflow that might happen when
4303          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4304          * depth for such case down to 256 so that the worst case scenario
4305          * would result in 8k stack size (32 which is tailcall limit * 256 =
4306          * 8k).
4307          *
4308          * To get the idea what might happen, see an example:
4309          * func1 -> sub rsp, 128
4310          *  subfunc1 -> sub rsp, 256
4311          *  tailcall1 -> add rsp, 256
4312          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4313          *   subfunc2 -> sub rsp, 64
4314          *   subfunc22 -> sub rsp, 128
4315          *   tailcall2 -> add rsp, 128
4316          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4317          *
4318          * tailcall will unwind the current stack frame but it will not get rid
4319          * of caller's stack as shown on the example above.
4320          */
4321         if (idx && subprog[idx].has_tail_call && depth >= 256) {
4322                 verbose(env,
4323                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4324                         depth);
4325                 return -EACCES;
4326         }
4327         /* round up to 32-bytes, since this is granularity
4328          * of interpreter stack size
4329          */
4330         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4331         if (depth > MAX_BPF_STACK) {
4332                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4333                         frame + 1, depth);
4334                 return -EACCES;
4335         }
4336 continue_func:
4337         subprog_end = subprog[idx + 1].start;
4338         for (; i < subprog_end; i++) {
4339                 int next_insn;
4340
4341                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4342                         continue;
4343                 /* remember insn and function to return to */
4344                 ret_insn[frame] = i + 1;
4345                 ret_prog[frame] = idx;
4346
4347                 /* find the callee */
4348                 next_insn = i + insn[i].imm + 1;
4349                 idx = find_subprog(env, next_insn);
4350                 if (idx < 0) {
4351                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4352                                   next_insn);
4353                         return -EFAULT;
4354                 }
4355                 if (subprog[idx].is_async_cb) {
4356                         if (subprog[idx].has_tail_call) {
4357                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4358                                 return -EFAULT;
4359                         }
4360                          /* async callbacks don't increase bpf prog stack size */
4361                         continue;
4362                 }
4363                 i = next_insn;
4364
4365                 if (subprog[idx].has_tail_call)
4366                         tail_call_reachable = true;
4367
4368                 frame++;
4369                 if (frame >= MAX_CALL_FRAMES) {
4370                         verbose(env, "the call stack of %d frames is too deep !\n",
4371                                 frame);
4372                         return -E2BIG;
4373                 }
4374                 goto process_func;
4375         }
4376         /* if tail call got detected across bpf2bpf calls then mark each of the
4377          * currently present subprog frames as tail call reachable subprogs;
4378          * this info will be utilized by JIT so that we will be preserving the
4379          * tail call counter throughout bpf2bpf calls combined with tailcalls
4380          */
4381         if (tail_call_reachable)
4382                 for (j = 0; j < frame; j++)
4383                         subprog[ret_prog[j]].tail_call_reachable = true;
4384         if (subprog[0].tail_call_reachable)
4385                 env->prog->aux->tail_call_reachable = true;
4386
4387         /* end of for() loop means the last insn of the 'subprog'
4388          * was reached. Doesn't matter whether it was JA or EXIT
4389          */
4390         if (frame == 0)
4391                 return 0;
4392         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4393         frame--;
4394         i = ret_insn[frame];
4395         idx = ret_prog[frame];
4396         goto continue_func;
4397 }
4398
4399 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4400 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4401                                   const struct bpf_insn *insn, int idx)
4402 {
4403         int start = idx + insn->imm + 1, subprog;
4404
4405         subprog = find_subprog(env, start);
4406         if (subprog < 0) {
4407                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4408                           start);
4409                 return -EFAULT;
4410         }
4411         return env->subprog_info[subprog].stack_depth;
4412 }
4413 #endif
4414
4415 static int __check_buffer_access(struct bpf_verifier_env *env,
4416                                  const char *buf_info,
4417                                  const struct bpf_reg_state *reg,
4418                                  int regno, int off, int size)
4419 {
4420         if (off < 0) {
4421                 verbose(env,
4422                         "R%d invalid %s buffer access: off=%d, size=%d\n",
4423                         regno, buf_info, off, size);
4424                 return -EACCES;
4425         }
4426         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4427                 char tn_buf[48];
4428
4429                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4430                 verbose(env,
4431                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4432                         regno, off, tn_buf);
4433                 return -EACCES;
4434         }
4435
4436         return 0;
4437 }
4438
4439 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4440                                   const struct bpf_reg_state *reg,
4441                                   int regno, int off, int size)
4442 {
4443         int err;
4444
4445         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4446         if (err)
4447                 return err;
4448
4449         if (off + size > env->prog->aux->max_tp_access)
4450                 env->prog->aux->max_tp_access = off + size;
4451
4452         return 0;
4453 }
4454
4455 static int check_buffer_access(struct bpf_verifier_env *env,
4456                                const struct bpf_reg_state *reg,
4457                                int regno, int off, int size,
4458                                bool zero_size_allowed,
4459                                u32 *max_access)
4460 {
4461         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4462         int err;
4463
4464         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4465         if (err)
4466                 return err;
4467
4468         if (off + size > *max_access)
4469                 *max_access = off + size;
4470
4471         return 0;
4472 }
4473
4474 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4475 static void zext_32_to_64(struct bpf_reg_state *reg)
4476 {
4477         reg->var_off = tnum_subreg(reg->var_off);
4478         __reg_assign_32_into_64(reg);
4479 }
4480
4481 /* truncate register to smaller size (in bytes)
4482  * must be called with size < BPF_REG_SIZE
4483  */
4484 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4485 {
4486         u64 mask;
4487
4488         /* clear high bits in bit representation */
4489         reg->var_off = tnum_cast(reg->var_off, size);
4490
4491         /* fix arithmetic bounds */
4492         mask = ((u64)1 << (size * 8)) - 1;
4493         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4494                 reg->umin_value &= mask;
4495                 reg->umax_value &= mask;
4496         } else {
4497                 reg->umin_value = 0;
4498                 reg->umax_value = mask;
4499         }
4500         reg->smin_value = reg->umin_value;
4501         reg->smax_value = reg->umax_value;
4502
4503         /* If size is smaller than 32bit register the 32bit register
4504          * values are also truncated so we push 64-bit bounds into
4505          * 32-bit bounds. Above were truncated < 32-bits already.
4506          */
4507         if (size >= 4)
4508                 return;
4509         __reg_combine_64_into_32(reg);
4510 }
4511
4512 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4513 {
4514         /* A map is considered read-only if the following condition are true:
4515          *
4516          * 1) BPF program side cannot change any of the map content. The
4517          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4518          *    and was set at map creation time.
4519          * 2) The map value(s) have been initialized from user space by a
4520          *    loader and then "frozen", such that no new map update/delete
4521          *    operations from syscall side are possible for the rest of
4522          *    the map's lifetime from that point onwards.
4523          * 3) Any parallel/pending map update/delete operations from syscall
4524          *    side have been completed. Only after that point, it's safe to
4525          *    assume that map value(s) are immutable.
4526          */
4527         return (map->map_flags & BPF_F_RDONLY_PROG) &&
4528                READ_ONCE(map->frozen) &&
4529                !bpf_map_write_active(map);
4530 }
4531
4532 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4533 {
4534         void *ptr;
4535         u64 addr;
4536         int err;
4537
4538         err = map->ops->map_direct_value_addr(map, &addr, off);
4539         if (err)
4540                 return err;
4541         ptr = (void *)(long)addr + off;
4542
4543         switch (size) {
4544         case sizeof(u8):
4545                 *val = (u64)*(u8 *)ptr;
4546                 break;
4547         case sizeof(u16):
4548                 *val = (u64)*(u16 *)ptr;
4549                 break;
4550         case sizeof(u32):
4551                 *val = (u64)*(u32 *)ptr;
4552                 break;
4553         case sizeof(u64):
4554                 *val = *(u64 *)ptr;
4555                 break;
4556         default:
4557                 return -EINVAL;
4558         }
4559         return 0;
4560 }
4561
4562 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4563                                    struct bpf_reg_state *regs,
4564                                    int regno, int off, int size,
4565                                    enum bpf_access_type atype,
4566                                    int value_regno)
4567 {
4568         struct bpf_reg_state *reg = regs + regno;
4569         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4570         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4571         enum bpf_type_flag flag = 0;
4572         u32 btf_id;
4573         int ret;
4574
4575         if (off < 0) {
4576                 verbose(env,
4577                         "R%d is ptr_%s invalid negative access: off=%d\n",
4578                         regno, tname, off);
4579                 return -EACCES;
4580         }
4581         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4582                 char tn_buf[48];
4583
4584                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4585                 verbose(env,
4586                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4587                         regno, tname, off, tn_buf);
4588                 return -EACCES;
4589         }
4590
4591         if (reg->type & MEM_USER) {
4592                 verbose(env,
4593                         "R%d is ptr_%s access user memory: off=%d\n",
4594                         regno, tname, off);
4595                 return -EACCES;
4596         }
4597
4598         if (reg->type & MEM_PERCPU) {
4599                 verbose(env,
4600                         "R%d is ptr_%s access percpu memory: off=%d\n",
4601                         regno, tname, off);
4602                 return -EACCES;
4603         }
4604
4605         if (env->ops->btf_struct_access) {
4606                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4607                                                   off, size, atype, &btf_id, &flag);
4608         } else {
4609                 if (atype != BPF_READ) {
4610                         verbose(env, "only read is supported\n");
4611                         return -EACCES;
4612                 }
4613
4614                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4615                                         atype, &btf_id, &flag);
4616         }
4617
4618         if (ret < 0)
4619                 return ret;
4620
4621         /* If this is an untrusted pointer, all pointers formed by walking it
4622          * also inherit the untrusted flag.
4623          */
4624         if (type_flag(reg->type) & PTR_UNTRUSTED)
4625                 flag |= PTR_UNTRUSTED;
4626
4627         if (atype == BPF_READ && value_regno >= 0)
4628                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4629
4630         return 0;
4631 }
4632
4633 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4634                                    struct bpf_reg_state *regs,
4635                                    int regno, int off, int size,
4636                                    enum bpf_access_type atype,
4637                                    int value_regno)
4638 {
4639         struct bpf_reg_state *reg = regs + regno;
4640         struct bpf_map *map = reg->map_ptr;
4641         enum bpf_type_flag flag = 0;
4642         const struct btf_type *t;
4643         const char *tname;
4644         u32 btf_id;
4645         int ret;
4646
4647         if (!btf_vmlinux) {
4648                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4649                 return -ENOTSUPP;
4650         }
4651
4652         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4653                 verbose(env, "map_ptr access not supported for map type %d\n",
4654                         map->map_type);
4655                 return -ENOTSUPP;
4656         }
4657
4658         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4659         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4660
4661         if (!env->allow_ptr_to_map_access) {
4662                 verbose(env,
4663                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4664                         tname);
4665                 return -EPERM;
4666         }
4667
4668         if (off < 0) {
4669                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4670                         regno, tname, off);
4671                 return -EACCES;
4672         }
4673
4674         if (atype != BPF_READ) {
4675                 verbose(env, "only read from %s is supported\n", tname);
4676                 return -EACCES;
4677         }
4678
4679         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4680         if (ret < 0)
4681                 return ret;
4682
4683         if (value_regno >= 0)
4684                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4685
4686         return 0;
4687 }
4688
4689 /* Check that the stack access at the given offset is within bounds. The
4690  * maximum valid offset is -1.
4691  *
4692  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4693  * -state->allocated_stack for reads.
4694  */
4695 static int check_stack_slot_within_bounds(int off,
4696                                           struct bpf_func_state *state,
4697                                           enum bpf_access_type t)
4698 {
4699         int min_valid_off;
4700
4701         if (t == BPF_WRITE)
4702                 min_valid_off = -MAX_BPF_STACK;
4703         else
4704                 min_valid_off = -state->allocated_stack;
4705
4706         if (off < min_valid_off || off > -1)
4707                 return -EACCES;
4708         return 0;
4709 }
4710
4711 /* Check that the stack access at 'regno + off' falls within the maximum stack
4712  * bounds.
4713  *
4714  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4715  */
4716 static int check_stack_access_within_bounds(
4717                 struct bpf_verifier_env *env,
4718                 int regno, int off, int access_size,
4719                 enum bpf_access_src src, enum bpf_access_type type)
4720 {
4721         struct bpf_reg_state *regs = cur_regs(env);
4722         struct bpf_reg_state *reg = regs + regno;
4723         struct bpf_func_state *state = func(env, reg);
4724         int min_off, max_off;
4725         int err;
4726         char *err_extra;
4727
4728         if (src == ACCESS_HELPER)
4729                 /* We don't know if helpers are reading or writing (or both). */
4730                 err_extra = " indirect access to";
4731         else if (type == BPF_READ)
4732                 err_extra = " read from";
4733         else
4734                 err_extra = " write to";
4735
4736         if (tnum_is_const(reg->var_off)) {
4737                 min_off = reg->var_off.value + off;
4738                 if (access_size > 0)
4739                         max_off = min_off + access_size - 1;
4740                 else
4741                         max_off = min_off;
4742         } else {
4743                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4744                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4745                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4746                                 err_extra, regno);
4747                         return -EACCES;
4748                 }
4749                 min_off = reg->smin_value + off;
4750                 if (access_size > 0)
4751                         max_off = reg->smax_value + off + access_size - 1;
4752                 else
4753                         max_off = min_off;
4754         }
4755
4756         err = check_stack_slot_within_bounds(min_off, state, type);
4757         if (!err)
4758                 err = check_stack_slot_within_bounds(max_off, state, type);
4759
4760         if (err) {
4761                 if (tnum_is_const(reg->var_off)) {
4762                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4763                                 err_extra, regno, off, access_size);
4764                 } else {
4765                         char tn_buf[48];
4766
4767                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4768                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4769                                 err_extra, regno, tn_buf, access_size);
4770                 }
4771         }
4772         return err;
4773 }
4774
4775 /* check whether memory at (regno + off) is accessible for t = (read | write)
4776  * if t==write, value_regno is a register which value is stored into memory
4777  * if t==read, value_regno is a register which will receive the value from memory
4778  * if t==write && value_regno==-1, some unknown value is stored into memory
4779  * if t==read && value_regno==-1, don't care what we read from memory
4780  */
4781 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4782                             int off, int bpf_size, enum bpf_access_type t,
4783                             int value_regno, bool strict_alignment_once)
4784 {
4785         struct bpf_reg_state *regs = cur_regs(env);
4786         struct bpf_reg_state *reg = regs + regno;
4787         struct bpf_func_state *state;
4788         int size, err = 0;
4789
4790         size = bpf_size_to_bytes(bpf_size);
4791         if (size < 0)
4792                 return size;
4793
4794         /* alignment checks will add in reg->off themselves */
4795         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4796         if (err)
4797                 return err;
4798
4799         /* for access checks, reg->off is just part of off */
4800         off += reg->off;
4801
4802         if (reg->type == PTR_TO_MAP_KEY) {
4803                 if (t == BPF_WRITE) {
4804                         verbose(env, "write to change key R%d not allowed\n", regno);
4805                         return -EACCES;
4806                 }
4807
4808                 err = check_mem_region_access(env, regno, off, size,
4809                                               reg->map_ptr->key_size, false);
4810                 if (err)
4811                         return err;
4812                 if (value_regno >= 0)
4813                         mark_reg_unknown(env, regs, value_regno);
4814         } else if (reg->type == PTR_TO_MAP_VALUE) {
4815                 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4816
4817                 if (t == BPF_WRITE && value_regno >= 0 &&
4818                     is_pointer_value(env, value_regno)) {
4819                         verbose(env, "R%d leaks addr into map\n", value_regno);
4820                         return -EACCES;
4821                 }
4822                 err = check_map_access_type(env, regno, off, size, t);
4823                 if (err)
4824                         return err;
4825                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4826                 if (err)
4827                         return err;
4828                 if (tnum_is_const(reg->var_off))
4829                         kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4830                                                                   off + reg->var_off.value);
4831                 if (kptr_off_desc) {
4832                         err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4833                                                     kptr_off_desc);
4834                 } else if (t == BPF_READ && value_regno >= 0) {
4835                         struct bpf_map *map = reg->map_ptr;
4836
4837                         /* if map is read-only, track its contents as scalars */
4838                         if (tnum_is_const(reg->var_off) &&
4839                             bpf_map_is_rdonly(map) &&
4840                             map->ops->map_direct_value_addr) {
4841                                 int map_off = off + reg->var_off.value;
4842                                 u64 val = 0;
4843
4844                                 err = bpf_map_direct_read(map, map_off, size,
4845                                                           &val);
4846                                 if (err)
4847                                         return err;
4848
4849                                 regs[value_regno].type = SCALAR_VALUE;
4850                                 __mark_reg_known(&regs[value_regno], val);
4851                         } else {
4852                                 mark_reg_unknown(env, regs, value_regno);
4853                         }
4854                 }
4855         } else if (base_type(reg->type) == PTR_TO_MEM) {
4856                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4857
4858                 if (type_may_be_null(reg->type)) {
4859                         verbose(env, "R%d invalid mem access '%s'\n", regno,
4860                                 reg_type_str(env, reg->type));
4861                         return -EACCES;
4862                 }
4863
4864                 if (t == BPF_WRITE && rdonly_mem) {
4865                         verbose(env, "R%d cannot write into %s\n",
4866                                 regno, reg_type_str(env, reg->type));
4867                         return -EACCES;
4868                 }
4869
4870                 if (t == BPF_WRITE && value_regno >= 0 &&
4871                     is_pointer_value(env, value_regno)) {
4872                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4873                         return -EACCES;
4874                 }
4875
4876                 err = check_mem_region_access(env, regno, off, size,
4877                                               reg->mem_size, false);
4878                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4879                         mark_reg_unknown(env, regs, value_regno);
4880         } else if (reg->type == PTR_TO_CTX) {
4881                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4882                 struct btf *btf = NULL;
4883                 u32 btf_id = 0;
4884
4885                 if (t == BPF_WRITE && value_regno >= 0 &&
4886                     is_pointer_value(env, value_regno)) {
4887                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4888                         return -EACCES;
4889                 }
4890
4891                 err = check_ptr_off_reg(env, reg, regno);
4892                 if (err < 0)
4893                         return err;
4894
4895                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4896                                        &btf_id);
4897                 if (err)
4898                         verbose_linfo(env, insn_idx, "; ");
4899                 if (!err && t == BPF_READ && value_regno >= 0) {
4900                         /* ctx access returns either a scalar, or a
4901                          * PTR_TO_PACKET[_META,_END]. In the latter
4902                          * case, we know the offset is zero.
4903                          */
4904                         if (reg_type == SCALAR_VALUE) {
4905                                 mark_reg_unknown(env, regs, value_regno);
4906                         } else {
4907                                 mark_reg_known_zero(env, regs,
4908                                                     value_regno);
4909                                 if (type_may_be_null(reg_type))
4910                                         regs[value_regno].id = ++env->id_gen;
4911                                 /* A load of ctx field could have different
4912                                  * actual load size with the one encoded in the
4913                                  * insn. When the dst is PTR, it is for sure not
4914                                  * a sub-register.
4915                                  */
4916                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4917                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4918                                         regs[value_regno].btf = btf;
4919                                         regs[value_regno].btf_id = btf_id;
4920                                 }
4921                         }
4922                         regs[value_regno].type = reg_type;
4923                 }
4924
4925         } else if (reg->type == PTR_TO_STACK) {
4926                 /* Basic bounds checks. */
4927                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4928                 if (err)
4929                         return err;
4930
4931                 state = func(env, reg);
4932                 err = update_stack_depth(env, state, off);
4933                 if (err)
4934                         return err;
4935
4936                 if (t == BPF_READ)
4937                         err = check_stack_read(env, regno, off, size,
4938                                                value_regno);
4939                 else
4940                         err = check_stack_write(env, regno, off, size,
4941                                                 value_regno, insn_idx);
4942         } else if (reg_is_pkt_pointer(reg)) {
4943                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4944                         verbose(env, "cannot write into packet\n");
4945                         return -EACCES;
4946                 }
4947                 if (t == BPF_WRITE && value_regno >= 0 &&
4948                     is_pointer_value(env, value_regno)) {
4949                         verbose(env, "R%d leaks addr into packet\n",
4950                                 value_regno);
4951                         return -EACCES;
4952                 }
4953                 err = check_packet_access(env, regno, off, size, false);
4954                 if (!err && t == BPF_READ && value_regno >= 0)
4955                         mark_reg_unknown(env, regs, value_regno);
4956         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4957                 if (t == BPF_WRITE && value_regno >= 0 &&
4958                     is_pointer_value(env, value_regno)) {
4959                         verbose(env, "R%d leaks addr into flow keys\n",
4960                                 value_regno);
4961                         return -EACCES;
4962                 }
4963
4964                 err = check_flow_keys_access(env, off, size);
4965                 if (!err && t == BPF_READ && value_regno >= 0)
4966                         mark_reg_unknown(env, regs, value_regno);
4967         } else if (type_is_sk_pointer(reg->type)) {
4968                 if (t == BPF_WRITE) {
4969                         verbose(env, "R%d cannot write into %s\n",
4970                                 regno, reg_type_str(env, reg->type));
4971                         return -EACCES;
4972                 }
4973                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4974                 if (!err && value_regno >= 0)
4975                         mark_reg_unknown(env, regs, value_regno);
4976         } else if (reg->type == PTR_TO_TP_BUFFER) {
4977                 err = check_tp_buffer_access(env, reg, regno, off, size);
4978                 if (!err && t == BPF_READ && value_regno >= 0)
4979                         mark_reg_unknown(env, regs, value_regno);
4980         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4981                    !type_may_be_null(reg->type)) {
4982                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4983                                               value_regno);
4984         } else if (reg->type == CONST_PTR_TO_MAP) {
4985                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4986                                               value_regno);
4987         } else if (base_type(reg->type) == PTR_TO_BUF) {
4988                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4989                 u32 *max_access;
4990
4991                 if (rdonly_mem) {
4992                         if (t == BPF_WRITE) {
4993                                 verbose(env, "R%d cannot write into %s\n",
4994                                         regno, reg_type_str(env, reg->type));
4995                                 return -EACCES;
4996                         }
4997                         max_access = &env->prog->aux->max_rdonly_access;
4998                 } else {
4999                         max_access = &env->prog->aux->max_rdwr_access;
5000                 }
5001
5002                 err = check_buffer_access(env, reg, regno, off, size, false,
5003                                           max_access);
5004
5005                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5006                         mark_reg_unknown(env, regs, value_regno);
5007         } else {
5008                 verbose(env, "R%d invalid mem access '%s'\n", regno,
5009                         reg_type_str(env, reg->type));
5010                 return -EACCES;
5011         }
5012
5013         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5014             regs[value_regno].type == SCALAR_VALUE) {
5015                 /* b/h/w load zero-extends, mark upper bits as known 0 */
5016                 coerce_reg_to_size(&regs[value_regno], size);
5017         }
5018         return err;
5019 }
5020
5021 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5022 {
5023         int load_reg;
5024         int err;
5025
5026         switch (insn->imm) {
5027         case BPF_ADD:
5028         case BPF_ADD | BPF_FETCH:
5029         case BPF_AND:
5030         case BPF_AND | BPF_FETCH:
5031         case BPF_OR:
5032         case BPF_OR | BPF_FETCH:
5033         case BPF_XOR:
5034         case BPF_XOR | BPF_FETCH:
5035         case BPF_XCHG:
5036         case BPF_CMPXCHG:
5037                 break;
5038         default:
5039                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5040                 return -EINVAL;
5041         }
5042
5043         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5044                 verbose(env, "invalid atomic operand size\n");
5045                 return -EINVAL;
5046         }
5047
5048         /* check src1 operand */
5049         err = check_reg_arg(env, insn->src_reg, SRC_OP);
5050         if (err)
5051                 return err;
5052
5053         /* check src2 operand */
5054         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5055         if (err)
5056                 return err;
5057
5058         if (insn->imm == BPF_CMPXCHG) {
5059                 /* Check comparison of R0 with memory location */
5060                 const u32 aux_reg = BPF_REG_0;
5061
5062                 err = check_reg_arg(env, aux_reg, SRC_OP);
5063                 if (err)
5064                         return err;
5065
5066                 if (is_pointer_value(env, aux_reg)) {
5067                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
5068                         return -EACCES;
5069                 }
5070         }
5071
5072         if (is_pointer_value(env, insn->src_reg)) {
5073                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5074                 return -EACCES;
5075         }
5076
5077         if (is_ctx_reg(env, insn->dst_reg) ||
5078             is_pkt_reg(env, insn->dst_reg) ||
5079             is_flow_key_reg(env, insn->dst_reg) ||
5080             is_sk_reg(env, insn->dst_reg)) {
5081                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5082                         insn->dst_reg,
5083                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5084                 return -EACCES;
5085         }
5086
5087         if (insn->imm & BPF_FETCH) {
5088                 if (insn->imm == BPF_CMPXCHG)
5089                         load_reg = BPF_REG_0;
5090                 else
5091                         load_reg = insn->src_reg;
5092
5093                 /* check and record load of old value */
5094                 err = check_reg_arg(env, load_reg, DST_OP);
5095                 if (err)
5096                         return err;
5097         } else {
5098                 /* This instruction accesses a memory location but doesn't
5099                  * actually load it into a register.
5100                  */
5101                 load_reg = -1;
5102         }
5103
5104         /* Check whether we can read the memory, with second call for fetch
5105          * case to simulate the register fill.
5106          */
5107         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5108                                BPF_SIZE(insn->code), BPF_READ, -1, true);
5109         if (!err && load_reg >= 0)
5110                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5111                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
5112                                        true);
5113         if (err)
5114                 return err;
5115
5116         /* Check whether we can write into the same memory. */
5117         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5118                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5119         if (err)
5120                 return err;
5121
5122         return 0;
5123 }
5124
5125 /* When register 'regno' is used to read the stack (either directly or through
5126  * a helper function) make sure that it's within stack boundary and, depending
5127  * on the access type, that all elements of the stack are initialized.
5128  *
5129  * 'off' includes 'regno->off', but not its dynamic part (if any).
5130  *
5131  * All registers that have been spilled on the stack in the slots within the
5132  * read offsets are marked as read.
5133  */
5134 static int check_stack_range_initialized(
5135                 struct bpf_verifier_env *env, int regno, int off,
5136                 int access_size, bool zero_size_allowed,
5137                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5138 {
5139         struct bpf_reg_state *reg = reg_state(env, regno);
5140         struct bpf_func_state *state = func(env, reg);
5141         int err, min_off, max_off, i, j, slot, spi;
5142         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5143         enum bpf_access_type bounds_check_type;
5144         /* Some accesses can write anything into the stack, others are
5145          * read-only.
5146          */
5147         bool clobber = false;
5148
5149         if (access_size == 0 && !zero_size_allowed) {
5150                 verbose(env, "invalid zero-sized read\n");
5151                 return -EACCES;
5152         }
5153
5154         if (type == ACCESS_HELPER) {
5155                 /* The bounds checks for writes are more permissive than for
5156                  * reads. However, if raw_mode is not set, we'll do extra
5157                  * checks below.
5158                  */
5159                 bounds_check_type = BPF_WRITE;
5160                 clobber = true;
5161         } else {
5162                 bounds_check_type = BPF_READ;
5163         }
5164         err = check_stack_access_within_bounds(env, regno, off, access_size,
5165                                                type, bounds_check_type);
5166         if (err)
5167                 return err;
5168
5169
5170         if (tnum_is_const(reg->var_off)) {
5171                 min_off = max_off = reg->var_off.value + off;
5172         } else {
5173                 /* Variable offset is prohibited for unprivileged mode for
5174                  * simplicity since it requires corresponding support in
5175                  * Spectre masking for stack ALU.
5176                  * See also retrieve_ptr_limit().
5177                  */
5178                 if (!env->bypass_spec_v1) {
5179                         char tn_buf[48];
5180
5181                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5182                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5183                                 regno, err_extra, tn_buf);
5184                         return -EACCES;
5185                 }
5186                 /* Only initialized buffer on stack is allowed to be accessed
5187                  * with variable offset. With uninitialized buffer it's hard to
5188                  * guarantee that whole memory is marked as initialized on
5189                  * helper return since specific bounds are unknown what may
5190                  * cause uninitialized stack leaking.
5191                  */
5192                 if (meta && meta->raw_mode)
5193                         meta = NULL;
5194
5195                 min_off = reg->smin_value + off;
5196                 max_off = reg->smax_value + off;
5197         }
5198
5199         if (meta && meta->raw_mode) {
5200                 meta->access_size = access_size;
5201                 meta->regno = regno;
5202                 return 0;
5203         }
5204
5205         for (i = min_off; i < max_off + access_size; i++) {
5206                 u8 *stype;
5207
5208                 slot = -i - 1;
5209                 spi = slot / BPF_REG_SIZE;
5210                 if (state->allocated_stack <= slot)
5211                         goto err;
5212                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5213                 if (*stype == STACK_MISC)
5214                         goto mark;
5215                 if (*stype == STACK_ZERO) {
5216                         if (clobber) {
5217                                 /* helper can write anything into the stack */
5218                                 *stype = STACK_MISC;
5219                         }
5220                         goto mark;
5221                 }
5222
5223                 if (is_spilled_reg(&state->stack[spi]) &&
5224                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5225                      env->allow_ptr_leaks)) {
5226                         if (clobber) {
5227                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5228                                 for (j = 0; j < BPF_REG_SIZE; j++)
5229                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5230                         }
5231                         goto mark;
5232                 }
5233
5234 err:
5235                 if (tnum_is_const(reg->var_off)) {
5236                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5237                                 err_extra, regno, min_off, i - min_off, access_size);
5238                 } else {
5239                         char tn_buf[48];
5240
5241                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5242                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5243                                 err_extra, regno, tn_buf, i - min_off, access_size);
5244                 }
5245                 return -EACCES;
5246 mark:
5247                 /* reading any byte out of 8-byte 'spill_slot' will cause
5248                  * the whole slot to be marked as 'read'
5249                  */
5250                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5251                               state->stack[spi].spilled_ptr.parent,
5252                               REG_LIVE_READ64);
5253                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5254                  * be sure that whether stack slot is written to or not. Hence,
5255                  * we must still conservatively propagate reads upwards even if
5256                  * helper may write to the entire memory range.
5257                  */
5258         }
5259         return update_stack_depth(env, state, min_off);
5260 }
5261
5262 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5263                                    int access_size, bool zero_size_allowed,
5264                                    struct bpf_call_arg_meta *meta)
5265 {
5266         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5267         u32 *max_access;
5268
5269         switch (base_type(reg->type)) {
5270         case PTR_TO_PACKET:
5271         case PTR_TO_PACKET_META:
5272                 return check_packet_access(env, regno, reg->off, access_size,
5273                                            zero_size_allowed);
5274         case PTR_TO_MAP_KEY:
5275                 if (meta && meta->raw_mode) {
5276                         verbose(env, "R%d cannot write into %s\n", regno,
5277                                 reg_type_str(env, reg->type));
5278                         return -EACCES;
5279                 }
5280                 return check_mem_region_access(env, regno, reg->off, access_size,
5281                                                reg->map_ptr->key_size, false);
5282         case PTR_TO_MAP_VALUE:
5283                 if (check_map_access_type(env, regno, reg->off, access_size,
5284                                           meta && meta->raw_mode ? BPF_WRITE :
5285                                           BPF_READ))
5286                         return -EACCES;
5287                 return check_map_access(env, regno, reg->off, access_size,
5288                                         zero_size_allowed, ACCESS_HELPER);
5289         case PTR_TO_MEM:
5290                 if (type_is_rdonly_mem(reg->type)) {
5291                         if (meta && meta->raw_mode) {
5292                                 verbose(env, "R%d cannot write into %s\n", regno,
5293                                         reg_type_str(env, reg->type));
5294                                 return -EACCES;
5295                         }
5296                 }
5297                 return check_mem_region_access(env, regno, reg->off,
5298                                                access_size, reg->mem_size,
5299                                                zero_size_allowed);
5300         case PTR_TO_BUF:
5301                 if (type_is_rdonly_mem(reg->type)) {
5302                         if (meta && meta->raw_mode) {
5303                                 verbose(env, "R%d cannot write into %s\n", regno,
5304                                         reg_type_str(env, reg->type));
5305                                 return -EACCES;
5306                         }
5307
5308                         max_access = &env->prog->aux->max_rdonly_access;
5309                 } else {
5310                         max_access = &env->prog->aux->max_rdwr_access;
5311                 }
5312                 return check_buffer_access(env, reg, regno, reg->off,
5313                                            access_size, zero_size_allowed,
5314                                            max_access);
5315         case PTR_TO_STACK:
5316                 return check_stack_range_initialized(
5317                                 env,
5318                                 regno, reg->off, access_size,
5319                                 zero_size_allowed, ACCESS_HELPER, meta);
5320         case PTR_TO_CTX:
5321                 /* in case the function doesn't know how to access the context,
5322                  * (because we are in a program of type SYSCALL for example), we
5323                  * can not statically check its size.
5324                  * Dynamically check it now.
5325                  */
5326                 if (!env->ops->convert_ctx_access) {
5327                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5328                         int offset = access_size - 1;
5329
5330                         /* Allow zero-byte read from PTR_TO_CTX */
5331                         if (access_size == 0)
5332                                 return zero_size_allowed ? 0 : -EACCES;
5333
5334                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5335                                                 atype, -1, false);
5336                 }
5337
5338                 fallthrough;
5339         default: /* scalar_value or invalid ptr */
5340                 /* Allow zero-byte read from NULL, regardless of pointer type */
5341                 if (zero_size_allowed && access_size == 0 &&
5342                     register_is_null(reg))
5343                         return 0;
5344
5345                 verbose(env, "R%d type=%s ", regno,
5346                         reg_type_str(env, reg->type));
5347                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5348                 return -EACCES;
5349         }
5350 }
5351
5352 static int check_mem_size_reg(struct bpf_verifier_env *env,
5353                               struct bpf_reg_state *reg, u32 regno,
5354                               bool zero_size_allowed,
5355                               struct bpf_call_arg_meta *meta)
5356 {
5357         int err;
5358
5359         /* This is used to refine r0 return value bounds for helpers
5360          * that enforce this value as an upper bound on return values.
5361          * See do_refine_retval_range() for helpers that can refine
5362          * the return value. C type of helper is u32 so we pull register
5363          * bound from umax_value however, if negative verifier errors
5364          * out. Only upper bounds can be learned because retval is an
5365          * int type and negative retvals are allowed.
5366          */
5367         meta->msize_max_value = reg->umax_value;
5368
5369         /* The register is SCALAR_VALUE; the access check
5370          * happens using its boundaries.
5371          */
5372         if (!tnum_is_const(reg->var_off))
5373                 /* For unprivileged variable accesses, disable raw
5374                  * mode so that the program is required to
5375                  * initialize all the memory that the helper could
5376                  * just partially fill up.
5377                  */
5378                 meta = NULL;
5379
5380         if (reg->smin_value < 0) {
5381                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5382                         regno);
5383                 return -EACCES;
5384         }
5385
5386         if (reg->umin_value == 0) {
5387                 err = check_helper_mem_access(env, regno - 1, 0,
5388                                               zero_size_allowed,
5389                                               meta);
5390                 if (err)
5391                         return err;
5392         }
5393
5394         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5395                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5396                         regno);
5397                 return -EACCES;
5398         }
5399         err = check_helper_mem_access(env, regno - 1,
5400                                       reg->umax_value,
5401                                       zero_size_allowed, meta);
5402         if (!err)
5403                 err = mark_chain_precision(env, regno);
5404         return err;
5405 }
5406
5407 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5408                    u32 regno, u32 mem_size)
5409 {
5410         bool may_be_null = type_may_be_null(reg->type);
5411         struct bpf_reg_state saved_reg;
5412         struct bpf_call_arg_meta meta;
5413         int err;
5414
5415         if (register_is_null(reg))
5416                 return 0;
5417
5418         memset(&meta, 0, sizeof(meta));
5419         /* Assuming that the register contains a value check if the memory
5420          * access is safe. Temporarily save and restore the register's state as
5421          * the conversion shouldn't be visible to a caller.
5422          */
5423         if (may_be_null) {
5424                 saved_reg = *reg;
5425                 mark_ptr_not_null_reg(reg);
5426         }
5427
5428         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5429         /* Check access for BPF_WRITE */
5430         meta.raw_mode = true;
5431         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5432
5433         if (may_be_null)
5434                 *reg = saved_reg;
5435
5436         return err;
5437 }
5438
5439 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5440                              u32 regno)
5441 {
5442         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5443         bool may_be_null = type_may_be_null(mem_reg->type);
5444         struct bpf_reg_state saved_reg;
5445         struct bpf_call_arg_meta meta;
5446         int err;
5447
5448         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5449
5450         memset(&meta, 0, sizeof(meta));
5451
5452         if (may_be_null) {
5453                 saved_reg = *mem_reg;
5454                 mark_ptr_not_null_reg(mem_reg);
5455         }
5456
5457         err = check_mem_size_reg(env, reg, regno, true, &meta);
5458         /* Check access for BPF_WRITE */
5459         meta.raw_mode = true;
5460         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5461
5462         if (may_be_null)
5463                 *mem_reg = saved_reg;
5464         return err;
5465 }
5466
5467 /* Implementation details:
5468  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5469  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5470  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5471  * value_or_null->value transition, since the verifier only cares about
5472  * the range of access to valid map value pointer and doesn't care about actual
5473  * address of the map element.
5474  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5475  * reg->id > 0 after value_or_null->value transition. By doing so
5476  * two bpf_map_lookups will be considered two different pointers that
5477  * point to different bpf_spin_locks.
5478  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5479  * dead-locks.
5480  * Since only one bpf_spin_lock is allowed the checks are simpler than
5481  * reg_is_refcounted() logic. The verifier needs to remember only
5482  * one spin_lock instead of array of acquired_refs.
5483  * cur_state->active_spin_lock remembers which map value element got locked
5484  * and clears it after bpf_spin_unlock.
5485  */
5486 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5487                              bool is_lock)
5488 {
5489         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5490         struct bpf_verifier_state *cur = env->cur_state;
5491         bool is_const = tnum_is_const(reg->var_off);
5492         struct bpf_map *map = reg->map_ptr;
5493         u64 val = reg->var_off.value;
5494
5495         if (!is_const) {
5496                 verbose(env,
5497                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5498                         regno);
5499                 return -EINVAL;
5500         }
5501         if (!map->btf) {
5502                 verbose(env,
5503                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5504                         map->name);
5505                 return -EINVAL;
5506         }
5507         if (!map_value_has_spin_lock(map)) {
5508                 if (map->spin_lock_off == -E2BIG)
5509                         verbose(env,
5510                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5511                                 map->name);
5512                 else if (map->spin_lock_off == -ENOENT)
5513                         verbose(env,
5514                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5515                                 map->name);
5516                 else
5517                         verbose(env,
5518                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5519                                 map->name);
5520                 return -EINVAL;
5521         }
5522         if (map->spin_lock_off != val + reg->off) {
5523                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5524                         val + reg->off);
5525                 return -EINVAL;
5526         }
5527         if (is_lock) {
5528                 if (cur->active_spin_lock) {
5529                         verbose(env,
5530                                 "Locking two bpf_spin_locks are not allowed\n");
5531                         return -EINVAL;
5532                 }
5533                 cur->active_spin_lock = reg->id;
5534         } else {
5535                 if (!cur->active_spin_lock) {
5536                         verbose(env, "bpf_spin_unlock without taking a lock\n");
5537                         return -EINVAL;
5538                 }
5539                 if (cur->active_spin_lock != reg->id) {
5540                         verbose(env, "bpf_spin_unlock of different lock\n");
5541                         return -EINVAL;
5542                 }
5543                 cur->active_spin_lock = 0;
5544         }
5545         return 0;
5546 }
5547
5548 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5549                               struct bpf_call_arg_meta *meta)
5550 {
5551         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5552         bool is_const = tnum_is_const(reg->var_off);
5553         struct bpf_map *map = reg->map_ptr;
5554         u64 val = reg->var_off.value;
5555
5556         if (!is_const) {
5557                 verbose(env,
5558                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5559                         regno);
5560                 return -EINVAL;
5561         }
5562         if (!map->btf) {
5563                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5564                         map->name);
5565                 return -EINVAL;
5566         }
5567         if (!map_value_has_timer(map)) {
5568                 if (map->timer_off == -E2BIG)
5569                         verbose(env,
5570                                 "map '%s' has more than one 'struct bpf_timer'\n",
5571                                 map->name);
5572                 else if (map->timer_off == -ENOENT)
5573                         verbose(env,
5574                                 "map '%s' doesn't have 'struct bpf_timer'\n",
5575                                 map->name);
5576                 else
5577                         verbose(env,
5578                                 "map '%s' is not a struct type or bpf_timer is mangled\n",
5579                                 map->name);
5580                 return -EINVAL;
5581         }
5582         if (map->timer_off != val + reg->off) {
5583                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5584                         val + reg->off, map->timer_off);
5585                 return -EINVAL;
5586         }
5587         if (meta->map_ptr) {
5588                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5589                 return -EFAULT;
5590         }
5591         meta->map_uid = reg->map_uid;
5592         meta->map_ptr = map;
5593         return 0;
5594 }
5595
5596 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5597                              struct bpf_call_arg_meta *meta)
5598 {
5599         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5600         struct bpf_map_value_off_desc *off_desc;
5601         struct bpf_map *map_ptr = reg->map_ptr;
5602         u32 kptr_off;
5603         int ret;
5604
5605         if (!tnum_is_const(reg->var_off)) {
5606                 verbose(env,
5607                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5608                         regno);
5609                 return -EINVAL;
5610         }
5611         if (!map_ptr->btf) {
5612                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5613                         map_ptr->name);
5614                 return -EINVAL;
5615         }
5616         if (!map_value_has_kptrs(map_ptr)) {
5617                 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5618                 if (ret == -E2BIG)
5619                         verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5620                                 BPF_MAP_VALUE_OFF_MAX);
5621                 else if (ret == -EEXIST)
5622                         verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5623                 else
5624                         verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5625                 return -EINVAL;
5626         }
5627
5628         meta->map_ptr = map_ptr;
5629         kptr_off = reg->off + reg->var_off.value;
5630         off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5631         if (!off_desc) {
5632                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5633                 return -EACCES;
5634         }
5635         if (off_desc->type != BPF_KPTR_REF) {
5636                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5637                 return -EACCES;
5638         }
5639         meta->kptr_off_desc = off_desc;
5640         return 0;
5641 }
5642
5643 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5644 {
5645         return type == ARG_CONST_SIZE ||
5646                type == ARG_CONST_SIZE_OR_ZERO;
5647 }
5648
5649 static bool arg_type_is_release(enum bpf_arg_type type)
5650 {
5651         return type & OBJ_RELEASE;
5652 }
5653
5654 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5655 {
5656         return base_type(type) == ARG_PTR_TO_DYNPTR;
5657 }
5658
5659 static int int_ptr_type_to_size(enum bpf_arg_type type)
5660 {
5661         if (type == ARG_PTR_TO_INT)
5662                 return sizeof(u32);
5663         else if (type == ARG_PTR_TO_LONG)
5664                 return sizeof(u64);
5665
5666         return -EINVAL;
5667 }
5668
5669 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5670                                  const struct bpf_call_arg_meta *meta,
5671                                  enum bpf_arg_type *arg_type)
5672 {
5673         if (!meta->map_ptr) {
5674                 /* kernel subsystem misconfigured verifier */
5675                 verbose(env, "invalid map_ptr to access map->type\n");
5676                 return -EACCES;
5677         }
5678
5679         switch (meta->map_ptr->map_type) {
5680         case BPF_MAP_TYPE_SOCKMAP:
5681         case BPF_MAP_TYPE_SOCKHASH:
5682                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5683                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5684                 } else {
5685                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
5686                         return -EINVAL;
5687                 }
5688                 break;
5689         case BPF_MAP_TYPE_BLOOM_FILTER:
5690                 if (meta->func_id == BPF_FUNC_map_peek_elem)
5691                         *arg_type = ARG_PTR_TO_MAP_VALUE;
5692                 break;
5693         default:
5694                 break;
5695         }
5696         return 0;
5697 }
5698
5699 struct bpf_reg_types {
5700         const enum bpf_reg_type types[10];
5701         u32 *btf_id;
5702 };
5703
5704 static const struct bpf_reg_types map_key_value_types = {
5705         .types = {
5706                 PTR_TO_STACK,
5707                 PTR_TO_PACKET,
5708                 PTR_TO_PACKET_META,
5709                 PTR_TO_MAP_KEY,
5710                 PTR_TO_MAP_VALUE,
5711         },
5712 };
5713
5714 static const struct bpf_reg_types sock_types = {
5715         .types = {
5716                 PTR_TO_SOCK_COMMON,
5717                 PTR_TO_SOCKET,
5718                 PTR_TO_TCP_SOCK,
5719                 PTR_TO_XDP_SOCK,
5720         },
5721 };
5722
5723 #ifdef CONFIG_NET
5724 static const struct bpf_reg_types btf_id_sock_common_types = {
5725         .types = {
5726                 PTR_TO_SOCK_COMMON,
5727                 PTR_TO_SOCKET,
5728                 PTR_TO_TCP_SOCK,
5729                 PTR_TO_XDP_SOCK,
5730                 PTR_TO_BTF_ID,
5731         },
5732         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5733 };
5734 #endif
5735
5736 static const struct bpf_reg_types mem_types = {
5737         .types = {
5738                 PTR_TO_STACK,
5739                 PTR_TO_PACKET,
5740                 PTR_TO_PACKET_META,
5741                 PTR_TO_MAP_KEY,
5742                 PTR_TO_MAP_VALUE,
5743                 PTR_TO_MEM,
5744                 PTR_TO_MEM | MEM_ALLOC,
5745                 PTR_TO_BUF,
5746         },
5747 };
5748
5749 static const struct bpf_reg_types int_ptr_types = {
5750         .types = {
5751                 PTR_TO_STACK,
5752                 PTR_TO_PACKET,
5753                 PTR_TO_PACKET_META,
5754                 PTR_TO_MAP_KEY,
5755                 PTR_TO_MAP_VALUE,
5756         },
5757 };
5758
5759 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5760 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5761 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5762 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5763 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5764 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5765 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5766 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5767 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5768 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5769 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5770 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5771 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5772 static const struct bpf_reg_types dynptr_types = {
5773         .types = {
5774                 PTR_TO_STACK,
5775                 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5776         }
5777 };
5778
5779 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5780         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
5781         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
5782         [ARG_CONST_SIZE]                = &scalar_types,
5783         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
5784         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
5785         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
5786         [ARG_PTR_TO_CTX]                = &context_types,
5787         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
5788 #ifdef CONFIG_NET
5789         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5790 #endif
5791         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
5792         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
5793         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
5794         [ARG_PTR_TO_MEM]                = &mem_types,
5795         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
5796         [ARG_PTR_TO_INT]                = &int_ptr_types,
5797         [ARG_PTR_TO_LONG]               = &int_ptr_types,
5798         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
5799         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
5800         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
5801         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
5802         [ARG_PTR_TO_TIMER]              = &timer_types,
5803         [ARG_PTR_TO_KPTR]               = &kptr_types,
5804         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
5805 };
5806
5807 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5808                           enum bpf_arg_type arg_type,
5809                           const u32 *arg_btf_id,
5810                           struct bpf_call_arg_meta *meta)
5811 {
5812         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5813         enum bpf_reg_type expected, type = reg->type;
5814         const struct bpf_reg_types *compatible;
5815         int i, j;
5816
5817         compatible = compatible_reg_types[base_type(arg_type)];
5818         if (!compatible) {
5819                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5820                 return -EFAULT;
5821         }
5822
5823         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5824          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5825          *
5826          * Same for MAYBE_NULL:
5827          *
5828          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5829          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5830          *
5831          * Therefore we fold these flags depending on the arg_type before comparison.
5832          */
5833         if (arg_type & MEM_RDONLY)
5834                 type &= ~MEM_RDONLY;
5835         if (arg_type & PTR_MAYBE_NULL)
5836                 type &= ~PTR_MAYBE_NULL;
5837
5838         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5839                 expected = compatible->types[i];
5840                 if (expected == NOT_INIT)
5841                         break;
5842
5843                 if (type == expected)
5844                         goto found;
5845         }
5846
5847         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5848         for (j = 0; j + 1 < i; j++)
5849                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5850         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5851         return -EACCES;
5852
5853 found:
5854         if (reg->type == PTR_TO_BTF_ID) {
5855                 /* For bpf_sk_release, it needs to match against first member
5856                  * 'struct sock_common', hence make an exception for it. This
5857                  * allows bpf_sk_release to work for multiple socket types.
5858                  */
5859                 bool strict_type_match = arg_type_is_release(arg_type) &&
5860                                          meta->func_id != BPF_FUNC_sk_release;
5861
5862                 if (!arg_btf_id) {
5863                         if (!compatible->btf_id) {
5864                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5865                                 return -EFAULT;
5866                         }
5867                         arg_btf_id = compatible->btf_id;
5868                 }
5869
5870                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5871                         if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5872                                 return -EACCES;
5873                 } else {
5874                         if (arg_btf_id == BPF_PTR_POISON) {
5875                                 verbose(env, "verifier internal error:");
5876                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5877                                         regno);
5878                                 return -EACCES;
5879                         }
5880
5881                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5882                                                   btf_vmlinux, *arg_btf_id,
5883                                                   strict_type_match)) {
5884                                 verbose(env, "R%d is of type %s but %s is expected\n",
5885                                         regno, kernel_type_name(reg->btf, reg->btf_id),
5886                                         kernel_type_name(btf_vmlinux, *arg_btf_id));
5887                                 return -EACCES;
5888                         }
5889                 }
5890         }
5891
5892         return 0;
5893 }
5894
5895 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5896                            const struct bpf_reg_state *reg, int regno,
5897                            enum bpf_arg_type arg_type)
5898 {
5899         enum bpf_reg_type type = reg->type;
5900         bool fixed_off_ok = false;
5901
5902         switch ((u32)type) {
5903         /* Pointer types where reg offset is explicitly allowed: */
5904         case PTR_TO_STACK:
5905                 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5906                         verbose(env, "cannot pass in dynptr at an offset\n");
5907                         return -EINVAL;
5908                 }
5909                 fallthrough;
5910         case PTR_TO_PACKET:
5911         case PTR_TO_PACKET_META:
5912         case PTR_TO_MAP_KEY:
5913         case PTR_TO_MAP_VALUE:
5914         case PTR_TO_MEM:
5915         case PTR_TO_MEM | MEM_RDONLY:
5916         case PTR_TO_MEM | MEM_ALLOC:
5917         case PTR_TO_BUF:
5918         case PTR_TO_BUF | MEM_RDONLY:
5919         case SCALAR_VALUE:
5920                 /* Some of the argument types nevertheless require a
5921                  * zero register offset.
5922                  */
5923                 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5924                         return 0;
5925                 break;
5926         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5927          * fixed offset.
5928          */
5929         case PTR_TO_BTF_ID:
5930                 /* When referenced PTR_TO_BTF_ID is passed to release function,
5931                  * it's fixed offset must be 0. In the other cases, fixed offset
5932                  * can be non-zero.
5933                  */
5934                 if (arg_type_is_release(arg_type) && reg->off) {
5935                         verbose(env, "R%d must have zero offset when passed to release func\n",
5936                                 regno);
5937                         return -EINVAL;
5938                 }
5939                 /* For arg is release pointer, fixed_off_ok must be false, but
5940                  * we already checked and rejected reg->off != 0 above, so set
5941                  * to true to allow fixed offset for all other cases.
5942                  */
5943                 fixed_off_ok = true;
5944                 break;
5945         default:
5946                 break;
5947         }
5948         return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5949 }
5950
5951 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5952 {
5953         struct bpf_func_state *state = func(env, reg);
5954         int spi = get_spi(reg->off);
5955
5956         return state->stack[spi].spilled_ptr.id;
5957 }
5958
5959 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5960                           struct bpf_call_arg_meta *meta,
5961                           const struct bpf_func_proto *fn)
5962 {
5963         u32 regno = BPF_REG_1 + arg;
5964         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5965         enum bpf_arg_type arg_type = fn->arg_type[arg];
5966         enum bpf_reg_type type = reg->type;
5967         u32 *arg_btf_id = NULL;
5968         int err = 0;
5969
5970         if (arg_type == ARG_DONTCARE)
5971                 return 0;
5972
5973         err = check_reg_arg(env, regno, SRC_OP);
5974         if (err)
5975                 return err;
5976
5977         if (arg_type == ARG_ANYTHING) {
5978                 if (is_pointer_value(env, regno)) {
5979                         verbose(env, "R%d leaks addr into helper function\n",
5980                                 regno);
5981                         return -EACCES;
5982                 }
5983                 return 0;
5984         }
5985
5986         if (type_is_pkt_pointer(type) &&
5987             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5988                 verbose(env, "helper access to the packet is not allowed\n");
5989                 return -EACCES;
5990         }
5991
5992         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5993                 err = resolve_map_arg_type(env, meta, &arg_type);
5994                 if (err)
5995                         return err;
5996         }
5997
5998         if (register_is_null(reg) && type_may_be_null(arg_type))
5999                 /* A NULL register has a SCALAR_VALUE type, so skip
6000                  * type checking.
6001                  */
6002                 goto skip_type_check;
6003
6004         /* arg_btf_id and arg_size are in a union. */
6005         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
6006                 arg_btf_id = fn->arg_btf_id[arg];
6007
6008         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6009         if (err)
6010                 return err;
6011
6012         err = check_func_arg_reg_off(env, reg, regno, arg_type);
6013         if (err)
6014                 return err;
6015
6016 skip_type_check:
6017         if (arg_type_is_release(arg_type)) {
6018                 if (arg_type_is_dynptr(arg_type)) {
6019                         struct bpf_func_state *state = func(env, reg);
6020                         int spi = get_spi(reg->off);
6021
6022                         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6023                             !state->stack[spi].spilled_ptr.id) {
6024                                 verbose(env, "arg %d is an unacquired reference\n", regno);
6025                                 return -EINVAL;
6026                         }
6027                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6028                         verbose(env, "R%d must be referenced when passed to release function\n",
6029                                 regno);
6030                         return -EINVAL;
6031                 }
6032                 if (meta->release_regno) {
6033                         verbose(env, "verifier internal error: more than one release argument\n");
6034                         return -EFAULT;
6035                 }
6036                 meta->release_regno = regno;
6037         }
6038
6039         if (reg->ref_obj_id) {
6040                 if (meta->ref_obj_id) {
6041                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6042                                 regno, reg->ref_obj_id,
6043                                 meta->ref_obj_id);
6044                         return -EFAULT;
6045                 }
6046                 meta->ref_obj_id = reg->ref_obj_id;
6047         }
6048
6049         switch (base_type(arg_type)) {
6050         case ARG_CONST_MAP_PTR:
6051                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6052                 if (meta->map_ptr) {
6053                         /* Use map_uid (which is unique id of inner map) to reject:
6054                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6055                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6056                          * if (inner_map1 && inner_map2) {
6057                          *     timer = bpf_map_lookup_elem(inner_map1);
6058                          *     if (timer)
6059                          *         // mismatch would have been allowed
6060                          *         bpf_timer_init(timer, inner_map2);
6061                          * }
6062                          *
6063                          * Comparing map_ptr is enough to distinguish normal and outer maps.
6064                          */
6065                         if (meta->map_ptr != reg->map_ptr ||
6066                             meta->map_uid != reg->map_uid) {
6067                                 verbose(env,
6068                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6069                                         meta->map_uid, reg->map_uid);
6070                                 return -EINVAL;
6071                         }
6072                 }
6073                 meta->map_ptr = reg->map_ptr;
6074                 meta->map_uid = reg->map_uid;
6075                 break;
6076         case ARG_PTR_TO_MAP_KEY:
6077                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6078                  * check that [key, key + map->key_size) are within
6079                  * stack limits and initialized
6080                  */
6081                 if (!meta->map_ptr) {
6082                         /* in function declaration map_ptr must come before
6083                          * map_key, so that it's verified and known before
6084                          * we have to check map_key here. Otherwise it means
6085                          * that kernel subsystem misconfigured verifier
6086                          */
6087                         verbose(env, "invalid map_ptr to access map->key\n");
6088                         return -EACCES;
6089                 }
6090                 err = check_helper_mem_access(env, regno,
6091                                               meta->map_ptr->key_size, false,
6092                                               NULL);
6093                 break;
6094         case ARG_PTR_TO_MAP_VALUE:
6095                 if (type_may_be_null(arg_type) && register_is_null(reg))
6096                         return 0;
6097
6098                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6099                  * check [value, value + map->value_size) validity
6100                  */
6101                 if (!meta->map_ptr) {
6102                         /* kernel subsystem misconfigured verifier */
6103                         verbose(env, "invalid map_ptr to access map->value\n");
6104                         return -EACCES;
6105                 }
6106                 meta->raw_mode = arg_type & MEM_UNINIT;
6107                 err = check_helper_mem_access(env, regno,
6108                                               meta->map_ptr->value_size, false,
6109                                               meta);
6110                 break;
6111         case ARG_PTR_TO_PERCPU_BTF_ID:
6112                 if (!reg->btf_id) {
6113                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6114                         return -EACCES;
6115                 }
6116                 meta->ret_btf = reg->btf;
6117                 meta->ret_btf_id = reg->btf_id;
6118                 break;
6119         case ARG_PTR_TO_SPIN_LOCK:
6120                 if (meta->func_id == BPF_FUNC_spin_lock) {
6121                         if (process_spin_lock(env, regno, true))
6122                                 return -EACCES;
6123                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6124                         if (process_spin_lock(env, regno, false))
6125                                 return -EACCES;
6126                 } else {
6127                         verbose(env, "verifier internal error\n");
6128                         return -EFAULT;
6129                 }
6130                 break;
6131         case ARG_PTR_TO_TIMER:
6132                 if (process_timer_func(env, regno, meta))
6133                         return -EACCES;
6134                 break;
6135         case ARG_PTR_TO_FUNC:
6136                 meta->subprogno = reg->subprogno;
6137                 break;
6138         case ARG_PTR_TO_MEM:
6139                 /* The access to this pointer is only checked when we hit the
6140                  * next is_mem_size argument below.
6141                  */
6142                 meta->raw_mode = arg_type & MEM_UNINIT;
6143                 if (arg_type & MEM_FIXED_SIZE) {
6144                         err = check_helper_mem_access(env, regno,
6145                                                       fn->arg_size[arg], false,
6146                                                       meta);
6147                 }
6148                 break;
6149         case ARG_CONST_SIZE:
6150                 err = check_mem_size_reg(env, reg, regno, false, meta);
6151                 break;
6152         case ARG_CONST_SIZE_OR_ZERO:
6153                 err = check_mem_size_reg(env, reg, regno, true, meta);
6154                 break;
6155         case ARG_PTR_TO_DYNPTR:
6156                 /* We only need to check for initialized / uninitialized helper
6157                  * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6158                  * assumption is that if it is, that a helper function
6159                  * initialized the dynptr on behalf of the BPF program.
6160                  */
6161                 if (base_type(reg->type) == PTR_TO_DYNPTR)
6162                         break;
6163                 if (arg_type & MEM_UNINIT) {
6164                         if (!is_dynptr_reg_valid_uninit(env, reg)) {
6165                                 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6166                                 return -EINVAL;
6167                         }
6168
6169                         /* We only support one dynptr being uninitialized at the moment,
6170                          * which is sufficient for the helper functions we have right now.
6171                          */
6172                         if (meta->uninit_dynptr_regno) {
6173                                 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6174                                 return -EFAULT;
6175                         }
6176
6177                         meta->uninit_dynptr_regno = regno;
6178                 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6179                         verbose(env,
6180                                 "Expected an initialized dynptr as arg #%d\n",
6181                                 arg + 1);
6182                         return -EINVAL;
6183                 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6184                         const char *err_extra = "";
6185
6186                         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6187                         case DYNPTR_TYPE_LOCAL:
6188                                 err_extra = "local";
6189                                 break;
6190                         case DYNPTR_TYPE_RINGBUF:
6191                                 err_extra = "ringbuf";
6192                                 break;
6193                         default:
6194                                 err_extra = "<unknown>";
6195                                 break;
6196                         }
6197                         verbose(env,
6198                                 "Expected a dynptr of type %s as arg #%d\n",
6199                                 err_extra, arg + 1);
6200                         return -EINVAL;
6201                 }
6202                 break;
6203         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6204                 if (!tnum_is_const(reg->var_off)) {
6205                         verbose(env, "R%d is not a known constant'\n",
6206                                 regno);
6207                         return -EACCES;
6208                 }
6209                 meta->mem_size = reg->var_off.value;
6210                 err = mark_chain_precision(env, regno);
6211                 if (err)
6212                         return err;
6213                 break;
6214         case ARG_PTR_TO_INT:
6215         case ARG_PTR_TO_LONG:
6216         {
6217                 int size = int_ptr_type_to_size(arg_type);
6218
6219                 err = check_helper_mem_access(env, regno, size, false, meta);
6220                 if (err)
6221                         return err;
6222                 err = check_ptr_alignment(env, reg, 0, size, true);
6223                 break;
6224         }
6225         case ARG_PTR_TO_CONST_STR:
6226         {
6227                 struct bpf_map *map = reg->map_ptr;
6228                 int map_off;
6229                 u64 map_addr;
6230                 char *str_ptr;
6231
6232                 if (!bpf_map_is_rdonly(map)) {
6233                         verbose(env, "R%d does not point to a readonly map'\n", regno);
6234                         return -EACCES;
6235                 }
6236
6237                 if (!tnum_is_const(reg->var_off)) {
6238                         verbose(env, "R%d is not a constant address'\n", regno);
6239                         return -EACCES;
6240                 }
6241
6242                 if (!map->ops->map_direct_value_addr) {
6243                         verbose(env, "no direct value access support for this map type\n");
6244                         return -EACCES;
6245                 }
6246
6247                 err = check_map_access(env, regno, reg->off,
6248                                        map->value_size - reg->off, false,
6249                                        ACCESS_HELPER);
6250                 if (err)
6251                         return err;
6252
6253                 map_off = reg->off + reg->var_off.value;
6254                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6255                 if (err) {
6256                         verbose(env, "direct value access on string failed\n");
6257                         return err;
6258                 }
6259
6260                 str_ptr = (char *)(long)(map_addr);
6261                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6262                         verbose(env, "string is not zero-terminated\n");
6263                         return -EINVAL;
6264                 }
6265                 break;
6266         }
6267         case ARG_PTR_TO_KPTR:
6268                 if (process_kptr_func(env, regno, meta))
6269                         return -EACCES;
6270                 break;
6271         }
6272
6273         return err;
6274 }
6275
6276 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6277 {
6278         enum bpf_attach_type eatype = env->prog->expected_attach_type;
6279         enum bpf_prog_type type = resolve_prog_type(env->prog);
6280
6281         if (func_id != BPF_FUNC_map_update_elem)
6282                 return false;
6283
6284         /* It's not possible to get access to a locked struct sock in these
6285          * contexts, so updating is safe.
6286          */
6287         switch (type) {
6288         case BPF_PROG_TYPE_TRACING:
6289                 if (eatype == BPF_TRACE_ITER)
6290                         return true;
6291                 break;
6292         case BPF_PROG_TYPE_SOCKET_FILTER:
6293         case BPF_PROG_TYPE_SCHED_CLS:
6294         case BPF_PROG_TYPE_SCHED_ACT:
6295         case BPF_PROG_TYPE_XDP:
6296         case BPF_PROG_TYPE_SK_REUSEPORT:
6297         case BPF_PROG_TYPE_FLOW_DISSECTOR:
6298         case BPF_PROG_TYPE_SK_LOOKUP:
6299                 return true;
6300         default:
6301                 break;
6302         }
6303
6304         verbose(env, "cannot update sockmap in this context\n");
6305         return false;
6306 }
6307
6308 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6309 {
6310         return env->prog->jit_requested &&
6311                bpf_jit_supports_subprog_tailcalls();
6312 }
6313
6314 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6315                                         struct bpf_map *map, int func_id)
6316 {
6317         if (!map)
6318                 return 0;
6319
6320         /* We need a two way check, first is from map perspective ... */
6321         switch (map->map_type) {
6322         case BPF_MAP_TYPE_PROG_ARRAY:
6323                 if (func_id != BPF_FUNC_tail_call)
6324                         goto error;
6325                 break;
6326         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6327                 if (func_id != BPF_FUNC_perf_event_read &&
6328                     func_id != BPF_FUNC_perf_event_output &&
6329                     func_id != BPF_FUNC_skb_output &&
6330                     func_id != BPF_FUNC_perf_event_read_value &&
6331                     func_id != BPF_FUNC_xdp_output)
6332                         goto error;
6333                 break;
6334         case BPF_MAP_TYPE_RINGBUF:
6335                 if (func_id != BPF_FUNC_ringbuf_output &&
6336                     func_id != BPF_FUNC_ringbuf_reserve &&
6337                     func_id != BPF_FUNC_ringbuf_query &&
6338                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6339                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6340                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
6341                         goto error;
6342                 break;
6343         case BPF_MAP_TYPE_USER_RINGBUF:
6344                 if (func_id != BPF_FUNC_user_ringbuf_drain)
6345                         goto error;
6346                 break;
6347         case BPF_MAP_TYPE_STACK_TRACE:
6348                 if (func_id != BPF_FUNC_get_stackid)
6349                         goto error;
6350                 break;
6351         case BPF_MAP_TYPE_CGROUP_ARRAY:
6352                 if (func_id != BPF_FUNC_skb_under_cgroup &&
6353                     func_id != BPF_FUNC_current_task_under_cgroup)
6354                         goto error;
6355                 break;
6356         case BPF_MAP_TYPE_CGROUP_STORAGE:
6357         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6358                 if (func_id != BPF_FUNC_get_local_storage)
6359                         goto error;
6360                 break;
6361         case BPF_MAP_TYPE_DEVMAP:
6362         case BPF_MAP_TYPE_DEVMAP_HASH:
6363                 if (func_id != BPF_FUNC_redirect_map &&
6364                     func_id != BPF_FUNC_map_lookup_elem)
6365                         goto error;
6366                 break;
6367         /* Restrict bpf side of cpumap and xskmap, open when use-cases
6368          * appear.
6369          */
6370         case BPF_MAP_TYPE_CPUMAP:
6371                 if (func_id != BPF_FUNC_redirect_map)
6372                         goto error;
6373                 break;
6374         case BPF_MAP_TYPE_XSKMAP:
6375                 if (func_id != BPF_FUNC_redirect_map &&
6376                     func_id != BPF_FUNC_map_lookup_elem)
6377                         goto error;
6378                 break;
6379         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6380         case BPF_MAP_TYPE_HASH_OF_MAPS:
6381                 if (func_id != BPF_FUNC_map_lookup_elem)
6382                         goto error;
6383                 break;
6384         case BPF_MAP_TYPE_SOCKMAP:
6385                 if (func_id != BPF_FUNC_sk_redirect_map &&
6386                     func_id != BPF_FUNC_sock_map_update &&
6387                     func_id != BPF_FUNC_map_delete_elem &&
6388                     func_id != BPF_FUNC_msg_redirect_map &&
6389                     func_id != BPF_FUNC_sk_select_reuseport &&
6390                     func_id != BPF_FUNC_map_lookup_elem &&
6391                     !may_update_sockmap(env, func_id))
6392                         goto error;
6393                 break;
6394         case BPF_MAP_TYPE_SOCKHASH:
6395                 if (func_id != BPF_FUNC_sk_redirect_hash &&
6396                     func_id != BPF_FUNC_sock_hash_update &&
6397                     func_id != BPF_FUNC_map_delete_elem &&
6398                     func_id != BPF_FUNC_msg_redirect_hash &&
6399                     func_id != BPF_FUNC_sk_select_reuseport &&
6400                     func_id != BPF_FUNC_map_lookup_elem &&
6401                     !may_update_sockmap(env, func_id))
6402                         goto error;
6403                 break;
6404         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6405                 if (func_id != BPF_FUNC_sk_select_reuseport)
6406                         goto error;
6407                 break;
6408         case BPF_MAP_TYPE_QUEUE:
6409         case BPF_MAP_TYPE_STACK:
6410                 if (func_id != BPF_FUNC_map_peek_elem &&
6411                     func_id != BPF_FUNC_map_pop_elem &&
6412                     func_id != BPF_FUNC_map_push_elem)
6413                         goto error;
6414                 break;
6415         case BPF_MAP_TYPE_SK_STORAGE:
6416                 if (func_id != BPF_FUNC_sk_storage_get &&
6417                     func_id != BPF_FUNC_sk_storage_delete)
6418                         goto error;
6419                 break;
6420         case BPF_MAP_TYPE_INODE_STORAGE:
6421                 if (func_id != BPF_FUNC_inode_storage_get &&
6422                     func_id != BPF_FUNC_inode_storage_delete)
6423                         goto error;
6424                 break;
6425         case BPF_MAP_TYPE_TASK_STORAGE:
6426                 if (func_id != BPF_FUNC_task_storage_get &&
6427                     func_id != BPF_FUNC_task_storage_delete)
6428                         goto error;
6429                 break;
6430         case BPF_MAP_TYPE_BLOOM_FILTER:
6431                 if (func_id != BPF_FUNC_map_peek_elem &&
6432                     func_id != BPF_FUNC_map_push_elem)
6433                         goto error;
6434                 break;
6435         default:
6436                 break;
6437         }
6438
6439         /* ... and second from the function itself. */
6440         switch (func_id) {
6441         case BPF_FUNC_tail_call:
6442                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6443                         goto error;
6444                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6445                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6446                         return -EINVAL;
6447                 }
6448                 break;
6449         case BPF_FUNC_perf_event_read:
6450         case BPF_FUNC_perf_event_output:
6451         case BPF_FUNC_perf_event_read_value:
6452         case BPF_FUNC_skb_output:
6453         case BPF_FUNC_xdp_output:
6454                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6455                         goto error;
6456                 break;
6457         case BPF_FUNC_ringbuf_output:
6458         case BPF_FUNC_ringbuf_reserve:
6459         case BPF_FUNC_ringbuf_query:
6460         case BPF_FUNC_ringbuf_reserve_dynptr:
6461         case BPF_FUNC_ringbuf_submit_dynptr:
6462         case BPF_FUNC_ringbuf_discard_dynptr:
6463                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6464                         goto error;
6465                 break;
6466         case BPF_FUNC_user_ringbuf_drain:
6467                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6468                         goto error;
6469                 break;
6470         case BPF_FUNC_get_stackid:
6471                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6472                         goto error;
6473                 break;
6474         case BPF_FUNC_current_task_under_cgroup:
6475         case BPF_FUNC_skb_under_cgroup:
6476                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6477                         goto error;
6478                 break;
6479         case BPF_FUNC_redirect_map:
6480                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6481                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6482                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
6483                     map->map_type != BPF_MAP_TYPE_XSKMAP)
6484                         goto error;
6485                 break;
6486         case BPF_FUNC_sk_redirect_map:
6487         case BPF_FUNC_msg_redirect_map:
6488         case BPF_FUNC_sock_map_update:
6489                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6490                         goto error;
6491                 break;
6492         case BPF_FUNC_sk_redirect_hash:
6493         case BPF_FUNC_msg_redirect_hash:
6494         case BPF_FUNC_sock_hash_update:
6495                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6496                         goto error;
6497                 break;
6498         case BPF_FUNC_get_local_storage:
6499                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6500                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6501                         goto error;
6502                 break;
6503         case BPF_FUNC_sk_select_reuseport:
6504                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6505                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6506                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
6507                         goto error;
6508                 break;
6509         case BPF_FUNC_map_pop_elem:
6510                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6511                     map->map_type != BPF_MAP_TYPE_STACK)
6512                         goto error;
6513                 break;
6514         case BPF_FUNC_map_peek_elem:
6515         case BPF_FUNC_map_push_elem:
6516                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6517                     map->map_type != BPF_MAP_TYPE_STACK &&
6518                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6519                         goto error;
6520                 break;
6521         case BPF_FUNC_map_lookup_percpu_elem:
6522                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6523                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6524                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6525                         goto error;
6526                 break;
6527         case BPF_FUNC_sk_storage_get:
6528         case BPF_FUNC_sk_storage_delete:
6529                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6530                         goto error;
6531                 break;
6532         case BPF_FUNC_inode_storage_get:
6533         case BPF_FUNC_inode_storage_delete:
6534                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6535                         goto error;
6536                 break;
6537         case BPF_FUNC_task_storage_get:
6538         case BPF_FUNC_task_storage_delete:
6539                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6540                         goto error;
6541                 break;
6542         default:
6543                 break;
6544         }
6545
6546         return 0;
6547 error:
6548         verbose(env, "cannot pass map_type %d into func %s#%d\n",
6549                 map->map_type, func_id_name(func_id), func_id);
6550         return -EINVAL;
6551 }
6552
6553 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6554 {
6555         int count = 0;
6556
6557         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6558                 count++;
6559         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6560                 count++;
6561         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6562                 count++;
6563         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6564                 count++;
6565         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6566                 count++;
6567
6568         /* We only support one arg being in raw mode at the moment,
6569          * which is sufficient for the helper functions we have
6570          * right now.
6571          */
6572         return count <= 1;
6573 }
6574
6575 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6576 {
6577         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6578         bool has_size = fn->arg_size[arg] != 0;
6579         bool is_next_size = false;
6580
6581         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6582                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6583
6584         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6585                 return is_next_size;
6586
6587         return has_size == is_next_size || is_next_size == is_fixed;
6588 }
6589
6590 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6591 {
6592         /* bpf_xxx(..., buf, len) call will access 'len'
6593          * bytes from memory 'buf'. Both arg types need
6594          * to be paired, so make sure there's no buggy
6595          * helper function specification.
6596          */
6597         if (arg_type_is_mem_size(fn->arg1_type) ||
6598             check_args_pair_invalid(fn, 0) ||
6599             check_args_pair_invalid(fn, 1) ||
6600             check_args_pair_invalid(fn, 2) ||
6601             check_args_pair_invalid(fn, 3) ||
6602             check_args_pair_invalid(fn, 4))
6603                 return false;
6604
6605         return true;
6606 }
6607
6608 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6609 {
6610         int i;
6611
6612         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6613                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6614                         return false;
6615
6616                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6617                     /* arg_btf_id and arg_size are in a union. */
6618                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6619                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6620                         return false;
6621         }
6622
6623         return true;
6624 }
6625
6626 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6627 {
6628         return check_raw_mode_ok(fn) &&
6629                check_arg_pair_ok(fn) &&
6630                check_btf_id_ok(fn) ? 0 : -EINVAL;
6631 }
6632
6633 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6634  * are now invalid, so turn them into unknown SCALAR_VALUE.
6635  */
6636 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6637 {
6638         struct bpf_func_state *state;
6639         struct bpf_reg_state *reg;
6640
6641         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6642                 if (reg_is_pkt_pointer_any(reg))
6643                         __mark_reg_unknown(env, reg);
6644         }));
6645 }
6646
6647 enum {
6648         AT_PKT_END = -1,
6649         BEYOND_PKT_END = -2,
6650 };
6651
6652 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6653 {
6654         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6655         struct bpf_reg_state *reg = &state->regs[regn];
6656
6657         if (reg->type != PTR_TO_PACKET)
6658                 /* PTR_TO_PACKET_META is not supported yet */
6659                 return;
6660
6661         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6662          * How far beyond pkt_end it goes is unknown.
6663          * if (!range_open) it's the case of pkt >= pkt_end
6664          * if (range_open) it's the case of pkt > pkt_end
6665          * hence this pointer is at least 1 byte bigger than pkt_end
6666          */
6667         if (range_open)
6668                 reg->range = BEYOND_PKT_END;
6669         else
6670                 reg->range = AT_PKT_END;
6671 }
6672
6673 /* The pointer with the specified id has released its reference to kernel
6674  * resources. Identify all copies of the same pointer and clear the reference.
6675  */
6676 static int release_reference(struct bpf_verifier_env *env,
6677                              int ref_obj_id)
6678 {
6679         struct bpf_func_state *state;
6680         struct bpf_reg_state *reg;
6681         int err;
6682
6683         err = release_reference_state(cur_func(env), ref_obj_id);
6684         if (err)
6685                 return err;
6686
6687         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6688                 if (reg->ref_obj_id == ref_obj_id) {
6689                         if (!env->allow_ptr_leaks)
6690                                 __mark_reg_not_init(env, reg);
6691                         else
6692                                 __mark_reg_unknown(env, reg);
6693                 }
6694         }));
6695
6696         return 0;
6697 }
6698
6699 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6700                                     struct bpf_reg_state *regs)
6701 {
6702         int i;
6703
6704         /* after the call registers r0 - r5 were scratched */
6705         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6706                 mark_reg_not_init(env, regs, caller_saved[i]);
6707                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6708         }
6709 }
6710
6711 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6712                                    struct bpf_func_state *caller,
6713                                    struct bpf_func_state *callee,
6714                                    int insn_idx);
6715
6716 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6717                              int *insn_idx, int subprog,
6718                              set_callee_state_fn set_callee_state_cb)
6719 {
6720         struct bpf_verifier_state *state = env->cur_state;
6721         struct bpf_func_info_aux *func_info_aux;
6722         struct bpf_func_state *caller, *callee;
6723         int err;
6724         bool is_global = false;
6725
6726         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6727                 verbose(env, "the call stack of %d frames is too deep\n",
6728                         state->curframe + 2);
6729                 return -E2BIG;
6730         }
6731
6732         caller = state->frame[state->curframe];
6733         if (state->frame[state->curframe + 1]) {
6734                 verbose(env, "verifier bug. Frame %d already allocated\n",
6735                         state->curframe + 1);
6736                 return -EFAULT;
6737         }
6738
6739         func_info_aux = env->prog->aux->func_info_aux;
6740         if (func_info_aux)
6741                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6742         err = btf_check_subprog_call(env, subprog, caller->regs);
6743         if (err == -EFAULT)
6744                 return err;
6745         if (is_global) {
6746                 if (err) {
6747                         verbose(env, "Caller passes invalid args into func#%d\n",
6748                                 subprog);
6749                         return err;
6750                 } else {
6751                         if (env->log.level & BPF_LOG_LEVEL)
6752                                 verbose(env,
6753                                         "Func#%d is global and valid. Skipping.\n",
6754                                         subprog);
6755                         clear_caller_saved_regs(env, caller->regs);
6756
6757                         /* All global functions return a 64-bit SCALAR_VALUE */
6758                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
6759                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6760
6761                         /* continue with next insn after call */
6762                         return 0;
6763                 }
6764         }
6765
6766         if (insn->code == (BPF_JMP | BPF_CALL) &&
6767             insn->src_reg == 0 &&
6768             insn->imm == BPF_FUNC_timer_set_callback) {
6769                 struct bpf_verifier_state *async_cb;
6770
6771                 /* there is no real recursion here. timer callbacks are async */
6772                 env->subprog_info[subprog].is_async_cb = true;
6773                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6774                                          *insn_idx, subprog);
6775                 if (!async_cb)
6776                         return -EFAULT;
6777                 callee = async_cb->frame[0];
6778                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6779
6780                 /* Convert bpf_timer_set_callback() args into timer callback args */
6781                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6782                 if (err)
6783                         return err;
6784
6785                 clear_caller_saved_regs(env, caller->regs);
6786                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6787                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6788                 /* continue with next insn after call */
6789                 return 0;
6790         }
6791
6792         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6793         if (!callee)
6794                 return -ENOMEM;
6795         state->frame[state->curframe + 1] = callee;
6796
6797         /* callee cannot access r0, r6 - r9 for reading and has to write
6798          * into its own stack before reading from it.
6799          * callee can read/write into caller's stack
6800          */
6801         init_func_state(env, callee,
6802                         /* remember the callsite, it will be used by bpf_exit */
6803                         *insn_idx /* callsite */,
6804                         state->curframe + 1 /* frameno within this callchain */,
6805                         subprog /* subprog number within this prog */);
6806
6807         /* Transfer references to the callee */
6808         err = copy_reference_state(callee, caller);
6809         if (err)
6810                 goto err_out;
6811
6812         err = set_callee_state_cb(env, caller, callee, *insn_idx);
6813         if (err)
6814                 goto err_out;
6815
6816         clear_caller_saved_regs(env, caller->regs);
6817
6818         /* only increment it after check_reg_arg() finished */
6819         state->curframe++;
6820
6821         /* and go analyze first insn of the callee */
6822         *insn_idx = env->subprog_info[subprog].start - 1;
6823
6824         if (env->log.level & BPF_LOG_LEVEL) {
6825                 verbose(env, "caller:\n");
6826                 print_verifier_state(env, caller, true);
6827                 verbose(env, "callee:\n");
6828                 print_verifier_state(env, callee, true);
6829         }
6830         return 0;
6831
6832 err_out:
6833         free_func_state(callee);
6834         state->frame[state->curframe + 1] = NULL;
6835         return err;
6836 }
6837
6838 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6839                                    struct bpf_func_state *caller,
6840                                    struct bpf_func_state *callee)
6841 {
6842         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6843          *      void *callback_ctx, u64 flags);
6844          * callback_fn(struct bpf_map *map, void *key, void *value,
6845          *      void *callback_ctx);
6846          */
6847         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6848
6849         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6850         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6851         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6852
6853         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6854         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6855         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6856
6857         /* pointer to stack or null */
6858         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6859
6860         /* unused */
6861         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6862         return 0;
6863 }
6864
6865 static int set_callee_state(struct bpf_verifier_env *env,
6866                             struct bpf_func_state *caller,
6867                             struct bpf_func_state *callee, int insn_idx)
6868 {
6869         int i;
6870
6871         /* copy r1 - r5 args that callee can access.  The copy includes parent
6872          * pointers, which connects us up to the liveness chain
6873          */
6874         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6875                 callee->regs[i] = caller->regs[i];
6876         return 0;
6877 }
6878
6879 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6880                            int *insn_idx)
6881 {
6882         int subprog, target_insn;
6883
6884         target_insn = *insn_idx + insn->imm + 1;
6885         subprog = find_subprog(env, target_insn);
6886         if (subprog < 0) {
6887                 verbose(env, "verifier bug. No program starts at insn %d\n",
6888                         target_insn);
6889                 return -EFAULT;
6890         }
6891
6892         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6893 }
6894
6895 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6896                                        struct bpf_func_state *caller,
6897                                        struct bpf_func_state *callee,
6898                                        int insn_idx)
6899 {
6900         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6901         struct bpf_map *map;
6902         int err;
6903
6904         if (bpf_map_ptr_poisoned(insn_aux)) {
6905                 verbose(env, "tail_call abusing map_ptr\n");
6906                 return -EINVAL;
6907         }
6908
6909         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6910         if (!map->ops->map_set_for_each_callback_args ||
6911             !map->ops->map_for_each_callback) {
6912                 verbose(env, "callback function not allowed for map\n");
6913                 return -ENOTSUPP;
6914         }
6915
6916         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6917         if (err)
6918                 return err;
6919
6920         callee->in_callback_fn = true;
6921         callee->callback_ret_range = tnum_range(0, 1);
6922         return 0;
6923 }
6924
6925 static int set_loop_callback_state(struct bpf_verifier_env *env,
6926                                    struct bpf_func_state *caller,
6927                                    struct bpf_func_state *callee,
6928                                    int insn_idx)
6929 {
6930         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6931          *          u64 flags);
6932          * callback_fn(u32 index, void *callback_ctx);
6933          */
6934         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6935         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6936
6937         /* unused */
6938         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6939         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6940         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6941
6942         callee->in_callback_fn = true;
6943         callee->callback_ret_range = tnum_range(0, 1);
6944         return 0;
6945 }
6946
6947 static int set_timer_callback_state(struct bpf_verifier_env *env,
6948                                     struct bpf_func_state *caller,
6949                                     struct bpf_func_state *callee,
6950                                     int insn_idx)
6951 {
6952         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6953
6954         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6955          * callback_fn(struct bpf_map *map, void *key, void *value);
6956          */
6957         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6958         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6959         callee->regs[BPF_REG_1].map_ptr = map_ptr;
6960
6961         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6962         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6963         callee->regs[BPF_REG_2].map_ptr = map_ptr;
6964
6965         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6966         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6967         callee->regs[BPF_REG_3].map_ptr = map_ptr;
6968
6969         /* unused */
6970         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6971         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6972         callee->in_async_callback_fn = true;
6973         callee->callback_ret_range = tnum_range(0, 1);
6974         return 0;
6975 }
6976
6977 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6978                                        struct bpf_func_state *caller,
6979                                        struct bpf_func_state *callee,
6980                                        int insn_idx)
6981 {
6982         /* bpf_find_vma(struct task_struct *task, u64 addr,
6983          *               void *callback_fn, void *callback_ctx, u64 flags)
6984          * (callback_fn)(struct task_struct *task,
6985          *               struct vm_area_struct *vma, void *callback_ctx);
6986          */
6987         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6988
6989         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6990         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6991         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6992         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6993
6994         /* pointer to stack or null */
6995         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6996
6997         /* unused */
6998         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6999         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7000         callee->in_callback_fn = true;
7001         callee->callback_ret_range = tnum_range(0, 1);
7002         return 0;
7003 }
7004
7005 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7006                                            struct bpf_func_state *caller,
7007                                            struct bpf_func_state *callee,
7008                                            int insn_idx)
7009 {
7010         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7011          *                        callback_ctx, u64 flags);
7012          * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7013          */
7014         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7015         callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7016         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7017         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7018
7019         /* unused */
7020         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7021         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7022         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7023
7024         callee->in_callback_fn = true;
7025         callee->callback_ret_range = tnum_range(0, 1);
7026         return 0;
7027 }
7028
7029 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7030 {
7031         struct bpf_verifier_state *state = env->cur_state;
7032         struct bpf_func_state *caller, *callee;
7033         struct bpf_reg_state *r0;
7034         int err;
7035
7036         callee = state->frame[state->curframe];
7037         r0 = &callee->regs[BPF_REG_0];
7038         if (r0->type == PTR_TO_STACK) {
7039                 /* technically it's ok to return caller's stack pointer
7040                  * (or caller's caller's pointer) back to the caller,
7041                  * since these pointers are valid. Only current stack
7042                  * pointer will be invalid as soon as function exits,
7043                  * but let's be conservative
7044                  */
7045                 verbose(env, "cannot return stack pointer to the caller\n");
7046                 return -EINVAL;
7047         }
7048
7049         caller = state->frame[state->curframe - 1];
7050         if (callee->in_callback_fn) {
7051                 /* enforce R0 return value range [0, 1]. */
7052                 struct tnum range = callee->callback_ret_range;
7053
7054                 if (r0->type != SCALAR_VALUE) {
7055                         verbose(env, "R0 not a scalar value\n");
7056                         return -EACCES;
7057                 }
7058                 if (!tnum_in(range, r0->var_off)) {
7059                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7060                         return -EINVAL;
7061                 }
7062         } else {
7063                 /* return to the caller whatever r0 had in the callee */
7064                 caller->regs[BPF_REG_0] = *r0;
7065         }
7066
7067         /* callback_fn frame should have released its own additions to parent's
7068          * reference state at this point, or check_reference_leak would
7069          * complain, hence it must be the same as the caller. There is no need
7070          * to copy it back.
7071          */
7072         if (!callee->in_callback_fn) {
7073                 /* Transfer references to the caller */
7074                 err = copy_reference_state(caller, callee);
7075                 if (err)
7076                         return err;
7077         }
7078
7079         *insn_idx = callee->callsite + 1;
7080         if (env->log.level & BPF_LOG_LEVEL) {
7081                 verbose(env, "returning from callee:\n");
7082                 print_verifier_state(env, callee, true);
7083                 verbose(env, "to caller at %d:\n", *insn_idx);
7084                 print_verifier_state(env, caller, true);
7085         }
7086         /* clear everything in the callee */
7087         free_func_state(callee);
7088         state->frame[state->curframe--] = NULL;
7089         return 0;
7090 }
7091
7092 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7093                                    int func_id,
7094                                    struct bpf_call_arg_meta *meta)
7095 {
7096         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7097
7098         if (ret_type != RET_INTEGER ||
7099             (func_id != BPF_FUNC_get_stack &&
7100              func_id != BPF_FUNC_get_task_stack &&
7101              func_id != BPF_FUNC_probe_read_str &&
7102              func_id != BPF_FUNC_probe_read_kernel_str &&
7103              func_id != BPF_FUNC_probe_read_user_str))
7104                 return;
7105
7106         ret_reg->smax_value = meta->msize_max_value;
7107         ret_reg->s32_max_value = meta->msize_max_value;
7108         ret_reg->smin_value = -MAX_ERRNO;
7109         ret_reg->s32_min_value = -MAX_ERRNO;
7110         reg_bounds_sync(ret_reg);
7111 }
7112
7113 static int
7114 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7115                 int func_id, int insn_idx)
7116 {
7117         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7118         struct bpf_map *map = meta->map_ptr;
7119
7120         if (func_id != BPF_FUNC_tail_call &&
7121             func_id != BPF_FUNC_map_lookup_elem &&
7122             func_id != BPF_FUNC_map_update_elem &&
7123             func_id != BPF_FUNC_map_delete_elem &&
7124             func_id != BPF_FUNC_map_push_elem &&
7125             func_id != BPF_FUNC_map_pop_elem &&
7126             func_id != BPF_FUNC_map_peek_elem &&
7127             func_id != BPF_FUNC_for_each_map_elem &&
7128             func_id != BPF_FUNC_redirect_map &&
7129             func_id != BPF_FUNC_map_lookup_percpu_elem)
7130                 return 0;
7131
7132         if (map == NULL) {
7133                 verbose(env, "kernel subsystem misconfigured verifier\n");
7134                 return -EINVAL;
7135         }
7136
7137         /* In case of read-only, some additional restrictions
7138          * need to be applied in order to prevent altering the
7139          * state of the map from program side.
7140          */
7141         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7142             (func_id == BPF_FUNC_map_delete_elem ||
7143              func_id == BPF_FUNC_map_update_elem ||
7144              func_id == BPF_FUNC_map_push_elem ||
7145              func_id == BPF_FUNC_map_pop_elem)) {
7146                 verbose(env, "write into map forbidden\n");
7147                 return -EACCES;
7148         }
7149
7150         if (!BPF_MAP_PTR(aux->map_ptr_state))
7151                 bpf_map_ptr_store(aux, meta->map_ptr,
7152                                   !meta->map_ptr->bypass_spec_v1);
7153         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7154                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7155                                   !meta->map_ptr->bypass_spec_v1);
7156         return 0;
7157 }
7158
7159 static int
7160 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7161                 int func_id, int insn_idx)
7162 {
7163         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7164         struct bpf_reg_state *regs = cur_regs(env), *reg;
7165         struct bpf_map *map = meta->map_ptr;
7166         u64 val, max;
7167         int err;
7168
7169         if (func_id != BPF_FUNC_tail_call)
7170                 return 0;
7171         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7172                 verbose(env, "kernel subsystem misconfigured verifier\n");
7173                 return -EINVAL;
7174         }
7175
7176         reg = &regs[BPF_REG_3];
7177         val = reg->var_off.value;
7178         max = map->max_entries;
7179
7180         if (!(register_is_const(reg) && val < max)) {
7181                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7182                 return 0;
7183         }
7184
7185         err = mark_chain_precision(env, BPF_REG_3);
7186         if (err)
7187                 return err;
7188         if (bpf_map_key_unseen(aux))
7189                 bpf_map_key_store(aux, val);
7190         else if (!bpf_map_key_poisoned(aux) &&
7191                   bpf_map_key_immediate(aux) != val)
7192                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7193         return 0;
7194 }
7195
7196 static int check_reference_leak(struct bpf_verifier_env *env)
7197 {
7198         struct bpf_func_state *state = cur_func(env);
7199         bool refs_lingering = false;
7200         int i;
7201
7202         if (state->frameno && !state->in_callback_fn)
7203                 return 0;
7204
7205         for (i = 0; i < state->acquired_refs; i++) {
7206                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7207                         continue;
7208                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7209                         state->refs[i].id, state->refs[i].insn_idx);
7210                 refs_lingering = true;
7211         }
7212         return refs_lingering ? -EINVAL : 0;
7213 }
7214
7215 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7216                                    struct bpf_reg_state *regs)
7217 {
7218         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7219         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7220         struct bpf_map *fmt_map = fmt_reg->map_ptr;
7221         int err, fmt_map_off, num_args;
7222         u64 fmt_addr;
7223         char *fmt;
7224
7225         /* data must be an array of u64 */
7226         if (data_len_reg->var_off.value % 8)
7227                 return -EINVAL;
7228         num_args = data_len_reg->var_off.value / 8;
7229
7230         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7231          * and map_direct_value_addr is set.
7232          */
7233         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7234         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7235                                                   fmt_map_off);
7236         if (err) {
7237                 verbose(env, "verifier bug\n");
7238                 return -EFAULT;
7239         }
7240         fmt = (char *)(long)fmt_addr + fmt_map_off;
7241
7242         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7243          * can focus on validating the format specifiers.
7244          */
7245         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7246         if (err < 0)
7247                 verbose(env, "Invalid format string\n");
7248
7249         return err;
7250 }
7251
7252 static int check_get_func_ip(struct bpf_verifier_env *env)
7253 {
7254         enum bpf_prog_type type = resolve_prog_type(env->prog);
7255         int func_id = BPF_FUNC_get_func_ip;
7256
7257         if (type == BPF_PROG_TYPE_TRACING) {
7258                 if (!bpf_prog_has_trampoline(env->prog)) {
7259                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7260                                 func_id_name(func_id), func_id);
7261                         return -ENOTSUPP;
7262                 }
7263                 return 0;
7264         } else if (type == BPF_PROG_TYPE_KPROBE) {
7265                 return 0;
7266         }
7267
7268         verbose(env, "func %s#%d not supported for program type %d\n",
7269                 func_id_name(func_id), func_id, type);
7270         return -ENOTSUPP;
7271 }
7272
7273 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7274 {
7275         return &env->insn_aux_data[env->insn_idx];
7276 }
7277
7278 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7279 {
7280         struct bpf_reg_state *regs = cur_regs(env);
7281         struct bpf_reg_state *reg = &regs[BPF_REG_4];
7282         bool reg_is_null = register_is_null(reg);
7283
7284         if (reg_is_null)
7285                 mark_chain_precision(env, BPF_REG_4);
7286
7287         return reg_is_null;
7288 }
7289
7290 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7291 {
7292         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7293
7294         if (!state->initialized) {
7295                 state->initialized = 1;
7296                 state->fit_for_inline = loop_flag_is_zero(env);
7297                 state->callback_subprogno = subprogno;
7298                 return;
7299         }
7300
7301         if (!state->fit_for_inline)
7302                 return;
7303
7304         state->fit_for_inline = (loop_flag_is_zero(env) &&
7305                                  state->callback_subprogno == subprogno);
7306 }
7307
7308 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7309                              int *insn_idx_p)
7310 {
7311         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7312         const struct bpf_func_proto *fn = NULL;
7313         enum bpf_return_type ret_type;
7314         enum bpf_type_flag ret_flag;
7315         struct bpf_reg_state *regs;
7316         struct bpf_call_arg_meta meta;
7317         int insn_idx = *insn_idx_p;
7318         bool changes_data;
7319         int i, err, func_id;
7320
7321         /* find function prototype */
7322         func_id = insn->imm;
7323         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7324                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7325                         func_id);
7326                 return -EINVAL;
7327         }
7328
7329         if (env->ops->get_func_proto)
7330                 fn = env->ops->get_func_proto(func_id, env->prog);
7331         if (!fn) {
7332                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7333                         func_id);
7334                 return -EINVAL;
7335         }
7336
7337         /* eBPF programs must be GPL compatible to use GPL-ed functions */
7338         if (!env->prog->gpl_compatible && fn->gpl_only) {
7339                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7340                 return -EINVAL;
7341         }
7342
7343         if (fn->allowed && !fn->allowed(env->prog)) {
7344                 verbose(env, "helper call is not allowed in probe\n");
7345                 return -EINVAL;
7346         }
7347
7348         /* With LD_ABS/IND some JITs save/restore skb from r1. */
7349         changes_data = bpf_helper_changes_pkt_data(fn->func);
7350         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7351                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7352                         func_id_name(func_id), func_id);
7353                 return -EINVAL;
7354         }
7355
7356         memset(&meta, 0, sizeof(meta));
7357         meta.pkt_access = fn->pkt_access;
7358
7359         err = check_func_proto(fn, func_id);
7360         if (err) {
7361                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7362                         func_id_name(func_id), func_id);
7363                 return err;
7364         }
7365
7366         meta.func_id = func_id;
7367         /* check args */
7368         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7369                 err = check_func_arg(env, i, &meta, fn);
7370                 if (err)
7371                         return err;
7372         }
7373
7374         err = record_func_map(env, &meta, func_id, insn_idx);
7375         if (err)
7376                 return err;
7377
7378         err = record_func_key(env, &meta, func_id, insn_idx);
7379         if (err)
7380                 return err;
7381
7382         /* Mark slots with STACK_MISC in case of raw mode, stack offset
7383          * is inferred from register state.
7384          */
7385         for (i = 0; i < meta.access_size; i++) {
7386                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7387                                        BPF_WRITE, -1, false);
7388                 if (err)
7389                         return err;
7390         }
7391
7392         regs = cur_regs(env);
7393
7394         if (meta.uninit_dynptr_regno) {
7395                 /* we write BPF_DW bits (8 bytes) at a time */
7396                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7397                         err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7398                                                i, BPF_DW, BPF_WRITE, -1, false);
7399                         if (err)
7400                                 return err;
7401                 }
7402
7403                 err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7404                                               fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7405                                               insn_idx);
7406                 if (err)
7407                         return err;
7408         }
7409
7410         if (meta.release_regno) {
7411                 err = -EINVAL;
7412                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7413                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7414                 else if (meta.ref_obj_id)
7415                         err = release_reference(env, meta.ref_obj_id);
7416                 /* meta.ref_obj_id can only be 0 if register that is meant to be
7417                  * released is NULL, which must be > R0.
7418                  */
7419                 else if (register_is_null(&regs[meta.release_regno]))
7420                         err = 0;
7421                 if (err) {
7422                         verbose(env, "func %s#%d reference has not been acquired before\n",
7423                                 func_id_name(func_id), func_id);
7424                         return err;
7425                 }
7426         }
7427
7428         switch (func_id) {
7429         case BPF_FUNC_tail_call:
7430                 err = check_reference_leak(env);
7431                 if (err) {
7432                         verbose(env, "tail_call would lead to reference leak\n");
7433                         return err;
7434                 }
7435                 break;
7436         case BPF_FUNC_get_local_storage:
7437                 /* check that flags argument in get_local_storage(map, flags) is 0,
7438                  * this is required because get_local_storage() can't return an error.
7439                  */
7440                 if (!register_is_null(&regs[BPF_REG_2])) {
7441                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7442                         return -EINVAL;
7443                 }
7444                 break;
7445         case BPF_FUNC_for_each_map_elem:
7446                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7447                                         set_map_elem_callback_state);
7448                 break;
7449         case BPF_FUNC_timer_set_callback:
7450                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7451                                         set_timer_callback_state);
7452                 break;
7453         case BPF_FUNC_find_vma:
7454                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7455                                         set_find_vma_callback_state);
7456                 break;
7457         case BPF_FUNC_snprintf:
7458                 err = check_bpf_snprintf_call(env, regs);
7459                 break;
7460         case BPF_FUNC_loop:
7461                 update_loop_inline_state(env, meta.subprogno);
7462                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7463                                         set_loop_callback_state);
7464                 break;
7465         case BPF_FUNC_dynptr_from_mem:
7466                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7467                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7468                                 reg_type_str(env, regs[BPF_REG_1].type));
7469                         return -EACCES;
7470                 }
7471                 break;
7472         case BPF_FUNC_set_retval:
7473                 if (prog_type == BPF_PROG_TYPE_LSM &&
7474                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7475                         if (!env->prog->aux->attach_func_proto->type) {
7476                                 /* Make sure programs that attach to void
7477                                  * hooks don't try to modify return value.
7478                                  */
7479                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7480                                 return -EINVAL;
7481                         }
7482                 }
7483                 break;
7484         case BPF_FUNC_dynptr_data:
7485                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7486                         if (arg_type_is_dynptr(fn->arg_type[i])) {
7487                                 struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7488
7489                                 if (meta.ref_obj_id) {
7490                                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7491                                         return -EFAULT;
7492                                 }
7493
7494                                 if (base_type(reg->type) != PTR_TO_DYNPTR)
7495                                         /* Find the id of the dynptr we're
7496                                          * tracking the reference of
7497                                          */
7498                                         meta.ref_obj_id = stack_slot_get_id(env, reg);
7499                                 break;
7500                         }
7501                 }
7502                 if (i == MAX_BPF_FUNC_REG_ARGS) {
7503                         verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7504                         return -EFAULT;
7505                 }
7506                 break;
7507         case BPF_FUNC_user_ringbuf_drain:
7508                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7509                                         set_user_ringbuf_callback_state);
7510                 break;
7511         }
7512
7513         if (err)
7514                 return err;
7515
7516         /* reset caller saved regs */
7517         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7518                 mark_reg_not_init(env, regs, caller_saved[i]);
7519                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7520         }
7521
7522         /* helper call returns 64-bit value. */
7523         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7524
7525         /* update return register (already marked as written above) */
7526         ret_type = fn->ret_type;
7527         ret_flag = type_flag(ret_type);
7528
7529         switch (base_type(ret_type)) {
7530         case RET_INTEGER:
7531                 /* sets type to SCALAR_VALUE */
7532                 mark_reg_unknown(env, regs, BPF_REG_0);
7533                 break;
7534         case RET_VOID:
7535                 regs[BPF_REG_0].type = NOT_INIT;
7536                 break;
7537         case RET_PTR_TO_MAP_VALUE:
7538                 /* There is no offset yet applied, variable or fixed */
7539                 mark_reg_known_zero(env, regs, BPF_REG_0);
7540                 /* remember map_ptr, so that check_map_access()
7541                  * can check 'value_size' boundary of memory access
7542                  * to map element returned from bpf_map_lookup_elem()
7543                  */
7544                 if (meta.map_ptr == NULL) {
7545                         verbose(env,
7546                                 "kernel subsystem misconfigured verifier\n");
7547                         return -EINVAL;
7548                 }
7549                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7550                 regs[BPF_REG_0].map_uid = meta.map_uid;
7551                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7552                 if (!type_may_be_null(ret_type) &&
7553                     map_value_has_spin_lock(meta.map_ptr)) {
7554                         regs[BPF_REG_0].id = ++env->id_gen;
7555                 }
7556                 break;
7557         case RET_PTR_TO_SOCKET:
7558                 mark_reg_known_zero(env, regs, BPF_REG_0);
7559                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7560                 break;
7561         case RET_PTR_TO_SOCK_COMMON:
7562                 mark_reg_known_zero(env, regs, BPF_REG_0);
7563                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7564                 break;
7565         case RET_PTR_TO_TCP_SOCK:
7566                 mark_reg_known_zero(env, regs, BPF_REG_0);
7567                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7568                 break;
7569         case RET_PTR_TO_ALLOC_MEM:
7570                 mark_reg_known_zero(env, regs, BPF_REG_0);
7571                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7572                 regs[BPF_REG_0].mem_size = meta.mem_size;
7573                 break;
7574         case RET_PTR_TO_MEM_OR_BTF_ID:
7575         {
7576                 const struct btf_type *t;
7577
7578                 mark_reg_known_zero(env, regs, BPF_REG_0);
7579                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7580                 if (!btf_type_is_struct(t)) {
7581                         u32 tsize;
7582                         const struct btf_type *ret;
7583                         const char *tname;
7584
7585                         /* resolve the type size of ksym. */
7586                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7587                         if (IS_ERR(ret)) {
7588                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7589                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7590                                         tname, PTR_ERR(ret));
7591                                 return -EINVAL;
7592                         }
7593                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7594                         regs[BPF_REG_0].mem_size = tsize;
7595                 } else {
7596                         /* MEM_RDONLY may be carried from ret_flag, but it
7597                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7598                          * it will confuse the check of PTR_TO_BTF_ID in
7599                          * check_mem_access().
7600                          */
7601                         ret_flag &= ~MEM_RDONLY;
7602
7603                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7604                         regs[BPF_REG_0].btf = meta.ret_btf;
7605                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7606                 }
7607                 break;
7608         }
7609         case RET_PTR_TO_BTF_ID:
7610         {
7611                 struct btf *ret_btf;
7612                 int ret_btf_id;
7613
7614                 mark_reg_known_zero(env, regs, BPF_REG_0);
7615                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7616                 if (func_id == BPF_FUNC_kptr_xchg) {
7617                         ret_btf = meta.kptr_off_desc->kptr.btf;
7618                         ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7619                 } else {
7620                         if (fn->ret_btf_id == BPF_PTR_POISON) {
7621                                 verbose(env, "verifier internal error:");
7622                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7623                                         func_id_name(func_id));
7624                                 return -EINVAL;
7625                         }
7626                         ret_btf = btf_vmlinux;
7627                         ret_btf_id = *fn->ret_btf_id;
7628                 }
7629                 if (ret_btf_id == 0) {
7630                         verbose(env, "invalid return type %u of func %s#%d\n",
7631                                 base_type(ret_type), func_id_name(func_id),
7632                                 func_id);
7633                         return -EINVAL;
7634                 }
7635                 regs[BPF_REG_0].btf = ret_btf;
7636                 regs[BPF_REG_0].btf_id = ret_btf_id;
7637                 break;
7638         }
7639         default:
7640                 verbose(env, "unknown return type %u of func %s#%d\n",
7641                         base_type(ret_type), func_id_name(func_id), func_id);
7642                 return -EINVAL;
7643         }
7644
7645         if (type_may_be_null(regs[BPF_REG_0].type))
7646                 regs[BPF_REG_0].id = ++env->id_gen;
7647
7648         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7649                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7650                         func_id_name(func_id), func_id);
7651                 return -EFAULT;
7652         }
7653
7654         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7655                 /* For release_reference() */
7656                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7657         } else if (is_acquire_function(func_id, meta.map_ptr)) {
7658                 int id = acquire_reference_state(env, insn_idx);
7659
7660                 if (id < 0)
7661                         return id;
7662                 /* For mark_ptr_or_null_reg() */
7663                 regs[BPF_REG_0].id = id;
7664                 /* For release_reference() */
7665                 regs[BPF_REG_0].ref_obj_id = id;
7666         }
7667
7668         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7669
7670         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7671         if (err)
7672                 return err;
7673
7674         if ((func_id == BPF_FUNC_get_stack ||
7675              func_id == BPF_FUNC_get_task_stack) &&
7676             !env->prog->has_callchain_buf) {
7677                 const char *err_str;
7678
7679 #ifdef CONFIG_PERF_EVENTS
7680                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7681                 err_str = "cannot get callchain buffer for func %s#%d\n";
7682 #else
7683                 err = -ENOTSUPP;
7684                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7685 #endif
7686                 if (err) {
7687                         verbose(env, err_str, func_id_name(func_id), func_id);
7688                         return err;
7689                 }
7690
7691                 env->prog->has_callchain_buf = true;
7692         }
7693
7694         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7695                 env->prog->call_get_stack = true;
7696
7697         if (func_id == BPF_FUNC_get_func_ip) {
7698                 if (check_get_func_ip(env))
7699                         return -ENOTSUPP;
7700                 env->prog->call_get_func_ip = true;
7701         }
7702
7703         if (changes_data)
7704                 clear_all_pkt_pointers(env);
7705         return 0;
7706 }
7707
7708 /* mark_btf_func_reg_size() is used when the reg size is determined by
7709  * the BTF func_proto's return value size and argument.
7710  */
7711 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7712                                    size_t reg_size)
7713 {
7714         struct bpf_reg_state *reg = &cur_regs(env)[regno];
7715
7716         if (regno == BPF_REG_0) {
7717                 /* Function return value */
7718                 reg->live |= REG_LIVE_WRITTEN;
7719                 reg->subreg_def = reg_size == sizeof(u64) ?
7720                         DEF_NOT_SUBREG : env->insn_idx + 1;
7721         } else {
7722                 /* Function argument */
7723                 if (reg_size == sizeof(u64)) {
7724                         mark_insn_zext(env, reg);
7725                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7726                 } else {
7727                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7728                 }
7729         }
7730 }
7731
7732 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7733                             int *insn_idx_p)
7734 {
7735         const struct btf_type *t, *func, *func_proto, *ptr_type;
7736         struct bpf_reg_state *regs = cur_regs(env);
7737         struct bpf_kfunc_arg_meta meta = { 0 };
7738         const char *func_name, *ptr_type_name;
7739         u32 i, nargs, func_id, ptr_type_id;
7740         int err, insn_idx = *insn_idx_p;
7741         const struct btf_param *args;
7742         struct btf *desc_btf;
7743         u32 *kfunc_flags;
7744         bool acq;
7745
7746         /* skip for now, but return error when we find this in fixup_kfunc_call */
7747         if (!insn->imm)
7748                 return 0;
7749
7750         desc_btf = find_kfunc_desc_btf(env, insn->off);
7751         if (IS_ERR(desc_btf))
7752                 return PTR_ERR(desc_btf);
7753
7754         func_id = insn->imm;
7755         func = btf_type_by_id(desc_btf, func_id);
7756         func_name = btf_name_by_offset(desc_btf, func->name_off);
7757         func_proto = btf_type_by_id(desc_btf, func->type);
7758
7759         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7760         if (!kfunc_flags) {
7761                 verbose(env, "calling kernel function %s is not allowed\n",
7762                         func_name);
7763                 return -EACCES;
7764         }
7765         if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7766                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7767                 return -EACCES;
7768         }
7769
7770         acq = *kfunc_flags & KF_ACQUIRE;
7771
7772         meta.flags = *kfunc_flags;
7773
7774         /* Check the arguments */
7775         err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7776         if (err < 0)
7777                 return err;
7778         /* In case of release function, we get register number of refcounted
7779          * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7780          */
7781         if (err) {
7782                 err = release_reference(env, regs[err].ref_obj_id);
7783                 if (err) {
7784                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7785                                 func_name, func_id);
7786                         return err;
7787                 }
7788         }
7789
7790         for (i = 0; i < CALLER_SAVED_REGS; i++)
7791                 mark_reg_not_init(env, regs, caller_saved[i]);
7792
7793         /* Check return type */
7794         t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7795
7796         if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7797                 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7798                 return -EINVAL;
7799         }
7800
7801         if (btf_type_is_scalar(t)) {
7802                 mark_reg_unknown(env, regs, BPF_REG_0);
7803                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7804         } else if (btf_type_is_ptr(t)) {
7805                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7806                                                    &ptr_type_id);
7807                 if (!btf_type_is_struct(ptr_type)) {
7808                         if (!meta.r0_size) {
7809                                 ptr_type_name = btf_name_by_offset(desc_btf,
7810                                                                    ptr_type->name_off);
7811                                 verbose(env,
7812                                         "kernel function %s returns pointer type %s %s is not supported\n",
7813                                         func_name,
7814                                         btf_type_str(ptr_type),
7815                                         ptr_type_name);
7816                                 return -EINVAL;
7817                         }
7818
7819                         mark_reg_known_zero(env, regs, BPF_REG_0);
7820                         regs[BPF_REG_0].type = PTR_TO_MEM;
7821                         regs[BPF_REG_0].mem_size = meta.r0_size;
7822
7823                         if (meta.r0_rdonly)
7824                                 regs[BPF_REG_0].type |= MEM_RDONLY;
7825
7826                         /* Ensures we don't access the memory after a release_reference() */
7827                         if (meta.ref_obj_id)
7828                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7829                 } else {
7830                         mark_reg_known_zero(env, regs, BPF_REG_0);
7831                         regs[BPF_REG_0].btf = desc_btf;
7832                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7833                         regs[BPF_REG_0].btf_id = ptr_type_id;
7834                 }
7835                 if (*kfunc_flags & KF_RET_NULL) {
7836                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7837                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7838                         regs[BPF_REG_0].id = ++env->id_gen;
7839                 }
7840                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7841                 if (acq) {
7842                         int id = acquire_reference_state(env, insn_idx);
7843
7844                         if (id < 0)
7845                                 return id;
7846                         regs[BPF_REG_0].id = id;
7847                         regs[BPF_REG_0].ref_obj_id = id;
7848                 }
7849         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7850
7851         nargs = btf_type_vlen(func_proto);
7852         args = (const struct btf_param *)(func_proto + 1);
7853         for (i = 0; i < nargs; i++) {
7854                 u32 regno = i + 1;
7855
7856                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7857                 if (btf_type_is_ptr(t))
7858                         mark_btf_func_reg_size(env, regno, sizeof(void *));
7859                 else
7860                         /* scalar. ensured by btf_check_kfunc_arg_match() */
7861                         mark_btf_func_reg_size(env, regno, t->size);
7862         }
7863
7864         return 0;
7865 }
7866
7867 static bool signed_add_overflows(s64 a, s64 b)
7868 {
7869         /* Do the add in u64, where overflow is well-defined */
7870         s64 res = (s64)((u64)a + (u64)b);
7871
7872         if (b < 0)
7873                 return res > a;
7874         return res < a;
7875 }
7876
7877 static bool signed_add32_overflows(s32 a, s32 b)
7878 {
7879         /* Do the add in u32, where overflow is well-defined */
7880         s32 res = (s32)((u32)a + (u32)b);
7881
7882         if (b < 0)
7883                 return res > a;
7884         return res < a;
7885 }
7886
7887 static bool signed_sub_overflows(s64 a, s64 b)
7888 {
7889         /* Do the sub in u64, where overflow is well-defined */
7890         s64 res = (s64)((u64)a - (u64)b);
7891
7892         if (b < 0)
7893                 return res < a;
7894         return res > a;
7895 }
7896
7897 static bool signed_sub32_overflows(s32 a, s32 b)
7898 {
7899         /* Do the sub in u32, where overflow is well-defined */
7900         s32 res = (s32)((u32)a - (u32)b);
7901
7902         if (b < 0)
7903                 return res < a;
7904         return res > a;
7905 }
7906
7907 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7908                                   const struct bpf_reg_state *reg,
7909                                   enum bpf_reg_type type)
7910 {
7911         bool known = tnum_is_const(reg->var_off);
7912         s64 val = reg->var_off.value;
7913         s64 smin = reg->smin_value;
7914
7915         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7916                 verbose(env, "math between %s pointer and %lld is not allowed\n",
7917                         reg_type_str(env, type), val);
7918                 return false;
7919         }
7920
7921         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7922                 verbose(env, "%s pointer offset %d is not allowed\n",
7923                         reg_type_str(env, type), reg->off);
7924                 return false;
7925         }
7926
7927         if (smin == S64_MIN) {
7928                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7929                         reg_type_str(env, type));
7930                 return false;
7931         }
7932
7933         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7934                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7935                         smin, reg_type_str(env, type));
7936                 return false;
7937         }
7938
7939         return true;
7940 }
7941
7942 enum {
7943         REASON_BOUNDS   = -1,
7944         REASON_TYPE     = -2,
7945         REASON_PATHS    = -3,
7946         REASON_LIMIT    = -4,
7947         REASON_STACK    = -5,
7948 };
7949
7950 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7951                               u32 *alu_limit, bool mask_to_left)
7952 {
7953         u32 max = 0, ptr_limit = 0;
7954
7955         switch (ptr_reg->type) {
7956         case PTR_TO_STACK:
7957                 /* Offset 0 is out-of-bounds, but acceptable start for the
7958                  * left direction, see BPF_REG_FP. Also, unknown scalar
7959                  * offset where we would need to deal with min/max bounds is
7960                  * currently prohibited for unprivileged.
7961                  */
7962                 max = MAX_BPF_STACK + mask_to_left;
7963                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7964                 break;
7965         case PTR_TO_MAP_VALUE:
7966                 max = ptr_reg->map_ptr->value_size;
7967                 ptr_limit = (mask_to_left ?
7968                              ptr_reg->smin_value :
7969                              ptr_reg->umax_value) + ptr_reg->off;
7970                 break;
7971         default:
7972                 return REASON_TYPE;
7973         }
7974
7975         if (ptr_limit >= max)
7976                 return REASON_LIMIT;
7977         *alu_limit = ptr_limit;
7978         return 0;
7979 }
7980
7981 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7982                                     const struct bpf_insn *insn)
7983 {
7984         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7985 }
7986
7987 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7988                                        u32 alu_state, u32 alu_limit)
7989 {
7990         /* If we arrived here from different branches with different
7991          * state or limits to sanitize, then this won't work.
7992          */
7993         if (aux->alu_state &&
7994             (aux->alu_state != alu_state ||
7995              aux->alu_limit != alu_limit))
7996                 return REASON_PATHS;
7997
7998         /* Corresponding fixup done in do_misc_fixups(). */
7999         aux->alu_state = alu_state;
8000         aux->alu_limit = alu_limit;
8001         return 0;
8002 }
8003
8004 static int sanitize_val_alu(struct bpf_verifier_env *env,
8005                             struct bpf_insn *insn)
8006 {
8007         struct bpf_insn_aux_data *aux = cur_aux(env);
8008
8009         if (can_skip_alu_sanitation(env, insn))
8010                 return 0;
8011
8012         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
8013 }
8014
8015 static bool sanitize_needed(u8 opcode)
8016 {
8017         return opcode == BPF_ADD || opcode == BPF_SUB;
8018 }
8019
8020 struct bpf_sanitize_info {
8021         struct bpf_insn_aux_data aux;
8022         bool mask_to_left;
8023 };
8024
8025 static struct bpf_verifier_state *
8026 sanitize_speculative_path(struct bpf_verifier_env *env,
8027                           const struct bpf_insn *insn,
8028                           u32 next_idx, u32 curr_idx)
8029 {
8030         struct bpf_verifier_state *branch;
8031         struct bpf_reg_state *regs;
8032
8033         branch = push_stack(env, next_idx, curr_idx, true);
8034         if (branch && insn) {
8035                 regs = branch->frame[branch->curframe]->regs;
8036                 if (BPF_SRC(insn->code) == BPF_K) {
8037                         mark_reg_unknown(env, regs, insn->dst_reg);
8038                 } else if (BPF_SRC(insn->code) == BPF_X) {
8039                         mark_reg_unknown(env, regs, insn->dst_reg);
8040                         mark_reg_unknown(env, regs, insn->src_reg);
8041                 }
8042         }
8043         return branch;
8044 }
8045
8046 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8047                             struct bpf_insn *insn,
8048                             const struct bpf_reg_state *ptr_reg,
8049                             const struct bpf_reg_state *off_reg,
8050                             struct bpf_reg_state *dst_reg,
8051                             struct bpf_sanitize_info *info,
8052                             const bool commit_window)
8053 {
8054         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8055         struct bpf_verifier_state *vstate = env->cur_state;
8056         bool off_is_imm = tnum_is_const(off_reg->var_off);
8057         bool off_is_neg = off_reg->smin_value < 0;
8058         bool ptr_is_dst_reg = ptr_reg == dst_reg;
8059         u8 opcode = BPF_OP(insn->code);
8060         u32 alu_state, alu_limit;
8061         struct bpf_reg_state tmp;
8062         bool ret;
8063         int err;
8064
8065         if (can_skip_alu_sanitation(env, insn))
8066                 return 0;
8067
8068         /* We already marked aux for masking from non-speculative
8069          * paths, thus we got here in the first place. We only care
8070          * to explore bad access from here.
8071          */
8072         if (vstate->speculative)
8073                 goto do_sim;
8074
8075         if (!commit_window) {
8076                 if (!tnum_is_const(off_reg->var_off) &&
8077                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8078                         return REASON_BOUNDS;
8079
8080                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
8081                                      (opcode == BPF_SUB && !off_is_neg);
8082         }
8083
8084         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8085         if (err < 0)
8086                 return err;
8087
8088         if (commit_window) {
8089                 /* In commit phase we narrow the masking window based on
8090                  * the observed pointer move after the simulated operation.
8091                  */
8092                 alu_state = info->aux.alu_state;
8093                 alu_limit = abs(info->aux.alu_limit - alu_limit);
8094         } else {
8095                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8096                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8097                 alu_state |= ptr_is_dst_reg ?
8098                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8099
8100                 /* Limit pruning on unknown scalars to enable deep search for
8101                  * potential masking differences from other program paths.
8102                  */
8103                 if (!off_is_imm)
8104                         env->explore_alu_limits = true;
8105         }
8106
8107         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8108         if (err < 0)
8109                 return err;
8110 do_sim:
8111         /* If we're in commit phase, we're done here given we already
8112          * pushed the truncated dst_reg into the speculative verification
8113          * stack.
8114          *
8115          * Also, when register is a known constant, we rewrite register-based
8116          * operation to immediate-based, and thus do not need masking (and as
8117          * a consequence, do not need to simulate the zero-truncation either).
8118          */
8119         if (commit_window || off_is_imm)
8120                 return 0;
8121
8122         /* Simulate and find potential out-of-bounds access under
8123          * speculative execution from truncation as a result of
8124          * masking when off was not within expected range. If off
8125          * sits in dst, then we temporarily need to move ptr there
8126          * to simulate dst (== 0) +/-= ptr. Needed, for example,
8127          * for cases where we use K-based arithmetic in one direction
8128          * and truncated reg-based in the other in order to explore
8129          * bad access.
8130          */
8131         if (!ptr_is_dst_reg) {
8132                 tmp = *dst_reg;
8133                 copy_register_state(dst_reg, ptr_reg);
8134         }
8135         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8136                                         env->insn_idx);
8137         if (!ptr_is_dst_reg && ret)
8138                 *dst_reg = tmp;
8139         return !ret ? REASON_STACK : 0;
8140 }
8141
8142 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8143 {
8144         struct bpf_verifier_state *vstate = env->cur_state;
8145
8146         /* If we simulate paths under speculation, we don't update the
8147          * insn as 'seen' such that when we verify unreachable paths in
8148          * the non-speculative domain, sanitize_dead_code() can still
8149          * rewrite/sanitize them.
8150          */
8151         if (!vstate->speculative)
8152                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8153 }
8154
8155 static int sanitize_err(struct bpf_verifier_env *env,
8156                         const struct bpf_insn *insn, int reason,
8157                         const struct bpf_reg_state *off_reg,
8158                         const struct bpf_reg_state *dst_reg)
8159 {
8160         static const char *err = "pointer arithmetic with it prohibited for !root";
8161         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8162         u32 dst = insn->dst_reg, src = insn->src_reg;
8163
8164         switch (reason) {
8165         case REASON_BOUNDS:
8166                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8167                         off_reg == dst_reg ? dst : src, err);
8168                 break;
8169         case REASON_TYPE:
8170                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8171                         off_reg == dst_reg ? src : dst, err);
8172                 break;
8173         case REASON_PATHS:
8174                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8175                         dst, op, err);
8176                 break;
8177         case REASON_LIMIT:
8178                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8179                         dst, op, err);
8180                 break;
8181         case REASON_STACK:
8182                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8183                         dst, err);
8184                 break;
8185         default:
8186                 verbose(env, "verifier internal error: unknown reason (%d)\n",
8187                         reason);
8188                 break;
8189         }
8190
8191         return -EACCES;
8192 }
8193
8194 /* check that stack access falls within stack limits and that 'reg' doesn't
8195  * have a variable offset.
8196  *
8197  * Variable offset is prohibited for unprivileged mode for simplicity since it
8198  * requires corresponding support in Spectre masking for stack ALU.  See also
8199  * retrieve_ptr_limit().
8200  *
8201  *
8202  * 'off' includes 'reg->off'.
8203  */
8204 static int check_stack_access_for_ptr_arithmetic(
8205                                 struct bpf_verifier_env *env,
8206                                 int regno,
8207                                 const struct bpf_reg_state *reg,
8208                                 int off)
8209 {
8210         if (!tnum_is_const(reg->var_off)) {
8211                 char tn_buf[48];
8212
8213                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8214                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8215                         regno, tn_buf, off);
8216                 return -EACCES;
8217         }
8218
8219         if (off >= 0 || off < -MAX_BPF_STACK) {
8220                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8221                         "prohibited for !root; off=%d\n", regno, off);
8222                 return -EACCES;
8223         }
8224
8225         return 0;
8226 }
8227
8228 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8229                                  const struct bpf_insn *insn,
8230                                  const struct bpf_reg_state *dst_reg)
8231 {
8232         u32 dst = insn->dst_reg;
8233
8234         /* For unprivileged we require that resulting offset must be in bounds
8235          * in order to be able to sanitize access later on.
8236          */
8237         if (env->bypass_spec_v1)
8238                 return 0;
8239
8240         switch (dst_reg->type) {
8241         case PTR_TO_STACK:
8242                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8243                                         dst_reg->off + dst_reg->var_off.value))
8244                         return -EACCES;
8245                 break;
8246         case PTR_TO_MAP_VALUE:
8247                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8248                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8249                                 "prohibited for !root\n", dst);
8250                         return -EACCES;
8251                 }
8252                 break;
8253         default:
8254                 break;
8255         }
8256
8257         return 0;
8258 }
8259
8260 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8261  * Caller should also handle BPF_MOV case separately.
8262  * If we return -EACCES, caller may want to try again treating pointer as a
8263  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8264  */
8265 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8266                                    struct bpf_insn *insn,
8267                                    const struct bpf_reg_state *ptr_reg,
8268                                    const struct bpf_reg_state *off_reg)
8269 {
8270         struct bpf_verifier_state *vstate = env->cur_state;
8271         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8272         struct bpf_reg_state *regs = state->regs, *dst_reg;
8273         bool known = tnum_is_const(off_reg->var_off);
8274         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8275             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8276         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8277             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8278         struct bpf_sanitize_info info = {};
8279         u8 opcode = BPF_OP(insn->code);
8280         u32 dst = insn->dst_reg;
8281         int ret;
8282
8283         dst_reg = &regs[dst];
8284
8285         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8286             smin_val > smax_val || umin_val > umax_val) {
8287                 /* Taint dst register if offset had invalid bounds derived from
8288                  * e.g. dead branches.
8289                  */
8290                 __mark_reg_unknown(env, dst_reg);
8291                 return 0;
8292         }
8293
8294         if (BPF_CLASS(insn->code) != BPF_ALU64) {
8295                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8296                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8297                         __mark_reg_unknown(env, dst_reg);
8298                         return 0;
8299                 }
8300
8301                 verbose(env,
8302                         "R%d 32-bit pointer arithmetic prohibited\n",
8303                         dst);
8304                 return -EACCES;
8305         }
8306
8307         if (ptr_reg->type & PTR_MAYBE_NULL) {
8308                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8309                         dst, reg_type_str(env, ptr_reg->type));
8310                 return -EACCES;
8311         }
8312
8313         switch (base_type(ptr_reg->type)) {
8314         case CONST_PTR_TO_MAP:
8315                 /* smin_val represents the known value */
8316                 if (known && smin_val == 0 && opcode == BPF_ADD)
8317                         break;
8318                 fallthrough;
8319         case PTR_TO_PACKET_END:
8320         case PTR_TO_SOCKET:
8321         case PTR_TO_SOCK_COMMON:
8322         case PTR_TO_TCP_SOCK:
8323         case PTR_TO_XDP_SOCK:
8324                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8325                         dst, reg_type_str(env, ptr_reg->type));
8326                 return -EACCES;
8327         default:
8328                 break;
8329         }
8330
8331         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8332          * The id may be overwritten later if we create a new variable offset.
8333          */
8334         dst_reg->type = ptr_reg->type;
8335         dst_reg->id = ptr_reg->id;
8336
8337         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8338             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8339                 return -EINVAL;
8340
8341         /* pointer types do not carry 32-bit bounds at the moment. */
8342         __mark_reg32_unbounded(dst_reg);
8343
8344         if (sanitize_needed(opcode)) {
8345                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8346                                        &info, false);
8347                 if (ret < 0)
8348                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8349         }
8350
8351         switch (opcode) {
8352         case BPF_ADD:
8353                 /* We can take a fixed offset as long as it doesn't overflow
8354                  * the s32 'off' field
8355                  */
8356                 if (known && (ptr_reg->off + smin_val ==
8357                               (s64)(s32)(ptr_reg->off + smin_val))) {
8358                         /* pointer += K.  Accumulate it into fixed offset */
8359                         dst_reg->smin_value = smin_ptr;
8360                         dst_reg->smax_value = smax_ptr;
8361                         dst_reg->umin_value = umin_ptr;
8362                         dst_reg->umax_value = umax_ptr;
8363                         dst_reg->var_off = ptr_reg->var_off;
8364                         dst_reg->off = ptr_reg->off + smin_val;
8365                         dst_reg->raw = ptr_reg->raw;
8366                         break;
8367                 }
8368                 /* A new variable offset is created.  Note that off_reg->off
8369                  * == 0, since it's a scalar.
8370                  * dst_reg gets the pointer type and since some positive
8371                  * integer value was added to the pointer, give it a new 'id'
8372                  * if it's a PTR_TO_PACKET.
8373                  * this creates a new 'base' pointer, off_reg (variable) gets
8374                  * added into the variable offset, and we copy the fixed offset
8375                  * from ptr_reg.
8376                  */
8377                 if (signed_add_overflows(smin_ptr, smin_val) ||
8378                     signed_add_overflows(smax_ptr, smax_val)) {
8379                         dst_reg->smin_value = S64_MIN;
8380                         dst_reg->smax_value = S64_MAX;
8381                 } else {
8382                         dst_reg->smin_value = smin_ptr + smin_val;
8383                         dst_reg->smax_value = smax_ptr + smax_val;
8384                 }
8385                 if (umin_ptr + umin_val < umin_ptr ||
8386                     umax_ptr + umax_val < umax_ptr) {
8387                         dst_reg->umin_value = 0;
8388                         dst_reg->umax_value = U64_MAX;
8389                 } else {
8390                         dst_reg->umin_value = umin_ptr + umin_val;
8391                         dst_reg->umax_value = umax_ptr + umax_val;
8392                 }
8393                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8394                 dst_reg->off = ptr_reg->off;
8395                 dst_reg->raw = ptr_reg->raw;
8396                 if (reg_is_pkt_pointer(ptr_reg)) {
8397                         dst_reg->id = ++env->id_gen;
8398                         /* something was added to pkt_ptr, set range to zero */
8399                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8400                 }
8401                 break;
8402         case BPF_SUB:
8403                 if (dst_reg == off_reg) {
8404                         /* scalar -= pointer.  Creates an unknown scalar */
8405                         verbose(env, "R%d tried to subtract pointer from scalar\n",
8406                                 dst);
8407                         return -EACCES;
8408                 }
8409                 /* We don't allow subtraction from FP, because (according to
8410                  * test_verifier.c test "invalid fp arithmetic", JITs might not
8411                  * be able to deal with it.
8412                  */
8413                 if (ptr_reg->type == PTR_TO_STACK) {
8414                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
8415                                 dst);
8416                         return -EACCES;
8417                 }
8418                 if (known && (ptr_reg->off - smin_val ==
8419                               (s64)(s32)(ptr_reg->off - smin_val))) {
8420                         /* pointer -= K.  Subtract it from fixed offset */
8421                         dst_reg->smin_value = smin_ptr;
8422                         dst_reg->smax_value = smax_ptr;
8423                         dst_reg->umin_value = umin_ptr;
8424                         dst_reg->umax_value = umax_ptr;
8425                         dst_reg->var_off = ptr_reg->var_off;
8426                         dst_reg->id = ptr_reg->id;
8427                         dst_reg->off = ptr_reg->off - smin_val;
8428                         dst_reg->raw = ptr_reg->raw;
8429                         break;
8430                 }
8431                 /* A new variable offset is created.  If the subtrahend is known
8432                  * nonnegative, then any reg->range we had before is still good.
8433                  */
8434                 if (signed_sub_overflows(smin_ptr, smax_val) ||
8435                     signed_sub_overflows(smax_ptr, smin_val)) {
8436                         /* Overflow possible, we know nothing */
8437                         dst_reg->smin_value = S64_MIN;
8438                         dst_reg->smax_value = S64_MAX;
8439                 } else {
8440                         dst_reg->smin_value = smin_ptr - smax_val;
8441                         dst_reg->smax_value = smax_ptr - smin_val;
8442                 }
8443                 if (umin_ptr < umax_val) {
8444                         /* Overflow possible, we know nothing */
8445                         dst_reg->umin_value = 0;
8446                         dst_reg->umax_value = U64_MAX;
8447                 } else {
8448                         /* Cannot overflow (as long as bounds are consistent) */
8449                         dst_reg->umin_value = umin_ptr - umax_val;
8450                         dst_reg->umax_value = umax_ptr - umin_val;
8451                 }
8452                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8453                 dst_reg->off = ptr_reg->off;
8454                 dst_reg->raw = ptr_reg->raw;
8455                 if (reg_is_pkt_pointer(ptr_reg)) {
8456                         dst_reg->id = ++env->id_gen;
8457                         /* something was added to pkt_ptr, set range to zero */
8458                         if (smin_val < 0)
8459                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8460                 }
8461                 break;
8462         case BPF_AND:
8463         case BPF_OR:
8464         case BPF_XOR:
8465                 /* bitwise ops on pointers are troublesome, prohibit. */
8466                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8467                         dst, bpf_alu_string[opcode >> 4]);
8468                 return -EACCES;
8469         default:
8470                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8471                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8472                         dst, bpf_alu_string[opcode >> 4]);
8473                 return -EACCES;
8474         }
8475
8476         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8477                 return -EINVAL;
8478         reg_bounds_sync(dst_reg);
8479         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8480                 return -EACCES;
8481         if (sanitize_needed(opcode)) {
8482                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8483                                        &info, true);
8484                 if (ret < 0)
8485                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8486         }
8487
8488         return 0;
8489 }
8490
8491 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8492                                  struct bpf_reg_state *src_reg)
8493 {
8494         s32 smin_val = src_reg->s32_min_value;
8495         s32 smax_val = src_reg->s32_max_value;
8496         u32 umin_val = src_reg->u32_min_value;
8497         u32 umax_val = src_reg->u32_max_value;
8498
8499         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8500             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8501                 dst_reg->s32_min_value = S32_MIN;
8502                 dst_reg->s32_max_value = S32_MAX;
8503         } else {
8504                 dst_reg->s32_min_value += smin_val;
8505                 dst_reg->s32_max_value += smax_val;
8506         }
8507         if (dst_reg->u32_min_value + umin_val < umin_val ||
8508             dst_reg->u32_max_value + umax_val < umax_val) {
8509                 dst_reg->u32_min_value = 0;
8510                 dst_reg->u32_max_value = U32_MAX;
8511         } else {
8512                 dst_reg->u32_min_value += umin_val;
8513                 dst_reg->u32_max_value += umax_val;
8514         }
8515 }
8516
8517 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8518                                struct bpf_reg_state *src_reg)
8519 {
8520         s64 smin_val = src_reg->smin_value;
8521         s64 smax_val = src_reg->smax_value;
8522         u64 umin_val = src_reg->umin_value;
8523         u64 umax_val = src_reg->umax_value;
8524
8525         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8526             signed_add_overflows(dst_reg->smax_value, smax_val)) {
8527                 dst_reg->smin_value = S64_MIN;
8528                 dst_reg->smax_value = S64_MAX;
8529         } else {
8530                 dst_reg->smin_value += smin_val;
8531                 dst_reg->smax_value += smax_val;
8532         }
8533         if (dst_reg->umin_value + umin_val < umin_val ||
8534             dst_reg->umax_value + umax_val < umax_val) {
8535                 dst_reg->umin_value = 0;
8536                 dst_reg->umax_value = U64_MAX;
8537         } else {
8538                 dst_reg->umin_value += umin_val;
8539                 dst_reg->umax_value += umax_val;
8540         }
8541 }
8542
8543 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8544                                  struct bpf_reg_state *src_reg)
8545 {
8546         s32 smin_val = src_reg->s32_min_value;
8547         s32 smax_val = src_reg->s32_max_value;
8548         u32 umin_val = src_reg->u32_min_value;
8549         u32 umax_val = src_reg->u32_max_value;
8550
8551         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8552             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8553                 /* Overflow possible, we know nothing */
8554                 dst_reg->s32_min_value = S32_MIN;
8555                 dst_reg->s32_max_value = S32_MAX;
8556         } else {
8557                 dst_reg->s32_min_value -= smax_val;
8558                 dst_reg->s32_max_value -= smin_val;
8559         }
8560         if (dst_reg->u32_min_value < umax_val) {
8561                 /* Overflow possible, we know nothing */
8562                 dst_reg->u32_min_value = 0;
8563                 dst_reg->u32_max_value = U32_MAX;
8564         } else {
8565                 /* Cannot overflow (as long as bounds are consistent) */
8566                 dst_reg->u32_min_value -= umax_val;
8567                 dst_reg->u32_max_value -= umin_val;
8568         }
8569 }
8570
8571 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8572                                struct bpf_reg_state *src_reg)
8573 {
8574         s64 smin_val = src_reg->smin_value;
8575         s64 smax_val = src_reg->smax_value;
8576         u64 umin_val = src_reg->umin_value;
8577         u64 umax_val = src_reg->umax_value;
8578
8579         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8580             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8581                 /* Overflow possible, we know nothing */
8582                 dst_reg->smin_value = S64_MIN;
8583                 dst_reg->smax_value = S64_MAX;
8584         } else {
8585                 dst_reg->smin_value -= smax_val;
8586                 dst_reg->smax_value -= smin_val;
8587         }
8588         if (dst_reg->umin_value < umax_val) {
8589                 /* Overflow possible, we know nothing */
8590                 dst_reg->umin_value = 0;
8591                 dst_reg->umax_value = U64_MAX;
8592         } else {
8593                 /* Cannot overflow (as long as bounds are consistent) */
8594                 dst_reg->umin_value -= umax_val;
8595                 dst_reg->umax_value -= umin_val;
8596         }
8597 }
8598
8599 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8600                                  struct bpf_reg_state *src_reg)
8601 {
8602         s32 smin_val = src_reg->s32_min_value;
8603         u32 umin_val = src_reg->u32_min_value;
8604         u32 umax_val = src_reg->u32_max_value;
8605
8606         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8607                 /* Ain't nobody got time to multiply that sign */
8608                 __mark_reg32_unbounded(dst_reg);
8609                 return;
8610         }
8611         /* Both values are positive, so we can work with unsigned and
8612          * copy the result to signed (unless it exceeds S32_MAX).
8613          */
8614         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8615                 /* Potential overflow, we know nothing */
8616                 __mark_reg32_unbounded(dst_reg);
8617                 return;
8618         }
8619         dst_reg->u32_min_value *= umin_val;
8620         dst_reg->u32_max_value *= umax_val;
8621         if (dst_reg->u32_max_value > S32_MAX) {
8622                 /* Overflow possible, we know nothing */
8623                 dst_reg->s32_min_value = S32_MIN;
8624                 dst_reg->s32_max_value = S32_MAX;
8625         } else {
8626                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8627                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8628         }
8629 }
8630
8631 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8632                                struct bpf_reg_state *src_reg)
8633 {
8634         s64 smin_val = src_reg->smin_value;
8635         u64 umin_val = src_reg->umin_value;
8636         u64 umax_val = src_reg->umax_value;
8637
8638         if (smin_val < 0 || dst_reg->smin_value < 0) {
8639                 /* Ain't nobody got time to multiply that sign */
8640                 __mark_reg64_unbounded(dst_reg);
8641                 return;
8642         }
8643         /* Both values are positive, so we can work with unsigned and
8644          * copy the result to signed (unless it exceeds S64_MAX).
8645          */
8646         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8647                 /* Potential overflow, we know nothing */
8648                 __mark_reg64_unbounded(dst_reg);
8649                 return;
8650         }
8651         dst_reg->umin_value *= umin_val;
8652         dst_reg->umax_value *= umax_val;
8653         if (dst_reg->umax_value > S64_MAX) {
8654                 /* Overflow possible, we know nothing */
8655                 dst_reg->smin_value = S64_MIN;
8656                 dst_reg->smax_value = S64_MAX;
8657         } else {
8658                 dst_reg->smin_value = dst_reg->umin_value;
8659                 dst_reg->smax_value = dst_reg->umax_value;
8660         }
8661 }
8662
8663 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8664                                  struct bpf_reg_state *src_reg)
8665 {
8666         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8667         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8668         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8669         s32 smin_val = src_reg->s32_min_value;
8670         u32 umax_val = src_reg->u32_max_value;
8671
8672         if (src_known && dst_known) {
8673                 __mark_reg32_known(dst_reg, var32_off.value);
8674                 return;
8675         }
8676
8677         /* We get our minimum from the var_off, since that's inherently
8678          * bitwise.  Our maximum is the minimum of the operands' maxima.
8679          */
8680         dst_reg->u32_min_value = var32_off.value;
8681         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8682         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8683                 /* Lose signed bounds when ANDing negative numbers,
8684                  * ain't nobody got time for that.
8685                  */
8686                 dst_reg->s32_min_value = S32_MIN;
8687                 dst_reg->s32_max_value = S32_MAX;
8688         } else {
8689                 /* ANDing two positives gives a positive, so safe to
8690                  * cast result into s64.
8691                  */
8692                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8693                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8694         }
8695 }
8696
8697 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8698                                struct bpf_reg_state *src_reg)
8699 {
8700         bool src_known = tnum_is_const(src_reg->var_off);
8701         bool dst_known = tnum_is_const(dst_reg->var_off);
8702         s64 smin_val = src_reg->smin_value;
8703         u64 umax_val = src_reg->umax_value;
8704
8705         if (src_known && dst_known) {
8706                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8707                 return;
8708         }
8709
8710         /* We get our minimum from the var_off, since that's inherently
8711          * bitwise.  Our maximum is the minimum of the operands' maxima.
8712          */
8713         dst_reg->umin_value = dst_reg->var_off.value;
8714         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8715         if (dst_reg->smin_value < 0 || smin_val < 0) {
8716                 /* Lose signed bounds when ANDing negative numbers,
8717                  * ain't nobody got time for that.
8718                  */
8719                 dst_reg->smin_value = S64_MIN;
8720                 dst_reg->smax_value = S64_MAX;
8721         } else {
8722                 /* ANDing two positives gives a positive, so safe to
8723                  * cast result into s64.
8724                  */
8725                 dst_reg->smin_value = dst_reg->umin_value;
8726                 dst_reg->smax_value = dst_reg->umax_value;
8727         }
8728         /* We may learn something more from the var_off */
8729         __update_reg_bounds(dst_reg);
8730 }
8731
8732 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8733                                 struct bpf_reg_state *src_reg)
8734 {
8735         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8736         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8737         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8738         s32 smin_val = src_reg->s32_min_value;
8739         u32 umin_val = src_reg->u32_min_value;
8740
8741         if (src_known && dst_known) {
8742                 __mark_reg32_known(dst_reg, var32_off.value);
8743                 return;
8744         }
8745
8746         /* We get our maximum from the var_off, and our minimum is the
8747          * maximum of the operands' minima
8748          */
8749         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8750         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8751         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8752                 /* Lose signed bounds when ORing negative numbers,
8753                  * ain't nobody got time for that.
8754                  */
8755                 dst_reg->s32_min_value = S32_MIN;
8756                 dst_reg->s32_max_value = S32_MAX;
8757         } else {
8758                 /* ORing two positives gives a positive, so safe to
8759                  * cast result into s64.
8760                  */
8761                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8762                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8763         }
8764 }
8765
8766 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8767                               struct bpf_reg_state *src_reg)
8768 {
8769         bool src_known = tnum_is_const(src_reg->var_off);
8770         bool dst_known = tnum_is_const(dst_reg->var_off);
8771         s64 smin_val = src_reg->smin_value;
8772         u64 umin_val = src_reg->umin_value;
8773
8774         if (src_known && dst_known) {
8775                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8776                 return;
8777         }
8778
8779         /* We get our maximum from the var_off, and our minimum is the
8780          * maximum of the operands' minima
8781          */
8782         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8783         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8784         if (dst_reg->smin_value < 0 || smin_val < 0) {
8785                 /* Lose signed bounds when ORing negative numbers,
8786                  * ain't nobody got time for that.
8787                  */
8788                 dst_reg->smin_value = S64_MIN;
8789                 dst_reg->smax_value = S64_MAX;
8790         } else {
8791                 /* ORing two positives gives a positive, so safe to
8792                  * cast result into s64.
8793                  */
8794                 dst_reg->smin_value = dst_reg->umin_value;
8795                 dst_reg->smax_value = dst_reg->umax_value;
8796         }
8797         /* We may learn something more from the var_off */
8798         __update_reg_bounds(dst_reg);
8799 }
8800
8801 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8802                                  struct bpf_reg_state *src_reg)
8803 {
8804         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8805         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8806         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8807         s32 smin_val = src_reg->s32_min_value;
8808
8809         if (src_known && dst_known) {
8810                 __mark_reg32_known(dst_reg, var32_off.value);
8811                 return;
8812         }
8813
8814         /* We get both minimum and maximum from the var32_off. */
8815         dst_reg->u32_min_value = var32_off.value;
8816         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8817
8818         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8819                 /* XORing two positive sign numbers gives a positive,
8820                  * so safe to cast u32 result into s32.
8821                  */
8822                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8823                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8824         } else {
8825                 dst_reg->s32_min_value = S32_MIN;
8826                 dst_reg->s32_max_value = S32_MAX;
8827         }
8828 }
8829
8830 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8831                                struct bpf_reg_state *src_reg)
8832 {
8833         bool src_known = tnum_is_const(src_reg->var_off);
8834         bool dst_known = tnum_is_const(dst_reg->var_off);
8835         s64 smin_val = src_reg->smin_value;
8836
8837         if (src_known && dst_known) {
8838                 /* dst_reg->var_off.value has been updated earlier */
8839                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8840                 return;
8841         }
8842
8843         /* We get both minimum and maximum from the var_off. */
8844         dst_reg->umin_value = dst_reg->var_off.value;
8845         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8846
8847         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8848                 /* XORing two positive sign numbers gives a positive,
8849                  * so safe to cast u64 result into s64.
8850                  */
8851                 dst_reg->smin_value = dst_reg->umin_value;
8852                 dst_reg->smax_value = dst_reg->umax_value;
8853         } else {
8854                 dst_reg->smin_value = S64_MIN;
8855                 dst_reg->smax_value = S64_MAX;
8856         }
8857
8858         __update_reg_bounds(dst_reg);
8859 }
8860
8861 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8862                                    u64 umin_val, u64 umax_val)
8863 {
8864         /* We lose all sign bit information (except what we can pick
8865          * up from var_off)
8866          */
8867         dst_reg->s32_min_value = S32_MIN;
8868         dst_reg->s32_max_value = S32_MAX;
8869         /* If we might shift our top bit out, then we know nothing */
8870         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8871                 dst_reg->u32_min_value = 0;
8872                 dst_reg->u32_max_value = U32_MAX;
8873         } else {
8874                 dst_reg->u32_min_value <<= umin_val;
8875                 dst_reg->u32_max_value <<= umax_val;
8876         }
8877 }
8878
8879 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8880                                  struct bpf_reg_state *src_reg)
8881 {
8882         u32 umax_val = src_reg->u32_max_value;
8883         u32 umin_val = src_reg->u32_min_value;
8884         /* u32 alu operation will zext upper bits */
8885         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8886
8887         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8888         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8889         /* Not required but being careful mark reg64 bounds as unknown so
8890          * that we are forced to pick them up from tnum and zext later and
8891          * if some path skips this step we are still safe.
8892          */
8893         __mark_reg64_unbounded(dst_reg);
8894         __update_reg32_bounds(dst_reg);
8895 }
8896
8897 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8898                                    u64 umin_val, u64 umax_val)
8899 {
8900         /* Special case <<32 because it is a common compiler pattern to sign
8901          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8902          * positive we know this shift will also be positive so we can track
8903          * bounds correctly. Otherwise we lose all sign bit information except
8904          * what we can pick up from var_off. Perhaps we can generalize this
8905          * later to shifts of any length.
8906          */
8907         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8908                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8909         else
8910                 dst_reg->smax_value = S64_MAX;
8911
8912         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8913                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8914         else
8915                 dst_reg->smin_value = S64_MIN;
8916
8917         /* If we might shift our top bit out, then we know nothing */
8918         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8919                 dst_reg->umin_value = 0;
8920                 dst_reg->umax_value = U64_MAX;
8921         } else {
8922                 dst_reg->umin_value <<= umin_val;
8923                 dst_reg->umax_value <<= umax_val;
8924         }
8925 }
8926
8927 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8928                                struct bpf_reg_state *src_reg)
8929 {
8930         u64 umax_val = src_reg->umax_value;
8931         u64 umin_val = src_reg->umin_value;
8932
8933         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8934         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8935         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8936
8937         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8938         /* We may learn something more from the var_off */
8939         __update_reg_bounds(dst_reg);
8940 }
8941
8942 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8943                                  struct bpf_reg_state *src_reg)
8944 {
8945         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8946         u32 umax_val = src_reg->u32_max_value;
8947         u32 umin_val = src_reg->u32_min_value;
8948
8949         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8950          * be negative, then either:
8951          * 1) src_reg might be zero, so the sign bit of the result is
8952          *    unknown, so we lose our signed bounds
8953          * 2) it's known negative, thus the unsigned bounds capture the
8954          *    signed bounds
8955          * 3) the signed bounds cross zero, so they tell us nothing
8956          *    about the result
8957          * If the value in dst_reg is known nonnegative, then again the
8958          * unsigned bounds capture the signed bounds.
8959          * Thus, in all cases it suffices to blow away our signed bounds
8960          * and rely on inferring new ones from the unsigned bounds and
8961          * var_off of the result.
8962          */
8963         dst_reg->s32_min_value = S32_MIN;
8964         dst_reg->s32_max_value = S32_MAX;
8965
8966         dst_reg->var_off = tnum_rshift(subreg, umin_val);
8967         dst_reg->u32_min_value >>= umax_val;
8968         dst_reg->u32_max_value >>= umin_val;
8969
8970         __mark_reg64_unbounded(dst_reg);
8971         __update_reg32_bounds(dst_reg);
8972 }
8973
8974 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8975                                struct bpf_reg_state *src_reg)
8976 {
8977         u64 umax_val = src_reg->umax_value;
8978         u64 umin_val = src_reg->umin_value;
8979
8980         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8981          * be negative, then either:
8982          * 1) src_reg might be zero, so the sign bit of the result is
8983          *    unknown, so we lose our signed bounds
8984          * 2) it's known negative, thus the unsigned bounds capture the
8985          *    signed bounds
8986          * 3) the signed bounds cross zero, so they tell us nothing
8987          *    about the result
8988          * If the value in dst_reg is known nonnegative, then again the
8989          * unsigned bounds capture the signed bounds.
8990          * Thus, in all cases it suffices to blow away our signed bounds
8991          * and rely on inferring new ones from the unsigned bounds and
8992          * var_off of the result.
8993          */
8994         dst_reg->smin_value = S64_MIN;
8995         dst_reg->smax_value = S64_MAX;
8996         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8997         dst_reg->umin_value >>= umax_val;
8998         dst_reg->umax_value >>= umin_val;
8999
9000         /* Its not easy to operate on alu32 bounds here because it depends
9001          * on bits being shifted in. Take easy way out and mark unbounded
9002          * so we can recalculate later from tnum.
9003          */
9004         __mark_reg32_unbounded(dst_reg);
9005         __update_reg_bounds(dst_reg);
9006 }
9007
9008 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
9009                                   struct bpf_reg_state *src_reg)
9010 {
9011         u64 umin_val = src_reg->u32_min_value;
9012
9013         /* Upon reaching here, src_known is true and
9014          * umax_val is equal to umin_val.
9015          */
9016         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
9017         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
9018
9019         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
9020
9021         /* blow away the dst_reg umin_value/umax_value and rely on
9022          * dst_reg var_off to refine the result.
9023          */
9024         dst_reg->u32_min_value = 0;
9025         dst_reg->u32_max_value = U32_MAX;
9026
9027         __mark_reg64_unbounded(dst_reg);
9028         __update_reg32_bounds(dst_reg);
9029 }
9030
9031 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
9032                                 struct bpf_reg_state *src_reg)
9033 {
9034         u64 umin_val = src_reg->umin_value;
9035
9036         /* Upon reaching here, src_known is true and umax_val is equal
9037          * to umin_val.
9038          */
9039         dst_reg->smin_value >>= umin_val;
9040         dst_reg->smax_value >>= umin_val;
9041
9042         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
9043
9044         /* blow away the dst_reg umin_value/umax_value and rely on
9045          * dst_reg var_off to refine the result.
9046          */
9047         dst_reg->umin_value = 0;
9048         dst_reg->umax_value = U64_MAX;
9049
9050         /* Its not easy to operate on alu32 bounds here because it depends
9051          * on bits being shifted in from upper 32-bits. Take easy way out
9052          * and mark unbounded so we can recalculate later from tnum.
9053          */
9054         __mark_reg32_unbounded(dst_reg);
9055         __update_reg_bounds(dst_reg);
9056 }
9057
9058 /* WARNING: This function does calculations on 64-bit values, but the actual
9059  * execution may occur on 32-bit values. Therefore, things like bitshifts
9060  * need extra checks in the 32-bit case.
9061  */
9062 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9063                                       struct bpf_insn *insn,
9064                                       struct bpf_reg_state *dst_reg,
9065                                       struct bpf_reg_state src_reg)
9066 {
9067         struct bpf_reg_state *regs = cur_regs(env);
9068         u8 opcode = BPF_OP(insn->code);
9069         bool src_known;
9070         s64 smin_val, smax_val;
9071         u64 umin_val, umax_val;
9072         s32 s32_min_val, s32_max_val;
9073         u32 u32_min_val, u32_max_val;
9074         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9075         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9076         int ret;
9077
9078         smin_val = src_reg.smin_value;
9079         smax_val = src_reg.smax_value;
9080         umin_val = src_reg.umin_value;
9081         umax_val = src_reg.umax_value;
9082
9083         s32_min_val = src_reg.s32_min_value;
9084         s32_max_val = src_reg.s32_max_value;
9085         u32_min_val = src_reg.u32_min_value;
9086         u32_max_val = src_reg.u32_max_value;
9087
9088         if (alu32) {
9089                 src_known = tnum_subreg_is_const(src_reg.var_off);
9090                 if ((src_known &&
9091                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9092                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9093                         /* Taint dst register if offset had invalid bounds
9094                          * derived from e.g. dead branches.
9095                          */
9096                         __mark_reg_unknown(env, dst_reg);
9097                         return 0;
9098                 }
9099         } else {
9100                 src_known = tnum_is_const(src_reg.var_off);
9101                 if ((src_known &&
9102                      (smin_val != smax_val || umin_val != umax_val)) ||
9103                     smin_val > smax_val || umin_val > umax_val) {
9104                         /* Taint dst register if offset had invalid bounds
9105                          * derived from e.g. dead branches.
9106                          */
9107                         __mark_reg_unknown(env, dst_reg);
9108                         return 0;
9109                 }
9110         }
9111
9112         if (!src_known &&
9113             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9114                 __mark_reg_unknown(env, dst_reg);
9115                 return 0;
9116         }
9117
9118         if (sanitize_needed(opcode)) {
9119                 ret = sanitize_val_alu(env, insn);
9120                 if (ret < 0)
9121                         return sanitize_err(env, insn, ret, NULL, NULL);
9122         }
9123
9124         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9125          * There are two classes of instructions: The first class we track both
9126          * alu32 and alu64 sign/unsigned bounds independently this provides the
9127          * greatest amount of precision when alu operations are mixed with jmp32
9128          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9129          * and BPF_OR. This is possible because these ops have fairly easy to
9130          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9131          * See alu32 verifier tests for examples. The second class of
9132          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9133          * with regards to tracking sign/unsigned bounds because the bits may
9134          * cross subreg boundaries in the alu64 case. When this happens we mark
9135          * the reg unbounded in the subreg bound space and use the resulting
9136          * tnum to calculate an approximation of the sign/unsigned bounds.
9137          */
9138         switch (opcode) {
9139         case BPF_ADD:
9140                 scalar32_min_max_add(dst_reg, &src_reg);
9141                 scalar_min_max_add(dst_reg, &src_reg);
9142                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9143                 break;
9144         case BPF_SUB:
9145                 scalar32_min_max_sub(dst_reg, &src_reg);
9146                 scalar_min_max_sub(dst_reg, &src_reg);
9147                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9148                 break;
9149         case BPF_MUL:
9150                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9151                 scalar32_min_max_mul(dst_reg, &src_reg);
9152                 scalar_min_max_mul(dst_reg, &src_reg);
9153                 break;
9154         case BPF_AND:
9155                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9156                 scalar32_min_max_and(dst_reg, &src_reg);
9157                 scalar_min_max_and(dst_reg, &src_reg);
9158                 break;
9159         case BPF_OR:
9160                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9161                 scalar32_min_max_or(dst_reg, &src_reg);
9162                 scalar_min_max_or(dst_reg, &src_reg);
9163                 break;
9164         case BPF_XOR:
9165                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9166                 scalar32_min_max_xor(dst_reg, &src_reg);
9167                 scalar_min_max_xor(dst_reg, &src_reg);
9168                 break;
9169         case BPF_LSH:
9170                 if (umax_val >= insn_bitness) {
9171                         /* Shifts greater than 31 or 63 are undefined.
9172                          * This includes shifts by a negative number.
9173                          */
9174                         mark_reg_unknown(env, regs, insn->dst_reg);
9175                         break;
9176                 }
9177                 if (alu32)
9178                         scalar32_min_max_lsh(dst_reg, &src_reg);
9179                 else
9180                         scalar_min_max_lsh(dst_reg, &src_reg);
9181                 break;
9182         case BPF_RSH:
9183                 if (umax_val >= insn_bitness) {
9184                         /* Shifts greater than 31 or 63 are undefined.
9185                          * This includes shifts by a negative number.
9186                          */
9187                         mark_reg_unknown(env, regs, insn->dst_reg);
9188                         break;
9189                 }
9190                 if (alu32)
9191                         scalar32_min_max_rsh(dst_reg, &src_reg);
9192                 else
9193                         scalar_min_max_rsh(dst_reg, &src_reg);
9194                 break;
9195         case BPF_ARSH:
9196                 if (umax_val >= insn_bitness) {
9197                         /* Shifts greater than 31 or 63 are undefined.
9198                          * This includes shifts by a negative number.
9199                          */
9200                         mark_reg_unknown(env, regs, insn->dst_reg);
9201                         break;
9202                 }
9203                 if (alu32)
9204                         scalar32_min_max_arsh(dst_reg, &src_reg);
9205                 else
9206                         scalar_min_max_arsh(dst_reg, &src_reg);
9207                 break;
9208         default:
9209                 mark_reg_unknown(env, regs, insn->dst_reg);
9210                 break;
9211         }
9212
9213         /* ALU32 ops are zero extended into 64bit register */
9214         if (alu32)
9215                 zext_32_to_64(dst_reg);
9216         reg_bounds_sync(dst_reg);
9217         return 0;
9218 }
9219
9220 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9221  * and var_off.
9222  */
9223 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9224                                    struct bpf_insn *insn)
9225 {
9226         struct bpf_verifier_state *vstate = env->cur_state;
9227         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9228         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9229         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9230         u8 opcode = BPF_OP(insn->code);
9231         int err;
9232
9233         dst_reg = &regs[insn->dst_reg];
9234         src_reg = NULL;
9235         if (dst_reg->type != SCALAR_VALUE)
9236                 ptr_reg = dst_reg;
9237         else
9238                 /* Make sure ID is cleared otherwise dst_reg min/max could be
9239                  * incorrectly propagated into other registers by find_equal_scalars()
9240                  */
9241                 dst_reg->id = 0;
9242         if (BPF_SRC(insn->code) == BPF_X) {
9243                 src_reg = &regs[insn->src_reg];
9244                 if (src_reg->type != SCALAR_VALUE) {
9245                         if (dst_reg->type != SCALAR_VALUE) {
9246                                 /* Combining two pointers by any ALU op yields
9247                                  * an arbitrary scalar. Disallow all math except
9248                                  * pointer subtraction
9249                                  */
9250                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9251                                         mark_reg_unknown(env, regs, insn->dst_reg);
9252                                         return 0;
9253                                 }
9254                                 verbose(env, "R%d pointer %s pointer prohibited\n",
9255                                         insn->dst_reg,
9256                                         bpf_alu_string[opcode >> 4]);
9257                                 return -EACCES;
9258                         } else {
9259                                 /* scalar += pointer
9260                                  * This is legal, but we have to reverse our
9261                                  * src/dest handling in computing the range
9262                                  */
9263                                 err = mark_chain_precision(env, insn->dst_reg);
9264                                 if (err)
9265                                         return err;
9266                                 return adjust_ptr_min_max_vals(env, insn,
9267                                                                src_reg, dst_reg);
9268                         }
9269                 } else if (ptr_reg) {
9270                         /* pointer += scalar */
9271                         err = mark_chain_precision(env, insn->src_reg);
9272                         if (err)
9273                                 return err;
9274                         return adjust_ptr_min_max_vals(env, insn,
9275                                                        dst_reg, src_reg);
9276                 } else if (dst_reg->precise) {
9277                         /* if dst_reg is precise, src_reg should be precise as well */
9278                         err = mark_chain_precision(env, insn->src_reg);
9279                         if (err)
9280                                 return err;
9281                 }
9282         } else {
9283                 /* Pretend the src is a reg with a known value, since we only
9284                  * need to be able to read from this state.
9285                  */
9286                 off_reg.type = SCALAR_VALUE;
9287                 __mark_reg_known(&off_reg, insn->imm);
9288                 src_reg = &off_reg;
9289                 if (ptr_reg) /* pointer += K */
9290                         return adjust_ptr_min_max_vals(env, insn,
9291                                                        ptr_reg, src_reg);
9292         }
9293
9294         /* Got here implies adding two SCALAR_VALUEs */
9295         if (WARN_ON_ONCE(ptr_reg)) {
9296                 print_verifier_state(env, state, true);
9297                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9298                 return -EINVAL;
9299         }
9300         if (WARN_ON(!src_reg)) {
9301                 print_verifier_state(env, state, true);
9302                 verbose(env, "verifier internal error: no src_reg\n");
9303                 return -EINVAL;
9304         }
9305         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9306 }
9307
9308 /* check validity of 32-bit and 64-bit arithmetic operations */
9309 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9310 {
9311         struct bpf_reg_state *regs = cur_regs(env);
9312         u8 opcode = BPF_OP(insn->code);
9313         int err;
9314
9315         if (opcode == BPF_END || opcode == BPF_NEG) {
9316                 if (opcode == BPF_NEG) {
9317                         if (BPF_SRC(insn->code) != BPF_K ||
9318                             insn->src_reg != BPF_REG_0 ||
9319                             insn->off != 0 || insn->imm != 0) {
9320                                 verbose(env, "BPF_NEG uses reserved fields\n");
9321                                 return -EINVAL;
9322                         }
9323                 } else {
9324                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9325                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9326                             BPF_CLASS(insn->code) == BPF_ALU64) {
9327                                 verbose(env, "BPF_END uses reserved fields\n");
9328                                 return -EINVAL;
9329                         }
9330                 }
9331
9332                 /* check src operand */
9333                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9334                 if (err)
9335                         return err;
9336
9337                 if (is_pointer_value(env, insn->dst_reg)) {
9338                         verbose(env, "R%d pointer arithmetic prohibited\n",
9339                                 insn->dst_reg);
9340                         return -EACCES;
9341                 }
9342
9343                 /* check dest operand */
9344                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9345                 if (err)
9346                         return err;
9347
9348         } else if (opcode == BPF_MOV) {
9349
9350                 if (BPF_SRC(insn->code) == BPF_X) {
9351                         if (insn->imm != 0 || insn->off != 0) {
9352                                 verbose(env, "BPF_MOV uses reserved fields\n");
9353                                 return -EINVAL;
9354                         }
9355
9356                         /* check src operand */
9357                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9358                         if (err)
9359                                 return err;
9360                 } else {
9361                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9362                                 verbose(env, "BPF_MOV uses reserved fields\n");
9363                                 return -EINVAL;
9364                         }
9365                 }
9366
9367                 /* check dest operand, mark as required later */
9368                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9369                 if (err)
9370                         return err;
9371
9372                 if (BPF_SRC(insn->code) == BPF_X) {
9373                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
9374                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9375
9376                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9377                                 /* case: R1 = R2
9378                                  * copy register state to dest reg
9379                                  */
9380                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9381                                         /* Assign src and dst registers the same ID
9382                                          * that will be used by find_equal_scalars()
9383                                          * to propagate min/max range.
9384                                          */
9385                                         src_reg->id = ++env->id_gen;
9386                                 copy_register_state(dst_reg, src_reg);
9387                                 dst_reg->live |= REG_LIVE_WRITTEN;
9388                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
9389                         } else {
9390                                 /* R1 = (u32) R2 */
9391                                 if (is_pointer_value(env, insn->src_reg)) {
9392                                         verbose(env,
9393                                                 "R%d partial copy of pointer\n",
9394                                                 insn->src_reg);
9395                                         return -EACCES;
9396                                 } else if (src_reg->type == SCALAR_VALUE) {
9397                                         copy_register_state(dst_reg, src_reg);
9398                                         /* Make sure ID is cleared otherwise
9399                                          * dst_reg min/max could be incorrectly
9400                                          * propagated into src_reg by find_equal_scalars()
9401                                          */
9402                                         dst_reg->id = 0;
9403                                         dst_reg->live |= REG_LIVE_WRITTEN;
9404                                         dst_reg->subreg_def = env->insn_idx + 1;
9405                                 } else {
9406                                         mark_reg_unknown(env, regs,
9407                                                          insn->dst_reg);
9408                                 }
9409                                 zext_32_to_64(dst_reg);
9410                                 reg_bounds_sync(dst_reg);
9411                         }
9412                 } else {
9413                         /* case: R = imm
9414                          * remember the value we stored into this reg
9415                          */
9416                         /* clear any state __mark_reg_known doesn't set */
9417                         mark_reg_unknown(env, regs, insn->dst_reg);
9418                         regs[insn->dst_reg].type = SCALAR_VALUE;
9419                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9420                                 __mark_reg_known(regs + insn->dst_reg,
9421                                                  insn->imm);
9422                         } else {
9423                                 __mark_reg_known(regs + insn->dst_reg,
9424                                                  (u32)insn->imm);
9425                         }
9426                 }
9427
9428         } else if (opcode > BPF_END) {
9429                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9430                 return -EINVAL;
9431
9432         } else {        /* all other ALU ops: and, sub, xor, add, ... */
9433
9434                 if (BPF_SRC(insn->code) == BPF_X) {
9435                         if (insn->imm != 0 || insn->off != 0) {
9436                                 verbose(env, "BPF_ALU uses reserved fields\n");
9437                                 return -EINVAL;
9438                         }
9439                         /* check src1 operand */
9440                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9441                         if (err)
9442                                 return err;
9443                 } else {
9444                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9445                                 verbose(env, "BPF_ALU uses reserved fields\n");
9446                                 return -EINVAL;
9447                         }
9448                 }
9449
9450                 /* check src2 operand */
9451                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9452                 if (err)
9453                         return err;
9454
9455                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9456                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9457                         verbose(env, "div by zero\n");
9458                         return -EINVAL;
9459                 }
9460
9461                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9462                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9463                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9464
9465                         if (insn->imm < 0 || insn->imm >= size) {
9466                                 verbose(env, "invalid shift %d\n", insn->imm);
9467                                 return -EINVAL;
9468                         }
9469                 }
9470
9471                 /* check dest operand */
9472                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9473                 if (err)
9474                         return err;
9475
9476                 return adjust_reg_min_max_vals(env, insn);
9477         }
9478
9479         return 0;
9480 }
9481
9482 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9483                                    struct bpf_reg_state *dst_reg,
9484                                    enum bpf_reg_type type,
9485                                    bool range_right_open)
9486 {
9487         struct bpf_func_state *state;
9488         struct bpf_reg_state *reg;
9489         int new_range;
9490
9491         if (dst_reg->off < 0 ||
9492             (dst_reg->off == 0 && range_right_open))
9493                 /* This doesn't give us any range */
9494                 return;
9495
9496         if (dst_reg->umax_value > MAX_PACKET_OFF ||
9497             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9498                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
9499                  * than pkt_end, but that's because it's also less than pkt.
9500                  */
9501                 return;
9502
9503         new_range = dst_reg->off;
9504         if (range_right_open)
9505                 new_range++;
9506
9507         /* Examples for register markings:
9508          *
9509          * pkt_data in dst register:
9510          *
9511          *   r2 = r3;
9512          *   r2 += 8;
9513          *   if (r2 > pkt_end) goto <handle exception>
9514          *   <access okay>
9515          *
9516          *   r2 = r3;
9517          *   r2 += 8;
9518          *   if (r2 < pkt_end) goto <access okay>
9519          *   <handle exception>
9520          *
9521          *   Where:
9522          *     r2 == dst_reg, pkt_end == src_reg
9523          *     r2=pkt(id=n,off=8,r=0)
9524          *     r3=pkt(id=n,off=0,r=0)
9525          *
9526          * pkt_data in src register:
9527          *
9528          *   r2 = r3;
9529          *   r2 += 8;
9530          *   if (pkt_end >= r2) goto <access okay>
9531          *   <handle exception>
9532          *
9533          *   r2 = r3;
9534          *   r2 += 8;
9535          *   if (pkt_end <= r2) goto <handle exception>
9536          *   <access okay>
9537          *
9538          *   Where:
9539          *     pkt_end == dst_reg, r2 == src_reg
9540          *     r2=pkt(id=n,off=8,r=0)
9541          *     r3=pkt(id=n,off=0,r=0)
9542          *
9543          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9544          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9545          * and [r3, r3 + 8-1) respectively is safe to access depending on
9546          * the check.
9547          */
9548
9549         /* If our ids match, then we must have the same max_value.  And we
9550          * don't care about the other reg's fixed offset, since if it's too big
9551          * the range won't allow anything.
9552          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9553          */
9554         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9555                 if (reg->type == type && reg->id == dst_reg->id)
9556                         /* keep the maximum range already checked */
9557                         reg->range = max(reg->range, new_range);
9558         }));
9559 }
9560
9561 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9562 {
9563         struct tnum subreg = tnum_subreg(reg->var_off);
9564         s32 sval = (s32)val;
9565
9566         switch (opcode) {
9567         case BPF_JEQ:
9568                 if (tnum_is_const(subreg))
9569                         return !!tnum_equals_const(subreg, val);
9570                 break;
9571         case BPF_JNE:
9572                 if (tnum_is_const(subreg))
9573                         return !tnum_equals_const(subreg, val);
9574                 break;
9575         case BPF_JSET:
9576                 if ((~subreg.mask & subreg.value) & val)
9577                         return 1;
9578                 if (!((subreg.mask | subreg.value) & val))
9579                         return 0;
9580                 break;
9581         case BPF_JGT:
9582                 if (reg->u32_min_value > val)
9583                         return 1;
9584                 else if (reg->u32_max_value <= val)
9585                         return 0;
9586                 break;
9587         case BPF_JSGT:
9588                 if (reg->s32_min_value > sval)
9589                         return 1;
9590                 else if (reg->s32_max_value <= sval)
9591                         return 0;
9592                 break;
9593         case BPF_JLT:
9594                 if (reg->u32_max_value < val)
9595                         return 1;
9596                 else if (reg->u32_min_value >= val)
9597                         return 0;
9598                 break;
9599         case BPF_JSLT:
9600                 if (reg->s32_max_value < sval)
9601                         return 1;
9602                 else if (reg->s32_min_value >= sval)
9603                         return 0;
9604                 break;
9605         case BPF_JGE:
9606                 if (reg->u32_min_value >= val)
9607                         return 1;
9608                 else if (reg->u32_max_value < val)
9609                         return 0;
9610                 break;
9611         case BPF_JSGE:
9612                 if (reg->s32_min_value >= sval)
9613                         return 1;
9614                 else if (reg->s32_max_value < sval)
9615                         return 0;
9616                 break;
9617         case BPF_JLE:
9618                 if (reg->u32_max_value <= val)
9619                         return 1;
9620                 else if (reg->u32_min_value > val)
9621                         return 0;
9622                 break;
9623         case BPF_JSLE:
9624                 if (reg->s32_max_value <= sval)
9625                         return 1;
9626                 else if (reg->s32_min_value > sval)
9627                         return 0;
9628                 break;
9629         }
9630
9631         return -1;
9632 }
9633
9634
9635 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9636 {
9637         s64 sval = (s64)val;
9638
9639         switch (opcode) {
9640         case BPF_JEQ:
9641                 if (tnum_is_const(reg->var_off))
9642                         return !!tnum_equals_const(reg->var_off, val);
9643                 break;
9644         case BPF_JNE:
9645                 if (tnum_is_const(reg->var_off))
9646                         return !tnum_equals_const(reg->var_off, val);
9647                 break;
9648         case BPF_JSET:
9649                 if ((~reg->var_off.mask & reg->var_off.value) & val)
9650                         return 1;
9651                 if (!((reg->var_off.mask | reg->var_off.value) & val))
9652                         return 0;
9653                 break;
9654         case BPF_JGT:
9655                 if (reg->umin_value > val)
9656                         return 1;
9657                 else if (reg->umax_value <= val)
9658                         return 0;
9659                 break;
9660         case BPF_JSGT:
9661                 if (reg->smin_value > sval)
9662                         return 1;
9663                 else if (reg->smax_value <= sval)
9664                         return 0;
9665                 break;
9666         case BPF_JLT:
9667                 if (reg->umax_value < val)
9668                         return 1;
9669                 else if (reg->umin_value >= val)
9670                         return 0;
9671                 break;
9672         case BPF_JSLT:
9673                 if (reg->smax_value < sval)
9674                         return 1;
9675                 else if (reg->smin_value >= sval)
9676                         return 0;
9677                 break;
9678         case BPF_JGE:
9679                 if (reg->umin_value >= val)
9680                         return 1;
9681                 else if (reg->umax_value < val)
9682                         return 0;
9683                 break;
9684         case BPF_JSGE:
9685                 if (reg->smin_value >= sval)
9686                         return 1;
9687                 else if (reg->smax_value < sval)
9688                         return 0;
9689                 break;
9690         case BPF_JLE:
9691                 if (reg->umax_value <= val)
9692                         return 1;
9693                 else if (reg->umin_value > val)
9694                         return 0;
9695                 break;
9696         case BPF_JSLE:
9697                 if (reg->smax_value <= sval)
9698                         return 1;
9699                 else if (reg->smin_value > sval)
9700                         return 0;
9701                 break;
9702         }
9703
9704         return -1;
9705 }
9706
9707 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9708  * and return:
9709  *  1 - branch will be taken and "goto target" will be executed
9710  *  0 - branch will not be taken and fall-through to next insn
9711  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9712  *      range [0,10]
9713  */
9714 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9715                            bool is_jmp32)
9716 {
9717         if (__is_pointer_value(false, reg)) {
9718                 if (!reg_type_not_null(reg->type))
9719                         return -1;
9720
9721                 /* If pointer is valid tests against zero will fail so we can
9722                  * use this to direct branch taken.
9723                  */
9724                 if (val != 0)
9725                         return -1;
9726
9727                 switch (opcode) {
9728                 case BPF_JEQ:
9729                         return 0;
9730                 case BPF_JNE:
9731                         return 1;
9732                 default:
9733                         return -1;
9734                 }
9735         }
9736
9737         if (is_jmp32)
9738                 return is_branch32_taken(reg, val, opcode);
9739         return is_branch64_taken(reg, val, opcode);
9740 }
9741
9742 static int flip_opcode(u32 opcode)
9743 {
9744         /* How can we transform "a <op> b" into "b <op> a"? */
9745         static const u8 opcode_flip[16] = {
9746                 /* these stay the same */
9747                 [BPF_JEQ  >> 4] = BPF_JEQ,
9748                 [BPF_JNE  >> 4] = BPF_JNE,
9749                 [BPF_JSET >> 4] = BPF_JSET,
9750                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9751                 [BPF_JGE  >> 4] = BPF_JLE,
9752                 [BPF_JGT  >> 4] = BPF_JLT,
9753                 [BPF_JLE  >> 4] = BPF_JGE,
9754                 [BPF_JLT  >> 4] = BPF_JGT,
9755                 [BPF_JSGE >> 4] = BPF_JSLE,
9756                 [BPF_JSGT >> 4] = BPF_JSLT,
9757                 [BPF_JSLE >> 4] = BPF_JSGE,
9758                 [BPF_JSLT >> 4] = BPF_JSGT
9759         };
9760         return opcode_flip[opcode >> 4];
9761 }
9762
9763 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9764                                    struct bpf_reg_state *src_reg,
9765                                    u8 opcode)
9766 {
9767         struct bpf_reg_state *pkt;
9768
9769         if (src_reg->type == PTR_TO_PACKET_END) {
9770                 pkt = dst_reg;
9771         } else if (dst_reg->type == PTR_TO_PACKET_END) {
9772                 pkt = src_reg;
9773                 opcode = flip_opcode(opcode);
9774         } else {
9775                 return -1;
9776         }
9777
9778         if (pkt->range >= 0)
9779                 return -1;
9780
9781         switch (opcode) {
9782         case BPF_JLE:
9783                 /* pkt <= pkt_end */
9784                 fallthrough;
9785         case BPF_JGT:
9786                 /* pkt > pkt_end */
9787                 if (pkt->range == BEYOND_PKT_END)
9788                         /* pkt has at last one extra byte beyond pkt_end */
9789                         return opcode == BPF_JGT;
9790                 break;
9791         case BPF_JLT:
9792                 /* pkt < pkt_end */
9793                 fallthrough;
9794         case BPF_JGE:
9795                 /* pkt >= pkt_end */
9796                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9797                         return opcode == BPF_JGE;
9798                 break;
9799         }
9800         return -1;
9801 }
9802
9803 /* Adjusts the register min/max values in the case that the dst_reg is the
9804  * variable register that we are working on, and src_reg is a constant or we're
9805  * simply doing a BPF_K check.
9806  * In JEQ/JNE cases we also adjust the var_off values.
9807  */
9808 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9809                             struct bpf_reg_state *false_reg,
9810                             u64 val, u32 val32,
9811                             u8 opcode, bool is_jmp32)
9812 {
9813         struct tnum false_32off = tnum_subreg(false_reg->var_off);
9814         struct tnum false_64off = false_reg->var_off;
9815         struct tnum true_32off = tnum_subreg(true_reg->var_off);
9816         struct tnum true_64off = true_reg->var_off;
9817         s64 sval = (s64)val;
9818         s32 sval32 = (s32)val32;
9819
9820         /* If the dst_reg is a pointer, we can't learn anything about its
9821          * variable offset from the compare (unless src_reg were a pointer into
9822          * the same object, but we don't bother with that.
9823          * Since false_reg and true_reg have the same type by construction, we
9824          * only need to check one of them for pointerness.
9825          */
9826         if (__is_pointer_value(false, false_reg))
9827                 return;
9828
9829         switch (opcode) {
9830         /* JEQ/JNE comparison doesn't change the register equivalence.
9831          *
9832          * r1 = r2;
9833          * if (r1 == 42) goto label;
9834          * ...
9835          * label: // here both r1 and r2 are known to be 42.
9836          *
9837          * Hence when marking register as known preserve it's ID.
9838          */
9839         case BPF_JEQ:
9840                 if (is_jmp32) {
9841                         __mark_reg32_known(true_reg, val32);
9842                         true_32off = tnum_subreg(true_reg->var_off);
9843                 } else {
9844                         ___mark_reg_known(true_reg, val);
9845                         true_64off = true_reg->var_off;
9846                 }
9847                 break;
9848         case BPF_JNE:
9849                 if (is_jmp32) {
9850                         __mark_reg32_known(false_reg, val32);
9851                         false_32off = tnum_subreg(false_reg->var_off);
9852                 } else {
9853                         ___mark_reg_known(false_reg, val);
9854                         false_64off = false_reg->var_off;
9855                 }
9856                 break;
9857         case BPF_JSET:
9858                 if (is_jmp32) {
9859                         false_32off = tnum_and(false_32off, tnum_const(~val32));
9860                         if (is_power_of_2(val32))
9861                                 true_32off = tnum_or(true_32off,
9862                                                      tnum_const(val32));
9863                 } else {
9864                         false_64off = tnum_and(false_64off, tnum_const(~val));
9865                         if (is_power_of_2(val))
9866                                 true_64off = tnum_or(true_64off,
9867                                                      tnum_const(val));
9868                 }
9869                 break;
9870         case BPF_JGE:
9871         case BPF_JGT:
9872         {
9873                 if (is_jmp32) {
9874                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9875                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9876
9877                         false_reg->u32_max_value = min(false_reg->u32_max_value,
9878                                                        false_umax);
9879                         true_reg->u32_min_value = max(true_reg->u32_min_value,
9880                                                       true_umin);
9881                 } else {
9882                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9883                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9884
9885                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
9886                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
9887                 }
9888                 break;
9889         }
9890         case BPF_JSGE:
9891         case BPF_JSGT:
9892         {
9893                 if (is_jmp32) {
9894                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9895                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9896
9897                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9898                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9899                 } else {
9900                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9901                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9902
9903                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
9904                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
9905                 }
9906                 break;
9907         }
9908         case BPF_JLE:
9909         case BPF_JLT:
9910         {
9911                 if (is_jmp32) {
9912                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9913                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9914
9915                         false_reg->u32_min_value = max(false_reg->u32_min_value,
9916                                                        false_umin);
9917                         true_reg->u32_max_value = min(true_reg->u32_max_value,
9918                                                       true_umax);
9919                 } else {
9920                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9921                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9922
9923                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
9924                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
9925                 }
9926                 break;
9927         }
9928         case BPF_JSLE:
9929         case BPF_JSLT:
9930         {
9931                 if (is_jmp32) {
9932                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9933                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9934
9935                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9936                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9937                 } else {
9938                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9939                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9940
9941                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
9942                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
9943                 }
9944                 break;
9945         }
9946         default:
9947                 return;
9948         }
9949
9950         if (is_jmp32) {
9951                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9952                                              tnum_subreg(false_32off));
9953                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9954                                             tnum_subreg(true_32off));
9955                 __reg_combine_32_into_64(false_reg);
9956                 __reg_combine_32_into_64(true_reg);
9957         } else {
9958                 false_reg->var_off = false_64off;
9959                 true_reg->var_off = true_64off;
9960                 __reg_combine_64_into_32(false_reg);
9961                 __reg_combine_64_into_32(true_reg);
9962         }
9963 }
9964
9965 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9966  * the variable reg.
9967  */
9968 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9969                                 struct bpf_reg_state *false_reg,
9970                                 u64 val, u32 val32,
9971                                 u8 opcode, bool is_jmp32)
9972 {
9973         opcode = flip_opcode(opcode);
9974         /* This uses zero as "not present in table"; luckily the zero opcode,
9975          * BPF_JA, can't get here.
9976          */
9977         if (opcode)
9978                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9979 }
9980
9981 /* Regs are known to be equal, so intersect their min/max/var_off */
9982 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9983                                   struct bpf_reg_state *dst_reg)
9984 {
9985         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9986                                                         dst_reg->umin_value);
9987         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9988                                                         dst_reg->umax_value);
9989         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9990                                                         dst_reg->smin_value);
9991         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9992                                                         dst_reg->smax_value);
9993         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9994                                                              dst_reg->var_off);
9995         reg_bounds_sync(src_reg);
9996         reg_bounds_sync(dst_reg);
9997 }
9998
9999 static void reg_combine_min_max(struct bpf_reg_state *true_src,
10000                                 struct bpf_reg_state *true_dst,
10001                                 struct bpf_reg_state *false_src,
10002                                 struct bpf_reg_state *false_dst,
10003                                 u8 opcode)
10004 {
10005         switch (opcode) {
10006         case BPF_JEQ:
10007                 __reg_combine_min_max(true_src, true_dst);
10008                 break;
10009         case BPF_JNE:
10010                 __reg_combine_min_max(false_src, false_dst);
10011                 break;
10012         }
10013 }
10014
10015 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
10016                                  struct bpf_reg_state *reg, u32 id,
10017                                  bool is_null)
10018 {
10019         if (type_may_be_null(reg->type) && reg->id == id &&
10020             !WARN_ON_ONCE(!reg->id)) {
10021                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
10022                                  !tnum_equals_const(reg->var_off, 0) ||
10023                                  reg->off)) {
10024                         /* Old offset (both fixed and variable parts) should
10025                          * have been known-zero, because we don't allow pointer
10026                          * arithmetic on pointers that might be NULL. If we
10027                          * see this happening, don't convert the register.
10028                          */
10029                         return;
10030                 }
10031                 if (is_null) {
10032                         reg->type = SCALAR_VALUE;
10033                         /* We don't need id and ref_obj_id from this point
10034                          * onwards anymore, thus we should better reset it,
10035                          * so that state pruning has chances to take effect.
10036                          */
10037                         reg->id = 0;
10038                         reg->ref_obj_id = 0;
10039
10040                         return;
10041                 }
10042
10043                 mark_ptr_not_null_reg(reg);
10044
10045                 if (!reg_may_point_to_spin_lock(reg)) {
10046                         /* For not-NULL ptr, reg->ref_obj_id will be reset
10047                          * in release_reference().
10048                          *
10049                          * reg->id is still used by spin_lock ptr. Other
10050                          * than spin_lock ptr type, reg->id can be reset.
10051                          */
10052                         reg->id = 0;
10053                 }
10054         }
10055 }
10056
10057 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10058  * be folded together at some point.
10059  */
10060 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10061                                   bool is_null)
10062 {
10063         struct bpf_func_state *state = vstate->frame[vstate->curframe];
10064         struct bpf_reg_state *regs = state->regs, *reg;
10065         u32 ref_obj_id = regs[regno].ref_obj_id;
10066         u32 id = regs[regno].id;
10067
10068         if (ref_obj_id && ref_obj_id == id && is_null)
10069                 /* regs[regno] is in the " == NULL" branch.
10070                  * No one could have freed the reference state before
10071                  * doing the NULL check.
10072                  */
10073                 WARN_ON_ONCE(release_reference_state(state, id));
10074
10075         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10076                 mark_ptr_or_null_reg(state, reg, id, is_null);
10077         }));
10078 }
10079
10080 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10081                                    struct bpf_reg_state *dst_reg,
10082                                    struct bpf_reg_state *src_reg,
10083                                    struct bpf_verifier_state *this_branch,
10084                                    struct bpf_verifier_state *other_branch)
10085 {
10086         if (BPF_SRC(insn->code) != BPF_X)
10087                 return false;
10088
10089         /* Pointers are always 64-bit. */
10090         if (BPF_CLASS(insn->code) == BPF_JMP32)
10091                 return false;
10092
10093         switch (BPF_OP(insn->code)) {
10094         case BPF_JGT:
10095                 if ((dst_reg->type == PTR_TO_PACKET &&
10096                      src_reg->type == PTR_TO_PACKET_END) ||
10097                     (dst_reg->type == PTR_TO_PACKET_META &&
10098                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10099                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10100                         find_good_pkt_pointers(this_branch, dst_reg,
10101                                                dst_reg->type, false);
10102                         mark_pkt_end(other_branch, insn->dst_reg, true);
10103                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10104                             src_reg->type == PTR_TO_PACKET) ||
10105                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10106                             src_reg->type == PTR_TO_PACKET_META)) {
10107                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10108                         find_good_pkt_pointers(other_branch, src_reg,
10109                                                src_reg->type, true);
10110                         mark_pkt_end(this_branch, insn->src_reg, false);
10111                 } else {
10112                         return false;
10113                 }
10114                 break;
10115         case BPF_JLT:
10116                 if ((dst_reg->type == PTR_TO_PACKET &&
10117                      src_reg->type == PTR_TO_PACKET_END) ||
10118                     (dst_reg->type == PTR_TO_PACKET_META &&
10119                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10120                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10121                         find_good_pkt_pointers(other_branch, dst_reg,
10122                                                dst_reg->type, true);
10123                         mark_pkt_end(this_branch, insn->dst_reg, false);
10124                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10125                             src_reg->type == PTR_TO_PACKET) ||
10126                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10127                             src_reg->type == PTR_TO_PACKET_META)) {
10128                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10129                         find_good_pkt_pointers(this_branch, src_reg,
10130                                                src_reg->type, false);
10131                         mark_pkt_end(other_branch, insn->src_reg, true);
10132                 } else {
10133                         return false;
10134                 }
10135                 break;
10136         case BPF_JGE:
10137                 if ((dst_reg->type == PTR_TO_PACKET &&
10138                      src_reg->type == PTR_TO_PACKET_END) ||
10139                     (dst_reg->type == PTR_TO_PACKET_META &&
10140                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10141                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10142                         find_good_pkt_pointers(this_branch, dst_reg,
10143                                                dst_reg->type, true);
10144                         mark_pkt_end(other_branch, insn->dst_reg, false);
10145                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10146                             src_reg->type == PTR_TO_PACKET) ||
10147                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10148                             src_reg->type == PTR_TO_PACKET_META)) {
10149                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10150                         find_good_pkt_pointers(other_branch, src_reg,
10151                                                src_reg->type, false);
10152                         mark_pkt_end(this_branch, insn->src_reg, true);
10153                 } else {
10154                         return false;
10155                 }
10156                 break;
10157         case BPF_JLE:
10158                 if ((dst_reg->type == PTR_TO_PACKET &&
10159                      src_reg->type == PTR_TO_PACKET_END) ||
10160                     (dst_reg->type == PTR_TO_PACKET_META &&
10161                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10162                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10163                         find_good_pkt_pointers(other_branch, dst_reg,
10164                                                dst_reg->type, false);
10165                         mark_pkt_end(this_branch, insn->dst_reg, true);
10166                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10167                             src_reg->type == PTR_TO_PACKET) ||
10168                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10169                             src_reg->type == PTR_TO_PACKET_META)) {
10170                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10171                         find_good_pkt_pointers(this_branch, src_reg,
10172                                                src_reg->type, true);
10173                         mark_pkt_end(other_branch, insn->src_reg, false);
10174                 } else {
10175                         return false;
10176                 }
10177                 break;
10178         default:
10179                 return false;
10180         }
10181
10182         return true;
10183 }
10184
10185 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10186                                struct bpf_reg_state *known_reg)
10187 {
10188         struct bpf_func_state *state;
10189         struct bpf_reg_state *reg;
10190
10191         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10192                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10193                         copy_register_state(reg, known_reg);
10194         }));
10195 }
10196
10197 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10198                              struct bpf_insn *insn, int *insn_idx)
10199 {
10200         struct bpf_verifier_state *this_branch = env->cur_state;
10201         struct bpf_verifier_state *other_branch;
10202         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10203         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10204         u8 opcode = BPF_OP(insn->code);
10205         bool is_jmp32;
10206         int pred = -1;
10207         int err;
10208
10209         /* Only conditional jumps are expected to reach here. */
10210         if (opcode == BPF_JA || opcode > BPF_JSLE) {
10211                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10212                 return -EINVAL;
10213         }
10214
10215         if (BPF_SRC(insn->code) == BPF_X) {
10216                 if (insn->imm != 0) {
10217                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10218                         return -EINVAL;
10219                 }
10220
10221                 /* check src1 operand */
10222                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10223                 if (err)
10224                         return err;
10225
10226                 if (is_pointer_value(env, insn->src_reg)) {
10227                         verbose(env, "R%d pointer comparison prohibited\n",
10228                                 insn->src_reg);
10229                         return -EACCES;
10230                 }
10231                 src_reg = &regs[insn->src_reg];
10232         } else {
10233                 if (insn->src_reg != BPF_REG_0) {
10234                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10235                         return -EINVAL;
10236                 }
10237         }
10238
10239         /* check src2 operand */
10240         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10241         if (err)
10242                 return err;
10243
10244         dst_reg = &regs[insn->dst_reg];
10245         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10246
10247         if (BPF_SRC(insn->code) == BPF_K) {
10248                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10249         } else if (src_reg->type == SCALAR_VALUE &&
10250                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10251                 pred = is_branch_taken(dst_reg,
10252                                        tnum_subreg(src_reg->var_off).value,
10253                                        opcode,
10254                                        is_jmp32);
10255         } else if (src_reg->type == SCALAR_VALUE &&
10256                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10257                 pred = is_branch_taken(dst_reg,
10258                                        src_reg->var_off.value,
10259                                        opcode,
10260                                        is_jmp32);
10261         } else if (reg_is_pkt_pointer_any(dst_reg) &&
10262                    reg_is_pkt_pointer_any(src_reg) &&
10263                    !is_jmp32) {
10264                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10265         }
10266
10267         if (pred >= 0) {
10268                 /* If we get here with a dst_reg pointer type it is because
10269                  * above is_branch_taken() special cased the 0 comparison.
10270                  */
10271                 if (!__is_pointer_value(false, dst_reg))
10272                         err = mark_chain_precision(env, insn->dst_reg);
10273                 if (BPF_SRC(insn->code) == BPF_X && !err &&
10274                     !__is_pointer_value(false, src_reg))
10275                         err = mark_chain_precision(env, insn->src_reg);
10276                 if (err)
10277                         return err;
10278         }
10279
10280         if (pred == 1) {
10281                 /* Only follow the goto, ignore fall-through. If needed, push
10282                  * the fall-through branch for simulation under speculative
10283                  * execution.
10284                  */
10285                 if (!env->bypass_spec_v1 &&
10286                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
10287                                                *insn_idx))
10288                         return -EFAULT;
10289                 *insn_idx += insn->off;
10290                 return 0;
10291         } else if (pred == 0) {
10292                 /* Only follow the fall-through branch, since that's where the
10293                  * program will go. If needed, push the goto branch for
10294                  * simulation under speculative execution.
10295                  */
10296                 if (!env->bypass_spec_v1 &&
10297                     !sanitize_speculative_path(env, insn,
10298                                                *insn_idx + insn->off + 1,
10299                                                *insn_idx))
10300                         return -EFAULT;
10301                 return 0;
10302         }
10303
10304         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10305                                   false);
10306         if (!other_branch)
10307                 return -EFAULT;
10308         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10309
10310         /* detect if we are comparing against a constant value so we can adjust
10311          * our min/max values for our dst register.
10312          * this is only legit if both are scalars (or pointers to the same
10313          * object, I suppose, but we don't support that right now), because
10314          * otherwise the different base pointers mean the offsets aren't
10315          * comparable.
10316          */
10317         if (BPF_SRC(insn->code) == BPF_X) {
10318                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10319
10320                 if (dst_reg->type == SCALAR_VALUE &&
10321                     src_reg->type == SCALAR_VALUE) {
10322                         if (tnum_is_const(src_reg->var_off) ||
10323                             (is_jmp32 &&
10324                              tnum_is_const(tnum_subreg(src_reg->var_off))))
10325                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10326                                                 dst_reg,
10327                                                 src_reg->var_off.value,
10328                                                 tnum_subreg(src_reg->var_off).value,
10329                                                 opcode, is_jmp32);
10330                         else if (tnum_is_const(dst_reg->var_off) ||
10331                                  (is_jmp32 &&
10332                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
10333                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10334                                                     src_reg,
10335                                                     dst_reg->var_off.value,
10336                                                     tnum_subreg(dst_reg->var_off).value,
10337                                                     opcode, is_jmp32);
10338                         else if (!is_jmp32 &&
10339                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
10340                                 /* Comparing for equality, we can combine knowledge */
10341                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10342                                                     &other_branch_regs[insn->dst_reg],
10343                                                     src_reg, dst_reg, opcode);
10344                         if (src_reg->id &&
10345                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10346                                 find_equal_scalars(this_branch, src_reg);
10347                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10348                         }
10349
10350                 }
10351         } else if (dst_reg->type == SCALAR_VALUE) {
10352                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10353                                         dst_reg, insn->imm, (u32)insn->imm,
10354                                         opcode, is_jmp32);
10355         }
10356
10357         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10358             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10359                 find_equal_scalars(this_branch, dst_reg);
10360                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10361         }
10362
10363         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10364          * NOTE: these optimizations below are related with pointer comparison
10365          *       which will never be JMP32.
10366          */
10367         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10368             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10369             type_may_be_null(dst_reg->type)) {
10370                 /* Mark all identical registers in each branch as either
10371                  * safe or unknown depending R == 0 or R != 0 conditional.
10372                  */
10373                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10374                                       opcode == BPF_JNE);
10375                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10376                                       opcode == BPF_JEQ);
10377         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10378                                            this_branch, other_branch) &&
10379                    is_pointer_value(env, insn->dst_reg)) {
10380                 verbose(env, "R%d pointer comparison prohibited\n",
10381                         insn->dst_reg);
10382                 return -EACCES;
10383         }
10384         if (env->log.level & BPF_LOG_LEVEL)
10385                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10386         return 0;
10387 }
10388
10389 /* verify BPF_LD_IMM64 instruction */
10390 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10391 {
10392         struct bpf_insn_aux_data *aux = cur_aux(env);
10393         struct bpf_reg_state *regs = cur_regs(env);
10394         struct bpf_reg_state *dst_reg;
10395         struct bpf_map *map;
10396         int err;
10397
10398         if (BPF_SIZE(insn->code) != BPF_DW) {
10399                 verbose(env, "invalid BPF_LD_IMM insn\n");
10400                 return -EINVAL;
10401         }
10402         if (insn->off != 0) {
10403                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10404                 return -EINVAL;
10405         }
10406
10407         err = check_reg_arg(env, insn->dst_reg, DST_OP);
10408         if (err)
10409                 return err;
10410
10411         dst_reg = &regs[insn->dst_reg];
10412         if (insn->src_reg == 0) {
10413                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10414
10415                 dst_reg->type = SCALAR_VALUE;
10416                 __mark_reg_known(&regs[insn->dst_reg], imm);
10417                 return 0;
10418         }
10419
10420         /* All special src_reg cases are listed below. From this point onwards
10421          * we either succeed and assign a corresponding dst_reg->type after
10422          * zeroing the offset, or fail and reject the program.
10423          */
10424         mark_reg_known_zero(env, regs, insn->dst_reg);
10425
10426         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10427                 dst_reg->type = aux->btf_var.reg_type;
10428                 switch (base_type(dst_reg->type)) {
10429                 case PTR_TO_MEM:
10430                         dst_reg->mem_size = aux->btf_var.mem_size;
10431                         break;
10432                 case PTR_TO_BTF_ID:
10433                         dst_reg->btf = aux->btf_var.btf;
10434                         dst_reg->btf_id = aux->btf_var.btf_id;
10435                         break;
10436                 default:
10437                         verbose(env, "bpf verifier is misconfigured\n");
10438                         return -EFAULT;
10439                 }
10440                 return 0;
10441         }
10442
10443         if (insn->src_reg == BPF_PSEUDO_FUNC) {
10444                 struct bpf_prog_aux *aux = env->prog->aux;
10445                 u32 subprogno = find_subprog(env,
10446                                              env->insn_idx + insn->imm + 1);
10447
10448                 if (!aux->func_info) {
10449                         verbose(env, "missing btf func_info\n");
10450                         return -EINVAL;
10451                 }
10452                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10453                         verbose(env, "callback function not static\n");
10454                         return -EINVAL;
10455                 }
10456
10457                 dst_reg->type = PTR_TO_FUNC;
10458                 dst_reg->subprogno = subprogno;
10459                 return 0;
10460         }
10461
10462         map = env->used_maps[aux->map_index];
10463         dst_reg->map_ptr = map;
10464
10465         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10466             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10467                 dst_reg->type = PTR_TO_MAP_VALUE;
10468                 dst_reg->off = aux->map_off;
10469                 if (map_value_has_spin_lock(map))
10470                         dst_reg->id = ++env->id_gen;
10471         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10472                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10473                 dst_reg->type = CONST_PTR_TO_MAP;
10474         } else {
10475                 verbose(env, "bpf verifier is misconfigured\n");
10476                 return -EINVAL;
10477         }
10478
10479         return 0;
10480 }
10481
10482 static bool may_access_skb(enum bpf_prog_type type)
10483 {
10484         switch (type) {
10485         case BPF_PROG_TYPE_SOCKET_FILTER:
10486         case BPF_PROG_TYPE_SCHED_CLS:
10487         case BPF_PROG_TYPE_SCHED_ACT:
10488                 return true;
10489         default:
10490                 return false;
10491         }
10492 }
10493
10494 /* verify safety of LD_ABS|LD_IND instructions:
10495  * - they can only appear in the programs where ctx == skb
10496  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10497  *   preserve R6-R9, and store return value into R0
10498  *
10499  * Implicit input:
10500  *   ctx == skb == R6 == CTX
10501  *
10502  * Explicit input:
10503  *   SRC == any register
10504  *   IMM == 32-bit immediate
10505  *
10506  * Output:
10507  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10508  */
10509 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10510 {
10511         struct bpf_reg_state *regs = cur_regs(env);
10512         static const int ctx_reg = BPF_REG_6;
10513         u8 mode = BPF_MODE(insn->code);
10514         int i, err;
10515
10516         if (!may_access_skb(resolve_prog_type(env->prog))) {
10517                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10518                 return -EINVAL;
10519         }
10520
10521         if (!env->ops->gen_ld_abs) {
10522                 verbose(env, "bpf verifier is misconfigured\n");
10523                 return -EINVAL;
10524         }
10525
10526         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10527             BPF_SIZE(insn->code) == BPF_DW ||
10528             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10529                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10530                 return -EINVAL;
10531         }
10532
10533         /* check whether implicit source operand (register R6) is readable */
10534         err = check_reg_arg(env, ctx_reg, SRC_OP);
10535         if (err)
10536                 return err;
10537
10538         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10539          * gen_ld_abs() may terminate the program at runtime, leading to
10540          * reference leak.
10541          */
10542         err = check_reference_leak(env);
10543         if (err) {
10544                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10545                 return err;
10546         }
10547
10548         if (env->cur_state->active_spin_lock) {
10549                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10550                 return -EINVAL;
10551         }
10552
10553         if (regs[ctx_reg].type != PTR_TO_CTX) {
10554                 verbose(env,
10555                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10556                 return -EINVAL;
10557         }
10558
10559         if (mode == BPF_IND) {
10560                 /* check explicit source operand */
10561                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10562                 if (err)
10563                         return err;
10564         }
10565
10566         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10567         if (err < 0)
10568                 return err;
10569
10570         /* reset caller saved regs to unreadable */
10571         for (i = 0; i < CALLER_SAVED_REGS; i++) {
10572                 mark_reg_not_init(env, regs, caller_saved[i]);
10573                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10574         }
10575
10576         /* mark destination R0 register as readable, since it contains
10577          * the value fetched from the packet.
10578          * Already marked as written above.
10579          */
10580         mark_reg_unknown(env, regs, BPF_REG_0);
10581         /* ld_abs load up to 32-bit skb data. */
10582         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10583         return 0;
10584 }
10585
10586 static int check_return_code(struct bpf_verifier_env *env)
10587 {
10588         struct tnum enforce_attach_type_range = tnum_unknown;
10589         const struct bpf_prog *prog = env->prog;
10590         struct bpf_reg_state *reg;
10591         struct tnum range = tnum_range(0, 1);
10592         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10593         int err;
10594         struct bpf_func_state *frame = env->cur_state->frame[0];
10595         const bool is_subprog = frame->subprogno;
10596
10597         /* LSM and struct_ops func-ptr's return type could be "void" */
10598         if (!is_subprog) {
10599                 switch (prog_type) {
10600                 case BPF_PROG_TYPE_LSM:
10601                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
10602                                 /* See below, can be 0 or 0-1 depending on hook. */
10603                                 break;
10604                         fallthrough;
10605                 case BPF_PROG_TYPE_STRUCT_OPS:
10606                         if (!prog->aux->attach_func_proto->type)
10607                                 return 0;
10608                         break;
10609                 default:
10610                         break;
10611                 }
10612         }
10613
10614         /* eBPF calling convention is such that R0 is used
10615          * to return the value from eBPF program.
10616          * Make sure that it's readable at this time
10617          * of bpf_exit, which means that program wrote
10618          * something into it earlier
10619          */
10620         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10621         if (err)
10622                 return err;
10623
10624         if (is_pointer_value(env, BPF_REG_0)) {
10625                 verbose(env, "R0 leaks addr as return value\n");
10626                 return -EACCES;
10627         }
10628
10629         reg = cur_regs(env) + BPF_REG_0;
10630
10631         if (frame->in_async_callback_fn) {
10632                 /* enforce return zero from async callbacks like timer */
10633                 if (reg->type != SCALAR_VALUE) {
10634                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10635                                 reg_type_str(env, reg->type));
10636                         return -EINVAL;
10637                 }
10638
10639                 if (!tnum_in(tnum_const(0), reg->var_off)) {
10640                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10641                         return -EINVAL;
10642                 }
10643                 return 0;
10644         }
10645
10646         if (is_subprog) {
10647                 if (reg->type != SCALAR_VALUE) {
10648                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10649                                 reg_type_str(env, reg->type));
10650                         return -EINVAL;
10651                 }
10652                 return 0;
10653         }
10654
10655         switch (prog_type) {
10656         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10657                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10658                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10659                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10660                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10661                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10662                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10663                         range = tnum_range(1, 1);
10664                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10665                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10666                         range = tnum_range(0, 3);
10667                 break;
10668         case BPF_PROG_TYPE_CGROUP_SKB:
10669                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10670                         range = tnum_range(0, 3);
10671                         enforce_attach_type_range = tnum_range(2, 3);
10672                 }
10673                 break;
10674         case BPF_PROG_TYPE_CGROUP_SOCK:
10675         case BPF_PROG_TYPE_SOCK_OPS:
10676         case BPF_PROG_TYPE_CGROUP_DEVICE:
10677         case BPF_PROG_TYPE_CGROUP_SYSCTL:
10678         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10679                 break;
10680         case BPF_PROG_TYPE_RAW_TRACEPOINT:
10681                 if (!env->prog->aux->attach_btf_id)
10682                         return 0;
10683                 range = tnum_const(0);
10684                 break;
10685         case BPF_PROG_TYPE_TRACING:
10686                 switch (env->prog->expected_attach_type) {
10687                 case BPF_TRACE_FENTRY:
10688                 case BPF_TRACE_FEXIT:
10689                         range = tnum_const(0);
10690                         break;
10691                 case BPF_TRACE_RAW_TP:
10692                 case BPF_MODIFY_RETURN:
10693                         return 0;
10694                 case BPF_TRACE_ITER:
10695                         break;
10696                 default:
10697                         return -ENOTSUPP;
10698                 }
10699                 break;
10700         case BPF_PROG_TYPE_SK_LOOKUP:
10701                 range = tnum_range(SK_DROP, SK_PASS);
10702                 break;
10703
10704         case BPF_PROG_TYPE_LSM:
10705                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10706                         /* Regular BPF_PROG_TYPE_LSM programs can return
10707                          * any value.
10708                          */
10709                         return 0;
10710                 }
10711                 if (!env->prog->aux->attach_func_proto->type) {
10712                         /* Make sure programs that attach to void
10713                          * hooks don't try to modify return value.
10714                          */
10715                         range = tnum_range(1, 1);
10716                 }
10717                 break;
10718
10719         case BPF_PROG_TYPE_EXT:
10720                 /* freplace program can return anything as its return value
10721                  * depends on the to-be-replaced kernel func or bpf program.
10722                  */
10723         default:
10724                 return 0;
10725         }
10726
10727         if (reg->type != SCALAR_VALUE) {
10728                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10729                         reg_type_str(env, reg->type));
10730                 return -EINVAL;
10731         }
10732
10733         if (!tnum_in(range, reg->var_off)) {
10734                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10735                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10736                     prog_type == BPF_PROG_TYPE_LSM &&
10737                     !prog->aux->attach_func_proto->type)
10738                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10739                 return -EINVAL;
10740         }
10741
10742         if (!tnum_is_unknown(enforce_attach_type_range) &&
10743             tnum_in(enforce_attach_type_range, reg->var_off))
10744                 env->prog->enforce_expected_attach_type = 1;
10745         return 0;
10746 }
10747
10748 /* non-recursive DFS pseudo code
10749  * 1  procedure DFS-iterative(G,v):
10750  * 2      label v as discovered
10751  * 3      let S be a stack
10752  * 4      S.push(v)
10753  * 5      while S is not empty
10754  * 6            t <- S.pop()
10755  * 7            if t is what we're looking for:
10756  * 8                return t
10757  * 9            for all edges e in G.adjacentEdges(t) do
10758  * 10               if edge e is already labelled
10759  * 11                   continue with the next edge
10760  * 12               w <- G.adjacentVertex(t,e)
10761  * 13               if vertex w is not discovered and not explored
10762  * 14                   label e as tree-edge
10763  * 15                   label w as discovered
10764  * 16                   S.push(w)
10765  * 17                   continue at 5
10766  * 18               else if vertex w is discovered
10767  * 19                   label e as back-edge
10768  * 20               else
10769  * 21                   // vertex w is explored
10770  * 22                   label e as forward- or cross-edge
10771  * 23           label t as explored
10772  * 24           S.pop()
10773  *
10774  * convention:
10775  * 0x10 - discovered
10776  * 0x11 - discovered and fall-through edge labelled
10777  * 0x12 - discovered and fall-through and branch edges labelled
10778  * 0x20 - explored
10779  */
10780
10781 enum {
10782         DISCOVERED = 0x10,
10783         EXPLORED = 0x20,
10784         FALLTHROUGH = 1,
10785         BRANCH = 2,
10786 };
10787
10788 static u32 state_htab_size(struct bpf_verifier_env *env)
10789 {
10790         return env->prog->len;
10791 }
10792
10793 static struct bpf_verifier_state_list **explored_state(
10794                                         struct bpf_verifier_env *env,
10795                                         int idx)
10796 {
10797         struct bpf_verifier_state *cur = env->cur_state;
10798         struct bpf_func_state *state = cur->frame[cur->curframe];
10799
10800         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10801 }
10802
10803 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10804 {
10805         env->insn_aux_data[idx].prune_point = true;
10806 }
10807
10808 enum {
10809         DONE_EXPLORING = 0,
10810         KEEP_EXPLORING = 1,
10811 };
10812
10813 /* t, w, e - match pseudo-code above:
10814  * t - index of current instruction
10815  * w - next instruction
10816  * e - edge
10817  */
10818 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10819                      bool loop_ok)
10820 {
10821         int *insn_stack = env->cfg.insn_stack;
10822         int *insn_state = env->cfg.insn_state;
10823
10824         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10825                 return DONE_EXPLORING;
10826
10827         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10828                 return DONE_EXPLORING;
10829
10830         if (w < 0 || w >= env->prog->len) {
10831                 verbose_linfo(env, t, "%d: ", t);
10832                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10833                 return -EINVAL;
10834         }
10835
10836         if (e == BRANCH)
10837                 /* mark branch target for state pruning */
10838                 init_explored_state(env, w);
10839
10840         if (insn_state[w] == 0) {
10841                 /* tree-edge */
10842                 insn_state[t] = DISCOVERED | e;
10843                 insn_state[w] = DISCOVERED;
10844                 if (env->cfg.cur_stack >= env->prog->len)
10845                         return -E2BIG;
10846                 insn_stack[env->cfg.cur_stack++] = w;
10847                 return KEEP_EXPLORING;
10848         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10849                 if (loop_ok && env->bpf_capable)
10850                         return DONE_EXPLORING;
10851                 verbose_linfo(env, t, "%d: ", t);
10852                 verbose_linfo(env, w, "%d: ", w);
10853                 verbose(env, "back-edge from insn %d to %d\n", t, w);
10854                 return -EINVAL;
10855         } else if (insn_state[w] == EXPLORED) {
10856                 /* forward- or cross-edge */
10857                 insn_state[t] = DISCOVERED | e;
10858         } else {
10859                 verbose(env, "insn state internal bug\n");
10860                 return -EFAULT;
10861         }
10862         return DONE_EXPLORING;
10863 }
10864
10865 static int visit_func_call_insn(int t, int insn_cnt,
10866                                 struct bpf_insn *insns,
10867                                 struct bpf_verifier_env *env,
10868                                 bool visit_callee)
10869 {
10870         int ret;
10871
10872         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10873         if (ret)
10874                 return ret;
10875
10876         if (t + 1 < insn_cnt)
10877                 init_explored_state(env, t + 1);
10878         if (visit_callee) {
10879                 init_explored_state(env, t);
10880                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10881                                 /* It's ok to allow recursion from CFG point of
10882                                  * view. __check_func_call() will do the actual
10883                                  * check.
10884                                  */
10885                                 bpf_pseudo_func(insns + t));
10886         }
10887         return ret;
10888 }
10889
10890 /* Visits the instruction at index t and returns one of the following:
10891  *  < 0 - an error occurred
10892  *  DONE_EXPLORING - the instruction was fully explored
10893  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10894  */
10895 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10896 {
10897         struct bpf_insn *insns = env->prog->insnsi;
10898         int ret;
10899
10900         if (bpf_pseudo_func(insns + t))
10901                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10902
10903         /* All non-branch instructions have a single fall-through edge. */
10904         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10905             BPF_CLASS(insns[t].code) != BPF_JMP32)
10906                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10907
10908         switch (BPF_OP(insns[t].code)) {
10909         case BPF_EXIT:
10910                 return DONE_EXPLORING;
10911
10912         case BPF_CALL:
10913                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10914                         /* Mark this call insn to trigger is_state_visited() check
10915                          * before call itself is processed by __check_func_call().
10916                          * Otherwise new async state will be pushed for further
10917                          * exploration.
10918                          */
10919                         init_explored_state(env, t);
10920                 return visit_func_call_insn(t, insn_cnt, insns, env,
10921                                             insns[t].src_reg == BPF_PSEUDO_CALL);
10922
10923         case BPF_JA:
10924                 if (BPF_SRC(insns[t].code) != BPF_K)
10925                         return -EINVAL;
10926
10927                 /* unconditional jump with single edge */
10928                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10929                                 true);
10930                 if (ret)
10931                         return ret;
10932
10933                 /* unconditional jmp is not a good pruning point,
10934                  * but it's marked, since backtracking needs
10935                  * to record jmp history in is_state_visited().
10936                  */
10937                 init_explored_state(env, t + insns[t].off + 1);
10938                 /* tell verifier to check for equivalent states
10939                  * after every call and jump
10940                  */
10941                 if (t + 1 < insn_cnt)
10942                         init_explored_state(env, t + 1);
10943
10944                 return ret;
10945
10946         default:
10947                 /* conditional jump with two edges */
10948                 init_explored_state(env, t);
10949                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10950                 if (ret)
10951                         return ret;
10952
10953                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10954         }
10955 }
10956
10957 /* non-recursive depth-first-search to detect loops in BPF program
10958  * loop == back-edge in directed graph
10959  */
10960 static int check_cfg(struct bpf_verifier_env *env)
10961 {
10962         int insn_cnt = env->prog->len;
10963         int *insn_stack, *insn_state;
10964         int ret = 0;
10965         int i;
10966
10967         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10968         if (!insn_state)
10969                 return -ENOMEM;
10970
10971         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10972         if (!insn_stack) {
10973                 kvfree(insn_state);
10974                 return -ENOMEM;
10975         }
10976
10977         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10978         insn_stack[0] = 0; /* 0 is the first instruction */
10979         env->cfg.cur_stack = 1;
10980
10981         while (env->cfg.cur_stack > 0) {
10982                 int t = insn_stack[env->cfg.cur_stack - 1];
10983
10984                 ret = visit_insn(t, insn_cnt, env);
10985                 switch (ret) {
10986                 case DONE_EXPLORING:
10987                         insn_state[t] = EXPLORED;
10988                         env->cfg.cur_stack--;
10989                         break;
10990                 case KEEP_EXPLORING:
10991                         break;
10992                 default:
10993                         if (ret > 0) {
10994                                 verbose(env, "visit_insn internal bug\n");
10995                                 ret = -EFAULT;
10996                         }
10997                         goto err_free;
10998                 }
10999         }
11000
11001         if (env->cfg.cur_stack < 0) {
11002                 verbose(env, "pop stack internal bug\n");
11003                 ret = -EFAULT;
11004                 goto err_free;
11005         }
11006
11007         for (i = 0; i < insn_cnt; i++) {
11008                 if (insn_state[i] != EXPLORED) {
11009                         verbose(env, "unreachable insn %d\n", i);
11010                         ret = -EINVAL;
11011                         goto err_free;
11012                 }
11013         }
11014         ret = 0; /* cfg looks good */
11015
11016 err_free:
11017         kvfree(insn_state);
11018         kvfree(insn_stack);
11019         env->cfg.insn_state = env->cfg.insn_stack = NULL;
11020         return ret;
11021 }
11022
11023 static int check_abnormal_return(struct bpf_verifier_env *env)
11024 {
11025         int i;
11026
11027         for (i = 1; i < env->subprog_cnt; i++) {
11028                 if (env->subprog_info[i].has_ld_abs) {
11029                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
11030                         return -EINVAL;
11031                 }
11032                 if (env->subprog_info[i].has_tail_call) {
11033                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
11034                         return -EINVAL;
11035                 }
11036         }
11037         return 0;
11038 }
11039
11040 /* The minimum supported BTF func info size */
11041 #define MIN_BPF_FUNCINFO_SIZE   8
11042 #define MAX_FUNCINFO_REC_SIZE   252
11043
11044 static int check_btf_func(struct bpf_verifier_env *env,
11045                           const union bpf_attr *attr,
11046                           bpfptr_t uattr)
11047 {
11048         const struct btf_type *type, *func_proto, *ret_type;
11049         u32 i, nfuncs, urec_size, min_size;
11050         u32 krec_size = sizeof(struct bpf_func_info);
11051         struct bpf_func_info *krecord;
11052         struct bpf_func_info_aux *info_aux = NULL;
11053         struct bpf_prog *prog;
11054         const struct btf *btf;
11055         bpfptr_t urecord;
11056         u32 prev_offset = 0;
11057         bool scalar_return;
11058         int ret = -ENOMEM;
11059
11060         nfuncs = attr->func_info_cnt;
11061         if (!nfuncs) {
11062                 if (check_abnormal_return(env))
11063                         return -EINVAL;
11064                 return 0;
11065         }
11066
11067         if (nfuncs != env->subprog_cnt) {
11068                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11069                 return -EINVAL;
11070         }
11071
11072         urec_size = attr->func_info_rec_size;
11073         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11074             urec_size > MAX_FUNCINFO_REC_SIZE ||
11075             urec_size % sizeof(u32)) {
11076                 verbose(env, "invalid func info rec size %u\n", urec_size);
11077                 return -EINVAL;
11078         }
11079
11080         prog = env->prog;
11081         btf = prog->aux->btf;
11082
11083         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11084         min_size = min_t(u32, krec_size, urec_size);
11085
11086         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11087         if (!krecord)
11088                 return -ENOMEM;
11089         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11090         if (!info_aux)
11091                 goto err_free;
11092
11093         for (i = 0; i < nfuncs; i++) {
11094                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11095                 if (ret) {
11096                         if (ret == -E2BIG) {
11097                                 verbose(env, "nonzero tailing record in func info");
11098                                 /* set the size kernel expects so loader can zero
11099                                  * out the rest of the record.
11100                                  */
11101                                 if (copy_to_bpfptr_offset(uattr,
11102                                                           offsetof(union bpf_attr, func_info_rec_size),
11103                                                           &min_size, sizeof(min_size)))
11104                                         ret = -EFAULT;
11105                         }
11106                         goto err_free;
11107                 }
11108
11109                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11110                         ret = -EFAULT;
11111                         goto err_free;
11112                 }
11113
11114                 /* check insn_off */
11115                 ret = -EINVAL;
11116                 if (i == 0) {
11117                         if (krecord[i].insn_off) {
11118                                 verbose(env,
11119                                         "nonzero insn_off %u for the first func info record",
11120                                         krecord[i].insn_off);
11121                                 goto err_free;
11122                         }
11123                 } else if (krecord[i].insn_off <= prev_offset) {
11124                         verbose(env,
11125                                 "same or smaller insn offset (%u) than previous func info record (%u)",
11126                                 krecord[i].insn_off, prev_offset);
11127                         goto err_free;
11128                 }
11129
11130                 if (env->subprog_info[i].start != krecord[i].insn_off) {
11131                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11132                         goto err_free;
11133                 }
11134
11135                 /* check type_id */
11136                 type = btf_type_by_id(btf, krecord[i].type_id);
11137                 if (!type || !btf_type_is_func(type)) {
11138                         verbose(env, "invalid type id %d in func info",
11139                                 krecord[i].type_id);
11140                         goto err_free;
11141                 }
11142                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11143
11144                 func_proto = btf_type_by_id(btf, type->type);
11145                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11146                         /* btf_func_check() already verified it during BTF load */
11147                         goto err_free;
11148                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11149                 scalar_return =
11150                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11151                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11152                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11153                         goto err_free;
11154                 }
11155                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11156                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11157                         goto err_free;
11158                 }
11159
11160                 prev_offset = krecord[i].insn_off;
11161                 bpfptr_add(&urecord, urec_size);
11162         }
11163
11164         prog->aux->func_info = krecord;
11165         prog->aux->func_info_cnt = nfuncs;
11166         prog->aux->func_info_aux = info_aux;
11167         return 0;
11168
11169 err_free:
11170         kvfree(krecord);
11171         kfree(info_aux);
11172         return ret;
11173 }
11174
11175 static void adjust_btf_func(struct bpf_verifier_env *env)
11176 {
11177         struct bpf_prog_aux *aux = env->prog->aux;
11178         int i;
11179
11180         if (!aux->func_info)
11181                 return;
11182
11183         for (i = 0; i < env->subprog_cnt; i++)
11184                 aux->func_info[i].insn_off = env->subprog_info[i].start;
11185 }
11186
11187 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
11188 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
11189
11190 static int check_btf_line(struct bpf_verifier_env *env,
11191                           const union bpf_attr *attr,
11192                           bpfptr_t uattr)
11193 {
11194         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11195         struct bpf_subprog_info *sub;
11196         struct bpf_line_info *linfo;
11197         struct bpf_prog *prog;
11198         const struct btf *btf;
11199         bpfptr_t ulinfo;
11200         int err;
11201
11202         nr_linfo = attr->line_info_cnt;
11203         if (!nr_linfo)
11204                 return 0;
11205         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11206                 return -EINVAL;
11207
11208         rec_size = attr->line_info_rec_size;
11209         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11210             rec_size > MAX_LINEINFO_REC_SIZE ||
11211             rec_size & (sizeof(u32) - 1))
11212                 return -EINVAL;
11213
11214         /* Need to zero it in case the userspace may
11215          * pass in a smaller bpf_line_info object.
11216          */
11217         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11218                          GFP_KERNEL | __GFP_NOWARN);
11219         if (!linfo)
11220                 return -ENOMEM;
11221
11222         prog = env->prog;
11223         btf = prog->aux->btf;
11224
11225         s = 0;
11226         sub = env->subprog_info;
11227         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11228         expected_size = sizeof(struct bpf_line_info);
11229         ncopy = min_t(u32, expected_size, rec_size);
11230         for (i = 0; i < nr_linfo; i++) {
11231                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11232                 if (err) {
11233                         if (err == -E2BIG) {
11234                                 verbose(env, "nonzero tailing record in line_info");
11235                                 if (copy_to_bpfptr_offset(uattr,
11236                                                           offsetof(union bpf_attr, line_info_rec_size),
11237                                                           &expected_size, sizeof(expected_size)))
11238                                         err = -EFAULT;
11239                         }
11240                         goto err_free;
11241                 }
11242
11243                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11244                         err = -EFAULT;
11245                         goto err_free;
11246                 }
11247
11248                 /*
11249                  * Check insn_off to ensure
11250                  * 1) strictly increasing AND
11251                  * 2) bounded by prog->len
11252                  *
11253                  * The linfo[0].insn_off == 0 check logically falls into
11254                  * the later "missing bpf_line_info for func..." case
11255                  * because the first linfo[0].insn_off must be the
11256                  * first sub also and the first sub must have
11257                  * subprog_info[0].start == 0.
11258                  */
11259                 if ((i && linfo[i].insn_off <= prev_offset) ||
11260                     linfo[i].insn_off >= prog->len) {
11261                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11262                                 i, linfo[i].insn_off, prev_offset,
11263                                 prog->len);
11264                         err = -EINVAL;
11265                         goto err_free;
11266                 }
11267
11268                 if (!prog->insnsi[linfo[i].insn_off].code) {
11269                         verbose(env,
11270                                 "Invalid insn code at line_info[%u].insn_off\n",
11271                                 i);
11272                         err = -EINVAL;
11273                         goto err_free;
11274                 }
11275
11276                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11277                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11278                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11279                         err = -EINVAL;
11280                         goto err_free;
11281                 }
11282
11283                 if (s != env->subprog_cnt) {
11284                         if (linfo[i].insn_off == sub[s].start) {
11285                                 sub[s].linfo_idx = i;
11286                                 s++;
11287                         } else if (sub[s].start < linfo[i].insn_off) {
11288                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
11289                                 err = -EINVAL;
11290                                 goto err_free;
11291                         }
11292                 }
11293
11294                 prev_offset = linfo[i].insn_off;
11295                 bpfptr_add(&ulinfo, rec_size);
11296         }
11297
11298         if (s != env->subprog_cnt) {
11299                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11300                         env->subprog_cnt - s, s);
11301                 err = -EINVAL;
11302                 goto err_free;
11303         }
11304
11305         prog->aux->linfo = linfo;
11306         prog->aux->nr_linfo = nr_linfo;
11307
11308         return 0;
11309
11310 err_free:
11311         kvfree(linfo);
11312         return err;
11313 }
11314
11315 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
11316 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
11317
11318 static int check_core_relo(struct bpf_verifier_env *env,
11319                            const union bpf_attr *attr,
11320                            bpfptr_t uattr)
11321 {
11322         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11323         struct bpf_core_relo core_relo = {};
11324         struct bpf_prog *prog = env->prog;
11325         const struct btf *btf = prog->aux->btf;
11326         struct bpf_core_ctx ctx = {
11327                 .log = &env->log,
11328                 .btf = btf,
11329         };
11330         bpfptr_t u_core_relo;
11331         int err;
11332
11333         nr_core_relo = attr->core_relo_cnt;
11334         if (!nr_core_relo)
11335                 return 0;
11336         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11337                 return -EINVAL;
11338
11339         rec_size = attr->core_relo_rec_size;
11340         if (rec_size < MIN_CORE_RELO_SIZE ||
11341             rec_size > MAX_CORE_RELO_SIZE ||
11342             rec_size % sizeof(u32))
11343                 return -EINVAL;
11344
11345         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11346         expected_size = sizeof(struct bpf_core_relo);
11347         ncopy = min_t(u32, expected_size, rec_size);
11348
11349         /* Unlike func_info and line_info, copy and apply each CO-RE
11350          * relocation record one at a time.
11351          */
11352         for (i = 0; i < nr_core_relo; i++) {
11353                 /* future proofing when sizeof(bpf_core_relo) changes */
11354                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11355                 if (err) {
11356                         if (err == -E2BIG) {
11357                                 verbose(env, "nonzero tailing record in core_relo");
11358                                 if (copy_to_bpfptr_offset(uattr,
11359                                                           offsetof(union bpf_attr, core_relo_rec_size),
11360                                                           &expected_size, sizeof(expected_size)))
11361                                         err = -EFAULT;
11362                         }
11363                         break;
11364                 }
11365
11366                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11367                         err = -EFAULT;
11368                         break;
11369                 }
11370
11371                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11372                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11373                                 i, core_relo.insn_off, prog->len);
11374                         err = -EINVAL;
11375                         break;
11376                 }
11377
11378                 err = bpf_core_apply(&ctx, &core_relo, i,
11379                                      &prog->insnsi[core_relo.insn_off / 8]);
11380                 if (err)
11381                         break;
11382                 bpfptr_add(&u_core_relo, rec_size);
11383         }
11384         return err;
11385 }
11386
11387 static int check_btf_info(struct bpf_verifier_env *env,
11388                           const union bpf_attr *attr,
11389                           bpfptr_t uattr)
11390 {
11391         struct btf *btf;
11392         int err;
11393
11394         if (!attr->func_info_cnt && !attr->line_info_cnt) {
11395                 if (check_abnormal_return(env))
11396                         return -EINVAL;
11397                 return 0;
11398         }
11399
11400         btf = btf_get_by_fd(attr->prog_btf_fd);
11401         if (IS_ERR(btf))
11402                 return PTR_ERR(btf);
11403         if (btf_is_kernel(btf)) {
11404                 btf_put(btf);
11405                 return -EACCES;
11406         }
11407         env->prog->aux->btf = btf;
11408
11409         err = check_btf_func(env, attr, uattr);
11410         if (err)
11411                 return err;
11412
11413         err = check_btf_line(env, attr, uattr);
11414         if (err)
11415                 return err;
11416
11417         err = check_core_relo(env, attr, uattr);
11418         if (err)
11419                 return err;
11420
11421         return 0;
11422 }
11423
11424 /* check %cur's range satisfies %old's */
11425 static bool range_within(struct bpf_reg_state *old,
11426                          struct bpf_reg_state *cur)
11427 {
11428         return old->umin_value <= cur->umin_value &&
11429                old->umax_value >= cur->umax_value &&
11430                old->smin_value <= cur->smin_value &&
11431                old->smax_value >= cur->smax_value &&
11432                old->u32_min_value <= cur->u32_min_value &&
11433                old->u32_max_value >= cur->u32_max_value &&
11434                old->s32_min_value <= cur->s32_min_value &&
11435                old->s32_max_value >= cur->s32_max_value;
11436 }
11437
11438 /* If in the old state two registers had the same id, then they need to have
11439  * the same id in the new state as well.  But that id could be different from
11440  * the old state, so we need to track the mapping from old to new ids.
11441  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11442  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11443  * regs with a different old id could still have new id 9, we don't care about
11444  * that.
11445  * So we look through our idmap to see if this old id has been seen before.  If
11446  * so, we require the new id to match; otherwise, we add the id pair to the map.
11447  */
11448 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11449 {
11450         unsigned int i;
11451
11452         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11453                 if (!idmap[i].old) {
11454                         /* Reached an empty slot; haven't seen this id before */
11455                         idmap[i].old = old_id;
11456                         idmap[i].cur = cur_id;
11457                         return true;
11458                 }
11459                 if (idmap[i].old == old_id)
11460                         return idmap[i].cur == cur_id;
11461         }
11462         /* We ran out of idmap slots, which should be impossible */
11463         WARN_ON_ONCE(1);
11464         return false;
11465 }
11466
11467 static void clean_func_state(struct bpf_verifier_env *env,
11468                              struct bpf_func_state *st)
11469 {
11470         enum bpf_reg_liveness live;
11471         int i, j;
11472
11473         for (i = 0; i < BPF_REG_FP; i++) {
11474                 live = st->regs[i].live;
11475                 /* liveness must not touch this register anymore */
11476                 st->regs[i].live |= REG_LIVE_DONE;
11477                 if (!(live & REG_LIVE_READ))
11478                         /* since the register is unused, clear its state
11479                          * to make further comparison simpler
11480                          */
11481                         __mark_reg_not_init(env, &st->regs[i]);
11482         }
11483
11484         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11485                 live = st->stack[i].spilled_ptr.live;
11486                 /* liveness must not touch this stack slot anymore */
11487                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11488                 if (!(live & REG_LIVE_READ)) {
11489                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11490                         for (j = 0; j < BPF_REG_SIZE; j++)
11491                                 st->stack[i].slot_type[j] = STACK_INVALID;
11492                 }
11493         }
11494 }
11495
11496 static void clean_verifier_state(struct bpf_verifier_env *env,
11497                                  struct bpf_verifier_state *st)
11498 {
11499         int i;
11500
11501         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11502                 /* all regs in this state in all frames were already marked */
11503                 return;
11504
11505         for (i = 0; i <= st->curframe; i++)
11506                 clean_func_state(env, st->frame[i]);
11507 }
11508
11509 /* the parentage chains form a tree.
11510  * the verifier states are added to state lists at given insn and
11511  * pushed into state stack for future exploration.
11512  * when the verifier reaches bpf_exit insn some of the verifer states
11513  * stored in the state lists have their final liveness state already,
11514  * but a lot of states will get revised from liveness point of view when
11515  * the verifier explores other branches.
11516  * Example:
11517  * 1: r0 = 1
11518  * 2: if r1 == 100 goto pc+1
11519  * 3: r0 = 2
11520  * 4: exit
11521  * when the verifier reaches exit insn the register r0 in the state list of
11522  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11523  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11524  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11525  *
11526  * Since the verifier pushes the branch states as it sees them while exploring
11527  * the program the condition of walking the branch instruction for the second
11528  * time means that all states below this branch were already explored and
11529  * their final liveness marks are already propagated.
11530  * Hence when the verifier completes the search of state list in is_state_visited()
11531  * we can call this clean_live_states() function to mark all liveness states
11532  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11533  * will not be used.
11534  * This function also clears the registers and stack for states that !READ
11535  * to simplify state merging.
11536  *
11537  * Important note here that walking the same branch instruction in the callee
11538  * doesn't meant that the states are DONE. The verifier has to compare
11539  * the callsites
11540  */
11541 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11542                               struct bpf_verifier_state *cur)
11543 {
11544         struct bpf_verifier_state_list *sl;
11545         int i;
11546
11547         sl = *explored_state(env, insn);
11548         while (sl) {
11549                 if (sl->state.branches)
11550                         goto next;
11551                 if (sl->state.insn_idx != insn ||
11552                     sl->state.curframe != cur->curframe)
11553                         goto next;
11554                 for (i = 0; i <= cur->curframe; i++)
11555                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11556                                 goto next;
11557                 clean_verifier_state(env, &sl->state);
11558 next:
11559                 sl = sl->next;
11560         }
11561 }
11562
11563 /* Returns true if (rold safe implies rcur safe) */
11564 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11565                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11566 {
11567         bool equal;
11568
11569         if (!(rold->live & REG_LIVE_READ))
11570                 /* explored state didn't use this */
11571                 return true;
11572
11573         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11574
11575         if (rold->type == PTR_TO_STACK)
11576                 /* two stack pointers are equal only if they're pointing to
11577                  * the same stack frame, since fp-8 in foo != fp-8 in bar
11578                  */
11579                 return equal && rold->frameno == rcur->frameno;
11580
11581         if (equal)
11582                 return true;
11583
11584         if (rold->type == NOT_INIT)
11585                 /* explored state can't have used this */
11586                 return true;
11587         if (rcur->type == NOT_INIT)
11588                 return false;
11589         switch (base_type(rold->type)) {
11590         case SCALAR_VALUE:
11591                 if (env->explore_alu_limits)
11592                         return false;
11593                 if (rcur->type == SCALAR_VALUE) {
11594                         if (!rold->precise && !rcur->precise)
11595                                 return true;
11596                         /* new val must satisfy old val knowledge */
11597                         return range_within(rold, rcur) &&
11598                                tnum_in(rold->var_off, rcur->var_off);
11599                 } else {
11600                         /* We're trying to use a pointer in place of a scalar.
11601                          * Even if the scalar was unbounded, this could lead to
11602                          * pointer leaks because scalars are allowed to leak
11603                          * while pointers are not. We could make this safe in
11604                          * special cases if root is calling us, but it's
11605                          * probably not worth the hassle.
11606                          */
11607                         return false;
11608                 }
11609         case PTR_TO_MAP_KEY:
11610         case PTR_TO_MAP_VALUE:
11611                 /* a PTR_TO_MAP_VALUE could be safe to use as a
11612                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11613                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11614                  * checked, doing so could have affected others with the same
11615                  * id, and we can't check for that because we lost the id when
11616                  * we converted to a PTR_TO_MAP_VALUE.
11617                  */
11618                 if (type_may_be_null(rold->type)) {
11619                         if (!type_may_be_null(rcur->type))
11620                                 return false;
11621                         if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11622                                 return false;
11623                         /* Check our ids match any regs they're supposed to */
11624                         return check_ids(rold->id, rcur->id, idmap);
11625                 }
11626
11627                 /* If the new min/max/var_off satisfy the old ones and
11628                  * everything else matches, we are OK.
11629                  * 'id' is not compared, since it's only used for maps with
11630                  * bpf_spin_lock inside map element and in such cases if
11631                  * the rest of the prog is valid for one map element then
11632                  * it's valid for all map elements regardless of the key
11633                  * used in bpf_map_lookup()
11634                  */
11635                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11636                        range_within(rold, rcur) &&
11637                        tnum_in(rold->var_off, rcur->var_off);
11638         case PTR_TO_PACKET_META:
11639         case PTR_TO_PACKET:
11640                 if (rcur->type != rold->type)
11641                         return false;
11642                 /* We must have at least as much range as the old ptr
11643                  * did, so that any accesses which were safe before are
11644                  * still safe.  This is true even if old range < old off,
11645                  * since someone could have accessed through (ptr - k), or
11646                  * even done ptr -= k in a register, to get a safe access.
11647                  */
11648                 if (rold->range > rcur->range)
11649                         return false;
11650                 /* If the offsets don't match, we can't trust our alignment;
11651                  * nor can we be sure that we won't fall out of range.
11652                  */
11653                 if (rold->off != rcur->off)
11654                         return false;
11655                 /* id relations must be preserved */
11656                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11657                         return false;
11658                 /* new val must satisfy old val knowledge */
11659                 return range_within(rold, rcur) &&
11660                        tnum_in(rold->var_off, rcur->var_off);
11661         case PTR_TO_CTX:
11662         case CONST_PTR_TO_MAP:
11663         case PTR_TO_PACKET_END:
11664         case PTR_TO_FLOW_KEYS:
11665         case PTR_TO_SOCKET:
11666         case PTR_TO_SOCK_COMMON:
11667         case PTR_TO_TCP_SOCK:
11668         case PTR_TO_XDP_SOCK:
11669                 /* Only valid matches are exact, which memcmp() above
11670                  * would have accepted
11671                  */
11672         default:
11673                 /* Don't know what's going on, just say it's not safe */
11674                 return false;
11675         }
11676
11677         /* Shouldn't get here; if we do, say it's not safe */
11678         WARN_ON_ONCE(1);
11679         return false;
11680 }
11681
11682 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11683                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11684 {
11685         int i, spi;
11686
11687         /* walk slots of the explored stack and ignore any additional
11688          * slots in the current stack, since explored(safe) state
11689          * didn't use them
11690          */
11691         for (i = 0; i < old->allocated_stack; i++) {
11692                 spi = i / BPF_REG_SIZE;
11693
11694                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11695                         i += BPF_REG_SIZE - 1;
11696                         /* explored state didn't use this */
11697                         continue;
11698                 }
11699
11700                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11701                         continue;
11702
11703                 /* explored stack has more populated slots than current stack
11704                  * and these slots were used
11705                  */
11706                 if (i >= cur->allocated_stack)
11707                         return false;
11708
11709                 /* if old state was safe with misc data in the stack
11710                  * it will be safe with zero-initialized stack.
11711                  * The opposite is not true
11712                  */
11713                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11714                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11715                         continue;
11716                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11717                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11718                         /* Ex: old explored (safe) state has STACK_SPILL in
11719                          * this stack slot, but current has STACK_MISC ->
11720                          * this verifier states are not equivalent,
11721                          * return false to continue verification of this path
11722                          */
11723                         return false;
11724                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11725                         continue;
11726                 if (!is_spilled_reg(&old->stack[spi]))
11727                         continue;
11728                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11729                              &cur->stack[spi].spilled_ptr, idmap))
11730                         /* when explored and current stack slot are both storing
11731                          * spilled registers, check that stored pointers types
11732                          * are the same as well.
11733                          * Ex: explored safe path could have stored
11734                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11735                          * but current path has stored:
11736                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11737                          * such verifier states are not equivalent.
11738                          * return false to continue verification of this path
11739                          */
11740                         return false;
11741         }
11742         return true;
11743 }
11744
11745 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11746 {
11747         if (old->acquired_refs != cur->acquired_refs)
11748                 return false;
11749         return !memcmp(old->refs, cur->refs,
11750                        sizeof(*old->refs) * old->acquired_refs);
11751 }
11752
11753 /* compare two verifier states
11754  *
11755  * all states stored in state_list are known to be valid, since
11756  * verifier reached 'bpf_exit' instruction through them
11757  *
11758  * this function is called when verifier exploring different branches of
11759  * execution popped from the state stack. If it sees an old state that has
11760  * more strict register state and more strict stack state then this execution
11761  * branch doesn't need to be explored further, since verifier already
11762  * concluded that more strict state leads to valid finish.
11763  *
11764  * Therefore two states are equivalent if register state is more conservative
11765  * and explored stack state is more conservative than the current one.
11766  * Example:
11767  *       explored                   current
11768  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11769  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11770  *
11771  * In other words if current stack state (one being explored) has more
11772  * valid slots than old one that already passed validation, it means
11773  * the verifier can stop exploring and conclude that current state is valid too
11774  *
11775  * Similarly with registers. If explored state has register type as invalid
11776  * whereas register type in current state is meaningful, it means that
11777  * the current state will reach 'bpf_exit' instruction safely
11778  */
11779 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11780                               struct bpf_func_state *cur)
11781 {
11782         int i;
11783
11784         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11785         for (i = 0; i < MAX_BPF_REG; i++)
11786                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11787                              env->idmap_scratch))
11788                         return false;
11789
11790         if (!stacksafe(env, old, cur, env->idmap_scratch))
11791                 return false;
11792
11793         if (!refsafe(old, cur))
11794                 return false;
11795
11796         return true;
11797 }
11798
11799 static bool states_equal(struct bpf_verifier_env *env,
11800                          struct bpf_verifier_state *old,
11801                          struct bpf_verifier_state *cur)
11802 {
11803         int i;
11804
11805         if (old->curframe != cur->curframe)
11806                 return false;
11807
11808         /* Verification state from speculative execution simulation
11809          * must never prune a non-speculative execution one.
11810          */
11811         if (old->speculative && !cur->speculative)
11812                 return false;
11813
11814         if (old->active_spin_lock != cur->active_spin_lock)
11815                 return false;
11816
11817         /* for states to be equal callsites have to be the same
11818          * and all frame states need to be equivalent
11819          */
11820         for (i = 0; i <= old->curframe; i++) {
11821                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11822                         return false;
11823                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11824                         return false;
11825         }
11826         return true;
11827 }
11828
11829 /* Return 0 if no propagation happened. Return negative error code if error
11830  * happened. Otherwise, return the propagated bit.
11831  */
11832 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11833                                   struct bpf_reg_state *reg,
11834                                   struct bpf_reg_state *parent_reg)
11835 {
11836         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11837         u8 flag = reg->live & REG_LIVE_READ;
11838         int err;
11839
11840         /* When comes here, read flags of PARENT_REG or REG could be any of
11841          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11842          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11843          */
11844         if (parent_flag == REG_LIVE_READ64 ||
11845             /* Or if there is no read flag from REG. */
11846             !flag ||
11847             /* Or if the read flag from REG is the same as PARENT_REG. */
11848             parent_flag == flag)
11849                 return 0;
11850
11851         err = mark_reg_read(env, reg, parent_reg, flag);
11852         if (err)
11853                 return err;
11854
11855         return flag;
11856 }
11857
11858 /* A write screens off any subsequent reads; but write marks come from the
11859  * straight-line code between a state and its parent.  When we arrive at an
11860  * equivalent state (jump target or such) we didn't arrive by the straight-line
11861  * code, so read marks in the state must propagate to the parent regardless
11862  * of the state's write marks. That's what 'parent == state->parent' comparison
11863  * in mark_reg_read() is for.
11864  */
11865 static int propagate_liveness(struct bpf_verifier_env *env,
11866                               const struct bpf_verifier_state *vstate,
11867                               struct bpf_verifier_state *vparent)
11868 {
11869         struct bpf_reg_state *state_reg, *parent_reg;
11870         struct bpf_func_state *state, *parent;
11871         int i, frame, err = 0;
11872
11873         if (vparent->curframe != vstate->curframe) {
11874                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11875                      vparent->curframe, vstate->curframe);
11876                 return -EFAULT;
11877         }
11878         /* Propagate read liveness of registers... */
11879         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11880         for (frame = 0; frame <= vstate->curframe; frame++) {
11881                 parent = vparent->frame[frame];
11882                 state = vstate->frame[frame];
11883                 parent_reg = parent->regs;
11884                 state_reg = state->regs;
11885                 /* We don't need to worry about FP liveness, it's read-only */
11886                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11887                         err = propagate_liveness_reg(env, &state_reg[i],
11888                                                      &parent_reg[i]);
11889                         if (err < 0)
11890                                 return err;
11891                         if (err == REG_LIVE_READ64)
11892                                 mark_insn_zext(env, &parent_reg[i]);
11893                 }
11894
11895                 /* Propagate stack slots. */
11896                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11897                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11898                         parent_reg = &parent->stack[i].spilled_ptr;
11899                         state_reg = &state->stack[i].spilled_ptr;
11900                         err = propagate_liveness_reg(env, state_reg,
11901                                                      parent_reg);
11902                         if (err < 0)
11903                                 return err;
11904                 }
11905         }
11906         return 0;
11907 }
11908
11909 /* find precise scalars in the previous equivalent state and
11910  * propagate them into the current state
11911  */
11912 static int propagate_precision(struct bpf_verifier_env *env,
11913                                const struct bpf_verifier_state *old)
11914 {
11915         struct bpf_reg_state *state_reg;
11916         struct bpf_func_state *state;
11917         int i, err = 0, fr;
11918
11919         for (fr = old->curframe; fr >= 0; fr--) {
11920                 state = old->frame[fr];
11921                 state_reg = state->regs;
11922                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11923                         if (state_reg->type != SCALAR_VALUE ||
11924                             !state_reg->precise ||
11925                             !(state_reg->live & REG_LIVE_READ))
11926                                 continue;
11927                         if (env->log.level & BPF_LOG_LEVEL2)
11928                                 verbose(env, "frame %d: propagating r%d\n", fr, i);
11929                         err = mark_chain_precision_frame(env, fr, i);
11930                         if (err < 0)
11931                                 return err;
11932                 }
11933
11934                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11935                         if (!is_spilled_reg(&state->stack[i]))
11936                                 continue;
11937                         state_reg = &state->stack[i].spilled_ptr;
11938                         if (state_reg->type != SCALAR_VALUE ||
11939                             !state_reg->precise ||
11940                             !(state_reg->live & REG_LIVE_READ))
11941                                 continue;
11942                         if (env->log.level & BPF_LOG_LEVEL2)
11943                                 verbose(env, "frame %d: propagating fp%d\n",
11944                                         fr, (-i - 1) * BPF_REG_SIZE);
11945                         err = mark_chain_precision_stack_frame(env, fr, i);
11946                         if (err < 0)
11947                                 return err;
11948                 }
11949         }
11950         return 0;
11951 }
11952
11953 static bool states_maybe_looping(struct bpf_verifier_state *old,
11954                                  struct bpf_verifier_state *cur)
11955 {
11956         struct bpf_func_state *fold, *fcur;
11957         int i, fr = cur->curframe;
11958
11959         if (old->curframe != fr)
11960                 return false;
11961
11962         fold = old->frame[fr];
11963         fcur = cur->frame[fr];
11964         for (i = 0; i < MAX_BPF_REG; i++)
11965                 if (memcmp(&fold->regs[i], &fcur->regs[i],
11966                            offsetof(struct bpf_reg_state, parent)))
11967                         return false;
11968         return true;
11969 }
11970
11971
11972 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11973 {
11974         struct bpf_verifier_state_list *new_sl;
11975         struct bpf_verifier_state_list *sl, **pprev;
11976         struct bpf_verifier_state *cur = env->cur_state, *new;
11977         int i, j, err, states_cnt = 0;
11978         bool add_new_state = env->test_state_freq ? true : false;
11979
11980         cur->last_insn_idx = env->prev_insn_idx;
11981         if (!env->insn_aux_data[insn_idx].prune_point)
11982                 /* this 'insn_idx' instruction wasn't marked, so we will not
11983                  * be doing state search here
11984                  */
11985                 return 0;
11986
11987         /* bpf progs typically have pruning point every 4 instructions
11988          * http://vger.kernel.org/bpfconf2019.html#session-1
11989          * Do not add new state for future pruning if the verifier hasn't seen
11990          * at least 2 jumps and at least 8 instructions.
11991          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11992          * In tests that amounts to up to 50% reduction into total verifier
11993          * memory consumption and 20% verifier time speedup.
11994          */
11995         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11996             env->insn_processed - env->prev_insn_processed >= 8)
11997                 add_new_state = true;
11998
11999         pprev = explored_state(env, insn_idx);
12000         sl = *pprev;
12001
12002         clean_live_states(env, insn_idx, cur);
12003
12004         while (sl) {
12005                 states_cnt++;
12006                 if (sl->state.insn_idx != insn_idx)
12007                         goto next;
12008
12009                 if (sl->state.branches) {
12010                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
12011
12012                         if (frame->in_async_callback_fn &&
12013                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
12014                                 /* Different async_entry_cnt means that the verifier is
12015                                  * processing another entry into async callback.
12016                                  * Seeing the same state is not an indication of infinite
12017                                  * loop or infinite recursion.
12018                                  * But finding the same state doesn't mean that it's safe
12019                                  * to stop processing the current state. The previous state
12020                                  * hasn't yet reached bpf_exit, since state.branches > 0.
12021                                  * Checking in_async_callback_fn alone is not enough either.
12022                                  * Since the verifier still needs to catch infinite loops
12023                                  * inside async callbacks.
12024                                  */
12025                         } else if (states_maybe_looping(&sl->state, cur) &&
12026                                    states_equal(env, &sl->state, cur)) {
12027                                 verbose_linfo(env, insn_idx, "; ");
12028                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
12029                                 return -EINVAL;
12030                         }
12031                         /* if the verifier is processing a loop, avoid adding new state
12032                          * too often, since different loop iterations have distinct
12033                          * states and may not help future pruning.
12034                          * This threshold shouldn't be too low to make sure that
12035                          * a loop with large bound will be rejected quickly.
12036                          * The most abusive loop will be:
12037                          * r1 += 1
12038                          * if r1 < 1000000 goto pc-2
12039                          * 1M insn_procssed limit / 100 == 10k peak states.
12040                          * This threshold shouldn't be too high either, since states
12041                          * at the end of the loop are likely to be useful in pruning.
12042                          */
12043                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
12044                             env->insn_processed - env->prev_insn_processed < 100)
12045                                 add_new_state = false;
12046                         goto miss;
12047                 }
12048                 if (states_equal(env, &sl->state, cur)) {
12049                         sl->hit_cnt++;
12050                         /* reached equivalent register/stack state,
12051                          * prune the search.
12052                          * Registers read by the continuation are read by us.
12053                          * If we have any write marks in env->cur_state, they
12054                          * will prevent corresponding reads in the continuation
12055                          * from reaching our parent (an explored_state).  Our
12056                          * own state will get the read marks recorded, but
12057                          * they'll be immediately forgotten as we're pruning
12058                          * this state and will pop a new one.
12059                          */
12060                         err = propagate_liveness(env, &sl->state, cur);
12061
12062                         /* if previous state reached the exit with precision and
12063                          * current state is equivalent to it (except precsion marks)
12064                          * the precision needs to be propagated back in
12065                          * the current state.
12066                          */
12067                         err = err ? : push_jmp_history(env, cur);
12068                         err = err ? : propagate_precision(env, &sl->state);
12069                         if (err)
12070                                 return err;
12071                         return 1;
12072                 }
12073 miss:
12074                 /* when new state is not going to be added do not increase miss count.
12075                  * Otherwise several loop iterations will remove the state
12076                  * recorded earlier. The goal of these heuristics is to have
12077                  * states from some iterations of the loop (some in the beginning
12078                  * and some at the end) to help pruning.
12079                  */
12080                 if (add_new_state)
12081                         sl->miss_cnt++;
12082                 /* heuristic to determine whether this state is beneficial
12083                  * to keep checking from state equivalence point of view.
12084                  * Higher numbers increase max_states_per_insn and verification time,
12085                  * but do not meaningfully decrease insn_processed.
12086                  */
12087                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12088                         /* the state is unlikely to be useful. Remove it to
12089                          * speed up verification
12090                          */
12091                         *pprev = sl->next;
12092                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12093                                 u32 br = sl->state.branches;
12094
12095                                 WARN_ONCE(br,
12096                                           "BUG live_done but branches_to_explore %d\n",
12097                                           br);
12098                                 free_verifier_state(&sl->state, false);
12099                                 kfree(sl);
12100                                 env->peak_states--;
12101                         } else {
12102                                 /* cannot free this state, since parentage chain may
12103                                  * walk it later. Add it for free_list instead to
12104                                  * be freed at the end of verification
12105                                  */
12106                                 sl->next = env->free_list;
12107                                 env->free_list = sl;
12108                         }
12109                         sl = *pprev;
12110                         continue;
12111                 }
12112 next:
12113                 pprev = &sl->next;
12114                 sl = *pprev;
12115         }
12116
12117         if (env->max_states_per_insn < states_cnt)
12118                 env->max_states_per_insn = states_cnt;
12119
12120         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12121                 return push_jmp_history(env, cur);
12122
12123         if (!add_new_state)
12124                 return push_jmp_history(env, cur);
12125
12126         /* There were no equivalent states, remember the current one.
12127          * Technically the current state is not proven to be safe yet,
12128          * but it will either reach outer most bpf_exit (which means it's safe)
12129          * or it will be rejected. When there are no loops the verifier won't be
12130          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12131          * again on the way to bpf_exit.
12132          * When looping the sl->state.branches will be > 0 and this state
12133          * will not be considered for equivalence until branches == 0.
12134          */
12135         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12136         if (!new_sl)
12137                 return -ENOMEM;
12138         env->total_states++;
12139         env->peak_states++;
12140         env->prev_jmps_processed = env->jmps_processed;
12141         env->prev_insn_processed = env->insn_processed;
12142
12143         /* add new state to the head of linked list */
12144         new = &new_sl->state;
12145         err = copy_verifier_state(new, cur);
12146         if (err) {
12147                 free_verifier_state(new, false);
12148                 kfree(new_sl);
12149                 return err;
12150         }
12151         new->insn_idx = insn_idx;
12152         WARN_ONCE(new->branches != 1,
12153                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12154
12155         cur->parent = new;
12156         cur->first_insn_idx = insn_idx;
12157         clear_jmp_history(cur);
12158         new_sl->next = *explored_state(env, insn_idx);
12159         *explored_state(env, insn_idx) = new_sl;
12160         /* connect new state to parentage chain. Current frame needs all
12161          * registers connected. Only r6 - r9 of the callers are alive (pushed
12162          * to the stack implicitly by JITs) so in callers' frames connect just
12163          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12164          * the state of the call instruction (with WRITTEN set), and r0 comes
12165          * from callee with its full parentage chain, anyway.
12166          */
12167         /* clear write marks in current state: the writes we did are not writes
12168          * our child did, so they don't screen off its reads from us.
12169          * (There are no read marks in current state, because reads always mark
12170          * their parent and current state never has children yet.  Only
12171          * explored_states can get read marks.)
12172          */
12173         for (j = 0; j <= cur->curframe; j++) {
12174                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12175                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12176                 for (i = 0; i < BPF_REG_FP; i++)
12177                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12178         }
12179
12180         /* all stack frames are accessible from callee, clear them all */
12181         for (j = 0; j <= cur->curframe; j++) {
12182                 struct bpf_func_state *frame = cur->frame[j];
12183                 struct bpf_func_state *newframe = new->frame[j];
12184
12185                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12186                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12187                         frame->stack[i].spilled_ptr.parent =
12188                                                 &newframe->stack[i].spilled_ptr;
12189                 }
12190         }
12191         return 0;
12192 }
12193
12194 /* Return true if it's OK to have the same insn return a different type. */
12195 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12196 {
12197         switch (base_type(type)) {
12198         case PTR_TO_CTX:
12199         case PTR_TO_SOCKET:
12200         case PTR_TO_SOCK_COMMON:
12201         case PTR_TO_TCP_SOCK:
12202         case PTR_TO_XDP_SOCK:
12203         case PTR_TO_BTF_ID:
12204                 return false;
12205         default:
12206                 return true;
12207         }
12208 }
12209
12210 /* If an instruction was previously used with particular pointer types, then we
12211  * need to be careful to avoid cases such as the below, where it may be ok
12212  * for one branch accessing the pointer, but not ok for the other branch:
12213  *
12214  * R1 = sock_ptr
12215  * goto X;
12216  * ...
12217  * R1 = some_other_valid_ptr;
12218  * goto X;
12219  * ...
12220  * R2 = *(u32 *)(R1 + 0);
12221  */
12222 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12223 {
12224         return src != prev && (!reg_type_mismatch_ok(src) ||
12225                                !reg_type_mismatch_ok(prev));
12226 }
12227
12228 static int do_check(struct bpf_verifier_env *env)
12229 {
12230         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12231         struct bpf_verifier_state *state = env->cur_state;
12232         struct bpf_insn *insns = env->prog->insnsi;
12233         struct bpf_reg_state *regs;
12234         int insn_cnt = env->prog->len;
12235         bool do_print_state = false;
12236         int prev_insn_idx = -1;
12237
12238         for (;;) {
12239                 struct bpf_insn *insn;
12240                 u8 class;
12241                 int err;
12242
12243                 env->prev_insn_idx = prev_insn_idx;
12244                 if (env->insn_idx >= insn_cnt) {
12245                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
12246                                 env->insn_idx, insn_cnt);
12247                         return -EFAULT;
12248                 }
12249
12250                 insn = &insns[env->insn_idx];
12251                 class = BPF_CLASS(insn->code);
12252
12253                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12254                         verbose(env,
12255                                 "BPF program is too large. Processed %d insn\n",
12256                                 env->insn_processed);
12257                         return -E2BIG;
12258                 }
12259
12260                 err = is_state_visited(env, env->insn_idx);
12261                 if (err < 0)
12262                         return err;
12263                 if (err == 1) {
12264                         /* found equivalent state, can prune the search */
12265                         if (env->log.level & BPF_LOG_LEVEL) {
12266                                 if (do_print_state)
12267                                         verbose(env, "\nfrom %d to %d%s: safe\n",
12268                                                 env->prev_insn_idx, env->insn_idx,
12269                                                 env->cur_state->speculative ?
12270                                                 " (speculative execution)" : "");
12271                                 else
12272                                         verbose(env, "%d: safe\n", env->insn_idx);
12273                         }
12274                         goto process_bpf_exit;
12275                 }
12276
12277                 if (signal_pending(current))
12278                         return -EAGAIN;
12279
12280                 if (need_resched())
12281                         cond_resched();
12282
12283                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12284                         verbose(env, "\nfrom %d to %d%s:",
12285                                 env->prev_insn_idx, env->insn_idx,
12286                                 env->cur_state->speculative ?
12287                                 " (speculative execution)" : "");
12288                         print_verifier_state(env, state->frame[state->curframe], true);
12289                         do_print_state = false;
12290                 }
12291
12292                 if (env->log.level & BPF_LOG_LEVEL) {
12293                         const struct bpf_insn_cbs cbs = {
12294                                 .cb_call        = disasm_kfunc_name,
12295                                 .cb_print       = verbose,
12296                                 .private_data   = env,
12297                         };
12298
12299                         if (verifier_state_scratched(env))
12300                                 print_insn_state(env, state->frame[state->curframe]);
12301
12302                         verbose_linfo(env, env->insn_idx, "; ");
12303                         env->prev_log_len = env->log.len_used;
12304                         verbose(env, "%d: ", env->insn_idx);
12305                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12306                         env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12307                         env->prev_log_len = env->log.len_used;
12308                 }
12309
12310                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12311                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12312                                                            env->prev_insn_idx);
12313                         if (err)
12314                                 return err;
12315                 }
12316
12317                 regs = cur_regs(env);
12318                 sanitize_mark_insn_seen(env);
12319                 prev_insn_idx = env->insn_idx;
12320
12321                 if (class == BPF_ALU || class == BPF_ALU64) {
12322                         err = check_alu_op(env, insn);
12323                         if (err)
12324                                 return err;
12325
12326                 } else if (class == BPF_LDX) {
12327                         enum bpf_reg_type *prev_src_type, src_reg_type;
12328
12329                         /* check for reserved fields is already done */
12330
12331                         /* check src operand */
12332                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12333                         if (err)
12334                                 return err;
12335
12336                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12337                         if (err)
12338                                 return err;
12339
12340                         src_reg_type = regs[insn->src_reg].type;
12341
12342                         /* check that memory (src_reg + off) is readable,
12343                          * the state of dst_reg will be updated by this func
12344                          */
12345                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
12346                                                insn->off, BPF_SIZE(insn->code),
12347                                                BPF_READ, insn->dst_reg, false);
12348                         if (err)
12349                                 return err;
12350
12351                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12352
12353                         if (*prev_src_type == NOT_INIT) {
12354                                 /* saw a valid insn
12355                                  * dst_reg = *(u32 *)(src_reg + off)
12356                                  * save type to validate intersecting paths
12357                                  */
12358                                 *prev_src_type = src_reg_type;
12359
12360                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12361                                 /* ABuser program is trying to use the same insn
12362                                  * dst_reg = *(u32*) (src_reg + off)
12363                                  * with different pointer types:
12364                                  * src_reg == ctx in one branch and
12365                                  * src_reg == stack|map in some other branch.
12366                                  * Reject it.
12367                                  */
12368                                 verbose(env, "same insn cannot be used with different pointers\n");
12369                                 return -EINVAL;
12370                         }
12371
12372                 } else if (class == BPF_STX) {
12373                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
12374
12375                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12376                                 err = check_atomic(env, env->insn_idx, insn);
12377                                 if (err)
12378                                         return err;
12379                                 env->insn_idx++;
12380                                 continue;
12381                         }
12382
12383                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12384                                 verbose(env, "BPF_STX uses reserved fields\n");
12385                                 return -EINVAL;
12386                         }
12387
12388                         /* check src1 operand */
12389                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12390                         if (err)
12391                                 return err;
12392                         /* check src2 operand */
12393                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12394                         if (err)
12395                                 return err;
12396
12397                         dst_reg_type = regs[insn->dst_reg].type;
12398
12399                         /* check that memory (dst_reg + off) is writeable */
12400                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12401                                                insn->off, BPF_SIZE(insn->code),
12402                                                BPF_WRITE, insn->src_reg, false);
12403                         if (err)
12404                                 return err;
12405
12406                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12407
12408                         if (*prev_dst_type == NOT_INIT) {
12409                                 *prev_dst_type = dst_reg_type;
12410                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12411                                 verbose(env, "same insn cannot be used with different pointers\n");
12412                                 return -EINVAL;
12413                         }
12414
12415                 } else if (class == BPF_ST) {
12416                         if (BPF_MODE(insn->code) != BPF_MEM ||
12417                             insn->src_reg != BPF_REG_0) {
12418                                 verbose(env, "BPF_ST uses reserved fields\n");
12419                                 return -EINVAL;
12420                         }
12421                         /* check src operand */
12422                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12423                         if (err)
12424                                 return err;
12425
12426                         if (is_ctx_reg(env, insn->dst_reg)) {
12427                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12428                                         insn->dst_reg,
12429                                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12430                                 return -EACCES;
12431                         }
12432
12433                         /* check that memory (dst_reg + off) is writeable */
12434                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12435                                                insn->off, BPF_SIZE(insn->code),
12436                                                BPF_WRITE, -1, false);
12437                         if (err)
12438                                 return err;
12439
12440                 } else if (class == BPF_JMP || class == BPF_JMP32) {
12441                         u8 opcode = BPF_OP(insn->code);
12442
12443                         env->jmps_processed++;
12444                         if (opcode == BPF_CALL) {
12445                                 if (BPF_SRC(insn->code) != BPF_K ||
12446                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12447                                      && insn->off != 0) ||
12448                                     (insn->src_reg != BPF_REG_0 &&
12449                                      insn->src_reg != BPF_PSEUDO_CALL &&
12450                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12451                                     insn->dst_reg != BPF_REG_0 ||
12452                                     class == BPF_JMP32) {
12453                                         verbose(env, "BPF_CALL uses reserved fields\n");
12454                                         return -EINVAL;
12455                                 }
12456
12457                                 if (env->cur_state->active_spin_lock &&
12458                                     (insn->src_reg == BPF_PSEUDO_CALL ||
12459                                      insn->imm != BPF_FUNC_spin_unlock)) {
12460                                         verbose(env, "function calls are not allowed while holding a lock\n");
12461                                         return -EINVAL;
12462                                 }
12463                                 if (insn->src_reg == BPF_PSEUDO_CALL)
12464                                         err = check_func_call(env, insn, &env->insn_idx);
12465                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12466                                         err = check_kfunc_call(env, insn, &env->insn_idx);
12467                                 else
12468                                         err = check_helper_call(env, insn, &env->insn_idx);
12469                                 if (err)
12470                                         return err;
12471                         } else if (opcode == BPF_JA) {
12472                                 if (BPF_SRC(insn->code) != BPF_K ||
12473                                     insn->imm != 0 ||
12474                                     insn->src_reg != BPF_REG_0 ||
12475                                     insn->dst_reg != BPF_REG_0 ||
12476                                     class == BPF_JMP32) {
12477                                         verbose(env, "BPF_JA uses reserved fields\n");
12478                                         return -EINVAL;
12479                                 }
12480
12481                                 env->insn_idx += insn->off + 1;
12482                                 continue;
12483
12484                         } else if (opcode == BPF_EXIT) {
12485                                 if (BPF_SRC(insn->code) != BPF_K ||
12486                                     insn->imm != 0 ||
12487                                     insn->src_reg != BPF_REG_0 ||
12488                                     insn->dst_reg != BPF_REG_0 ||
12489                                     class == BPF_JMP32) {
12490                                         verbose(env, "BPF_EXIT uses reserved fields\n");
12491                                         return -EINVAL;
12492                                 }
12493
12494                                 if (env->cur_state->active_spin_lock) {
12495                                         verbose(env, "bpf_spin_unlock is missing\n");
12496                                         return -EINVAL;
12497                                 }
12498
12499                                 /* We must do check_reference_leak here before
12500                                  * prepare_func_exit to handle the case when
12501                                  * state->curframe > 0, it may be a callback
12502                                  * function, for which reference_state must
12503                                  * match caller reference state when it exits.
12504                                  */
12505                                 err = check_reference_leak(env);
12506                                 if (err)
12507                                         return err;
12508
12509                                 if (state->curframe) {
12510                                         /* exit from nested function */
12511                                         err = prepare_func_exit(env, &env->insn_idx);
12512                                         if (err)
12513                                                 return err;
12514                                         do_print_state = true;
12515                                         continue;
12516                                 }
12517
12518                                 err = check_return_code(env);
12519                                 if (err)
12520                                         return err;
12521 process_bpf_exit:
12522                                 mark_verifier_state_scratched(env);
12523                                 update_branch_counts(env, env->cur_state);
12524                                 err = pop_stack(env, &prev_insn_idx,
12525                                                 &env->insn_idx, pop_log);
12526                                 if (err < 0) {
12527                                         if (err != -ENOENT)
12528                                                 return err;
12529                                         break;
12530                                 } else {
12531                                         do_print_state = true;
12532                                         continue;
12533                                 }
12534                         } else {
12535                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12536                                 if (err)
12537                                         return err;
12538                         }
12539                 } else if (class == BPF_LD) {
12540                         u8 mode = BPF_MODE(insn->code);
12541
12542                         if (mode == BPF_ABS || mode == BPF_IND) {
12543                                 err = check_ld_abs(env, insn);
12544                                 if (err)
12545                                         return err;
12546
12547                         } else if (mode == BPF_IMM) {
12548                                 err = check_ld_imm(env, insn);
12549                                 if (err)
12550                                         return err;
12551
12552                                 env->insn_idx++;
12553                                 sanitize_mark_insn_seen(env);
12554                         } else {
12555                                 verbose(env, "invalid BPF_LD mode\n");
12556                                 return -EINVAL;
12557                         }
12558                 } else {
12559                         verbose(env, "unknown insn class %d\n", class);
12560                         return -EINVAL;
12561                 }
12562
12563                 env->insn_idx++;
12564         }
12565
12566         return 0;
12567 }
12568
12569 static int find_btf_percpu_datasec(struct btf *btf)
12570 {
12571         const struct btf_type *t;
12572         const char *tname;
12573         int i, n;
12574
12575         /*
12576          * Both vmlinux and module each have their own ".data..percpu"
12577          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12578          * types to look at only module's own BTF types.
12579          */
12580         n = btf_nr_types(btf);
12581         if (btf_is_module(btf))
12582                 i = btf_nr_types(btf_vmlinux);
12583         else
12584                 i = 1;
12585
12586         for(; i < n; i++) {
12587                 t = btf_type_by_id(btf, i);
12588                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12589                         continue;
12590
12591                 tname = btf_name_by_offset(btf, t->name_off);
12592                 if (!strcmp(tname, ".data..percpu"))
12593                         return i;
12594         }
12595
12596         return -ENOENT;
12597 }
12598
12599 /* replace pseudo btf_id with kernel symbol address */
12600 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12601                                struct bpf_insn *insn,
12602                                struct bpf_insn_aux_data *aux)
12603 {
12604         const struct btf_var_secinfo *vsi;
12605         const struct btf_type *datasec;
12606         struct btf_mod_pair *btf_mod;
12607         const struct btf_type *t;
12608         const char *sym_name;
12609         bool percpu = false;
12610         u32 type, id = insn->imm;
12611         struct btf *btf;
12612         s32 datasec_id;
12613         u64 addr;
12614         int i, btf_fd, err;
12615
12616         btf_fd = insn[1].imm;
12617         if (btf_fd) {
12618                 btf = btf_get_by_fd(btf_fd);
12619                 if (IS_ERR(btf)) {
12620                         verbose(env, "invalid module BTF object FD specified.\n");
12621                         return -EINVAL;
12622                 }
12623         } else {
12624                 if (!btf_vmlinux) {
12625                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12626                         return -EINVAL;
12627                 }
12628                 btf = btf_vmlinux;
12629                 btf_get(btf);
12630         }
12631
12632         t = btf_type_by_id(btf, id);
12633         if (!t) {
12634                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12635                 err = -ENOENT;
12636                 goto err_put;
12637         }
12638
12639         if (!btf_type_is_var(t)) {
12640                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12641                 err = -EINVAL;
12642                 goto err_put;
12643         }
12644
12645         sym_name = btf_name_by_offset(btf, t->name_off);
12646         addr = kallsyms_lookup_name(sym_name);
12647         if (!addr) {
12648                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12649                         sym_name);
12650                 err = -ENOENT;
12651                 goto err_put;
12652         }
12653
12654         datasec_id = find_btf_percpu_datasec(btf);
12655         if (datasec_id > 0) {
12656                 datasec = btf_type_by_id(btf, datasec_id);
12657                 for_each_vsi(i, datasec, vsi) {
12658                         if (vsi->type == id) {
12659                                 percpu = true;
12660                                 break;
12661                         }
12662                 }
12663         }
12664
12665         insn[0].imm = (u32)addr;
12666         insn[1].imm = addr >> 32;
12667
12668         type = t->type;
12669         t = btf_type_skip_modifiers(btf, type, NULL);
12670         if (percpu) {
12671                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12672                 aux->btf_var.btf = btf;
12673                 aux->btf_var.btf_id = type;
12674         } else if (!btf_type_is_struct(t)) {
12675                 const struct btf_type *ret;
12676                 const char *tname;
12677                 u32 tsize;
12678
12679                 /* resolve the type size of ksym. */
12680                 ret = btf_resolve_size(btf, t, &tsize);
12681                 if (IS_ERR(ret)) {
12682                         tname = btf_name_by_offset(btf, t->name_off);
12683                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12684                                 tname, PTR_ERR(ret));
12685                         err = -EINVAL;
12686                         goto err_put;
12687                 }
12688                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12689                 aux->btf_var.mem_size = tsize;
12690         } else {
12691                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12692                 aux->btf_var.btf = btf;
12693                 aux->btf_var.btf_id = type;
12694         }
12695
12696         /* check whether we recorded this BTF (and maybe module) already */
12697         for (i = 0; i < env->used_btf_cnt; i++) {
12698                 if (env->used_btfs[i].btf == btf) {
12699                         btf_put(btf);
12700                         return 0;
12701                 }
12702         }
12703
12704         if (env->used_btf_cnt >= MAX_USED_BTFS) {
12705                 err = -E2BIG;
12706                 goto err_put;
12707         }
12708
12709         btf_mod = &env->used_btfs[env->used_btf_cnt];
12710         btf_mod->btf = btf;
12711         btf_mod->module = NULL;
12712
12713         /* if we reference variables from kernel module, bump its refcount */
12714         if (btf_is_module(btf)) {
12715                 btf_mod->module = btf_try_get_module(btf);
12716                 if (!btf_mod->module) {
12717                         err = -ENXIO;
12718                         goto err_put;
12719                 }
12720         }
12721
12722         env->used_btf_cnt++;
12723
12724         return 0;
12725 err_put:
12726         btf_put(btf);
12727         return err;
12728 }
12729
12730 static bool is_tracing_prog_type(enum bpf_prog_type type)
12731 {
12732         switch (type) {
12733         case BPF_PROG_TYPE_KPROBE:
12734         case BPF_PROG_TYPE_TRACEPOINT:
12735         case BPF_PROG_TYPE_PERF_EVENT:
12736         case BPF_PROG_TYPE_RAW_TRACEPOINT:
12737         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12738                 return true;
12739         default:
12740                 return false;
12741         }
12742 }
12743
12744 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12745                                         struct bpf_map *map,
12746                                         struct bpf_prog *prog)
12747
12748 {
12749         enum bpf_prog_type prog_type = resolve_prog_type(prog);
12750
12751         if (map_value_has_spin_lock(map)) {
12752                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12753                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12754                         return -EINVAL;
12755                 }
12756
12757                 if (is_tracing_prog_type(prog_type)) {
12758                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12759                         return -EINVAL;
12760                 }
12761
12762                 if (prog->aux->sleepable) {
12763                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12764                         return -EINVAL;
12765                 }
12766         }
12767
12768         if (map_value_has_timer(map)) {
12769                 if (is_tracing_prog_type(prog_type)) {
12770                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
12771                         return -EINVAL;
12772                 }
12773         }
12774
12775         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12776             !bpf_offload_prog_map_match(prog, map)) {
12777                 verbose(env, "offload device mismatch between prog and map\n");
12778                 return -EINVAL;
12779         }
12780
12781         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12782                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12783                 return -EINVAL;
12784         }
12785
12786         if (prog->aux->sleepable)
12787                 switch (map->map_type) {
12788                 case BPF_MAP_TYPE_HASH:
12789                 case BPF_MAP_TYPE_LRU_HASH:
12790                 case BPF_MAP_TYPE_ARRAY:
12791                 case BPF_MAP_TYPE_PERCPU_HASH:
12792                 case BPF_MAP_TYPE_PERCPU_ARRAY:
12793                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12794                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12795                 case BPF_MAP_TYPE_HASH_OF_MAPS:
12796                 case BPF_MAP_TYPE_RINGBUF:
12797                 case BPF_MAP_TYPE_USER_RINGBUF:
12798                 case BPF_MAP_TYPE_INODE_STORAGE:
12799                 case BPF_MAP_TYPE_SK_STORAGE:
12800                 case BPF_MAP_TYPE_TASK_STORAGE:
12801                         break;
12802                 default:
12803                         verbose(env,
12804                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12805                         return -EINVAL;
12806                 }
12807
12808         return 0;
12809 }
12810
12811 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12812 {
12813         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12814                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12815 }
12816
12817 /* find and rewrite pseudo imm in ld_imm64 instructions:
12818  *
12819  * 1. if it accesses map FD, replace it with actual map pointer.
12820  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12821  *
12822  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12823  */
12824 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12825 {
12826         struct bpf_insn *insn = env->prog->insnsi;
12827         int insn_cnt = env->prog->len;
12828         int i, j, err;
12829
12830         err = bpf_prog_calc_tag(env->prog);
12831         if (err)
12832                 return err;
12833
12834         for (i = 0; i < insn_cnt; i++, insn++) {
12835                 if (BPF_CLASS(insn->code) == BPF_LDX &&
12836                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12837                         verbose(env, "BPF_LDX uses reserved fields\n");
12838                         return -EINVAL;
12839                 }
12840
12841                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12842                         struct bpf_insn_aux_data *aux;
12843                         struct bpf_map *map;
12844                         struct fd f;
12845                         u64 addr;
12846                         u32 fd;
12847
12848                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
12849                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12850                             insn[1].off != 0) {
12851                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
12852                                 return -EINVAL;
12853                         }
12854
12855                         if (insn[0].src_reg == 0)
12856                                 /* valid generic load 64-bit imm */
12857                                 goto next_insn;
12858
12859                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12860                                 aux = &env->insn_aux_data[i];
12861                                 err = check_pseudo_btf_id(env, insn, aux);
12862                                 if (err)
12863                                         return err;
12864                                 goto next_insn;
12865                         }
12866
12867                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12868                                 aux = &env->insn_aux_data[i];
12869                                 aux->ptr_type = PTR_TO_FUNC;
12870                                 goto next_insn;
12871                         }
12872
12873                         /* In final convert_pseudo_ld_imm64() step, this is
12874                          * converted into regular 64-bit imm load insn.
12875                          */
12876                         switch (insn[0].src_reg) {
12877                         case BPF_PSEUDO_MAP_VALUE:
12878                         case BPF_PSEUDO_MAP_IDX_VALUE:
12879                                 break;
12880                         case BPF_PSEUDO_MAP_FD:
12881                         case BPF_PSEUDO_MAP_IDX:
12882                                 if (insn[1].imm == 0)
12883                                         break;
12884                                 fallthrough;
12885                         default:
12886                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12887                                 return -EINVAL;
12888                         }
12889
12890                         switch (insn[0].src_reg) {
12891                         case BPF_PSEUDO_MAP_IDX_VALUE:
12892                         case BPF_PSEUDO_MAP_IDX:
12893                                 if (bpfptr_is_null(env->fd_array)) {
12894                                         verbose(env, "fd_idx without fd_array is invalid\n");
12895                                         return -EPROTO;
12896                                 }
12897                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12898                                                             insn[0].imm * sizeof(fd),
12899                                                             sizeof(fd)))
12900                                         return -EFAULT;
12901                                 break;
12902                         default:
12903                                 fd = insn[0].imm;
12904                                 break;
12905                         }
12906
12907                         f = fdget(fd);
12908                         map = __bpf_map_get(f);
12909                         if (IS_ERR(map)) {
12910                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12911                                         insn[0].imm);
12912                                 return PTR_ERR(map);
12913                         }
12914
12915                         err = check_map_prog_compatibility(env, map, env->prog);
12916                         if (err) {
12917                                 fdput(f);
12918                                 return err;
12919                         }
12920
12921                         aux = &env->insn_aux_data[i];
12922                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12923                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12924                                 addr = (unsigned long)map;
12925                         } else {
12926                                 u32 off = insn[1].imm;
12927
12928                                 if (off >= BPF_MAX_VAR_OFF) {
12929                                         verbose(env, "direct value offset of %u is not allowed\n", off);
12930                                         fdput(f);
12931                                         return -EINVAL;
12932                                 }
12933
12934                                 if (!map->ops->map_direct_value_addr) {
12935                                         verbose(env, "no direct value access support for this map type\n");
12936                                         fdput(f);
12937                                         return -EINVAL;
12938                                 }
12939
12940                                 err = map->ops->map_direct_value_addr(map, &addr, off);
12941                                 if (err) {
12942                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12943                                                 map->value_size, off);
12944                                         fdput(f);
12945                                         return err;
12946                                 }
12947
12948                                 aux->map_off = off;
12949                                 addr += off;
12950                         }
12951
12952                         insn[0].imm = (u32)addr;
12953                         insn[1].imm = addr >> 32;
12954
12955                         /* check whether we recorded this map already */
12956                         for (j = 0; j < env->used_map_cnt; j++) {
12957                                 if (env->used_maps[j] == map) {
12958                                         aux->map_index = j;
12959                                         fdput(f);
12960                                         goto next_insn;
12961                                 }
12962                         }
12963
12964                         if (env->used_map_cnt >= MAX_USED_MAPS) {
12965                                 fdput(f);
12966                                 return -E2BIG;
12967                         }
12968
12969                         /* hold the map. If the program is rejected by verifier,
12970                          * the map will be released by release_maps() or it
12971                          * will be used by the valid program until it's unloaded
12972                          * and all maps are released in free_used_maps()
12973                          */
12974                         bpf_map_inc(map);
12975
12976                         aux->map_index = env->used_map_cnt;
12977                         env->used_maps[env->used_map_cnt++] = map;
12978
12979                         if (bpf_map_is_cgroup_storage(map) &&
12980                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
12981                                 verbose(env, "only one cgroup storage of each type is allowed\n");
12982                                 fdput(f);
12983                                 return -EBUSY;
12984                         }
12985
12986                         fdput(f);
12987 next_insn:
12988                         insn++;
12989                         i++;
12990                         continue;
12991                 }
12992
12993                 /* Basic sanity check before we invest more work here. */
12994                 if (!bpf_opcode_in_insntable(insn->code)) {
12995                         verbose(env, "unknown opcode %02x\n", insn->code);
12996                         return -EINVAL;
12997                 }
12998         }
12999
13000         /* now all pseudo BPF_LD_IMM64 instructions load valid
13001          * 'struct bpf_map *' into a register instead of user map_fd.
13002          * These pointers will be used later by verifier to validate map access.
13003          */
13004         return 0;
13005 }
13006
13007 /* drop refcnt of maps used by the rejected program */
13008 static void release_maps(struct bpf_verifier_env *env)
13009 {
13010         __bpf_free_used_maps(env->prog->aux, env->used_maps,
13011                              env->used_map_cnt);
13012 }
13013
13014 /* drop refcnt of maps used by the rejected program */
13015 static void release_btfs(struct bpf_verifier_env *env)
13016 {
13017         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
13018                              env->used_btf_cnt);
13019 }
13020
13021 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
13022 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
13023 {
13024         struct bpf_insn *insn = env->prog->insnsi;
13025         int insn_cnt = env->prog->len;
13026         int i;
13027
13028         for (i = 0; i < insn_cnt; i++, insn++) {
13029                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
13030                         continue;
13031                 if (insn->src_reg == BPF_PSEUDO_FUNC)
13032                         continue;
13033                 insn->src_reg = 0;
13034         }
13035 }
13036
13037 /* single env->prog->insni[off] instruction was replaced with the range
13038  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
13039  * [0, off) and [off, end) to new locations, so the patched range stays zero
13040  */
13041 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
13042                                  struct bpf_insn_aux_data *new_data,
13043                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
13044 {
13045         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
13046         struct bpf_insn *insn = new_prog->insnsi;
13047         u32 old_seen = old_data[off].seen;
13048         u32 prog_len;
13049         int i;
13050
13051         /* aux info at OFF always needs adjustment, no matter fast path
13052          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13053          * original insn at old prog.
13054          */
13055         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13056
13057         if (cnt == 1)
13058                 return;
13059         prog_len = new_prog->len;
13060
13061         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13062         memcpy(new_data + off + cnt - 1, old_data + off,
13063                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13064         for (i = off; i < off + cnt - 1; i++) {
13065                 /* Expand insni[off]'s seen count to the patched range. */
13066                 new_data[i].seen = old_seen;
13067                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
13068         }
13069         env->insn_aux_data = new_data;
13070         vfree(old_data);
13071 }
13072
13073 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13074 {
13075         int i;
13076
13077         if (len == 1)
13078                 return;
13079         /* NOTE: fake 'exit' subprog should be updated as well. */
13080         for (i = 0; i <= env->subprog_cnt; i++) {
13081                 if (env->subprog_info[i].start <= off)
13082                         continue;
13083                 env->subprog_info[i].start += len - 1;
13084         }
13085 }
13086
13087 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13088 {
13089         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13090         int i, sz = prog->aux->size_poke_tab;
13091         struct bpf_jit_poke_descriptor *desc;
13092
13093         for (i = 0; i < sz; i++) {
13094                 desc = &tab[i];
13095                 if (desc->insn_idx <= off)
13096                         continue;
13097                 desc->insn_idx += len - 1;
13098         }
13099 }
13100
13101 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13102                                             const struct bpf_insn *patch, u32 len)
13103 {
13104         struct bpf_prog *new_prog;
13105         struct bpf_insn_aux_data *new_data = NULL;
13106
13107         if (len > 1) {
13108                 new_data = vzalloc(array_size(env->prog->len + len - 1,
13109                                               sizeof(struct bpf_insn_aux_data)));
13110                 if (!new_data)
13111                         return NULL;
13112         }
13113
13114         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13115         if (IS_ERR(new_prog)) {
13116                 if (PTR_ERR(new_prog) == -ERANGE)
13117                         verbose(env,
13118                                 "insn %d cannot be patched due to 16-bit range\n",
13119                                 env->insn_aux_data[off].orig_idx);
13120                 vfree(new_data);
13121                 return NULL;
13122         }
13123         adjust_insn_aux_data(env, new_data, new_prog, off, len);
13124         adjust_subprog_starts(env, off, len);
13125         adjust_poke_descs(new_prog, off, len);
13126         return new_prog;
13127 }
13128
13129 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13130                                               u32 off, u32 cnt)
13131 {
13132         int i, j;
13133
13134         /* find first prog starting at or after off (first to remove) */
13135         for (i = 0; i < env->subprog_cnt; i++)
13136                 if (env->subprog_info[i].start >= off)
13137                         break;
13138         /* find first prog starting at or after off + cnt (first to stay) */
13139         for (j = i; j < env->subprog_cnt; j++)
13140                 if (env->subprog_info[j].start >= off + cnt)
13141                         break;
13142         /* if j doesn't start exactly at off + cnt, we are just removing
13143          * the front of previous prog
13144          */
13145         if (env->subprog_info[j].start != off + cnt)
13146                 j--;
13147
13148         if (j > i) {
13149                 struct bpf_prog_aux *aux = env->prog->aux;
13150                 int move;
13151
13152                 /* move fake 'exit' subprog as well */
13153                 move = env->subprog_cnt + 1 - j;
13154
13155                 memmove(env->subprog_info + i,
13156                         env->subprog_info + j,
13157                         sizeof(*env->subprog_info) * move);
13158                 env->subprog_cnt -= j - i;
13159
13160                 /* remove func_info */
13161                 if (aux->func_info) {
13162                         move = aux->func_info_cnt - j;
13163
13164                         memmove(aux->func_info + i,
13165                                 aux->func_info + j,
13166                                 sizeof(*aux->func_info) * move);
13167                         aux->func_info_cnt -= j - i;
13168                         /* func_info->insn_off is set after all code rewrites,
13169                          * in adjust_btf_func() - no need to adjust
13170                          */
13171                 }
13172         } else {
13173                 /* convert i from "first prog to remove" to "first to adjust" */
13174                 if (env->subprog_info[i].start == off)
13175                         i++;
13176         }
13177
13178         /* update fake 'exit' subprog as well */
13179         for (; i <= env->subprog_cnt; i++)
13180                 env->subprog_info[i].start -= cnt;
13181
13182         return 0;
13183 }
13184
13185 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13186                                       u32 cnt)
13187 {
13188         struct bpf_prog *prog = env->prog;
13189         u32 i, l_off, l_cnt, nr_linfo;
13190         struct bpf_line_info *linfo;
13191
13192         nr_linfo = prog->aux->nr_linfo;
13193         if (!nr_linfo)
13194                 return 0;
13195
13196         linfo = prog->aux->linfo;
13197
13198         /* find first line info to remove, count lines to be removed */
13199         for (i = 0; i < nr_linfo; i++)
13200                 if (linfo[i].insn_off >= off)
13201                         break;
13202
13203         l_off = i;
13204         l_cnt = 0;
13205         for (; i < nr_linfo; i++)
13206                 if (linfo[i].insn_off < off + cnt)
13207                         l_cnt++;
13208                 else
13209                         break;
13210
13211         /* First live insn doesn't match first live linfo, it needs to "inherit"
13212          * last removed linfo.  prog is already modified, so prog->len == off
13213          * means no live instructions after (tail of the program was removed).
13214          */
13215         if (prog->len != off && l_cnt &&
13216             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13217                 l_cnt--;
13218                 linfo[--i].insn_off = off + cnt;
13219         }
13220
13221         /* remove the line info which refer to the removed instructions */
13222         if (l_cnt) {
13223                 memmove(linfo + l_off, linfo + i,
13224                         sizeof(*linfo) * (nr_linfo - i));
13225
13226                 prog->aux->nr_linfo -= l_cnt;
13227                 nr_linfo = prog->aux->nr_linfo;
13228         }
13229
13230         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13231         for (i = l_off; i < nr_linfo; i++)
13232                 linfo[i].insn_off -= cnt;
13233
13234         /* fix up all subprogs (incl. 'exit') which start >= off */
13235         for (i = 0; i <= env->subprog_cnt; i++)
13236                 if (env->subprog_info[i].linfo_idx > l_off) {
13237                         /* program may have started in the removed region but
13238                          * may not be fully removed
13239                          */
13240                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13241                                 env->subprog_info[i].linfo_idx -= l_cnt;
13242                         else
13243                                 env->subprog_info[i].linfo_idx = l_off;
13244                 }
13245
13246         return 0;
13247 }
13248
13249 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13250 {
13251         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13252         unsigned int orig_prog_len = env->prog->len;
13253         int err;
13254
13255         if (bpf_prog_is_dev_bound(env->prog->aux))
13256                 bpf_prog_offload_remove_insns(env, off, cnt);
13257
13258         err = bpf_remove_insns(env->prog, off, cnt);
13259         if (err)
13260                 return err;
13261
13262         err = adjust_subprog_starts_after_remove(env, off, cnt);
13263         if (err)
13264                 return err;
13265
13266         err = bpf_adj_linfo_after_remove(env, off, cnt);
13267         if (err)
13268                 return err;
13269
13270         memmove(aux_data + off, aux_data + off + cnt,
13271                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13272
13273         return 0;
13274 }
13275
13276 /* The verifier does more data flow analysis than llvm and will not
13277  * explore branches that are dead at run time. Malicious programs can
13278  * have dead code too. Therefore replace all dead at-run-time code
13279  * with 'ja -1'.
13280  *
13281  * Just nops are not optimal, e.g. if they would sit at the end of the
13282  * program and through another bug we would manage to jump there, then
13283  * we'd execute beyond program memory otherwise. Returning exception
13284  * code also wouldn't work since we can have subprogs where the dead
13285  * code could be located.
13286  */
13287 static void sanitize_dead_code(struct bpf_verifier_env *env)
13288 {
13289         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13290         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13291         struct bpf_insn *insn = env->prog->insnsi;
13292         const int insn_cnt = env->prog->len;
13293         int i;
13294
13295         for (i = 0; i < insn_cnt; i++) {
13296                 if (aux_data[i].seen)
13297                         continue;
13298                 memcpy(insn + i, &trap, sizeof(trap));
13299                 aux_data[i].zext_dst = false;
13300         }
13301 }
13302
13303 static bool insn_is_cond_jump(u8 code)
13304 {
13305         u8 op;
13306
13307         if (BPF_CLASS(code) == BPF_JMP32)
13308                 return true;
13309
13310         if (BPF_CLASS(code) != BPF_JMP)
13311                 return false;
13312
13313         op = BPF_OP(code);
13314         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13315 }
13316
13317 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13318 {
13319         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13320         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13321         struct bpf_insn *insn = env->prog->insnsi;
13322         const int insn_cnt = env->prog->len;
13323         int i;
13324
13325         for (i = 0; i < insn_cnt; i++, insn++) {
13326                 if (!insn_is_cond_jump(insn->code))
13327                         continue;
13328
13329                 if (!aux_data[i + 1].seen)
13330                         ja.off = insn->off;
13331                 else if (!aux_data[i + 1 + insn->off].seen)
13332                         ja.off = 0;
13333                 else
13334                         continue;
13335
13336                 if (bpf_prog_is_dev_bound(env->prog->aux))
13337                         bpf_prog_offload_replace_insn(env, i, &ja);
13338
13339                 memcpy(insn, &ja, sizeof(ja));
13340         }
13341 }
13342
13343 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13344 {
13345         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13346         int insn_cnt = env->prog->len;
13347         int i, err;
13348
13349         for (i = 0; i < insn_cnt; i++) {
13350                 int j;
13351
13352                 j = 0;
13353                 while (i + j < insn_cnt && !aux_data[i + j].seen)
13354                         j++;
13355                 if (!j)
13356                         continue;
13357
13358                 err = verifier_remove_insns(env, i, j);
13359                 if (err)
13360                         return err;
13361                 insn_cnt = env->prog->len;
13362         }
13363
13364         return 0;
13365 }
13366
13367 static int opt_remove_nops(struct bpf_verifier_env *env)
13368 {
13369         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13370         struct bpf_insn *insn = env->prog->insnsi;
13371         int insn_cnt = env->prog->len;
13372         int i, err;
13373
13374         for (i = 0; i < insn_cnt; i++) {
13375                 if (memcmp(&insn[i], &ja, sizeof(ja)))
13376                         continue;
13377
13378                 err = verifier_remove_insns(env, i, 1);
13379                 if (err)
13380                         return err;
13381                 insn_cnt--;
13382                 i--;
13383         }
13384
13385         return 0;
13386 }
13387
13388 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13389                                          const union bpf_attr *attr)
13390 {
13391         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13392         struct bpf_insn_aux_data *aux = env->insn_aux_data;
13393         int i, patch_len, delta = 0, len = env->prog->len;
13394         struct bpf_insn *insns = env->prog->insnsi;
13395         struct bpf_prog *new_prog;
13396         bool rnd_hi32;
13397
13398         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13399         zext_patch[1] = BPF_ZEXT_REG(0);
13400         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13401         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13402         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13403         for (i = 0; i < len; i++) {
13404                 int adj_idx = i + delta;
13405                 struct bpf_insn insn;
13406                 int load_reg;
13407
13408                 insn = insns[adj_idx];
13409                 load_reg = insn_def_regno(&insn);
13410                 if (!aux[adj_idx].zext_dst) {
13411                         u8 code, class;
13412                         u32 imm_rnd;
13413
13414                         if (!rnd_hi32)
13415                                 continue;
13416
13417                         code = insn.code;
13418                         class = BPF_CLASS(code);
13419                         if (load_reg == -1)
13420                                 continue;
13421
13422                         /* NOTE: arg "reg" (the fourth one) is only used for
13423                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
13424                          *       here.
13425                          */
13426                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13427                                 if (class == BPF_LD &&
13428                                     BPF_MODE(code) == BPF_IMM)
13429                                         i++;
13430                                 continue;
13431                         }
13432
13433                         /* ctx load could be transformed into wider load. */
13434                         if (class == BPF_LDX &&
13435                             aux[adj_idx].ptr_type == PTR_TO_CTX)
13436                                 continue;
13437
13438                         imm_rnd = get_random_u32();
13439                         rnd_hi32_patch[0] = insn;
13440                         rnd_hi32_patch[1].imm = imm_rnd;
13441                         rnd_hi32_patch[3].dst_reg = load_reg;
13442                         patch = rnd_hi32_patch;
13443                         patch_len = 4;
13444                         goto apply_patch_buffer;
13445                 }
13446
13447                 /* Add in an zero-extend instruction if a) the JIT has requested
13448                  * it or b) it's a CMPXCHG.
13449                  *
13450                  * The latter is because: BPF_CMPXCHG always loads a value into
13451                  * R0, therefore always zero-extends. However some archs'
13452                  * equivalent instruction only does this load when the
13453                  * comparison is successful. This detail of CMPXCHG is
13454                  * orthogonal to the general zero-extension behaviour of the
13455                  * CPU, so it's treated independently of bpf_jit_needs_zext.
13456                  */
13457                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13458                         continue;
13459
13460                 /* Zero-extension is done by the caller. */
13461                 if (bpf_pseudo_kfunc_call(&insn))
13462                         continue;
13463
13464                 if (WARN_ON(load_reg == -1)) {
13465                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13466                         return -EFAULT;
13467                 }
13468
13469                 zext_patch[0] = insn;
13470                 zext_patch[1].dst_reg = load_reg;
13471                 zext_patch[1].src_reg = load_reg;
13472                 patch = zext_patch;
13473                 patch_len = 2;
13474 apply_patch_buffer:
13475                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13476                 if (!new_prog)
13477                         return -ENOMEM;
13478                 env->prog = new_prog;
13479                 insns = new_prog->insnsi;
13480                 aux = env->insn_aux_data;
13481                 delta += patch_len - 1;
13482         }
13483
13484         return 0;
13485 }
13486
13487 /* convert load instructions that access fields of a context type into a
13488  * sequence of instructions that access fields of the underlying structure:
13489  *     struct __sk_buff    -> struct sk_buff
13490  *     struct bpf_sock_ops -> struct sock
13491  */
13492 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13493 {
13494         const struct bpf_verifier_ops *ops = env->ops;
13495         int i, cnt, size, ctx_field_size, delta = 0;
13496         const int insn_cnt = env->prog->len;
13497         struct bpf_insn insn_buf[16], *insn;
13498         u32 target_size, size_default, off;
13499         struct bpf_prog *new_prog;
13500         enum bpf_access_type type;
13501         bool is_narrower_load;
13502
13503         if (ops->gen_prologue || env->seen_direct_write) {
13504                 if (!ops->gen_prologue) {
13505                         verbose(env, "bpf verifier is misconfigured\n");
13506                         return -EINVAL;
13507                 }
13508                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13509                                         env->prog);
13510                 if (cnt >= ARRAY_SIZE(insn_buf)) {
13511                         verbose(env, "bpf verifier is misconfigured\n");
13512                         return -EINVAL;
13513                 } else if (cnt) {
13514                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13515                         if (!new_prog)
13516                                 return -ENOMEM;
13517
13518                         env->prog = new_prog;
13519                         delta += cnt - 1;
13520                 }
13521         }
13522
13523         if (bpf_prog_is_dev_bound(env->prog->aux))
13524                 return 0;
13525
13526         insn = env->prog->insnsi + delta;
13527
13528         for (i = 0; i < insn_cnt; i++, insn++) {
13529                 bpf_convert_ctx_access_t convert_ctx_access;
13530                 bool ctx_access;
13531
13532                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13533                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13534                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13535                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13536                         type = BPF_READ;
13537                         ctx_access = true;
13538                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13539                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13540                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13541                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13542                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13543                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13544                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13545                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13546                         type = BPF_WRITE;
13547                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13548                 } else {
13549                         continue;
13550                 }
13551
13552                 if (type == BPF_WRITE &&
13553                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
13554                         struct bpf_insn patch[] = {
13555                                 *insn,
13556                                 BPF_ST_NOSPEC(),
13557                         };
13558
13559                         cnt = ARRAY_SIZE(patch);
13560                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13561                         if (!new_prog)
13562                                 return -ENOMEM;
13563
13564                         delta    += cnt - 1;
13565                         env->prog = new_prog;
13566                         insn      = new_prog->insnsi + i + delta;
13567                         continue;
13568                 }
13569
13570                 if (!ctx_access)
13571                         continue;
13572
13573                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13574                 case PTR_TO_CTX:
13575                         if (!ops->convert_ctx_access)
13576                                 continue;
13577                         convert_ctx_access = ops->convert_ctx_access;
13578                         break;
13579                 case PTR_TO_SOCKET:
13580                 case PTR_TO_SOCK_COMMON:
13581                         convert_ctx_access = bpf_sock_convert_ctx_access;
13582                         break;
13583                 case PTR_TO_TCP_SOCK:
13584                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13585                         break;
13586                 case PTR_TO_XDP_SOCK:
13587                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13588                         break;
13589                 case PTR_TO_BTF_ID:
13590                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13591                         if (type == BPF_READ) {
13592                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
13593                                         BPF_SIZE((insn)->code);
13594                                 env->prog->aux->num_exentries++;
13595                         }
13596                         continue;
13597                 default:
13598                         continue;
13599                 }
13600
13601                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13602                 size = BPF_LDST_BYTES(insn);
13603
13604                 /* If the read access is a narrower load of the field,
13605                  * convert to a 4/8-byte load, to minimum program type specific
13606                  * convert_ctx_access changes. If conversion is successful,
13607                  * we will apply proper mask to the result.
13608                  */
13609                 is_narrower_load = size < ctx_field_size;
13610                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13611                 off = insn->off;
13612                 if (is_narrower_load) {
13613                         u8 size_code;
13614
13615                         if (type == BPF_WRITE) {
13616                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13617                                 return -EINVAL;
13618                         }
13619
13620                         size_code = BPF_H;
13621                         if (ctx_field_size == 4)
13622                                 size_code = BPF_W;
13623                         else if (ctx_field_size == 8)
13624                                 size_code = BPF_DW;
13625
13626                         insn->off = off & ~(size_default - 1);
13627                         insn->code = BPF_LDX | BPF_MEM | size_code;
13628                 }
13629
13630                 target_size = 0;
13631                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13632                                          &target_size);
13633                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13634                     (ctx_field_size && !target_size)) {
13635                         verbose(env, "bpf verifier is misconfigured\n");
13636                         return -EINVAL;
13637                 }
13638
13639                 if (is_narrower_load && size < target_size) {
13640                         u8 shift = bpf_ctx_narrow_access_offset(
13641                                 off, size, size_default) * 8;
13642                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13643                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13644                                 return -EINVAL;
13645                         }
13646                         if (ctx_field_size <= 4) {
13647                                 if (shift)
13648                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13649                                                                         insn->dst_reg,
13650                                                                         shift);
13651                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13652                                                                 (1 << size * 8) - 1);
13653                         } else {
13654                                 if (shift)
13655                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13656                                                                         insn->dst_reg,
13657                                                                         shift);
13658                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13659                                                                 (1ULL << size * 8) - 1);
13660                         }
13661                 }
13662
13663                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13664                 if (!new_prog)
13665                         return -ENOMEM;
13666
13667                 delta += cnt - 1;
13668
13669                 /* keep walking new program and skip insns we just inserted */
13670                 env->prog = new_prog;
13671                 insn      = new_prog->insnsi + i + delta;
13672         }
13673
13674         return 0;
13675 }
13676
13677 static int jit_subprogs(struct bpf_verifier_env *env)
13678 {
13679         struct bpf_prog *prog = env->prog, **func, *tmp;
13680         int i, j, subprog_start, subprog_end = 0, len, subprog;
13681         struct bpf_map *map_ptr;
13682         struct bpf_insn *insn;
13683         void *old_bpf_func;
13684         int err, num_exentries;
13685
13686         if (env->subprog_cnt <= 1)
13687                 return 0;
13688
13689         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13690                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13691                         continue;
13692
13693                 /* Upon error here we cannot fall back to interpreter but
13694                  * need a hard reject of the program. Thus -EFAULT is
13695                  * propagated in any case.
13696                  */
13697                 subprog = find_subprog(env, i + insn->imm + 1);
13698                 if (subprog < 0) {
13699                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13700                                   i + insn->imm + 1);
13701                         return -EFAULT;
13702                 }
13703                 /* temporarily remember subprog id inside insn instead of
13704                  * aux_data, since next loop will split up all insns into funcs
13705                  */
13706                 insn->off = subprog;
13707                 /* remember original imm in case JIT fails and fallback
13708                  * to interpreter will be needed
13709                  */
13710                 env->insn_aux_data[i].call_imm = insn->imm;
13711                 /* point imm to __bpf_call_base+1 from JITs point of view */
13712                 insn->imm = 1;
13713                 if (bpf_pseudo_func(insn))
13714                         /* jit (e.g. x86_64) may emit fewer instructions
13715                          * if it learns a u32 imm is the same as a u64 imm.
13716                          * Force a non zero here.
13717                          */
13718                         insn[1].imm = 1;
13719         }
13720
13721         err = bpf_prog_alloc_jited_linfo(prog);
13722         if (err)
13723                 goto out_undo_insn;
13724
13725         err = -ENOMEM;
13726         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13727         if (!func)
13728                 goto out_undo_insn;
13729
13730         for (i = 0; i < env->subprog_cnt; i++) {
13731                 subprog_start = subprog_end;
13732                 subprog_end = env->subprog_info[i + 1].start;
13733
13734                 len = subprog_end - subprog_start;
13735                 /* bpf_prog_run() doesn't call subprogs directly,
13736                  * hence main prog stats include the runtime of subprogs.
13737                  * subprogs don't have IDs and not reachable via prog_get_next_id
13738                  * func[i]->stats will never be accessed and stays NULL
13739                  */
13740                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13741                 if (!func[i])
13742                         goto out_free;
13743                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13744                        len * sizeof(struct bpf_insn));
13745                 func[i]->type = prog->type;
13746                 func[i]->len = len;
13747                 if (bpf_prog_calc_tag(func[i]))
13748                         goto out_free;
13749                 func[i]->is_func = 1;
13750                 func[i]->aux->func_idx = i;
13751                 /* Below members will be freed only at prog->aux */
13752                 func[i]->aux->btf = prog->aux->btf;
13753                 func[i]->aux->func_info = prog->aux->func_info;
13754                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13755                 func[i]->aux->poke_tab = prog->aux->poke_tab;
13756                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13757
13758                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13759                         struct bpf_jit_poke_descriptor *poke;
13760
13761                         poke = &prog->aux->poke_tab[j];
13762                         if (poke->insn_idx < subprog_end &&
13763                             poke->insn_idx >= subprog_start)
13764                                 poke->aux = func[i]->aux;
13765                 }
13766
13767                 func[i]->aux->name[0] = 'F';
13768                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13769                 func[i]->jit_requested = 1;
13770                 func[i]->blinding_requested = prog->blinding_requested;
13771                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13772                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13773                 func[i]->aux->linfo = prog->aux->linfo;
13774                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13775                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13776                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13777                 num_exentries = 0;
13778                 insn = func[i]->insnsi;
13779                 for (j = 0; j < func[i]->len; j++, insn++) {
13780                         if (BPF_CLASS(insn->code) == BPF_LDX &&
13781                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
13782                                 num_exentries++;
13783                 }
13784                 func[i]->aux->num_exentries = num_exentries;
13785                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13786                 func[i] = bpf_int_jit_compile(func[i]);
13787                 if (!func[i]->jited) {
13788                         err = -ENOTSUPP;
13789                         goto out_free;
13790                 }
13791                 cond_resched();
13792         }
13793
13794         /* at this point all bpf functions were successfully JITed
13795          * now populate all bpf_calls with correct addresses and
13796          * run last pass of JIT
13797          */
13798         for (i = 0; i < env->subprog_cnt; i++) {
13799                 insn = func[i]->insnsi;
13800                 for (j = 0; j < func[i]->len; j++, insn++) {
13801                         if (bpf_pseudo_func(insn)) {
13802                                 subprog = insn->off;
13803                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13804                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13805                                 continue;
13806                         }
13807                         if (!bpf_pseudo_call(insn))
13808                                 continue;
13809                         subprog = insn->off;
13810                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13811                 }
13812
13813                 /* we use the aux data to keep a list of the start addresses
13814                  * of the JITed images for each function in the program
13815                  *
13816                  * for some architectures, such as powerpc64, the imm field
13817                  * might not be large enough to hold the offset of the start
13818                  * address of the callee's JITed image from __bpf_call_base
13819                  *
13820                  * in such cases, we can lookup the start address of a callee
13821                  * by using its subprog id, available from the off field of
13822                  * the call instruction, as an index for this list
13823                  */
13824                 func[i]->aux->func = func;
13825                 func[i]->aux->func_cnt = env->subprog_cnt;
13826         }
13827         for (i = 0; i < env->subprog_cnt; i++) {
13828                 old_bpf_func = func[i]->bpf_func;
13829                 tmp = bpf_int_jit_compile(func[i]);
13830                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13831                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13832                         err = -ENOTSUPP;
13833                         goto out_free;
13834                 }
13835                 cond_resched();
13836         }
13837
13838         /* finally lock prog and jit images for all functions and
13839          * populate kallsysm. Begin at the first subprogram, since
13840          * bpf_prog_load will add the kallsyms for the main program.
13841          */
13842         for (i = 1; i < env->subprog_cnt; i++) {
13843                 bpf_prog_lock_ro(func[i]);
13844                 bpf_prog_kallsyms_add(func[i]);
13845         }
13846
13847         /* Last step: make now unused interpreter insns from main
13848          * prog consistent for later dump requests, so they can
13849          * later look the same as if they were interpreted only.
13850          */
13851         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13852                 if (bpf_pseudo_func(insn)) {
13853                         insn[0].imm = env->insn_aux_data[i].call_imm;
13854                         insn[1].imm = insn->off;
13855                         insn->off = 0;
13856                         continue;
13857                 }
13858                 if (!bpf_pseudo_call(insn))
13859                         continue;
13860                 insn->off = env->insn_aux_data[i].call_imm;
13861                 subprog = find_subprog(env, i + insn->off + 1);
13862                 insn->imm = subprog;
13863         }
13864
13865         prog->jited = 1;
13866         prog->bpf_func = func[0]->bpf_func;
13867         prog->jited_len = func[0]->jited_len;
13868         prog->aux->extable = func[0]->aux->extable;
13869         prog->aux->num_exentries = func[0]->aux->num_exentries;
13870         prog->aux->func = func;
13871         prog->aux->func_cnt = env->subprog_cnt;
13872         bpf_prog_jit_attempt_done(prog);
13873         return 0;
13874 out_free:
13875         /* We failed JIT'ing, so at this point we need to unregister poke
13876          * descriptors from subprogs, so that kernel is not attempting to
13877          * patch it anymore as we're freeing the subprog JIT memory.
13878          */
13879         for (i = 0; i < prog->aux->size_poke_tab; i++) {
13880                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13881                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13882         }
13883         /* At this point we're guaranteed that poke descriptors are not
13884          * live anymore. We can just unlink its descriptor table as it's
13885          * released with the main prog.
13886          */
13887         for (i = 0; i < env->subprog_cnt; i++) {
13888                 if (!func[i])
13889                         continue;
13890                 func[i]->aux->poke_tab = NULL;
13891                 bpf_jit_free(func[i]);
13892         }
13893         kfree(func);
13894 out_undo_insn:
13895         /* cleanup main prog to be interpreted */
13896         prog->jit_requested = 0;
13897         prog->blinding_requested = 0;
13898         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13899                 if (!bpf_pseudo_call(insn))
13900                         continue;
13901                 insn->off = 0;
13902                 insn->imm = env->insn_aux_data[i].call_imm;
13903         }
13904         bpf_prog_jit_attempt_done(prog);
13905         return err;
13906 }
13907
13908 static int fixup_call_args(struct bpf_verifier_env *env)
13909 {
13910 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13911         struct bpf_prog *prog = env->prog;
13912         struct bpf_insn *insn = prog->insnsi;
13913         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13914         int i, depth;
13915 #endif
13916         int err = 0;
13917
13918         if (env->prog->jit_requested &&
13919             !bpf_prog_is_dev_bound(env->prog->aux)) {
13920                 err = jit_subprogs(env);
13921                 if (err == 0)
13922                         return 0;
13923                 if (err == -EFAULT)
13924                         return err;
13925         }
13926 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13927         if (has_kfunc_call) {
13928                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13929                 return -EINVAL;
13930         }
13931         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13932                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13933                  * have to be rejected, since interpreter doesn't support them yet.
13934                  */
13935                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13936                 return -EINVAL;
13937         }
13938         for (i = 0; i < prog->len; i++, insn++) {
13939                 if (bpf_pseudo_func(insn)) {
13940                         /* When JIT fails the progs with callback calls
13941                          * have to be rejected, since interpreter doesn't support them yet.
13942                          */
13943                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
13944                         return -EINVAL;
13945                 }
13946
13947                 if (!bpf_pseudo_call(insn))
13948                         continue;
13949                 depth = get_callee_stack_depth(env, insn, i);
13950                 if (depth < 0)
13951                         return depth;
13952                 bpf_patch_call_args(insn, depth);
13953         }
13954         err = 0;
13955 #endif
13956         return err;
13957 }
13958
13959 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13960                             struct bpf_insn *insn)
13961 {
13962         const struct bpf_kfunc_desc *desc;
13963
13964         if (!insn->imm) {
13965                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13966                 return -EINVAL;
13967         }
13968
13969         /* insn->imm has the btf func_id. Replace it with
13970          * an address (relative to __bpf_base_call).
13971          */
13972         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13973         if (!desc) {
13974                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13975                         insn->imm);
13976                 return -EFAULT;
13977         }
13978
13979         insn->imm = desc->imm;
13980
13981         return 0;
13982 }
13983
13984 /* Do various post-verification rewrites in a single program pass.
13985  * These rewrites simplify JIT and interpreter implementations.
13986  */
13987 static int do_misc_fixups(struct bpf_verifier_env *env)
13988 {
13989         struct bpf_prog *prog = env->prog;
13990         enum bpf_attach_type eatype = prog->expected_attach_type;
13991         enum bpf_prog_type prog_type = resolve_prog_type(prog);
13992         struct bpf_insn *insn = prog->insnsi;
13993         const struct bpf_func_proto *fn;
13994         const int insn_cnt = prog->len;
13995         const struct bpf_map_ops *ops;
13996         struct bpf_insn_aux_data *aux;
13997         struct bpf_insn insn_buf[16];
13998         struct bpf_prog *new_prog;
13999         struct bpf_map *map_ptr;
14000         int i, ret, cnt, delta = 0;
14001
14002         for (i = 0; i < insn_cnt; i++, insn++) {
14003                 /* Make divide-by-zero exceptions impossible. */
14004                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
14005                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
14006                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
14007                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
14008                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
14009                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
14010                         struct bpf_insn *patchlet;
14011                         struct bpf_insn chk_and_div[] = {
14012                                 /* [R,W]x div 0 -> 0 */
14013                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14014                                              BPF_JNE | BPF_K, insn->src_reg,
14015                                              0, 2, 0),
14016                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
14017                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14018                                 *insn,
14019                         };
14020                         struct bpf_insn chk_and_mod[] = {
14021                                 /* [R,W]x mod 0 -> [R,W]x */
14022                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14023                                              BPF_JEQ | BPF_K, insn->src_reg,
14024                                              0, 1 + (is64 ? 0 : 1), 0),
14025                                 *insn,
14026                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14027                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
14028                         };
14029
14030                         patchlet = isdiv ? chk_and_div : chk_and_mod;
14031                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
14032                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
14033
14034                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
14035                         if (!new_prog)
14036                                 return -ENOMEM;
14037
14038                         delta    += cnt - 1;
14039                         env->prog = prog = new_prog;
14040                         insn      = new_prog->insnsi + i + delta;
14041                         continue;
14042                 }
14043
14044                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
14045                 if (BPF_CLASS(insn->code) == BPF_LD &&
14046                     (BPF_MODE(insn->code) == BPF_ABS ||
14047                      BPF_MODE(insn->code) == BPF_IND)) {
14048                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
14049                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14050                                 verbose(env, "bpf verifier is misconfigured\n");
14051                                 return -EINVAL;
14052                         }
14053
14054                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14055                         if (!new_prog)
14056                                 return -ENOMEM;
14057
14058                         delta    += cnt - 1;
14059                         env->prog = prog = new_prog;
14060                         insn      = new_prog->insnsi + i + delta;
14061                         continue;
14062                 }
14063
14064                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
14065                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14066                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14067                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14068                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14069                         struct bpf_insn *patch = &insn_buf[0];
14070                         bool issrc, isneg, isimm;
14071                         u32 off_reg;
14072
14073                         aux = &env->insn_aux_data[i + delta];
14074                         if (!aux->alu_state ||
14075                             aux->alu_state == BPF_ALU_NON_POINTER)
14076                                 continue;
14077
14078                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14079                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14080                                 BPF_ALU_SANITIZE_SRC;
14081                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14082
14083                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
14084                         if (isimm) {
14085                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14086                         } else {
14087                                 if (isneg)
14088                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14089                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14090                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14091                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14092                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14093                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14094                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14095                         }
14096                         if (!issrc)
14097                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14098                         insn->src_reg = BPF_REG_AX;
14099                         if (isneg)
14100                                 insn->code = insn->code == code_add ?
14101                                              code_sub : code_add;
14102                         *patch++ = *insn;
14103                         if (issrc && isneg && !isimm)
14104                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14105                         cnt = patch - insn_buf;
14106
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->code != (BPF_JMP | BPF_CALL))
14118                         continue;
14119                 if (insn->src_reg == BPF_PSEUDO_CALL)
14120                         continue;
14121                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14122                         ret = fixup_kfunc_call(env, insn);
14123                         if (ret)
14124                                 return ret;
14125                         continue;
14126                 }
14127
14128                 if (insn->imm == BPF_FUNC_get_route_realm)
14129                         prog->dst_needed = 1;
14130                 if (insn->imm == BPF_FUNC_get_prandom_u32)
14131                         bpf_user_rnd_init_once();
14132                 if (insn->imm == BPF_FUNC_override_return)
14133                         prog->kprobe_override = 1;
14134                 if (insn->imm == BPF_FUNC_tail_call) {
14135                         /* If we tail call into other programs, we
14136                          * cannot make any assumptions since they can
14137                          * be replaced dynamically during runtime in
14138                          * the program array.
14139                          */
14140                         prog->cb_access = 1;
14141                         if (!allow_tail_call_in_subprogs(env))
14142                                 prog->aux->stack_depth = MAX_BPF_STACK;
14143                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14144
14145                         /* mark bpf_tail_call as different opcode to avoid
14146                          * conditional branch in the interpreter for every normal
14147                          * call and to prevent accidental JITing by JIT compiler
14148                          * that doesn't support bpf_tail_call yet
14149                          */
14150                         insn->imm = 0;
14151                         insn->code = BPF_JMP | BPF_TAIL_CALL;
14152
14153                         aux = &env->insn_aux_data[i + delta];
14154                         if (env->bpf_capable && !prog->blinding_requested &&
14155                             prog->jit_requested &&
14156                             !bpf_map_key_poisoned(aux) &&
14157                             !bpf_map_ptr_poisoned(aux) &&
14158                             !bpf_map_ptr_unpriv(aux)) {
14159                                 struct bpf_jit_poke_descriptor desc = {
14160                                         .reason = BPF_POKE_REASON_TAIL_CALL,
14161                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14162                                         .tail_call.key = bpf_map_key_immediate(aux),
14163                                         .insn_idx = i + delta,
14164                                 };
14165
14166                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14167                                 if (ret < 0) {
14168                                         verbose(env, "adding tail call poke descriptor failed\n");
14169                                         return ret;
14170                                 }
14171
14172                                 insn->imm = ret + 1;
14173                                 continue;
14174                         }
14175
14176                         if (!bpf_map_ptr_unpriv(aux))
14177                                 continue;
14178
14179                         /* instead of changing every JIT dealing with tail_call
14180                          * emit two extra insns:
14181                          * if (index >= max_entries) goto out;
14182                          * index &= array->index_mask;
14183                          * to avoid out-of-bounds cpu speculation
14184                          */
14185                         if (bpf_map_ptr_poisoned(aux)) {
14186                                 verbose(env, "tail_call abusing map_ptr\n");
14187                                 return -EINVAL;
14188                         }
14189
14190                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14191                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14192                                                   map_ptr->max_entries, 2);
14193                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14194                                                     container_of(map_ptr,
14195                                                                  struct bpf_array,
14196                                                                  map)->index_mask);
14197                         insn_buf[2] = *insn;
14198                         cnt = 3;
14199                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14200                         if (!new_prog)
14201                                 return -ENOMEM;
14202
14203                         delta    += cnt - 1;
14204                         env->prog = prog = new_prog;
14205                         insn      = new_prog->insnsi + i + delta;
14206                         continue;
14207                 }
14208
14209                 if (insn->imm == BPF_FUNC_timer_set_callback) {
14210                         /* The verifier will process callback_fn as many times as necessary
14211                          * with different maps and the register states prepared by
14212                          * set_timer_callback_state will be accurate.
14213                          *
14214                          * The following use case is valid:
14215                          *   map1 is shared by prog1, prog2, prog3.
14216                          *   prog1 calls bpf_timer_init for some map1 elements
14217                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
14218                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
14219                          *   prog3 calls bpf_timer_start for some map1 elements.
14220                          *     Those that were not both bpf_timer_init-ed and
14221                          *     bpf_timer_set_callback-ed will return -EINVAL.
14222                          */
14223                         struct bpf_insn ld_addrs[2] = {
14224                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14225                         };
14226
14227                         insn_buf[0] = ld_addrs[0];
14228                         insn_buf[1] = ld_addrs[1];
14229                         insn_buf[2] = *insn;
14230                         cnt = 3;
14231
14232                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14233                         if (!new_prog)
14234                                 return -ENOMEM;
14235
14236                         delta    += cnt - 1;
14237                         env->prog = prog = new_prog;
14238                         insn      = new_prog->insnsi + i + delta;
14239                         goto patch_call_imm;
14240                 }
14241
14242                 if (insn->imm == BPF_FUNC_task_storage_get ||
14243                     insn->imm == BPF_FUNC_sk_storage_get ||
14244                     insn->imm == BPF_FUNC_inode_storage_get) {
14245                         if (env->prog->aux->sleepable)
14246                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14247                         else
14248                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14249                         insn_buf[1] = *insn;
14250                         cnt = 2;
14251
14252                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14253                         if (!new_prog)
14254                                 return -ENOMEM;
14255
14256                         delta += cnt - 1;
14257                         env->prog = prog = new_prog;
14258                         insn = new_prog->insnsi + i + delta;
14259                         goto patch_call_imm;
14260                 }
14261
14262                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14263                  * and other inlining handlers are currently limited to 64 bit
14264                  * only.
14265                  */
14266                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14267                     (insn->imm == BPF_FUNC_map_lookup_elem ||
14268                      insn->imm == BPF_FUNC_map_update_elem ||
14269                      insn->imm == BPF_FUNC_map_delete_elem ||
14270                      insn->imm == BPF_FUNC_map_push_elem   ||
14271                      insn->imm == BPF_FUNC_map_pop_elem    ||
14272                      insn->imm == BPF_FUNC_map_peek_elem   ||
14273                      insn->imm == BPF_FUNC_redirect_map    ||
14274                      insn->imm == BPF_FUNC_for_each_map_elem ||
14275                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14276                         aux = &env->insn_aux_data[i + delta];
14277                         if (bpf_map_ptr_poisoned(aux))
14278                                 goto patch_call_imm;
14279
14280                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14281                         ops = map_ptr->ops;
14282                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
14283                             ops->map_gen_lookup) {
14284                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14285                                 if (cnt == -EOPNOTSUPP)
14286                                         goto patch_map_ops_generic;
14287                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14288                                         verbose(env, "bpf verifier is misconfigured\n");
14289                                         return -EINVAL;
14290                                 }
14291
14292                                 new_prog = bpf_patch_insn_data(env, i + delta,
14293                                                                insn_buf, cnt);
14294                                 if (!new_prog)
14295                                         return -ENOMEM;
14296
14297                                 delta    += cnt - 1;
14298                                 env->prog = prog = new_prog;
14299                                 insn      = new_prog->insnsi + i + delta;
14300                                 continue;
14301                         }
14302
14303                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14304                                      (void *(*)(struct bpf_map *map, void *key))NULL));
14305                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14306                                      (int (*)(struct bpf_map *map, void *key))NULL));
14307                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14308                                      (int (*)(struct bpf_map *map, void *key, void *value,
14309                                               u64 flags))NULL));
14310                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14311                                      (int (*)(struct bpf_map *map, void *value,
14312                                               u64 flags))NULL));
14313                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14314                                      (int (*)(struct bpf_map *map, void *value))NULL));
14315                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14316                                      (int (*)(struct bpf_map *map, void *value))NULL));
14317                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
14318                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14319                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14320                                      (int (*)(struct bpf_map *map,
14321                                               bpf_callback_t callback_fn,
14322                                               void *callback_ctx,
14323                                               u64 flags))NULL));
14324                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14325                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14326
14327 patch_map_ops_generic:
14328                         switch (insn->imm) {
14329                         case BPF_FUNC_map_lookup_elem:
14330                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14331                                 continue;
14332                         case BPF_FUNC_map_update_elem:
14333                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14334                                 continue;
14335                         case BPF_FUNC_map_delete_elem:
14336                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14337                                 continue;
14338                         case BPF_FUNC_map_push_elem:
14339                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14340                                 continue;
14341                         case BPF_FUNC_map_pop_elem:
14342                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14343                                 continue;
14344                         case BPF_FUNC_map_peek_elem:
14345                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14346                                 continue;
14347                         case BPF_FUNC_redirect_map:
14348                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14349                                 continue;
14350                         case BPF_FUNC_for_each_map_elem:
14351                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14352                                 continue;
14353                         case BPF_FUNC_map_lookup_percpu_elem:
14354                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14355                                 continue;
14356                         }
14357
14358                         goto patch_call_imm;
14359                 }
14360
14361                 /* Implement bpf_jiffies64 inline. */
14362                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14363                     insn->imm == BPF_FUNC_jiffies64) {
14364                         struct bpf_insn ld_jiffies_addr[2] = {
14365                                 BPF_LD_IMM64(BPF_REG_0,
14366                                              (unsigned long)&jiffies),
14367                         };
14368
14369                         insn_buf[0] = ld_jiffies_addr[0];
14370                         insn_buf[1] = ld_jiffies_addr[1];
14371                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14372                                                   BPF_REG_0, 0);
14373                         cnt = 3;
14374
14375                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14376                                                        cnt);
14377                         if (!new_prog)
14378                                 return -ENOMEM;
14379
14380                         delta    += cnt - 1;
14381                         env->prog = prog = new_prog;
14382                         insn      = new_prog->insnsi + i + delta;
14383                         continue;
14384                 }
14385
14386                 /* Implement bpf_get_func_arg inline. */
14387                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14388                     insn->imm == BPF_FUNC_get_func_arg) {
14389                         /* Load nr_args from ctx - 8 */
14390                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14391                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14392                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14393                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14394                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14395                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14396                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14397                         insn_buf[7] = BPF_JMP_A(1);
14398                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14399                         cnt = 9;
14400
14401                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14402                         if (!new_prog)
14403                                 return -ENOMEM;
14404
14405                         delta    += cnt - 1;
14406                         env->prog = prog = new_prog;
14407                         insn      = new_prog->insnsi + i + delta;
14408                         continue;
14409                 }
14410
14411                 /* Implement bpf_get_func_ret inline. */
14412                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14413                     insn->imm == BPF_FUNC_get_func_ret) {
14414                         if (eatype == BPF_TRACE_FEXIT ||
14415                             eatype == BPF_MODIFY_RETURN) {
14416                                 /* Load nr_args from ctx - 8 */
14417                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14418                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14419                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14420                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14421                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14422                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14423                                 cnt = 6;
14424                         } else {
14425                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14426                                 cnt = 1;
14427                         }
14428
14429                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14430                         if (!new_prog)
14431                                 return -ENOMEM;
14432
14433                         delta    += cnt - 1;
14434                         env->prog = prog = new_prog;
14435                         insn      = new_prog->insnsi + i + delta;
14436                         continue;
14437                 }
14438
14439                 /* Implement get_func_arg_cnt inline. */
14440                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14441                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
14442                         /* Load nr_args from ctx - 8 */
14443                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14444
14445                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14446                         if (!new_prog)
14447                                 return -ENOMEM;
14448
14449                         env->prog = prog = new_prog;
14450                         insn      = new_prog->insnsi + i + delta;
14451                         continue;
14452                 }
14453
14454                 /* Implement bpf_get_func_ip inline. */
14455                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14456                     insn->imm == BPF_FUNC_get_func_ip) {
14457                         /* Load IP address from ctx - 16 */
14458                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14459
14460                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14461                         if (!new_prog)
14462                                 return -ENOMEM;
14463
14464                         env->prog = prog = new_prog;
14465                         insn      = new_prog->insnsi + i + delta;
14466                         continue;
14467                 }
14468
14469 patch_call_imm:
14470                 fn = env->ops->get_func_proto(insn->imm, env->prog);
14471                 /* all functions that have prototype and verifier allowed
14472                  * programs to call them, must be real in-kernel functions
14473                  */
14474                 if (!fn->func) {
14475                         verbose(env,
14476                                 "kernel subsystem misconfigured func %s#%d\n",
14477                                 func_id_name(insn->imm), insn->imm);
14478                         return -EFAULT;
14479                 }
14480                 insn->imm = fn->func - __bpf_call_base;
14481         }
14482
14483         /* Since poke tab is now finalized, publish aux to tracker. */
14484         for (i = 0; i < prog->aux->size_poke_tab; i++) {
14485                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14486                 if (!map_ptr->ops->map_poke_track ||
14487                     !map_ptr->ops->map_poke_untrack ||
14488                     !map_ptr->ops->map_poke_run) {
14489                         verbose(env, "bpf verifier is misconfigured\n");
14490                         return -EINVAL;
14491                 }
14492
14493                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14494                 if (ret < 0) {
14495                         verbose(env, "tracking tail call prog failed\n");
14496                         return ret;
14497                 }
14498         }
14499
14500         sort_kfunc_descs_by_imm(env->prog);
14501
14502         return 0;
14503 }
14504
14505 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14506                                         int position,
14507                                         s32 stack_base,
14508                                         u32 callback_subprogno,
14509                                         u32 *cnt)
14510 {
14511         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14512         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14513         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14514         int reg_loop_max = BPF_REG_6;
14515         int reg_loop_cnt = BPF_REG_7;
14516         int reg_loop_ctx = BPF_REG_8;
14517
14518         struct bpf_prog *new_prog;
14519         u32 callback_start;
14520         u32 call_insn_offset;
14521         s32 callback_offset;
14522
14523         /* This represents an inlined version of bpf_iter.c:bpf_loop,
14524          * be careful to modify this code in sync.
14525          */
14526         struct bpf_insn insn_buf[] = {
14527                 /* Return error and jump to the end of the patch if
14528                  * expected number of iterations is too big.
14529                  */
14530                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14531                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14532                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14533                 /* spill R6, R7, R8 to use these as loop vars */
14534                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14535                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14536                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14537                 /* initialize loop vars */
14538                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14539                 BPF_MOV32_IMM(reg_loop_cnt, 0),
14540                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14541                 /* loop header,
14542                  * if reg_loop_cnt >= reg_loop_max skip the loop body
14543                  */
14544                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14545                 /* callback call,
14546                  * correct callback offset would be set after patching
14547                  */
14548                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14549                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14550                 BPF_CALL_REL(0),
14551                 /* increment loop counter */
14552                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14553                 /* jump to loop header if callback returned 0 */
14554                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14555                 /* return value of bpf_loop,
14556                  * set R0 to the number of iterations
14557                  */
14558                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14559                 /* restore original values of R6, R7, R8 */
14560                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14561                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14562                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14563         };
14564
14565         *cnt = ARRAY_SIZE(insn_buf);
14566         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14567         if (!new_prog)
14568                 return new_prog;
14569
14570         /* callback start is known only after patching */
14571         callback_start = env->subprog_info[callback_subprogno].start;
14572         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14573         call_insn_offset = position + 12;
14574         callback_offset = callback_start - call_insn_offset - 1;
14575         new_prog->insnsi[call_insn_offset].imm = callback_offset;
14576
14577         return new_prog;
14578 }
14579
14580 static bool is_bpf_loop_call(struct bpf_insn *insn)
14581 {
14582         return insn->code == (BPF_JMP | BPF_CALL) &&
14583                 insn->src_reg == 0 &&
14584                 insn->imm == BPF_FUNC_loop;
14585 }
14586
14587 /* For all sub-programs in the program (including main) check
14588  * insn_aux_data to see if there are bpf_loop calls that require
14589  * inlining. If such calls are found the calls are replaced with a
14590  * sequence of instructions produced by `inline_bpf_loop` function and
14591  * subprog stack_depth is increased by the size of 3 registers.
14592  * This stack space is used to spill values of the R6, R7, R8.  These
14593  * registers are used to store the loop bound, counter and context
14594  * variables.
14595  */
14596 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14597 {
14598         struct bpf_subprog_info *subprogs = env->subprog_info;
14599         int i, cur_subprog = 0, cnt, delta = 0;
14600         struct bpf_insn *insn = env->prog->insnsi;
14601         int insn_cnt = env->prog->len;
14602         u16 stack_depth = subprogs[cur_subprog].stack_depth;
14603         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14604         u16 stack_depth_extra = 0;
14605
14606         for (i = 0; i < insn_cnt; i++, insn++) {
14607                 struct bpf_loop_inline_state *inline_state =
14608                         &env->insn_aux_data[i + delta].loop_inline_state;
14609
14610                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14611                         struct bpf_prog *new_prog;
14612
14613                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14614                         new_prog = inline_bpf_loop(env,
14615                                                    i + delta,
14616                                                    -(stack_depth + stack_depth_extra),
14617                                                    inline_state->callback_subprogno,
14618                                                    &cnt);
14619                         if (!new_prog)
14620                                 return -ENOMEM;
14621
14622                         delta     += cnt - 1;
14623                         env->prog  = new_prog;
14624                         insn       = new_prog->insnsi + i + delta;
14625                 }
14626
14627                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14628                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
14629                         cur_subprog++;
14630                         stack_depth = subprogs[cur_subprog].stack_depth;
14631                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14632                         stack_depth_extra = 0;
14633                 }
14634         }
14635
14636         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14637
14638         return 0;
14639 }
14640
14641 static void free_states(struct bpf_verifier_env *env)
14642 {
14643         struct bpf_verifier_state_list *sl, *sln;
14644         int i;
14645
14646         sl = env->free_list;
14647         while (sl) {
14648                 sln = sl->next;
14649                 free_verifier_state(&sl->state, false);
14650                 kfree(sl);
14651                 sl = sln;
14652         }
14653         env->free_list = NULL;
14654
14655         if (!env->explored_states)
14656                 return;
14657
14658         for (i = 0; i < state_htab_size(env); i++) {
14659                 sl = env->explored_states[i];
14660
14661                 while (sl) {
14662                         sln = sl->next;
14663                         free_verifier_state(&sl->state, false);
14664                         kfree(sl);
14665                         sl = sln;
14666                 }
14667                 env->explored_states[i] = NULL;
14668         }
14669 }
14670
14671 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14672 {
14673         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14674         struct bpf_verifier_state *state;
14675         struct bpf_reg_state *regs;
14676         int ret, i;
14677
14678         env->prev_linfo = NULL;
14679         env->pass_cnt++;
14680
14681         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14682         if (!state)
14683                 return -ENOMEM;
14684         state->curframe = 0;
14685         state->speculative = false;
14686         state->branches = 1;
14687         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14688         if (!state->frame[0]) {
14689                 kfree(state);
14690                 return -ENOMEM;
14691         }
14692         env->cur_state = state;
14693         init_func_state(env, state->frame[0],
14694                         BPF_MAIN_FUNC /* callsite */,
14695                         0 /* frameno */,
14696                         subprog);
14697
14698         regs = state->frame[state->curframe]->regs;
14699         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14700                 ret = btf_prepare_func_args(env, subprog, regs);
14701                 if (ret)
14702                         goto out;
14703                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14704                         if (regs[i].type == PTR_TO_CTX)
14705                                 mark_reg_known_zero(env, regs, i);
14706                         else if (regs[i].type == SCALAR_VALUE)
14707                                 mark_reg_unknown(env, regs, i);
14708                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
14709                                 const u32 mem_size = regs[i].mem_size;
14710
14711                                 mark_reg_known_zero(env, regs, i);
14712                                 regs[i].mem_size = mem_size;
14713                                 regs[i].id = ++env->id_gen;
14714                         }
14715                 }
14716         } else {
14717                 /* 1st arg to a function */
14718                 regs[BPF_REG_1].type = PTR_TO_CTX;
14719                 mark_reg_known_zero(env, regs, BPF_REG_1);
14720                 ret = btf_check_subprog_arg_match(env, subprog, regs);
14721                 if (ret == -EFAULT)
14722                         /* unlikely verifier bug. abort.
14723                          * ret == 0 and ret < 0 are sadly acceptable for
14724                          * main() function due to backward compatibility.
14725                          * Like socket filter program may be written as:
14726                          * int bpf_prog(struct pt_regs *ctx)
14727                          * and never dereference that ctx in the program.
14728                          * 'struct pt_regs' is a type mismatch for socket
14729                          * filter that should be using 'struct __sk_buff'.
14730                          */
14731                         goto out;
14732         }
14733
14734         ret = do_check(env);
14735 out:
14736         /* check for NULL is necessary, since cur_state can be freed inside
14737          * do_check() under memory pressure.
14738          */
14739         if (env->cur_state) {
14740                 free_verifier_state(env->cur_state, true);
14741                 env->cur_state = NULL;
14742         }
14743         while (!pop_stack(env, NULL, NULL, false));
14744         if (!ret && pop_log)
14745                 bpf_vlog_reset(&env->log, 0);
14746         free_states(env);
14747         return ret;
14748 }
14749
14750 /* Verify all global functions in a BPF program one by one based on their BTF.
14751  * All global functions must pass verification. Otherwise the whole program is rejected.
14752  * Consider:
14753  * int bar(int);
14754  * int foo(int f)
14755  * {
14756  *    return bar(f);
14757  * }
14758  * int bar(int b)
14759  * {
14760  *    ...
14761  * }
14762  * foo() will be verified first for R1=any_scalar_value. During verification it
14763  * will be assumed that bar() already verified successfully and call to bar()
14764  * from foo() will be checked for type match only. Later bar() will be verified
14765  * independently to check that it's safe for R1=any_scalar_value.
14766  */
14767 static int do_check_subprogs(struct bpf_verifier_env *env)
14768 {
14769         struct bpf_prog_aux *aux = env->prog->aux;
14770         int i, ret;
14771
14772         if (!aux->func_info)
14773                 return 0;
14774
14775         for (i = 1; i < env->subprog_cnt; i++) {
14776                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14777                         continue;
14778                 env->insn_idx = env->subprog_info[i].start;
14779                 WARN_ON_ONCE(env->insn_idx == 0);
14780                 ret = do_check_common(env, i);
14781                 if (ret) {
14782                         return ret;
14783                 } else if (env->log.level & BPF_LOG_LEVEL) {
14784                         verbose(env,
14785                                 "Func#%d is safe for any args that match its prototype\n",
14786                                 i);
14787                 }
14788         }
14789         return 0;
14790 }
14791
14792 static int do_check_main(struct bpf_verifier_env *env)
14793 {
14794         int ret;
14795
14796         env->insn_idx = 0;
14797         ret = do_check_common(env, 0);
14798         if (!ret)
14799                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14800         return ret;
14801 }
14802
14803
14804 static void print_verification_stats(struct bpf_verifier_env *env)
14805 {
14806         int i;
14807
14808         if (env->log.level & BPF_LOG_STATS) {
14809                 verbose(env, "verification time %lld usec\n",
14810                         div_u64(env->verification_time, 1000));
14811                 verbose(env, "stack depth ");
14812                 for (i = 0; i < env->subprog_cnt; i++) {
14813                         u32 depth = env->subprog_info[i].stack_depth;
14814
14815                         verbose(env, "%d", depth);
14816                         if (i + 1 < env->subprog_cnt)
14817                                 verbose(env, "+");
14818                 }
14819                 verbose(env, "\n");
14820         }
14821         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14822                 "total_states %d peak_states %d mark_read %d\n",
14823                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14824                 env->max_states_per_insn, env->total_states,
14825                 env->peak_states, env->longest_mark_read_walk);
14826 }
14827
14828 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14829 {
14830         const struct btf_type *t, *func_proto;
14831         const struct bpf_struct_ops *st_ops;
14832         const struct btf_member *member;
14833         struct bpf_prog *prog = env->prog;
14834         u32 btf_id, member_idx;
14835         const char *mname;
14836
14837         if (!prog->gpl_compatible) {
14838                 verbose(env, "struct ops programs must have a GPL compatible license\n");
14839                 return -EINVAL;
14840         }
14841
14842         btf_id = prog->aux->attach_btf_id;
14843         st_ops = bpf_struct_ops_find(btf_id);
14844         if (!st_ops) {
14845                 verbose(env, "attach_btf_id %u is not a supported struct\n",
14846                         btf_id);
14847                 return -ENOTSUPP;
14848         }
14849
14850         t = st_ops->type;
14851         member_idx = prog->expected_attach_type;
14852         if (member_idx >= btf_type_vlen(t)) {
14853                 verbose(env, "attach to invalid member idx %u of struct %s\n",
14854                         member_idx, st_ops->name);
14855                 return -EINVAL;
14856         }
14857
14858         member = &btf_type_member(t)[member_idx];
14859         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14860         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14861                                                NULL);
14862         if (!func_proto) {
14863                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14864                         mname, member_idx, st_ops->name);
14865                 return -EINVAL;
14866         }
14867
14868         if (st_ops->check_member) {
14869                 int err = st_ops->check_member(t, member);
14870
14871                 if (err) {
14872                         verbose(env, "attach to unsupported member %s of struct %s\n",
14873                                 mname, st_ops->name);
14874                         return err;
14875                 }
14876         }
14877
14878         prog->aux->attach_func_proto = func_proto;
14879         prog->aux->attach_func_name = mname;
14880         env->ops = st_ops->verifier_ops;
14881
14882         return 0;
14883 }
14884 #define SECURITY_PREFIX "security_"
14885
14886 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14887 {
14888         if (within_error_injection_list(addr) ||
14889             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14890                 return 0;
14891
14892         return -EINVAL;
14893 }
14894
14895 /* list of non-sleepable functions that are otherwise on
14896  * ALLOW_ERROR_INJECTION list
14897  */
14898 BTF_SET_START(btf_non_sleepable_error_inject)
14899 /* Three functions below can be called from sleepable and non-sleepable context.
14900  * Assume non-sleepable from bpf safety point of view.
14901  */
14902 BTF_ID(func, __filemap_add_folio)
14903 BTF_ID(func, should_fail_alloc_page)
14904 BTF_ID(func, should_failslab)
14905 BTF_SET_END(btf_non_sleepable_error_inject)
14906
14907 static int check_non_sleepable_error_inject(u32 btf_id)
14908 {
14909         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14910 }
14911
14912 int bpf_check_attach_target(struct bpf_verifier_log *log,
14913                             const struct bpf_prog *prog,
14914                             const struct bpf_prog *tgt_prog,
14915                             u32 btf_id,
14916                             struct bpf_attach_target_info *tgt_info)
14917 {
14918         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14919         const char prefix[] = "btf_trace_";
14920         int ret = 0, subprog = -1, i;
14921         const struct btf_type *t;
14922         bool conservative = true;
14923         const char *tname;
14924         struct btf *btf;
14925         long addr = 0;
14926
14927         if (!btf_id) {
14928                 bpf_log(log, "Tracing programs must provide btf_id\n");
14929                 return -EINVAL;
14930         }
14931         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14932         if (!btf) {
14933                 bpf_log(log,
14934                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14935                 return -EINVAL;
14936         }
14937         t = btf_type_by_id(btf, btf_id);
14938         if (!t) {
14939                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14940                 return -EINVAL;
14941         }
14942         tname = btf_name_by_offset(btf, t->name_off);
14943         if (!tname) {
14944                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14945                 return -EINVAL;
14946         }
14947         if (tgt_prog) {
14948                 struct bpf_prog_aux *aux = tgt_prog->aux;
14949
14950                 for (i = 0; i < aux->func_info_cnt; i++)
14951                         if (aux->func_info[i].type_id == btf_id) {
14952                                 subprog = i;
14953                                 break;
14954                         }
14955                 if (subprog == -1) {
14956                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
14957                         return -EINVAL;
14958                 }
14959                 conservative = aux->func_info_aux[subprog].unreliable;
14960                 if (prog_extension) {
14961                         if (conservative) {
14962                                 bpf_log(log,
14963                                         "Cannot replace static functions\n");
14964                                 return -EINVAL;
14965                         }
14966                         if (!prog->jit_requested) {
14967                                 bpf_log(log,
14968                                         "Extension programs should be JITed\n");
14969                                 return -EINVAL;
14970                         }
14971                 }
14972                 if (!tgt_prog->jited) {
14973                         bpf_log(log, "Can attach to only JITed progs\n");
14974                         return -EINVAL;
14975                 }
14976                 if (tgt_prog->type == prog->type) {
14977                         /* Cannot fentry/fexit another fentry/fexit program.
14978                          * Cannot attach program extension to another extension.
14979                          * It's ok to attach fentry/fexit to extension program.
14980                          */
14981                         bpf_log(log, "Cannot recursively attach\n");
14982                         return -EINVAL;
14983                 }
14984                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14985                     prog_extension &&
14986                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14987                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14988                         /* Program extensions can extend all program types
14989                          * except fentry/fexit. The reason is the following.
14990                          * The fentry/fexit programs are used for performance
14991                          * analysis, stats and can be attached to any program
14992                          * type except themselves. When extension program is
14993                          * replacing XDP function it is necessary to allow
14994                          * performance analysis of all functions. Both original
14995                          * XDP program and its program extension. Hence
14996                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14997                          * allowed. If extending of fentry/fexit was allowed it
14998                          * would be possible to create long call chain
14999                          * fentry->extension->fentry->extension beyond
15000                          * reasonable stack size. Hence extending fentry is not
15001                          * allowed.
15002                          */
15003                         bpf_log(log, "Cannot extend fentry/fexit\n");
15004                         return -EINVAL;
15005                 }
15006         } else {
15007                 if (prog_extension) {
15008                         bpf_log(log, "Cannot replace kernel functions\n");
15009                         return -EINVAL;
15010                 }
15011         }
15012
15013         switch (prog->expected_attach_type) {
15014         case BPF_TRACE_RAW_TP:
15015                 if (tgt_prog) {
15016                         bpf_log(log,
15017                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
15018                         return -EINVAL;
15019                 }
15020                 if (!btf_type_is_typedef(t)) {
15021                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
15022                                 btf_id);
15023                         return -EINVAL;
15024                 }
15025                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
15026                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
15027                                 btf_id, tname);
15028                         return -EINVAL;
15029                 }
15030                 tname += sizeof(prefix) - 1;
15031                 t = btf_type_by_id(btf, t->type);
15032                 if (!btf_type_is_ptr(t))
15033                         /* should never happen in valid vmlinux build */
15034                         return -EINVAL;
15035                 t = btf_type_by_id(btf, t->type);
15036                 if (!btf_type_is_func_proto(t))
15037                         /* should never happen in valid vmlinux build */
15038                         return -EINVAL;
15039
15040                 break;
15041         case BPF_TRACE_ITER:
15042                 if (!btf_type_is_func(t)) {
15043                         bpf_log(log, "attach_btf_id %u is not a function\n",
15044                                 btf_id);
15045                         return -EINVAL;
15046                 }
15047                 t = btf_type_by_id(btf, t->type);
15048                 if (!btf_type_is_func_proto(t))
15049                         return -EINVAL;
15050                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15051                 if (ret)
15052                         return ret;
15053                 break;
15054         default:
15055                 if (!prog_extension)
15056                         return -EINVAL;
15057                 fallthrough;
15058         case BPF_MODIFY_RETURN:
15059         case BPF_LSM_MAC:
15060         case BPF_LSM_CGROUP:
15061         case BPF_TRACE_FENTRY:
15062         case BPF_TRACE_FEXIT:
15063                 if (!btf_type_is_func(t)) {
15064                         bpf_log(log, "attach_btf_id %u is not a function\n",
15065                                 btf_id);
15066                         return -EINVAL;
15067                 }
15068                 if (prog_extension &&
15069                     btf_check_type_match(log, prog, btf, t))
15070                         return -EINVAL;
15071                 t = btf_type_by_id(btf, t->type);
15072                 if (!btf_type_is_func_proto(t))
15073                         return -EINVAL;
15074
15075                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15076                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15077                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15078                         return -EINVAL;
15079
15080                 if (tgt_prog && conservative)
15081                         t = NULL;
15082
15083                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15084                 if (ret < 0)
15085                         return ret;
15086
15087                 if (tgt_prog) {
15088                         if (subprog == 0)
15089                                 addr = (long) tgt_prog->bpf_func;
15090                         else
15091                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15092                 } else {
15093                         addr = kallsyms_lookup_name(tname);
15094                         if (!addr) {
15095                                 bpf_log(log,
15096                                         "The address of function %s cannot be found\n",
15097                                         tname);
15098                                 return -ENOENT;
15099                         }
15100                 }
15101
15102                 if (prog->aux->sleepable) {
15103                         ret = -EINVAL;
15104                         switch (prog->type) {
15105                         case BPF_PROG_TYPE_TRACING:
15106                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15107                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15108                                  */
15109                                 if (!check_non_sleepable_error_inject(btf_id) &&
15110                                     within_error_injection_list(addr))
15111                                         ret = 0;
15112                                 break;
15113                         case BPF_PROG_TYPE_LSM:
15114                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15115                                  * Only some of them are sleepable.
15116                                  */
15117                                 if (bpf_lsm_is_sleepable_hook(btf_id))
15118                                         ret = 0;
15119                                 break;
15120                         default:
15121                                 break;
15122                         }
15123                         if (ret) {
15124                                 bpf_log(log, "%s is not sleepable\n", tname);
15125                                 return ret;
15126                         }
15127                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15128                         if (tgt_prog) {
15129                                 bpf_log(log, "can't modify return codes of BPF programs\n");
15130                                 return -EINVAL;
15131                         }
15132                         ret = check_attach_modify_return(addr, tname);
15133                         if (ret) {
15134                                 bpf_log(log, "%s() is not modifiable\n", tname);
15135                                 return ret;
15136                         }
15137                 }
15138
15139                 break;
15140         }
15141         tgt_info->tgt_addr = addr;
15142         tgt_info->tgt_name = tname;
15143         tgt_info->tgt_type = t;
15144         return 0;
15145 }
15146
15147 BTF_SET_START(btf_id_deny)
15148 BTF_ID_UNUSED
15149 #ifdef CONFIG_SMP
15150 BTF_ID(func, migrate_disable)
15151 BTF_ID(func, migrate_enable)
15152 #endif
15153 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15154 BTF_ID(func, rcu_read_unlock_strict)
15155 #endif
15156 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
15157 BTF_ID(func, preempt_count_add)
15158 BTF_ID(func, preempt_count_sub)
15159 #endif
15160 BTF_SET_END(btf_id_deny)
15161
15162 static int check_attach_btf_id(struct bpf_verifier_env *env)
15163 {
15164         struct bpf_prog *prog = env->prog;
15165         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15166         struct bpf_attach_target_info tgt_info = {};
15167         u32 btf_id = prog->aux->attach_btf_id;
15168         struct bpf_trampoline *tr;
15169         int ret;
15170         u64 key;
15171
15172         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15173                 if (prog->aux->sleepable)
15174                         /* attach_btf_id checked to be zero already */
15175                         return 0;
15176                 verbose(env, "Syscall programs can only be sleepable\n");
15177                 return -EINVAL;
15178         }
15179
15180         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15181             prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15182                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15183                 return -EINVAL;
15184         }
15185
15186         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15187                 return check_struct_ops_btf_id(env);
15188
15189         if (prog->type != BPF_PROG_TYPE_TRACING &&
15190             prog->type != BPF_PROG_TYPE_LSM &&
15191             prog->type != BPF_PROG_TYPE_EXT)
15192                 return 0;
15193
15194         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15195         if (ret)
15196                 return ret;
15197
15198         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15199                 /* to make freplace equivalent to their targets, they need to
15200                  * inherit env->ops and expected_attach_type for the rest of the
15201                  * verification
15202                  */
15203                 env->ops = bpf_verifier_ops[tgt_prog->type];
15204                 prog->expected_attach_type = tgt_prog->expected_attach_type;
15205         }
15206
15207         /* store info about the attachment target that will be used later */
15208         prog->aux->attach_func_proto = tgt_info.tgt_type;
15209         prog->aux->attach_func_name = tgt_info.tgt_name;
15210
15211         if (tgt_prog) {
15212                 prog->aux->saved_dst_prog_type = tgt_prog->type;
15213                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15214         }
15215
15216         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15217                 prog->aux->attach_btf_trace = true;
15218                 return 0;
15219         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15220                 if (!bpf_iter_prog_supported(prog))
15221                         return -EINVAL;
15222                 return 0;
15223         }
15224
15225         if (prog->type == BPF_PROG_TYPE_LSM) {
15226                 ret = bpf_lsm_verify_prog(&env->log, prog);
15227                 if (ret < 0)
15228                         return ret;
15229         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15230                    btf_id_set_contains(&btf_id_deny, btf_id)) {
15231                 return -EINVAL;
15232         }
15233
15234         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15235         tr = bpf_trampoline_get(key, &tgt_info);
15236         if (!tr)
15237                 return -ENOMEM;
15238
15239         prog->aux->dst_trampoline = tr;
15240         return 0;
15241 }
15242
15243 struct btf *bpf_get_btf_vmlinux(void)
15244 {
15245         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15246                 mutex_lock(&bpf_verifier_lock);
15247                 if (!btf_vmlinux)
15248                         btf_vmlinux = btf_parse_vmlinux();
15249                 mutex_unlock(&bpf_verifier_lock);
15250         }
15251         return btf_vmlinux;
15252 }
15253
15254 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15255 {
15256         u64 start_time = ktime_get_ns();
15257         struct bpf_verifier_env *env;
15258         struct bpf_verifier_log *log;
15259         int i, len, ret = -EINVAL;
15260         bool is_priv;
15261
15262         /* no program is valid */
15263         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15264                 return -EINVAL;
15265
15266         /* 'struct bpf_verifier_env' can be global, but since it's not small,
15267          * allocate/free it every time bpf_check() is called
15268          */
15269         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15270         if (!env)
15271                 return -ENOMEM;
15272         log = &env->log;
15273
15274         len = (*prog)->len;
15275         env->insn_aux_data =
15276                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15277         ret = -ENOMEM;
15278         if (!env->insn_aux_data)
15279                 goto err_free_env;
15280         for (i = 0; i < len; i++)
15281                 env->insn_aux_data[i].orig_idx = i;
15282         env->prog = *prog;
15283         env->ops = bpf_verifier_ops[env->prog->type];
15284         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15285         is_priv = bpf_capable();
15286
15287         bpf_get_btf_vmlinux();
15288
15289         /* grab the mutex to protect few globals used by verifier */
15290         if (!is_priv)
15291                 mutex_lock(&bpf_verifier_lock);
15292
15293         if (attr->log_level || attr->log_buf || attr->log_size) {
15294                 /* user requested verbose verifier output
15295                  * and supplied buffer to store the verification trace
15296                  */
15297                 log->level = attr->log_level;
15298                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15299                 log->len_total = attr->log_size;
15300
15301                 /* log attributes have to be sane */
15302                 if (!bpf_verifier_log_attr_valid(log)) {
15303                         ret = -EINVAL;
15304                         goto err_unlock;
15305                 }
15306         }
15307
15308         mark_verifier_state_clean(env);
15309
15310         if (IS_ERR(btf_vmlinux)) {
15311                 /* Either gcc or pahole or kernel are broken. */
15312                 verbose(env, "in-kernel BTF is malformed\n");
15313                 ret = PTR_ERR(btf_vmlinux);
15314                 goto skip_full_check;
15315         }
15316
15317         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15318         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15319                 env->strict_alignment = true;
15320         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15321                 env->strict_alignment = false;
15322
15323         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15324         env->allow_uninit_stack = bpf_allow_uninit_stack();
15325         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15326         env->bypass_spec_v1 = bpf_bypass_spec_v1();
15327         env->bypass_spec_v4 = bpf_bypass_spec_v4();
15328         env->bpf_capable = bpf_capable();
15329
15330         if (is_priv)
15331                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15332
15333         env->explored_states = kvcalloc(state_htab_size(env),
15334                                        sizeof(struct bpf_verifier_state_list *),
15335                                        GFP_USER);
15336         ret = -ENOMEM;
15337         if (!env->explored_states)
15338                 goto skip_full_check;
15339
15340         ret = add_subprog_and_kfunc(env);
15341         if (ret < 0)
15342                 goto skip_full_check;
15343
15344         ret = check_subprogs(env);
15345         if (ret < 0)
15346                 goto skip_full_check;
15347
15348         ret = check_btf_info(env, attr, uattr);
15349         if (ret < 0)
15350                 goto skip_full_check;
15351
15352         ret = check_attach_btf_id(env);
15353         if (ret)
15354                 goto skip_full_check;
15355
15356         ret = resolve_pseudo_ldimm64(env);
15357         if (ret < 0)
15358                 goto skip_full_check;
15359
15360         if (bpf_prog_is_dev_bound(env->prog->aux)) {
15361                 ret = bpf_prog_offload_verifier_prep(env->prog);
15362                 if (ret)
15363                         goto skip_full_check;
15364         }
15365
15366         ret = check_cfg(env);
15367         if (ret < 0)
15368                 goto skip_full_check;
15369
15370         ret = do_check_subprogs(env);
15371         ret = ret ?: do_check_main(env);
15372
15373         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15374                 ret = bpf_prog_offload_finalize(env);
15375
15376 skip_full_check:
15377         kvfree(env->explored_states);
15378
15379         if (ret == 0)
15380                 ret = check_max_stack_depth(env);
15381
15382         /* instruction rewrites happen after this point */
15383         if (ret == 0)
15384                 ret = optimize_bpf_loop(env);
15385
15386         if (is_priv) {
15387                 if (ret == 0)
15388                         opt_hard_wire_dead_code_branches(env);
15389                 if (ret == 0)
15390                         ret = opt_remove_dead_code(env);
15391                 if (ret == 0)
15392                         ret = opt_remove_nops(env);
15393         } else {
15394                 if (ret == 0)
15395                         sanitize_dead_code(env);
15396         }
15397
15398         if (ret == 0)
15399                 /* program is valid, convert *(u32*)(ctx + off) accesses */
15400                 ret = convert_ctx_accesses(env);
15401
15402         if (ret == 0)
15403                 ret = do_misc_fixups(env);
15404
15405         /* do 32-bit optimization after insn patching has done so those patched
15406          * insns could be handled correctly.
15407          */
15408         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15409                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15410                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15411                                                                      : false;
15412         }
15413
15414         if (ret == 0)
15415                 ret = fixup_call_args(env);
15416
15417         env->verification_time = ktime_get_ns() - start_time;
15418         print_verification_stats(env);
15419         env->prog->aux->verified_insns = env->insn_processed;
15420
15421         if (log->level && bpf_verifier_log_full(log))
15422                 ret = -ENOSPC;
15423         if (log->level && !log->ubuf) {
15424                 ret = -EFAULT;
15425                 goto err_release_maps;
15426         }
15427
15428         if (ret)
15429                 goto err_release_maps;
15430
15431         if (env->used_map_cnt) {
15432                 /* if program passed verifier, update used_maps in bpf_prog_info */
15433                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15434                                                           sizeof(env->used_maps[0]),
15435                                                           GFP_KERNEL);
15436
15437                 if (!env->prog->aux->used_maps) {
15438                         ret = -ENOMEM;
15439                         goto err_release_maps;
15440                 }
15441
15442                 memcpy(env->prog->aux->used_maps, env->used_maps,
15443                        sizeof(env->used_maps[0]) * env->used_map_cnt);
15444                 env->prog->aux->used_map_cnt = env->used_map_cnt;
15445         }
15446         if (env->used_btf_cnt) {
15447                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15448                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15449                                                           sizeof(env->used_btfs[0]),
15450                                                           GFP_KERNEL);
15451                 if (!env->prog->aux->used_btfs) {
15452                         ret = -ENOMEM;
15453                         goto err_release_maps;
15454                 }
15455
15456                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15457                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15458                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15459         }
15460         if (env->used_map_cnt || env->used_btf_cnt) {
15461                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15462                  * bpf_ld_imm64 instructions
15463                  */
15464                 convert_pseudo_ld_imm64(env);
15465         }
15466
15467         adjust_btf_func(env);
15468
15469 err_release_maps:
15470         if (!env->prog->aux->used_maps)
15471                 /* if we didn't copy map pointers into bpf_prog_info, release
15472                  * them now. Otherwise free_used_maps() will release them.
15473                  */
15474                 release_maps(env);
15475         if (!env->prog->aux->used_btfs)
15476                 release_btfs(env);
15477
15478         /* extension progs temporarily inherit the attach_type of their targets
15479            for verification purposes, so set it back to zero before returning
15480          */
15481         if (env->prog->type == BPF_PROG_TYPE_EXT)
15482                 env->prog->expected_attach_type = 0;
15483
15484         *prog = env->prog;
15485 err_unlock:
15486         if (!is_priv)
15487                 mutex_unlock(&bpf_verifier_lock);
15488         vfree(env->insn_aux_data);
15489 err_free_env:
15490         kfree(env);
15491         return ret;
15492 }