32ea9aaa8b8db68c2c7ca654cbae3441cdabcdc1
[platform/kernel/linux-starfive.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27
28 #include "disasm.h"
29
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32         [_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168         /* verifer state is 'st'
169          * before processing instruction 'insn_idx'
170          * and after processing instruction 'prev_insn_idx'
171          */
172         struct bpf_verifier_state st;
173         int insn_idx;
174         int prev_insn_idx;
175         struct bpf_verifier_stack_elem *next;
176         /* length of verifier log at the time this state was pushed on stack */
177         u32 log_pos;
178 };
179
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
181 #define BPF_COMPLEXITY_LIMIT_STATES     64
182
183 #define BPF_MAP_KEY_POISON      (1ULL << 63)
184 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
185
186 #define BPF_MAP_PTR_UNPRIV      1UL
187 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
188                                           POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193
194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 {
196         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
197 }
198
199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 {
201         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
202 }
203
204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205                               const struct bpf_map *map, bool unpriv)
206 {
207         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208         unpriv |= bpf_map_ptr_unpriv(aux);
209         aux->map_ptr_state = (unsigned long)map |
210                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211 }
212
213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 {
215         return aux->map_key_state & BPF_MAP_KEY_POISON;
216 }
217
218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 {
220         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221 }
222
223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 {
225         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226 }
227
228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 {
230         bool poisoned = bpf_map_key_poisoned(aux);
231
232         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
234 }
235
236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 {
238         return insn->code == (BPF_JMP | BPF_CALL) &&
239                insn->src_reg == BPF_PSEUDO_CALL;
240 }
241
242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 {
244         return insn->code == (BPF_JMP | BPF_CALL) &&
245                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246 }
247
248 struct bpf_call_arg_meta {
249         struct bpf_map *map_ptr;
250         bool raw_mode;
251         bool pkt_access;
252         u8 release_regno;
253         int regno;
254         int access_size;
255         int mem_size;
256         u64 msize_max_value;
257         int ref_obj_id;
258         int map_uid;
259         int func_id;
260         struct btf *btf;
261         u32 btf_id;
262         struct btf *ret_btf;
263         u32 ret_btf_id;
264         u32 subprogno;
265         struct bpf_map_value_off_desc *kptr_off_desc;
266         u8 uninit_dynptr_regno;
267 };
268
269 struct btf *btf_vmlinux;
270
271 static DEFINE_MUTEX(bpf_verifier_lock);
272
273 static const struct bpf_line_info *
274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 {
276         const struct bpf_line_info *linfo;
277         const struct bpf_prog *prog;
278         u32 i, nr_linfo;
279
280         prog = env->prog;
281         nr_linfo = prog->aux->nr_linfo;
282
283         if (!nr_linfo || insn_off >= prog->len)
284                 return NULL;
285
286         linfo = prog->aux->linfo;
287         for (i = 1; i < nr_linfo; i++)
288                 if (insn_off < linfo[i].insn_off)
289                         break;
290
291         return &linfo[i - 1];
292 }
293
294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295                        va_list args)
296 {
297         unsigned int n;
298
299         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300
301         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302                   "verifier log line truncated - local buffer too short\n");
303
304         if (log->level == BPF_LOG_KERNEL) {
305                 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306
307                 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
308                 return;
309         }
310
311         n = min(log->len_total - log->len_used - 1, n);
312         log->kbuf[n] = '\0';
313         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314                 log->len_used += n;
315         else
316                 log->ubuf = NULL;
317 }
318
319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320 {
321         char zero = 0;
322
323         if (!bpf_verifier_log_needed(log))
324                 return;
325
326         log->len_used = new_pos;
327         if (put_user(zero, log->ubuf + new_pos))
328                 log->ubuf = NULL;
329 }
330
331 /* log_level controls verbosity level of eBPF verifier.
332  * bpf_verifier_log_write() is used to dump the verification trace to the log,
333  * so the user can figure out what's wrong with the program
334  */
335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336                                            const char *fmt, ...)
337 {
338         va_list args;
339
340         if (!bpf_verifier_log_needed(&env->log))
341                 return;
342
343         va_start(args, fmt);
344         bpf_verifier_vlog(&env->log, fmt, args);
345         va_end(args);
346 }
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348
349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 {
351         struct bpf_verifier_env *env = private_data;
352         va_list args;
353
354         if (!bpf_verifier_log_needed(&env->log))
355                 return;
356
357         va_start(args, fmt);
358         bpf_verifier_vlog(&env->log, fmt, args);
359         va_end(args);
360 }
361
362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363                             const char *fmt, ...)
364 {
365         va_list args;
366
367         if (!bpf_verifier_log_needed(log))
368                 return;
369
370         va_start(args, fmt);
371         bpf_verifier_vlog(log, fmt, args);
372         va_end(args);
373 }
374 EXPORT_SYMBOL_GPL(bpf_log);
375
376 static const char *ltrim(const char *s)
377 {
378         while (isspace(*s))
379                 s++;
380
381         return s;
382 }
383
384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385                                          u32 insn_off,
386                                          const char *prefix_fmt, ...)
387 {
388         const struct bpf_line_info *linfo;
389
390         if (!bpf_verifier_log_needed(&env->log))
391                 return;
392
393         linfo = find_linfo(env, insn_off);
394         if (!linfo || linfo == env->prev_linfo)
395                 return;
396
397         if (prefix_fmt) {
398                 va_list args;
399
400                 va_start(args, prefix_fmt);
401                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
402                 va_end(args);
403         }
404
405         verbose(env, "%s\n",
406                 ltrim(btf_name_by_offset(env->prog->aux->btf,
407                                          linfo->line_off)));
408
409         env->prev_linfo = linfo;
410 }
411
412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413                                    struct bpf_reg_state *reg,
414                                    struct tnum *range, const char *ctx,
415                                    const char *reg_name)
416 {
417         char tn_buf[48];
418
419         verbose(env, "At %s the register %s ", ctx, reg_name);
420         if (!tnum_is_unknown(reg->var_off)) {
421                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422                 verbose(env, "has value %s", tn_buf);
423         } else {
424                 verbose(env, "has unknown scalar value");
425         }
426         tnum_strn(tn_buf, sizeof(tn_buf), *range);
427         verbose(env, " should have been in %s\n", tn_buf);
428 }
429
430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
431 {
432         type = base_type(type);
433         return type == PTR_TO_PACKET ||
434                type == PTR_TO_PACKET_META;
435 }
436
437 static bool type_is_sk_pointer(enum bpf_reg_type type)
438 {
439         return type == PTR_TO_SOCKET ||
440                 type == PTR_TO_SOCK_COMMON ||
441                 type == PTR_TO_TCP_SOCK ||
442                 type == PTR_TO_XDP_SOCK;
443 }
444
445 static bool reg_type_not_null(enum bpf_reg_type type)
446 {
447         return type == PTR_TO_SOCKET ||
448                 type == PTR_TO_TCP_SOCK ||
449                 type == PTR_TO_MAP_VALUE ||
450                 type == PTR_TO_MAP_KEY ||
451                 type == PTR_TO_SOCK_COMMON;
452 }
453
454 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
455 {
456         return reg->type == PTR_TO_MAP_VALUE &&
457                 map_value_has_spin_lock(reg->map_ptr);
458 }
459
460 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
461 {
462         type = base_type(type);
463         return type == PTR_TO_SOCKET || type == PTR_TO_TCP_SOCK ||
464                 type == PTR_TO_MEM || type == PTR_TO_BTF_ID;
465 }
466
467 static bool type_is_rdonly_mem(u32 type)
468 {
469         return type & MEM_RDONLY;
470 }
471
472 static bool type_may_be_null(u32 type)
473 {
474         return type & PTR_MAYBE_NULL;
475 }
476
477 static bool is_acquire_function(enum bpf_func_id func_id,
478                                 const struct bpf_map *map)
479 {
480         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
481
482         if (func_id == BPF_FUNC_sk_lookup_tcp ||
483             func_id == BPF_FUNC_sk_lookup_udp ||
484             func_id == BPF_FUNC_skc_lookup_tcp ||
485             func_id == BPF_FUNC_ringbuf_reserve ||
486             func_id == BPF_FUNC_kptr_xchg)
487                 return true;
488
489         if (func_id == BPF_FUNC_map_lookup_elem &&
490             (map_type == BPF_MAP_TYPE_SOCKMAP ||
491              map_type == BPF_MAP_TYPE_SOCKHASH))
492                 return true;
493
494         return false;
495 }
496
497 static bool is_ptr_cast_function(enum bpf_func_id func_id)
498 {
499         return func_id == BPF_FUNC_tcp_sock ||
500                 func_id == BPF_FUNC_sk_fullsock ||
501                 func_id == BPF_FUNC_skc_to_tcp_sock ||
502                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
503                 func_id == BPF_FUNC_skc_to_udp6_sock ||
504                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
505                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
506                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
507 }
508
509 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
510 {
511         return func_id == BPF_FUNC_dynptr_data;
512 }
513
514 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
515                                         const struct bpf_map *map)
516 {
517         int ref_obj_uses = 0;
518
519         if (is_ptr_cast_function(func_id))
520                 ref_obj_uses++;
521         if (is_acquire_function(func_id, map))
522                 ref_obj_uses++;
523         if (is_dynptr_ref_function(func_id))
524                 ref_obj_uses++;
525
526         return ref_obj_uses > 1;
527 }
528
529 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
530 {
531         return BPF_CLASS(insn->code) == BPF_STX &&
532                BPF_MODE(insn->code) == BPF_ATOMIC &&
533                insn->imm == BPF_CMPXCHG;
534 }
535
536 /* string representation of 'enum bpf_reg_type'
537  *
538  * Note that reg_type_str() can not appear more than once in a single verbose()
539  * statement.
540  */
541 static const char *reg_type_str(struct bpf_verifier_env *env,
542                                 enum bpf_reg_type type)
543 {
544         char postfix[16] = {0}, prefix[32] = {0};
545         static const char * const str[] = {
546                 [NOT_INIT]              = "?",
547                 [SCALAR_VALUE]          = "scalar",
548                 [PTR_TO_CTX]            = "ctx",
549                 [CONST_PTR_TO_MAP]      = "map_ptr",
550                 [PTR_TO_MAP_VALUE]      = "map_value",
551                 [PTR_TO_STACK]          = "fp",
552                 [PTR_TO_PACKET]         = "pkt",
553                 [PTR_TO_PACKET_META]    = "pkt_meta",
554                 [PTR_TO_PACKET_END]     = "pkt_end",
555                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
556                 [PTR_TO_SOCKET]         = "sock",
557                 [PTR_TO_SOCK_COMMON]    = "sock_common",
558                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
559                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
560                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
561                 [PTR_TO_BTF_ID]         = "ptr_",
562                 [PTR_TO_MEM]            = "mem",
563                 [PTR_TO_BUF]            = "buf",
564                 [PTR_TO_FUNC]           = "func",
565                 [PTR_TO_MAP_KEY]        = "map_key",
566                 [PTR_TO_DYNPTR]         = "dynptr_ptr",
567         };
568
569         if (type & PTR_MAYBE_NULL) {
570                 if (base_type(type) == PTR_TO_BTF_ID)
571                         strncpy(postfix, "or_null_", 16);
572                 else
573                         strncpy(postfix, "_or_null", 16);
574         }
575
576         if (type & MEM_RDONLY)
577                 strncpy(prefix, "rdonly_", 32);
578         if (type & MEM_ALLOC)
579                 strncpy(prefix, "alloc_", 32);
580         if (type & MEM_USER)
581                 strncpy(prefix, "user_", 32);
582         if (type & MEM_PERCPU)
583                 strncpy(prefix, "percpu_", 32);
584         if (type & PTR_UNTRUSTED)
585                 strncpy(prefix, "untrusted_", 32);
586
587         snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
588                  prefix, str[base_type(type)], postfix);
589         return env->type_str_buf;
590 }
591
592 static char slot_type_char[] = {
593         [STACK_INVALID] = '?',
594         [STACK_SPILL]   = 'r',
595         [STACK_MISC]    = 'm',
596         [STACK_ZERO]    = '0',
597         [STACK_DYNPTR]  = 'd',
598 };
599
600 static void print_liveness(struct bpf_verifier_env *env,
601                            enum bpf_reg_liveness live)
602 {
603         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
604             verbose(env, "_");
605         if (live & REG_LIVE_READ)
606                 verbose(env, "r");
607         if (live & REG_LIVE_WRITTEN)
608                 verbose(env, "w");
609         if (live & REG_LIVE_DONE)
610                 verbose(env, "D");
611 }
612
613 static int get_spi(s32 off)
614 {
615         return (-off - 1) / BPF_REG_SIZE;
616 }
617
618 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
619 {
620         int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
621
622         /* We need to check that slots between [spi - nr_slots + 1, spi] are
623          * within [0, allocated_stack).
624          *
625          * Please note that the spi grows downwards. For example, a dynptr
626          * takes the size of two stack slots; the first slot will be at
627          * spi and the second slot will be at spi - 1.
628          */
629         return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
630 }
631
632 static struct bpf_func_state *func(struct bpf_verifier_env *env,
633                                    const struct bpf_reg_state *reg)
634 {
635         struct bpf_verifier_state *cur = env->cur_state;
636
637         return cur->frame[reg->frameno];
638 }
639
640 static const char *kernel_type_name(const struct btf* btf, u32 id)
641 {
642         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
643 }
644
645 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
646 {
647         env->scratched_regs |= 1U << regno;
648 }
649
650 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
651 {
652         env->scratched_stack_slots |= 1ULL << spi;
653 }
654
655 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
656 {
657         return (env->scratched_regs >> regno) & 1;
658 }
659
660 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
661 {
662         return (env->scratched_stack_slots >> regno) & 1;
663 }
664
665 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
666 {
667         return env->scratched_regs || env->scratched_stack_slots;
668 }
669
670 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
671 {
672         env->scratched_regs = 0U;
673         env->scratched_stack_slots = 0ULL;
674 }
675
676 /* Used for printing the entire verifier state. */
677 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
678 {
679         env->scratched_regs = ~0U;
680         env->scratched_stack_slots = ~0ULL;
681 }
682
683 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
684 {
685         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
686         case DYNPTR_TYPE_LOCAL:
687                 return BPF_DYNPTR_TYPE_LOCAL;
688         case DYNPTR_TYPE_RINGBUF:
689                 return BPF_DYNPTR_TYPE_RINGBUF;
690         default:
691                 return BPF_DYNPTR_TYPE_INVALID;
692         }
693 }
694
695 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
696 {
697         return type == BPF_DYNPTR_TYPE_RINGBUF;
698 }
699
700 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
701                                    enum bpf_arg_type arg_type, int insn_idx)
702 {
703         struct bpf_func_state *state = func(env, reg);
704         enum bpf_dynptr_type type;
705         int spi, i, id;
706
707         spi = get_spi(reg->off);
708
709         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
710                 return -EINVAL;
711
712         for (i = 0; i < BPF_REG_SIZE; i++) {
713                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
714                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
715         }
716
717         type = arg_to_dynptr_type(arg_type);
718         if (type == BPF_DYNPTR_TYPE_INVALID)
719                 return -EINVAL;
720
721         state->stack[spi].spilled_ptr.dynptr.first_slot = true;
722         state->stack[spi].spilled_ptr.dynptr.type = type;
723         state->stack[spi - 1].spilled_ptr.dynptr.type = type;
724
725         if (dynptr_type_refcounted(type)) {
726                 /* The id is used to track proper releasing */
727                 id = acquire_reference_state(env, insn_idx);
728                 if (id < 0)
729                         return id;
730
731                 state->stack[spi].spilled_ptr.id = id;
732                 state->stack[spi - 1].spilled_ptr.id = id;
733         }
734
735         return 0;
736 }
737
738 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
739 {
740         struct bpf_func_state *state = func(env, reg);
741         int spi, i;
742
743         spi = get_spi(reg->off);
744
745         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
746                 return -EINVAL;
747
748         for (i = 0; i < BPF_REG_SIZE; i++) {
749                 state->stack[spi].slot_type[i] = STACK_INVALID;
750                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
751         }
752
753         /* Invalidate any slices associated with this dynptr */
754         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
755                 release_reference(env, state->stack[spi].spilled_ptr.id);
756                 state->stack[spi].spilled_ptr.id = 0;
757                 state->stack[spi - 1].spilled_ptr.id = 0;
758         }
759
760         state->stack[spi].spilled_ptr.dynptr.first_slot = false;
761         state->stack[spi].spilled_ptr.dynptr.type = 0;
762         state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
763
764         return 0;
765 }
766
767 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
768 {
769         struct bpf_func_state *state = func(env, reg);
770         int spi = get_spi(reg->off);
771         int i;
772
773         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
774                 return true;
775
776         for (i = 0; i < BPF_REG_SIZE; i++) {
777                 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
778                     state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
779                         return false;
780         }
781
782         return true;
783 }
784
785 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
786                               struct bpf_reg_state *reg)
787 {
788         struct bpf_func_state *state = func(env, reg);
789         int spi = get_spi(reg->off);
790         int i;
791
792         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
793             !state->stack[spi].spilled_ptr.dynptr.first_slot)
794                 return false;
795
796         for (i = 0; i < BPF_REG_SIZE; i++) {
797                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
798                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
799                         return false;
800         }
801
802         return true;
803 }
804
805 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
806                              struct bpf_reg_state *reg,
807                              enum bpf_arg_type arg_type)
808 {
809         struct bpf_func_state *state = func(env, reg);
810         enum bpf_dynptr_type dynptr_type;
811         int spi = get_spi(reg->off);
812
813         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
814         if (arg_type == ARG_PTR_TO_DYNPTR)
815                 return true;
816
817         dynptr_type = arg_to_dynptr_type(arg_type);
818
819         return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
820 }
821
822 /* The reg state of a pointer or a bounded scalar was saved when
823  * it was spilled to the stack.
824  */
825 static bool is_spilled_reg(const struct bpf_stack_state *stack)
826 {
827         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
828 }
829
830 static void scrub_spilled_slot(u8 *stype)
831 {
832         if (*stype != STACK_INVALID)
833                 *stype = STACK_MISC;
834 }
835
836 static void print_verifier_state(struct bpf_verifier_env *env,
837                                  const struct bpf_func_state *state,
838                                  bool print_all)
839 {
840         const struct bpf_reg_state *reg;
841         enum bpf_reg_type t;
842         int i;
843
844         if (state->frameno)
845                 verbose(env, " frame%d:", state->frameno);
846         for (i = 0; i < MAX_BPF_REG; i++) {
847                 reg = &state->regs[i];
848                 t = reg->type;
849                 if (t == NOT_INIT)
850                         continue;
851                 if (!print_all && !reg_scratched(env, i))
852                         continue;
853                 verbose(env, " R%d", i);
854                 print_liveness(env, reg->live);
855                 verbose(env, "=");
856                 if (t == SCALAR_VALUE && reg->precise)
857                         verbose(env, "P");
858                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
859                     tnum_is_const(reg->var_off)) {
860                         /* reg->off should be 0 for SCALAR_VALUE */
861                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
862                         verbose(env, "%lld", reg->var_off.value + reg->off);
863                 } else {
864                         const char *sep = "";
865
866                         verbose(env, "%s", reg_type_str(env, t));
867                         if (base_type(t) == PTR_TO_BTF_ID)
868                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
869                         verbose(env, "(");
870 /*
871  * _a stands for append, was shortened to avoid multiline statements below.
872  * This macro is used to output a comma separated list of attributes.
873  */
874 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
875
876                         if (reg->id)
877                                 verbose_a("id=%d", reg->id);
878                         if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
879                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
880                         if (t != SCALAR_VALUE)
881                                 verbose_a("off=%d", reg->off);
882                         if (type_is_pkt_pointer(t))
883                                 verbose_a("r=%d", reg->range);
884                         else if (base_type(t) == CONST_PTR_TO_MAP ||
885                                  base_type(t) == PTR_TO_MAP_KEY ||
886                                  base_type(t) == PTR_TO_MAP_VALUE)
887                                 verbose_a("ks=%d,vs=%d",
888                                           reg->map_ptr->key_size,
889                                           reg->map_ptr->value_size);
890                         if (tnum_is_const(reg->var_off)) {
891                                 /* Typically an immediate SCALAR_VALUE, but
892                                  * could be a pointer whose offset is too big
893                                  * for reg->off
894                                  */
895                                 verbose_a("imm=%llx", reg->var_off.value);
896                         } else {
897                                 if (reg->smin_value != reg->umin_value &&
898                                     reg->smin_value != S64_MIN)
899                                         verbose_a("smin=%lld", (long long)reg->smin_value);
900                                 if (reg->smax_value != reg->umax_value &&
901                                     reg->smax_value != S64_MAX)
902                                         verbose_a("smax=%lld", (long long)reg->smax_value);
903                                 if (reg->umin_value != 0)
904                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
905                                 if (reg->umax_value != U64_MAX)
906                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
907                                 if (!tnum_is_unknown(reg->var_off)) {
908                                         char tn_buf[48];
909
910                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
911                                         verbose_a("var_off=%s", tn_buf);
912                                 }
913                                 if (reg->s32_min_value != reg->smin_value &&
914                                     reg->s32_min_value != S32_MIN)
915                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
916                                 if (reg->s32_max_value != reg->smax_value &&
917                                     reg->s32_max_value != S32_MAX)
918                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
919                                 if (reg->u32_min_value != reg->umin_value &&
920                                     reg->u32_min_value != U32_MIN)
921                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
922                                 if (reg->u32_max_value != reg->umax_value &&
923                                     reg->u32_max_value != U32_MAX)
924                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
925                         }
926 #undef verbose_a
927
928                         verbose(env, ")");
929                 }
930         }
931         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
932                 char types_buf[BPF_REG_SIZE + 1];
933                 bool valid = false;
934                 int j;
935
936                 for (j = 0; j < BPF_REG_SIZE; j++) {
937                         if (state->stack[i].slot_type[j] != STACK_INVALID)
938                                 valid = true;
939                         types_buf[j] = slot_type_char[
940                                         state->stack[i].slot_type[j]];
941                 }
942                 types_buf[BPF_REG_SIZE] = 0;
943                 if (!valid)
944                         continue;
945                 if (!print_all && !stack_slot_scratched(env, i))
946                         continue;
947                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
948                 print_liveness(env, state->stack[i].spilled_ptr.live);
949                 if (is_spilled_reg(&state->stack[i])) {
950                         reg = &state->stack[i].spilled_ptr;
951                         t = reg->type;
952                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
953                         if (t == SCALAR_VALUE && reg->precise)
954                                 verbose(env, "P");
955                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
956                                 verbose(env, "%lld", reg->var_off.value + reg->off);
957                 } else {
958                         verbose(env, "=%s", types_buf);
959                 }
960         }
961         if (state->acquired_refs && state->refs[0].id) {
962                 verbose(env, " refs=%d", state->refs[0].id);
963                 for (i = 1; i < state->acquired_refs; i++)
964                         if (state->refs[i].id)
965                                 verbose(env, ",%d", state->refs[i].id);
966         }
967         if (state->in_callback_fn)
968                 verbose(env, " cb");
969         if (state->in_async_callback_fn)
970                 verbose(env, " async_cb");
971         verbose(env, "\n");
972         mark_verifier_state_clean(env);
973 }
974
975 static inline u32 vlog_alignment(u32 pos)
976 {
977         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
978                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
979 }
980
981 static void print_insn_state(struct bpf_verifier_env *env,
982                              const struct bpf_func_state *state)
983 {
984         if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
985                 /* remove new line character */
986                 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
987                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
988         } else {
989                 verbose(env, "%d:", env->insn_idx);
990         }
991         print_verifier_state(env, state, false);
992 }
993
994 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
995  * small to hold src. This is different from krealloc since we don't want to preserve
996  * the contents of dst.
997  *
998  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
999  * not be allocated.
1000  */
1001 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1002 {
1003         size_t alloc_bytes;
1004         void *orig = dst;
1005         size_t bytes;
1006
1007         if (ZERO_OR_NULL_PTR(src))
1008                 goto out;
1009
1010         if (unlikely(check_mul_overflow(n, size, &bytes)))
1011                 return NULL;
1012
1013         alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1014         dst = krealloc(orig, alloc_bytes, flags);
1015         if (!dst) {
1016                 kfree(orig);
1017                 return NULL;
1018         }
1019
1020         memcpy(dst, src, bytes);
1021 out:
1022         return dst ? dst : ZERO_SIZE_PTR;
1023 }
1024
1025 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1026  * small to hold new_n items. new items are zeroed out if the array grows.
1027  *
1028  * Contrary to krealloc_array, does not free arr if new_n is zero.
1029  */
1030 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1031 {
1032         size_t alloc_size;
1033         void *new_arr;
1034
1035         if (!new_n || old_n == new_n)
1036                 goto out;
1037
1038         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1039         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1040         if (!new_arr) {
1041                 kfree(arr);
1042                 return NULL;
1043         }
1044         arr = new_arr;
1045
1046         if (new_n > old_n)
1047                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1048
1049 out:
1050         return arr ? arr : ZERO_SIZE_PTR;
1051 }
1052
1053 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1054 {
1055         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1056                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1057         if (!dst->refs)
1058                 return -ENOMEM;
1059
1060         dst->acquired_refs = src->acquired_refs;
1061         return 0;
1062 }
1063
1064 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1065 {
1066         size_t n = src->allocated_stack / BPF_REG_SIZE;
1067
1068         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1069                                 GFP_KERNEL);
1070         if (!dst->stack)
1071                 return -ENOMEM;
1072
1073         dst->allocated_stack = src->allocated_stack;
1074         return 0;
1075 }
1076
1077 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1078 {
1079         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1080                                     sizeof(struct bpf_reference_state));
1081         if (!state->refs)
1082                 return -ENOMEM;
1083
1084         state->acquired_refs = n;
1085         return 0;
1086 }
1087
1088 static int grow_stack_state(struct bpf_func_state *state, int size)
1089 {
1090         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1091
1092         if (old_n >= n)
1093                 return 0;
1094
1095         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1096         if (!state->stack)
1097                 return -ENOMEM;
1098
1099         state->allocated_stack = size;
1100         return 0;
1101 }
1102
1103 /* Acquire a pointer id from the env and update the state->refs to include
1104  * this new pointer reference.
1105  * On success, returns a valid pointer id to associate with the register
1106  * On failure, returns a negative errno.
1107  */
1108 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1109 {
1110         struct bpf_func_state *state = cur_func(env);
1111         int new_ofs = state->acquired_refs;
1112         int id, err;
1113
1114         err = resize_reference_state(state, state->acquired_refs + 1);
1115         if (err)
1116                 return err;
1117         id = ++env->id_gen;
1118         state->refs[new_ofs].id = id;
1119         state->refs[new_ofs].insn_idx = insn_idx;
1120         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1121
1122         return id;
1123 }
1124
1125 /* release function corresponding to acquire_reference_state(). Idempotent. */
1126 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1127 {
1128         int i, last_idx;
1129
1130         last_idx = state->acquired_refs - 1;
1131         for (i = 0; i < state->acquired_refs; i++) {
1132                 if (state->refs[i].id == ptr_id) {
1133                         /* Cannot release caller references in callbacks */
1134                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1135                                 return -EINVAL;
1136                         if (last_idx && i != last_idx)
1137                                 memcpy(&state->refs[i], &state->refs[last_idx],
1138                                        sizeof(*state->refs));
1139                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1140                         state->acquired_refs--;
1141                         return 0;
1142                 }
1143         }
1144         return -EINVAL;
1145 }
1146
1147 static void free_func_state(struct bpf_func_state *state)
1148 {
1149         if (!state)
1150                 return;
1151         kfree(state->refs);
1152         kfree(state->stack);
1153         kfree(state);
1154 }
1155
1156 static void clear_jmp_history(struct bpf_verifier_state *state)
1157 {
1158         kfree(state->jmp_history);
1159         state->jmp_history = NULL;
1160         state->jmp_history_cnt = 0;
1161 }
1162
1163 static void free_verifier_state(struct bpf_verifier_state *state,
1164                                 bool free_self)
1165 {
1166         int i;
1167
1168         for (i = 0; i <= state->curframe; i++) {
1169                 free_func_state(state->frame[i]);
1170                 state->frame[i] = NULL;
1171         }
1172         clear_jmp_history(state);
1173         if (free_self)
1174                 kfree(state);
1175 }
1176
1177 /* copy verifier state from src to dst growing dst stack space
1178  * when necessary to accommodate larger src stack
1179  */
1180 static int copy_func_state(struct bpf_func_state *dst,
1181                            const struct bpf_func_state *src)
1182 {
1183         int err;
1184
1185         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1186         err = copy_reference_state(dst, src);
1187         if (err)
1188                 return err;
1189         return copy_stack_state(dst, src);
1190 }
1191
1192 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1193                                const struct bpf_verifier_state *src)
1194 {
1195         struct bpf_func_state *dst;
1196         int i, err;
1197
1198         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1199                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1200                                             GFP_USER);
1201         if (!dst_state->jmp_history)
1202                 return -ENOMEM;
1203         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1204
1205         /* if dst has more stack frames then src frame, free them */
1206         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1207                 free_func_state(dst_state->frame[i]);
1208                 dst_state->frame[i] = NULL;
1209         }
1210         dst_state->speculative = src->speculative;
1211         dst_state->curframe = src->curframe;
1212         dst_state->active_spin_lock = src->active_spin_lock;
1213         dst_state->branches = src->branches;
1214         dst_state->parent = src->parent;
1215         dst_state->first_insn_idx = src->first_insn_idx;
1216         dst_state->last_insn_idx = src->last_insn_idx;
1217         for (i = 0; i <= src->curframe; i++) {
1218                 dst = dst_state->frame[i];
1219                 if (!dst) {
1220                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1221                         if (!dst)
1222                                 return -ENOMEM;
1223                         dst_state->frame[i] = dst;
1224                 }
1225                 err = copy_func_state(dst, src->frame[i]);
1226                 if (err)
1227                         return err;
1228         }
1229         return 0;
1230 }
1231
1232 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1233 {
1234         while (st) {
1235                 u32 br = --st->branches;
1236
1237                 /* WARN_ON(br > 1) technically makes sense here,
1238                  * but see comment in push_stack(), hence:
1239                  */
1240                 WARN_ONCE((int)br < 0,
1241                           "BUG update_branch_counts:branches_to_explore=%d\n",
1242                           br);
1243                 if (br)
1244                         break;
1245                 st = st->parent;
1246         }
1247 }
1248
1249 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1250                      int *insn_idx, bool pop_log)
1251 {
1252         struct bpf_verifier_state *cur = env->cur_state;
1253         struct bpf_verifier_stack_elem *elem, *head = env->head;
1254         int err;
1255
1256         if (env->head == NULL)
1257                 return -ENOENT;
1258
1259         if (cur) {
1260                 err = copy_verifier_state(cur, &head->st);
1261                 if (err)
1262                         return err;
1263         }
1264         if (pop_log)
1265                 bpf_vlog_reset(&env->log, head->log_pos);
1266         if (insn_idx)
1267                 *insn_idx = head->insn_idx;
1268         if (prev_insn_idx)
1269                 *prev_insn_idx = head->prev_insn_idx;
1270         elem = head->next;
1271         free_verifier_state(&head->st, false);
1272         kfree(head);
1273         env->head = elem;
1274         env->stack_size--;
1275         return 0;
1276 }
1277
1278 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1279                                              int insn_idx, int prev_insn_idx,
1280                                              bool speculative)
1281 {
1282         struct bpf_verifier_state *cur = env->cur_state;
1283         struct bpf_verifier_stack_elem *elem;
1284         int err;
1285
1286         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1287         if (!elem)
1288                 goto err;
1289
1290         elem->insn_idx = insn_idx;
1291         elem->prev_insn_idx = prev_insn_idx;
1292         elem->next = env->head;
1293         elem->log_pos = env->log.len_used;
1294         env->head = elem;
1295         env->stack_size++;
1296         err = copy_verifier_state(&elem->st, cur);
1297         if (err)
1298                 goto err;
1299         elem->st.speculative |= speculative;
1300         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1301                 verbose(env, "The sequence of %d jumps is too complex.\n",
1302                         env->stack_size);
1303                 goto err;
1304         }
1305         if (elem->st.parent) {
1306                 ++elem->st.parent->branches;
1307                 /* WARN_ON(branches > 2) technically makes sense here,
1308                  * but
1309                  * 1. speculative states will bump 'branches' for non-branch
1310                  * instructions
1311                  * 2. is_state_visited() heuristics may decide not to create
1312                  * a new state for a sequence of branches and all such current
1313                  * and cloned states will be pointing to a single parent state
1314                  * which might have large 'branches' count.
1315                  */
1316         }
1317         return &elem->st;
1318 err:
1319         free_verifier_state(env->cur_state, true);
1320         env->cur_state = NULL;
1321         /* pop all elements and return */
1322         while (!pop_stack(env, NULL, NULL, false));
1323         return NULL;
1324 }
1325
1326 #define CALLER_SAVED_REGS 6
1327 static const int caller_saved[CALLER_SAVED_REGS] = {
1328         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1329 };
1330
1331 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1332                                 struct bpf_reg_state *reg);
1333
1334 /* This helper doesn't clear reg->id */
1335 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1336 {
1337         reg->var_off = tnum_const(imm);
1338         reg->smin_value = (s64)imm;
1339         reg->smax_value = (s64)imm;
1340         reg->umin_value = imm;
1341         reg->umax_value = imm;
1342
1343         reg->s32_min_value = (s32)imm;
1344         reg->s32_max_value = (s32)imm;
1345         reg->u32_min_value = (u32)imm;
1346         reg->u32_max_value = (u32)imm;
1347 }
1348
1349 /* Mark the unknown part of a register (variable offset or scalar value) as
1350  * known to have the value @imm.
1351  */
1352 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1353 {
1354         /* Clear id, off, and union(map_ptr, range) */
1355         memset(((u8 *)reg) + sizeof(reg->type), 0,
1356                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1357         ___mark_reg_known(reg, imm);
1358 }
1359
1360 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1361 {
1362         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1363         reg->s32_min_value = (s32)imm;
1364         reg->s32_max_value = (s32)imm;
1365         reg->u32_min_value = (u32)imm;
1366         reg->u32_max_value = (u32)imm;
1367 }
1368
1369 /* Mark the 'variable offset' part of a register as zero.  This should be
1370  * used only on registers holding a pointer type.
1371  */
1372 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1373 {
1374         __mark_reg_known(reg, 0);
1375 }
1376
1377 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1378 {
1379         __mark_reg_known(reg, 0);
1380         reg->type = SCALAR_VALUE;
1381 }
1382
1383 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1384                                 struct bpf_reg_state *regs, u32 regno)
1385 {
1386         if (WARN_ON(regno >= MAX_BPF_REG)) {
1387                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1388                 /* Something bad happened, let's kill all regs */
1389                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1390                         __mark_reg_not_init(env, regs + regno);
1391                 return;
1392         }
1393         __mark_reg_known_zero(regs + regno);
1394 }
1395
1396 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1397 {
1398         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1399                 const struct bpf_map *map = reg->map_ptr;
1400
1401                 if (map->inner_map_meta) {
1402                         reg->type = CONST_PTR_TO_MAP;
1403                         reg->map_ptr = map->inner_map_meta;
1404                         /* transfer reg's id which is unique for every map_lookup_elem
1405                          * as UID of the inner map.
1406                          */
1407                         if (map_value_has_timer(map->inner_map_meta))
1408                                 reg->map_uid = reg->id;
1409                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1410                         reg->type = PTR_TO_XDP_SOCK;
1411                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1412                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1413                         reg->type = PTR_TO_SOCKET;
1414                 } else {
1415                         reg->type = PTR_TO_MAP_VALUE;
1416                 }
1417                 return;
1418         }
1419
1420         reg->type &= ~PTR_MAYBE_NULL;
1421 }
1422
1423 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1424 {
1425         return type_is_pkt_pointer(reg->type);
1426 }
1427
1428 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1429 {
1430         return reg_is_pkt_pointer(reg) ||
1431                reg->type == PTR_TO_PACKET_END;
1432 }
1433
1434 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1435 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1436                                     enum bpf_reg_type which)
1437 {
1438         /* The register can already have a range from prior markings.
1439          * This is fine as long as it hasn't been advanced from its
1440          * origin.
1441          */
1442         return reg->type == which &&
1443                reg->id == 0 &&
1444                reg->off == 0 &&
1445                tnum_equals_const(reg->var_off, 0);
1446 }
1447
1448 /* Reset the min/max bounds of a register */
1449 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1450 {
1451         reg->smin_value = S64_MIN;
1452         reg->smax_value = S64_MAX;
1453         reg->umin_value = 0;
1454         reg->umax_value = U64_MAX;
1455
1456         reg->s32_min_value = S32_MIN;
1457         reg->s32_max_value = S32_MAX;
1458         reg->u32_min_value = 0;
1459         reg->u32_max_value = U32_MAX;
1460 }
1461
1462 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1463 {
1464         reg->smin_value = S64_MIN;
1465         reg->smax_value = S64_MAX;
1466         reg->umin_value = 0;
1467         reg->umax_value = U64_MAX;
1468 }
1469
1470 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1471 {
1472         reg->s32_min_value = S32_MIN;
1473         reg->s32_max_value = S32_MAX;
1474         reg->u32_min_value = 0;
1475         reg->u32_max_value = U32_MAX;
1476 }
1477
1478 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1479 {
1480         struct tnum var32_off = tnum_subreg(reg->var_off);
1481
1482         /* min signed is max(sign bit) | min(other bits) */
1483         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1484                         var32_off.value | (var32_off.mask & S32_MIN));
1485         /* max signed is min(sign bit) | max(other bits) */
1486         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1487                         var32_off.value | (var32_off.mask & S32_MAX));
1488         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1489         reg->u32_max_value = min(reg->u32_max_value,
1490                                  (u32)(var32_off.value | var32_off.mask));
1491 }
1492
1493 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1494 {
1495         /* min signed is max(sign bit) | min(other bits) */
1496         reg->smin_value = max_t(s64, reg->smin_value,
1497                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1498         /* max signed is min(sign bit) | max(other bits) */
1499         reg->smax_value = min_t(s64, reg->smax_value,
1500                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1501         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1502         reg->umax_value = min(reg->umax_value,
1503                               reg->var_off.value | reg->var_off.mask);
1504 }
1505
1506 static void __update_reg_bounds(struct bpf_reg_state *reg)
1507 {
1508         __update_reg32_bounds(reg);
1509         __update_reg64_bounds(reg);
1510 }
1511
1512 /* Uses signed min/max values to inform unsigned, and vice-versa */
1513 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1514 {
1515         /* Learn sign from signed bounds.
1516          * If we cannot cross the sign boundary, then signed and unsigned bounds
1517          * are the same, so combine.  This works even in the negative case, e.g.
1518          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1519          */
1520         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1521                 reg->s32_min_value = reg->u32_min_value =
1522                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1523                 reg->s32_max_value = reg->u32_max_value =
1524                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1525                 return;
1526         }
1527         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1528          * boundary, so we must be careful.
1529          */
1530         if ((s32)reg->u32_max_value >= 0) {
1531                 /* Positive.  We can't learn anything from the smin, but smax
1532                  * is positive, hence safe.
1533                  */
1534                 reg->s32_min_value = reg->u32_min_value;
1535                 reg->s32_max_value = reg->u32_max_value =
1536                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1537         } else if ((s32)reg->u32_min_value < 0) {
1538                 /* Negative.  We can't learn anything from the smax, but smin
1539                  * is negative, hence safe.
1540                  */
1541                 reg->s32_min_value = reg->u32_min_value =
1542                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1543                 reg->s32_max_value = reg->u32_max_value;
1544         }
1545 }
1546
1547 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1548 {
1549         /* Learn sign from signed bounds.
1550          * If we cannot cross the sign boundary, then signed and unsigned bounds
1551          * are the same, so combine.  This works even in the negative case, e.g.
1552          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1553          */
1554         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1555                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1556                                                           reg->umin_value);
1557                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1558                                                           reg->umax_value);
1559                 return;
1560         }
1561         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1562          * boundary, so we must be careful.
1563          */
1564         if ((s64)reg->umax_value >= 0) {
1565                 /* Positive.  We can't learn anything from the smin, but smax
1566                  * is positive, hence safe.
1567                  */
1568                 reg->smin_value = reg->umin_value;
1569                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1570                                                           reg->umax_value);
1571         } else if ((s64)reg->umin_value < 0) {
1572                 /* Negative.  We can't learn anything from the smax, but smin
1573                  * is negative, hence safe.
1574                  */
1575                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1576                                                           reg->umin_value);
1577                 reg->smax_value = reg->umax_value;
1578         }
1579 }
1580
1581 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1582 {
1583         __reg32_deduce_bounds(reg);
1584         __reg64_deduce_bounds(reg);
1585 }
1586
1587 /* Attempts to improve var_off based on unsigned min/max information */
1588 static void __reg_bound_offset(struct bpf_reg_state *reg)
1589 {
1590         struct tnum var64_off = tnum_intersect(reg->var_off,
1591                                                tnum_range(reg->umin_value,
1592                                                           reg->umax_value));
1593         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1594                                                 tnum_range(reg->u32_min_value,
1595                                                            reg->u32_max_value));
1596
1597         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1598 }
1599
1600 static void reg_bounds_sync(struct bpf_reg_state *reg)
1601 {
1602         /* We might have learned new bounds from the var_off. */
1603         __update_reg_bounds(reg);
1604         /* We might have learned something about the sign bit. */
1605         __reg_deduce_bounds(reg);
1606         /* We might have learned some bits from the bounds. */
1607         __reg_bound_offset(reg);
1608         /* Intersecting with the old var_off might have improved our bounds
1609          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1610          * then new var_off is (0; 0x7f...fc) which improves our umax.
1611          */
1612         __update_reg_bounds(reg);
1613 }
1614
1615 static bool __reg32_bound_s64(s32 a)
1616 {
1617         return a >= 0 && a <= S32_MAX;
1618 }
1619
1620 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1621 {
1622         reg->umin_value = reg->u32_min_value;
1623         reg->umax_value = reg->u32_max_value;
1624
1625         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1626          * be positive otherwise set to worse case bounds and refine later
1627          * from tnum.
1628          */
1629         if (__reg32_bound_s64(reg->s32_min_value) &&
1630             __reg32_bound_s64(reg->s32_max_value)) {
1631                 reg->smin_value = reg->s32_min_value;
1632                 reg->smax_value = reg->s32_max_value;
1633         } else {
1634                 reg->smin_value = 0;
1635                 reg->smax_value = U32_MAX;
1636         }
1637 }
1638
1639 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1640 {
1641         /* special case when 64-bit register has upper 32-bit register
1642          * zeroed. Typically happens after zext or <<32, >>32 sequence
1643          * allowing us to use 32-bit bounds directly,
1644          */
1645         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1646                 __reg_assign_32_into_64(reg);
1647         } else {
1648                 /* Otherwise the best we can do is push lower 32bit known and
1649                  * unknown bits into register (var_off set from jmp logic)
1650                  * then learn as much as possible from the 64-bit tnum
1651                  * known and unknown bits. The previous smin/smax bounds are
1652                  * invalid here because of jmp32 compare so mark them unknown
1653                  * so they do not impact tnum bounds calculation.
1654                  */
1655                 __mark_reg64_unbounded(reg);
1656         }
1657         reg_bounds_sync(reg);
1658 }
1659
1660 static bool __reg64_bound_s32(s64 a)
1661 {
1662         return a >= S32_MIN && a <= S32_MAX;
1663 }
1664
1665 static bool __reg64_bound_u32(u64 a)
1666 {
1667         return a >= U32_MIN && a <= U32_MAX;
1668 }
1669
1670 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1671 {
1672         __mark_reg32_unbounded(reg);
1673         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1674                 reg->s32_min_value = (s32)reg->smin_value;
1675                 reg->s32_max_value = (s32)reg->smax_value;
1676         }
1677         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1678                 reg->u32_min_value = (u32)reg->umin_value;
1679                 reg->u32_max_value = (u32)reg->umax_value;
1680         }
1681         reg_bounds_sync(reg);
1682 }
1683
1684 /* Mark a register as having a completely unknown (scalar) value. */
1685 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1686                                struct bpf_reg_state *reg)
1687 {
1688         /*
1689          * Clear type, id, off, and union(map_ptr, range) and
1690          * padding between 'type' and union
1691          */
1692         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1693         reg->type = SCALAR_VALUE;
1694         reg->var_off = tnum_unknown;
1695         reg->frameno = 0;
1696         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1697         __mark_reg_unbounded(reg);
1698 }
1699
1700 static void mark_reg_unknown(struct bpf_verifier_env *env,
1701                              struct bpf_reg_state *regs, u32 regno)
1702 {
1703         if (WARN_ON(regno >= MAX_BPF_REG)) {
1704                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1705                 /* Something bad happened, let's kill all regs except FP */
1706                 for (regno = 0; regno < BPF_REG_FP; regno++)
1707                         __mark_reg_not_init(env, regs + regno);
1708                 return;
1709         }
1710         __mark_reg_unknown(env, regs + regno);
1711 }
1712
1713 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1714                                 struct bpf_reg_state *reg)
1715 {
1716         __mark_reg_unknown(env, reg);
1717         reg->type = NOT_INIT;
1718 }
1719
1720 static void mark_reg_not_init(struct bpf_verifier_env *env,
1721                               struct bpf_reg_state *regs, u32 regno)
1722 {
1723         if (WARN_ON(regno >= MAX_BPF_REG)) {
1724                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1725                 /* Something bad happened, let's kill all regs except FP */
1726                 for (regno = 0; regno < BPF_REG_FP; regno++)
1727                         __mark_reg_not_init(env, regs + regno);
1728                 return;
1729         }
1730         __mark_reg_not_init(env, regs + regno);
1731 }
1732
1733 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1734                             struct bpf_reg_state *regs, u32 regno,
1735                             enum bpf_reg_type reg_type,
1736                             struct btf *btf, u32 btf_id,
1737                             enum bpf_type_flag flag)
1738 {
1739         if (reg_type == SCALAR_VALUE) {
1740                 mark_reg_unknown(env, regs, regno);
1741                 return;
1742         }
1743         mark_reg_known_zero(env, regs, regno);
1744         regs[regno].type = PTR_TO_BTF_ID | flag;
1745         regs[regno].btf = btf;
1746         regs[regno].btf_id = btf_id;
1747 }
1748
1749 #define DEF_NOT_SUBREG  (0)
1750 static void init_reg_state(struct bpf_verifier_env *env,
1751                            struct bpf_func_state *state)
1752 {
1753         struct bpf_reg_state *regs = state->regs;
1754         int i;
1755
1756         for (i = 0; i < MAX_BPF_REG; i++) {
1757                 mark_reg_not_init(env, regs, i);
1758                 regs[i].live = REG_LIVE_NONE;
1759                 regs[i].parent = NULL;
1760                 regs[i].subreg_def = DEF_NOT_SUBREG;
1761         }
1762
1763         /* frame pointer */
1764         regs[BPF_REG_FP].type = PTR_TO_STACK;
1765         mark_reg_known_zero(env, regs, BPF_REG_FP);
1766         regs[BPF_REG_FP].frameno = state->frameno;
1767 }
1768
1769 #define BPF_MAIN_FUNC (-1)
1770 static void init_func_state(struct bpf_verifier_env *env,
1771                             struct bpf_func_state *state,
1772                             int callsite, int frameno, int subprogno)
1773 {
1774         state->callsite = callsite;
1775         state->frameno = frameno;
1776         state->subprogno = subprogno;
1777         state->callback_ret_range = tnum_range(0, 0);
1778         init_reg_state(env, state);
1779         mark_verifier_state_scratched(env);
1780 }
1781
1782 /* Similar to push_stack(), but for async callbacks */
1783 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1784                                                 int insn_idx, int prev_insn_idx,
1785                                                 int subprog)
1786 {
1787         struct bpf_verifier_stack_elem *elem;
1788         struct bpf_func_state *frame;
1789
1790         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1791         if (!elem)
1792                 goto err;
1793
1794         elem->insn_idx = insn_idx;
1795         elem->prev_insn_idx = prev_insn_idx;
1796         elem->next = env->head;
1797         elem->log_pos = env->log.len_used;
1798         env->head = elem;
1799         env->stack_size++;
1800         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1801                 verbose(env,
1802                         "The sequence of %d jumps is too complex for async cb.\n",
1803                         env->stack_size);
1804                 goto err;
1805         }
1806         /* Unlike push_stack() do not copy_verifier_state().
1807          * The caller state doesn't matter.
1808          * This is async callback. It starts in a fresh stack.
1809          * Initialize it similar to do_check_common().
1810          */
1811         elem->st.branches = 1;
1812         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1813         if (!frame)
1814                 goto err;
1815         init_func_state(env, frame,
1816                         BPF_MAIN_FUNC /* callsite */,
1817                         0 /* frameno within this callchain */,
1818                         subprog /* subprog number within this prog */);
1819         elem->st.frame[0] = frame;
1820         return &elem->st;
1821 err:
1822         free_verifier_state(env->cur_state, true);
1823         env->cur_state = NULL;
1824         /* pop all elements and return */
1825         while (!pop_stack(env, NULL, NULL, false));
1826         return NULL;
1827 }
1828
1829
1830 enum reg_arg_type {
1831         SRC_OP,         /* register is used as source operand */
1832         DST_OP,         /* register is used as destination operand */
1833         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1834 };
1835
1836 static int cmp_subprogs(const void *a, const void *b)
1837 {
1838         return ((struct bpf_subprog_info *)a)->start -
1839                ((struct bpf_subprog_info *)b)->start;
1840 }
1841
1842 static int find_subprog(struct bpf_verifier_env *env, int off)
1843 {
1844         struct bpf_subprog_info *p;
1845
1846         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1847                     sizeof(env->subprog_info[0]), cmp_subprogs);
1848         if (!p)
1849                 return -ENOENT;
1850         return p - env->subprog_info;
1851
1852 }
1853
1854 static int add_subprog(struct bpf_verifier_env *env, int off)
1855 {
1856         int insn_cnt = env->prog->len;
1857         int ret;
1858
1859         if (off >= insn_cnt || off < 0) {
1860                 verbose(env, "call to invalid destination\n");
1861                 return -EINVAL;
1862         }
1863         ret = find_subprog(env, off);
1864         if (ret >= 0)
1865                 return ret;
1866         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1867                 verbose(env, "too many subprograms\n");
1868                 return -E2BIG;
1869         }
1870         /* determine subprog starts. The end is one before the next starts */
1871         env->subprog_info[env->subprog_cnt++].start = off;
1872         sort(env->subprog_info, env->subprog_cnt,
1873              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1874         return env->subprog_cnt - 1;
1875 }
1876
1877 #define MAX_KFUNC_DESCS 256
1878 #define MAX_KFUNC_BTFS  256
1879
1880 struct bpf_kfunc_desc {
1881         struct btf_func_model func_model;
1882         u32 func_id;
1883         s32 imm;
1884         u16 offset;
1885 };
1886
1887 struct bpf_kfunc_btf {
1888         struct btf *btf;
1889         struct module *module;
1890         u16 offset;
1891 };
1892
1893 struct bpf_kfunc_desc_tab {
1894         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1895         u32 nr_descs;
1896 };
1897
1898 struct bpf_kfunc_btf_tab {
1899         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1900         u32 nr_descs;
1901 };
1902
1903 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1904 {
1905         const struct bpf_kfunc_desc *d0 = a;
1906         const struct bpf_kfunc_desc *d1 = b;
1907
1908         /* func_id is not greater than BTF_MAX_TYPE */
1909         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1910 }
1911
1912 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1913 {
1914         const struct bpf_kfunc_btf *d0 = a;
1915         const struct bpf_kfunc_btf *d1 = b;
1916
1917         return d0->offset - d1->offset;
1918 }
1919
1920 static const struct bpf_kfunc_desc *
1921 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1922 {
1923         struct bpf_kfunc_desc desc = {
1924                 .func_id = func_id,
1925                 .offset = offset,
1926         };
1927         struct bpf_kfunc_desc_tab *tab;
1928
1929         tab = prog->aux->kfunc_tab;
1930         return bsearch(&desc, tab->descs, tab->nr_descs,
1931                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1932 }
1933
1934 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1935                                          s16 offset)
1936 {
1937         struct bpf_kfunc_btf kf_btf = { .offset = offset };
1938         struct bpf_kfunc_btf_tab *tab;
1939         struct bpf_kfunc_btf *b;
1940         struct module *mod;
1941         struct btf *btf;
1942         int btf_fd;
1943
1944         tab = env->prog->aux->kfunc_btf_tab;
1945         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1946                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1947         if (!b) {
1948                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1949                         verbose(env, "too many different module BTFs\n");
1950                         return ERR_PTR(-E2BIG);
1951                 }
1952
1953                 if (bpfptr_is_null(env->fd_array)) {
1954                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1955                         return ERR_PTR(-EPROTO);
1956                 }
1957
1958                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1959                                             offset * sizeof(btf_fd),
1960                                             sizeof(btf_fd)))
1961                         return ERR_PTR(-EFAULT);
1962
1963                 btf = btf_get_by_fd(btf_fd);
1964                 if (IS_ERR(btf)) {
1965                         verbose(env, "invalid module BTF fd specified\n");
1966                         return btf;
1967                 }
1968
1969                 if (!btf_is_module(btf)) {
1970                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
1971                         btf_put(btf);
1972                         return ERR_PTR(-EINVAL);
1973                 }
1974
1975                 mod = btf_try_get_module(btf);
1976                 if (!mod) {
1977                         btf_put(btf);
1978                         return ERR_PTR(-ENXIO);
1979                 }
1980
1981                 b = &tab->descs[tab->nr_descs++];
1982                 b->btf = btf;
1983                 b->module = mod;
1984                 b->offset = offset;
1985
1986                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1987                      kfunc_btf_cmp_by_off, NULL);
1988         }
1989         return b->btf;
1990 }
1991
1992 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1993 {
1994         if (!tab)
1995                 return;
1996
1997         while (tab->nr_descs--) {
1998                 module_put(tab->descs[tab->nr_descs].module);
1999                 btf_put(tab->descs[tab->nr_descs].btf);
2000         }
2001         kfree(tab);
2002 }
2003
2004 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2005 {
2006         if (offset) {
2007                 if (offset < 0) {
2008                         /* In the future, this can be allowed to increase limit
2009                          * of fd index into fd_array, interpreted as u16.
2010                          */
2011                         verbose(env, "negative offset disallowed for kernel module function call\n");
2012                         return ERR_PTR(-EINVAL);
2013                 }
2014
2015                 return __find_kfunc_desc_btf(env, offset);
2016         }
2017         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2018 }
2019
2020 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2021 {
2022         const struct btf_type *func, *func_proto;
2023         struct bpf_kfunc_btf_tab *btf_tab;
2024         struct bpf_kfunc_desc_tab *tab;
2025         struct bpf_prog_aux *prog_aux;
2026         struct bpf_kfunc_desc *desc;
2027         const char *func_name;
2028         struct btf *desc_btf;
2029         unsigned long call_imm;
2030         unsigned long addr;
2031         int err;
2032
2033         prog_aux = env->prog->aux;
2034         tab = prog_aux->kfunc_tab;
2035         btf_tab = prog_aux->kfunc_btf_tab;
2036         if (!tab) {
2037                 if (!btf_vmlinux) {
2038                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2039                         return -ENOTSUPP;
2040                 }
2041
2042                 if (!env->prog->jit_requested) {
2043                         verbose(env, "JIT is required for calling kernel function\n");
2044                         return -ENOTSUPP;
2045                 }
2046
2047                 if (!bpf_jit_supports_kfunc_call()) {
2048                         verbose(env, "JIT does not support calling kernel function\n");
2049                         return -ENOTSUPP;
2050                 }
2051
2052                 if (!env->prog->gpl_compatible) {
2053                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2054                         return -EINVAL;
2055                 }
2056
2057                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2058                 if (!tab)
2059                         return -ENOMEM;
2060                 prog_aux->kfunc_tab = tab;
2061         }
2062
2063         /* func_id == 0 is always invalid, but instead of returning an error, be
2064          * conservative and wait until the code elimination pass before returning
2065          * error, so that invalid calls that get pruned out can be in BPF programs
2066          * loaded from userspace.  It is also required that offset be untouched
2067          * for such calls.
2068          */
2069         if (!func_id && !offset)
2070                 return 0;
2071
2072         if (!btf_tab && offset) {
2073                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2074                 if (!btf_tab)
2075                         return -ENOMEM;
2076                 prog_aux->kfunc_btf_tab = btf_tab;
2077         }
2078
2079         desc_btf = find_kfunc_desc_btf(env, offset);
2080         if (IS_ERR(desc_btf)) {
2081                 verbose(env, "failed to find BTF for kernel function\n");
2082                 return PTR_ERR(desc_btf);
2083         }
2084
2085         if (find_kfunc_desc(env->prog, func_id, offset))
2086                 return 0;
2087
2088         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2089                 verbose(env, "too many different kernel function calls\n");
2090                 return -E2BIG;
2091         }
2092
2093         func = btf_type_by_id(desc_btf, func_id);
2094         if (!func || !btf_type_is_func(func)) {
2095                 verbose(env, "kernel btf_id %u is not a function\n",
2096                         func_id);
2097                 return -EINVAL;
2098         }
2099         func_proto = btf_type_by_id(desc_btf, func->type);
2100         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2101                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2102                         func_id);
2103                 return -EINVAL;
2104         }
2105
2106         func_name = btf_name_by_offset(desc_btf, func->name_off);
2107         addr = kallsyms_lookup_name(func_name);
2108         if (!addr) {
2109                 verbose(env, "cannot find address for kernel function %s\n",
2110                         func_name);
2111                 return -EINVAL;
2112         }
2113
2114         call_imm = BPF_CALL_IMM(addr);
2115         /* Check whether or not the relative offset overflows desc->imm */
2116         if ((unsigned long)(s32)call_imm != call_imm) {
2117                 verbose(env, "address of kernel function %s is out of range\n",
2118                         func_name);
2119                 return -EINVAL;
2120         }
2121
2122         desc = &tab->descs[tab->nr_descs++];
2123         desc->func_id = func_id;
2124         desc->imm = call_imm;
2125         desc->offset = offset;
2126         err = btf_distill_func_proto(&env->log, desc_btf,
2127                                      func_proto, func_name,
2128                                      &desc->func_model);
2129         if (!err)
2130                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2131                      kfunc_desc_cmp_by_id_off, NULL);
2132         return err;
2133 }
2134
2135 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2136 {
2137         const struct bpf_kfunc_desc *d0 = a;
2138         const struct bpf_kfunc_desc *d1 = b;
2139
2140         if (d0->imm > d1->imm)
2141                 return 1;
2142         else if (d0->imm < d1->imm)
2143                 return -1;
2144         return 0;
2145 }
2146
2147 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2148 {
2149         struct bpf_kfunc_desc_tab *tab;
2150
2151         tab = prog->aux->kfunc_tab;
2152         if (!tab)
2153                 return;
2154
2155         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2156              kfunc_desc_cmp_by_imm, NULL);
2157 }
2158
2159 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2160 {
2161         return !!prog->aux->kfunc_tab;
2162 }
2163
2164 const struct btf_func_model *
2165 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2166                          const struct bpf_insn *insn)
2167 {
2168         const struct bpf_kfunc_desc desc = {
2169                 .imm = insn->imm,
2170         };
2171         const struct bpf_kfunc_desc *res;
2172         struct bpf_kfunc_desc_tab *tab;
2173
2174         tab = prog->aux->kfunc_tab;
2175         res = bsearch(&desc, tab->descs, tab->nr_descs,
2176                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2177
2178         return res ? &res->func_model : NULL;
2179 }
2180
2181 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2182 {
2183         struct bpf_subprog_info *subprog = env->subprog_info;
2184         struct bpf_insn *insn = env->prog->insnsi;
2185         int i, ret, insn_cnt = env->prog->len;
2186
2187         /* Add entry function. */
2188         ret = add_subprog(env, 0);
2189         if (ret)
2190                 return ret;
2191
2192         for (i = 0; i < insn_cnt; i++, insn++) {
2193                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2194                     !bpf_pseudo_kfunc_call(insn))
2195                         continue;
2196
2197                 if (!env->bpf_capable) {
2198                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2199                         return -EPERM;
2200                 }
2201
2202                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2203                         ret = add_subprog(env, i + insn->imm + 1);
2204                 else
2205                         ret = add_kfunc_call(env, insn->imm, insn->off);
2206
2207                 if (ret < 0)
2208                         return ret;
2209         }
2210
2211         /* Add a fake 'exit' subprog which could simplify subprog iteration
2212          * logic. 'subprog_cnt' should not be increased.
2213          */
2214         subprog[env->subprog_cnt].start = insn_cnt;
2215
2216         if (env->log.level & BPF_LOG_LEVEL2)
2217                 for (i = 0; i < env->subprog_cnt; i++)
2218                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2219
2220         return 0;
2221 }
2222
2223 static int check_subprogs(struct bpf_verifier_env *env)
2224 {
2225         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2226         struct bpf_subprog_info *subprog = env->subprog_info;
2227         struct bpf_insn *insn = env->prog->insnsi;
2228         int insn_cnt = env->prog->len;
2229
2230         /* now check that all jumps are within the same subprog */
2231         subprog_start = subprog[cur_subprog].start;
2232         subprog_end = subprog[cur_subprog + 1].start;
2233         for (i = 0; i < insn_cnt; i++) {
2234                 u8 code = insn[i].code;
2235
2236                 if (code == (BPF_JMP | BPF_CALL) &&
2237                     insn[i].imm == BPF_FUNC_tail_call &&
2238                     insn[i].src_reg != BPF_PSEUDO_CALL)
2239                         subprog[cur_subprog].has_tail_call = true;
2240                 if (BPF_CLASS(code) == BPF_LD &&
2241                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2242                         subprog[cur_subprog].has_ld_abs = true;
2243                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2244                         goto next;
2245                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2246                         goto next;
2247                 off = i + insn[i].off + 1;
2248                 if (off < subprog_start || off >= subprog_end) {
2249                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2250                         return -EINVAL;
2251                 }
2252 next:
2253                 if (i == subprog_end - 1) {
2254                         /* to avoid fall-through from one subprog into another
2255                          * the last insn of the subprog should be either exit
2256                          * or unconditional jump back
2257                          */
2258                         if (code != (BPF_JMP | BPF_EXIT) &&
2259                             code != (BPF_JMP | BPF_JA)) {
2260                                 verbose(env, "last insn is not an exit or jmp\n");
2261                                 return -EINVAL;
2262                         }
2263                         subprog_start = subprog_end;
2264                         cur_subprog++;
2265                         if (cur_subprog < env->subprog_cnt)
2266                                 subprog_end = subprog[cur_subprog + 1].start;
2267                 }
2268         }
2269         return 0;
2270 }
2271
2272 /* Parentage chain of this register (or stack slot) should take care of all
2273  * issues like callee-saved registers, stack slot allocation time, etc.
2274  */
2275 static int mark_reg_read(struct bpf_verifier_env *env,
2276                          const struct bpf_reg_state *state,
2277                          struct bpf_reg_state *parent, u8 flag)
2278 {
2279         bool writes = parent == state->parent; /* Observe write marks */
2280         int cnt = 0;
2281
2282         while (parent) {
2283                 /* if read wasn't screened by an earlier write ... */
2284                 if (writes && state->live & REG_LIVE_WRITTEN)
2285                         break;
2286                 if (parent->live & REG_LIVE_DONE) {
2287                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2288                                 reg_type_str(env, parent->type),
2289                                 parent->var_off.value, parent->off);
2290                         return -EFAULT;
2291                 }
2292                 /* The first condition is more likely to be true than the
2293                  * second, checked it first.
2294                  */
2295                 if ((parent->live & REG_LIVE_READ) == flag ||
2296                     parent->live & REG_LIVE_READ64)
2297                         /* The parentage chain never changes and
2298                          * this parent was already marked as LIVE_READ.
2299                          * There is no need to keep walking the chain again and
2300                          * keep re-marking all parents as LIVE_READ.
2301                          * This case happens when the same register is read
2302                          * multiple times without writes into it in-between.
2303                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2304                          * then no need to set the weak REG_LIVE_READ32.
2305                          */
2306                         break;
2307                 /* ... then we depend on parent's value */
2308                 parent->live |= flag;
2309                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2310                 if (flag == REG_LIVE_READ64)
2311                         parent->live &= ~REG_LIVE_READ32;
2312                 state = parent;
2313                 parent = state->parent;
2314                 writes = true;
2315                 cnt++;
2316         }
2317
2318         if (env->longest_mark_read_walk < cnt)
2319                 env->longest_mark_read_walk = cnt;
2320         return 0;
2321 }
2322
2323 /* This function is supposed to be used by the following 32-bit optimization
2324  * code only. It returns TRUE if the source or destination register operates
2325  * on 64-bit, otherwise return FALSE.
2326  */
2327 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2328                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2329 {
2330         u8 code, class, op;
2331
2332         code = insn->code;
2333         class = BPF_CLASS(code);
2334         op = BPF_OP(code);
2335         if (class == BPF_JMP) {
2336                 /* BPF_EXIT for "main" will reach here. Return TRUE
2337                  * conservatively.
2338                  */
2339                 if (op == BPF_EXIT)
2340                         return true;
2341                 if (op == BPF_CALL) {
2342                         /* BPF to BPF call will reach here because of marking
2343                          * caller saved clobber with DST_OP_NO_MARK for which we
2344                          * don't care the register def because they are anyway
2345                          * marked as NOT_INIT already.
2346                          */
2347                         if (insn->src_reg == BPF_PSEUDO_CALL)
2348                                 return false;
2349                         /* Helper call will reach here because of arg type
2350                          * check, conservatively return TRUE.
2351                          */
2352                         if (t == SRC_OP)
2353                                 return true;
2354
2355                         return false;
2356                 }
2357         }
2358
2359         if (class == BPF_ALU64 || class == BPF_JMP ||
2360             /* BPF_END always use BPF_ALU class. */
2361             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2362                 return true;
2363
2364         if (class == BPF_ALU || class == BPF_JMP32)
2365                 return false;
2366
2367         if (class == BPF_LDX) {
2368                 if (t != SRC_OP)
2369                         return BPF_SIZE(code) == BPF_DW;
2370                 /* LDX source must be ptr. */
2371                 return true;
2372         }
2373
2374         if (class == BPF_STX) {
2375                 /* BPF_STX (including atomic variants) has multiple source
2376                  * operands, one of which is a ptr. Check whether the caller is
2377                  * asking about it.
2378                  */
2379                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2380                         return true;
2381                 return BPF_SIZE(code) == BPF_DW;
2382         }
2383
2384         if (class == BPF_LD) {
2385                 u8 mode = BPF_MODE(code);
2386
2387                 /* LD_IMM64 */
2388                 if (mode == BPF_IMM)
2389                         return true;
2390
2391                 /* Both LD_IND and LD_ABS return 32-bit data. */
2392                 if (t != SRC_OP)
2393                         return  false;
2394
2395                 /* Implicit ctx ptr. */
2396                 if (regno == BPF_REG_6)
2397                         return true;
2398
2399                 /* Explicit source could be any width. */
2400                 return true;
2401         }
2402
2403         if (class == BPF_ST)
2404                 /* The only source register for BPF_ST is a ptr. */
2405                 return true;
2406
2407         /* Conservatively return true at default. */
2408         return true;
2409 }
2410
2411 /* Return the regno defined by the insn, or -1. */
2412 static int insn_def_regno(const struct bpf_insn *insn)
2413 {
2414         switch (BPF_CLASS(insn->code)) {
2415         case BPF_JMP:
2416         case BPF_JMP32:
2417         case BPF_ST:
2418                 return -1;
2419         case BPF_STX:
2420                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2421                     (insn->imm & BPF_FETCH)) {
2422                         if (insn->imm == BPF_CMPXCHG)
2423                                 return BPF_REG_0;
2424                         else
2425                                 return insn->src_reg;
2426                 } else {
2427                         return -1;
2428                 }
2429         default:
2430                 return insn->dst_reg;
2431         }
2432 }
2433
2434 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2435 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2436 {
2437         int dst_reg = insn_def_regno(insn);
2438
2439         if (dst_reg == -1)
2440                 return false;
2441
2442         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2443 }
2444
2445 static void mark_insn_zext(struct bpf_verifier_env *env,
2446                            struct bpf_reg_state *reg)
2447 {
2448         s32 def_idx = reg->subreg_def;
2449
2450         if (def_idx == DEF_NOT_SUBREG)
2451                 return;
2452
2453         env->insn_aux_data[def_idx - 1].zext_dst = true;
2454         /* The dst will be zero extended, so won't be sub-register anymore. */
2455         reg->subreg_def = DEF_NOT_SUBREG;
2456 }
2457
2458 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2459                          enum reg_arg_type t)
2460 {
2461         struct bpf_verifier_state *vstate = env->cur_state;
2462         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2463         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2464         struct bpf_reg_state *reg, *regs = state->regs;
2465         bool rw64;
2466
2467         if (regno >= MAX_BPF_REG) {
2468                 verbose(env, "R%d is invalid\n", regno);
2469                 return -EINVAL;
2470         }
2471
2472         mark_reg_scratched(env, regno);
2473
2474         reg = &regs[regno];
2475         rw64 = is_reg64(env, insn, regno, reg, t);
2476         if (t == SRC_OP) {
2477                 /* check whether register used as source operand can be read */
2478                 if (reg->type == NOT_INIT) {
2479                         verbose(env, "R%d !read_ok\n", regno);
2480                         return -EACCES;
2481                 }
2482                 /* We don't need to worry about FP liveness because it's read-only */
2483                 if (regno == BPF_REG_FP)
2484                         return 0;
2485
2486                 if (rw64)
2487                         mark_insn_zext(env, reg);
2488
2489                 return mark_reg_read(env, reg, reg->parent,
2490                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2491         } else {
2492                 /* check whether register used as dest operand can be written to */
2493                 if (regno == BPF_REG_FP) {
2494                         verbose(env, "frame pointer is read only\n");
2495                         return -EACCES;
2496                 }
2497                 reg->live |= REG_LIVE_WRITTEN;
2498                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2499                 if (t == DST_OP)
2500                         mark_reg_unknown(env, regs, regno);
2501         }
2502         return 0;
2503 }
2504
2505 /* for any branch, call, exit record the history of jmps in the given state */
2506 static int push_jmp_history(struct bpf_verifier_env *env,
2507                             struct bpf_verifier_state *cur)
2508 {
2509         u32 cnt = cur->jmp_history_cnt;
2510         struct bpf_idx_pair *p;
2511         size_t alloc_size;
2512
2513         cnt++;
2514         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2515         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2516         if (!p)
2517                 return -ENOMEM;
2518         p[cnt - 1].idx = env->insn_idx;
2519         p[cnt - 1].prev_idx = env->prev_insn_idx;
2520         cur->jmp_history = p;
2521         cur->jmp_history_cnt = cnt;
2522         return 0;
2523 }
2524
2525 /* Backtrack one insn at a time. If idx is not at the top of recorded
2526  * history then previous instruction came from straight line execution.
2527  */
2528 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2529                              u32 *history)
2530 {
2531         u32 cnt = *history;
2532
2533         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2534                 i = st->jmp_history[cnt - 1].prev_idx;
2535                 (*history)--;
2536         } else {
2537                 i--;
2538         }
2539         return i;
2540 }
2541
2542 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2543 {
2544         const struct btf_type *func;
2545         struct btf *desc_btf;
2546
2547         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2548                 return NULL;
2549
2550         desc_btf = find_kfunc_desc_btf(data, insn->off);
2551         if (IS_ERR(desc_btf))
2552                 return "<error>";
2553
2554         func = btf_type_by_id(desc_btf, insn->imm);
2555         return btf_name_by_offset(desc_btf, func->name_off);
2556 }
2557
2558 /* For given verifier state backtrack_insn() is called from the last insn to
2559  * the first insn. Its purpose is to compute a bitmask of registers and
2560  * stack slots that needs precision in the parent verifier state.
2561  */
2562 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2563                           u32 *reg_mask, u64 *stack_mask)
2564 {
2565         const struct bpf_insn_cbs cbs = {
2566                 .cb_call        = disasm_kfunc_name,
2567                 .cb_print       = verbose,
2568                 .private_data   = env,
2569         };
2570         struct bpf_insn *insn = env->prog->insnsi + idx;
2571         u8 class = BPF_CLASS(insn->code);
2572         u8 opcode = BPF_OP(insn->code);
2573         u8 mode = BPF_MODE(insn->code);
2574         u32 dreg = 1u << insn->dst_reg;
2575         u32 sreg = 1u << insn->src_reg;
2576         u32 spi;
2577
2578         if (insn->code == 0)
2579                 return 0;
2580         if (env->log.level & BPF_LOG_LEVEL2) {
2581                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2582                 verbose(env, "%d: ", idx);
2583                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2584         }
2585
2586         if (class == BPF_ALU || class == BPF_ALU64) {
2587                 if (!(*reg_mask & dreg))
2588                         return 0;
2589                 if (opcode == BPF_MOV) {
2590                         if (BPF_SRC(insn->code) == BPF_X) {
2591                                 /* dreg = sreg
2592                                  * dreg needs precision after this insn
2593                                  * sreg needs precision before this insn
2594                                  */
2595                                 *reg_mask &= ~dreg;
2596                                 *reg_mask |= sreg;
2597                         } else {
2598                                 /* dreg = K
2599                                  * dreg needs precision after this insn.
2600                                  * Corresponding register is already marked
2601                                  * as precise=true in this verifier state.
2602                                  * No further markings in parent are necessary
2603                                  */
2604                                 *reg_mask &= ~dreg;
2605                         }
2606                 } else {
2607                         if (BPF_SRC(insn->code) == BPF_X) {
2608                                 /* dreg += sreg
2609                                  * both dreg and sreg need precision
2610                                  * before this insn
2611                                  */
2612                                 *reg_mask |= sreg;
2613                         } /* else dreg += K
2614                            * dreg still needs precision before this insn
2615                            */
2616                 }
2617         } else if (class == BPF_LDX) {
2618                 if (!(*reg_mask & dreg))
2619                         return 0;
2620                 *reg_mask &= ~dreg;
2621
2622                 /* scalars can only be spilled into stack w/o losing precision.
2623                  * Load from any other memory can be zero extended.
2624                  * The desire to keep that precision is already indicated
2625                  * by 'precise' mark in corresponding register of this state.
2626                  * No further tracking necessary.
2627                  */
2628                 if (insn->src_reg != BPF_REG_FP)
2629                         return 0;
2630
2631                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2632                  * that [fp - off] slot contains scalar that needs to be
2633                  * tracked with precision
2634                  */
2635                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2636                 if (spi >= 64) {
2637                         verbose(env, "BUG spi %d\n", spi);
2638                         WARN_ONCE(1, "verifier backtracking bug");
2639                         return -EFAULT;
2640                 }
2641                 *stack_mask |= 1ull << spi;
2642         } else if (class == BPF_STX || class == BPF_ST) {
2643                 if (*reg_mask & dreg)
2644                         /* stx & st shouldn't be using _scalar_ dst_reg
2645                          * to access memory. It means backtracking
2646                          * encountered a case of pointer subtraction.
2647                          */
2648                         return -ENOTSUPP;
2649                 /* scalars can only be spilled into stack */
2650                 if (insn->dst_reg != BPF_REG_FP)
2651                         return 0;
2652                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2653                 if (spi >= 64) {
2654                         verbose(env, "BUG spi %d\n", spi);
2655                         WARN_ONCE(1, "verifier backtracking bug");
2656                         return -EFAULT;
2657                 }
2658                 if (!(*stack_mask & (1ull << spi)))
2659                         return 0;
2660                 *stack_mask &= ~(1ull << spi);
2661                 if (class == BPF_STX)
2662                         *reg_mask |= sreg;
2663         } else if (class == BPF_JMP || class == BPF_JMP32) {
2664                 if (opcode == BPF_CALL) {
2665                         if (insn->src_reg == BPF_PSEUDO_CALL)
2666                                 return -ENOTSUPP;
2667                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
2668                          * catch this error later. Make backtracking conservative
2669                          * with ENOTSUPP.
2670                          */
2671                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2672                                 return -ENOTSUPP;
2673                         /* regular helper call sets R0 */
2674                         *reg_mask &= ~1;
2675                         if (*reg_mask & 0x3f) {
2676                                 /* if backtracing was looking for registers R1-R5
2677                                  * they should have been found already.
2678                                  */
2679                                 verbose(env, "BUG regs %x\n", *reg_mask);
2680                                 WARN_ONCE(1, "verifier backtracking bug");
2681                                 return -EFAULT;
2682                         }
2683                 } else if (opcode == BPF_EXIT) {
2684                         return -ENOTSUPP;
2685                 } 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 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3065  * stack boundary and alignment are checked in check_mem_access()
3066  */
3067 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3068                                        /* stack frame we're writing to */
3069                                        struct bpf_func_state *state,
3070                                        int off, int size, int value_regno,
3071                                        int insn_idx)
3072 {
3073         struct bpf_func_state *cur; /* state of the current function */
3074         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3075         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3076         struct bpf_reg_state *reg = NULL;
3077
3078         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3079         if (err)
3080                 return err;
3081         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3082          * so it's aligned access and [off, off + size) are within stack limits
3083          */
3084         if (!env->allow_ptr_leaks &&
3085             state->stack[spi].slot_type[0] == STACK_SPILL &&
3086             size != BPF_REG_SIZE) {
3087                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3088                 return -EACCES;
3089         }
3090
3091         cur = env->cur_state->frame[env->cur_state->curframe];
3092         if (value_regno >= 0)
3093                 reg = &cur->regs[value_regno];
3094         if (!env->bypass_spec_v4) {
3095                 bool sanitize = reg && is_spillable_regtype(reg->type);
3096
3097                 for (i = 0; i < size; i++) {
3098                         u8 type = state->stack[spi].slot_type[i];
3099
3100                         if (type != STACK_MISC && type != STACK_ZERO) {
3101                                 sanitize = true;
3102                                 break;
3103                         }
3104                 }
3105
3106                 if (sanitize)
3107                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3108         }
3109
3110         mark_stack_slot_scratched(env, spi);
3111         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3112             !register_is_null(reg) && env->bpf_capable) {
3113                 if (dst_reg != BPF_REG_FP) {
3114                         /* The backtracking logic can only recognize explicit
3115                          * stack slot address like [fp - 8]. Other spill of
3116                          * scalar via different register has to be conservative.
3117                          * Backtrack from here and mark all registers as precise
3118                          * that contributed into 'reg' being a constant.
3119                          */
3120                         err = mark_chain_precision(env, value_regno);
3121                         if (err)
3122                                 return err;
3123                 }
3124                 save_register_state(state, spi, reg, size);
3125         } else if (reg && is_spillable_regtype(reg->type)) {
3126                 /* register containing pointer is being spilled into stack */
3127                 if (size != BPF_REG_SIZE) {
3128                         verbose_linfo(env, insn_idx, "; ");
3129                         verbose(env, "invalid size of register spill\n");
3130                         return -EACCES;
3131                 }
3132                 if (state != cur && reg->type == PTR_TO_STACK) {
3133                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3134                         return -EINVAL;
3135                 }
3136                 save_register_state(state, spi, reg, size);
3137         } else {
3138                 u8 type = STACK_MISC;
3139
3140                 /* regular write of data into stack destroys any spilled ptr */
3141                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3142                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3143                 if (is_spilled_reg(&state->stack[spi]))
3144                         for (i = 0; i < BPF_REG_SIZE; i++)
3145                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3146
3147                 /* only mark the slot as written if all 8 bytes were written
3148                  * otherwise read propagation may incorrectly stop too soon
3149                  * when stack slots are partially written.
3150                  * This heuristic means that read propagation will be
3151                  * conservative, since it will add reg_live_read marks
3152                  * to stack slots all the way to first state when programs
3153                  * writes+reads less than 8 bytes
3154                  */
3155                 if (size == BPF_REG_SIZE)
3156                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3157
3158                 /* when we zero initialize stack slots mark them as such */
3159                 if (reg && register_is_null(reg)) {
3160                         /* backtracking doesn't work for STACK_ZERO yet. */
3161                         err = mark_chain_precision(env, value_regno);
3162                         if (err)
3163                                 return err;
3164                         type = STACK_ZERO;
3165                 }
3166
3167                 /* Mark slots affected by this stack write. */
3168                 for (i = 0; i < size; i++)
3169                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3170                                 type;
3171         }
3172         return 0;
3173 }
3174
3175 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3176  * known to contain a variable offset.
3177  * This function checks whether the write is permitted and conservatively
3178  * tracks the effects of the write, considering that each stack slot in the
3179  * dynamic range is potentially written to.
3180  *
3181  * 'off' includes 'regno->off'.
3182  * 'value_regno' can be -1, meaning that an unknown value is being written to
3183  * the stack.
3184  *
3185  * Spilled pointers in range are not marked as written because we don't know
3186  * what's going to be actually written. This means that read propagation for
3187  * future reads cannot be terminated by this write.
3188  *
3189  * For privileged programs, uninitialized stack slots are considered
3190  * initialized by this write (even though we don't know exactly what offsets
3191  * are going to be written to). The idea is that we don't want the verifier to
3192  * reject future reads that access slots written to through variable offsets.
3193  */
3194 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3195                                      /* func where register points to */
3196                                      struct bpf_func_state *state,
3197                                      int ptr_regno, int off, int size,
3198                                      int value_regno, int insn_idx)
3199 {
3200         struct bpf_func_state *cur; /* state of the current function */
3201         int min_off, max_off;
3202         int i, err;
3203         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3204         bool writing_zero = false;
3205         /* set if the fact that we're writing a zero is used to let any
3206          * stack slots remain STACK_ZERO
3207          */
3208         bool zero_used = false;
3209
3210         cur = env->cur_state->frame[env->cur_state->curframe];
3211         ptr_reg = &cur->regs[ptr_regno];
3212         min_off = ptr_reg->smin_value + off;
3213         max_off = ptr_reg->smax_value + off + size;
3214         if (value_regno >= 0)
3215                 value_reg = &cur->regs[value_regno];
3216         if (value_reg && register_is_null(value_reg))
3217                 writing_zero = true;
3218
3219         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3220         if (err)
3221                 return err;
3222
3223
3224         /* Variable offset writes destroy any spilled pointers in range. */
3225         for (i = min_off; i < max_off; i++) {
3226                 u8 new_type, *stype;
3227                 int slot, spi;
3228
3229                 slot = -i - 1;
3230                 spi = slot / BPF_REG_SIZE;
3231                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3232                 mark_stack_slot_scratched(env, spi);
3233
3234                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3235                         /* Reject the write if range we may write to has not
3236                          * been initialized beforehand. If we didn't reject
3237                          * here, the ptr status would be erased below (even
3238                          * though not all slots are actually overwritten),
3239                          * possibly opening the door to leaks.
3240                          *
3241                          * We do however catch STACK_INVALID case below, and
3242                          * only allow reading possibly uninitialized memory
3243                          * later for CAP_PERFMON, as the write may not happen to
3244                          * that slot.
3245                          */
3246                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3247                                 insn_idx, i);
3248                         return -EINVAL;
3249                 }
3250
3251                 /* Erase all spilled pointers. */
3252                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3253
3254                 /* Update the slot type. */
3255                 new_type = STACK_MISC;
3256                 if (writing_zero && *stype == STACK_ZERO) {
3257                         new_type = STACK_ZERO;
3258                         zero_used = true;
3259                 }
3260                 /* If the slot is STACK_INVALID, we check whether it's OK to
3261                  * pretend that it will be initialized by this write. The slot
3262                  * might not actually be written to, and so if we mark it as
3263                  * initialized future reads might leak uninitialized memory.
3264                  * For privileged programs, we will accept such reads to slots
3265                  * that may or may not be written because, if we're reject
3266                  * them, the error would be too confusing.
3267                  */
3268                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3269                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3270                                         insn_idx, i);
3271                         return -EINVAL;
3272                 }
3273                 *stype = new_type;
3274         }
3275         if (zero_used) {
3276                 /* backtracking doesn't work for STACK_ZERO yet. */
3277                 err = mark_chain_precision(env, value_regno);
3278                 if (err)
3279                         return err;
3280         }
3281         return 0;
3282 }
3283
3284 /* When register 'dst_regno' is assigned some values from stack[min_off,
3285  * max_off), we set the register's type according to the types of the
3286  * respective stack slots. If all the stack values are known to be zeros, then
3287  * so is the destination reg. Otherwise, the register is considered to be
3288  * SCALAR. This function does not deal with register filling; the caller must
3289  * ensure that all spilled registers in the stack range have been marked as
3290  * read.
3291  */
3292 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3293                                 /* func where src register points to */
3294                                 struct bpf_func_state *ptr_state,
3295                                 int min_off, int max_off, int dst_regno)
3296 {
3297         struct bpf_verifier_state *vstate = env->cur_state;
3298         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3299         int i, slot, spi;
3300         u8 *stype;
3301         int zeros = 0;
3302
3303         for (i = min_off; i < max_off; i++) {
3304                 slot = -i - 1;
3305                 spi = slot / BPF_REG_SIZE;
3306                 stype = ptr_state->stack[spi].slot_type;
3307                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3308                         break;
3309                 zeros++;
3310         }
3311         if (zeros == max_off - min_off) {
3312                 /* any access_size read into register is zero extended,
3313                  * so the whole register == const_zero
3314                  */
3315                 __mark_reg_const_zero(&state->regs[dst_regno]);
3316                 /* backtracking doesn't support STACK_ZERO yet,
3317                  * so mark it precise here, so that later
3318                  * backtracking can stop here.
3319                  * Backtracking may not need this if this register
3320                  * doesn't participate in pointer adjustment.
3321                  * Forward propagation of precise flag is not
3322                  * necessary either. This mark is only to stop
3323                  * backtracking. Any register that contributed
3324                  * to const 0 was marked precise before spill.
3325                  */
3326                 state->regs[dst_regno].precise = true;
3327         } else {
3328                 /* have read misc data from the stack */
3329                 mark_reg_unknown(env, state->regs, dst_regno);
3330         }
3331         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3332 }
3333
3334 /* Read the stack at 'off' and put the results into the register indicated by
3335  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3336  * spilled reg.
3337  *
3338  * 'dst_regno' can be -1, meaning that the read value is not going to a
3339  * register.
3340  *
3341  * The access is assumed to be within the current stack bounds.
3342  */
3343 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3344                                       /* func where src register points to */
3345                                       struct bpf_func_state *reg_state,
3346                                       int off, int size, int dst_regno)
3347 {
3348         struct bpf_verifier_state *vstate = env->cur_state;
3349         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3350         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3351         struct bpf_reg_state *reg;
3352         u8 *stype, type;
3353
3354         stype = reg_state->stack[spi].slot_type;
3355         reg = &reg_state->stack[spi].spilled_ptr;
3356
3357         if (is_spilled_reg(&reg_state->stack[spi])) {
3358                 u8 spill_size = 1;
3359
3360                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3361                         spill_size++;
3362
3363                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3364                         if (reg->type != SCALAR_VALUE) {
3365                                 verbose_linfo(env, env->insn_idx, "; ");
3366                                 verbose(env, "invalid size of register fill\n");
3367                                 return -EACCES;
3368                         }
3369
3370                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3371                         if (dst_regno < 0)
3372                                 return 0;
3373
3374                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
3375                                 /* The earlier check_reg_arg() has decided the
3376                                  * subreg_def for this insn.  Save it first.
3377                                  */
3378                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
3379
3380                                 copy_register_state(&state->regs[dst_regno], reg);
3381                                 state->regs[dst_regno].subreg_def = subreg_def;
3382                         } else {
3383                                 for (i = 0; i < size; i++) {
3384                                         type = stype[(slot - i) % BPF_REG_SIZE];
3385                                         if (type == STACK_SPILL)
3386                                                 continue;
3387                                         if (type == STACK_MISC)
3388                                                 continue;
3389                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3390                                                 off, i, size);
3391                                         return -EACCES;
3392                                 }
3393                                 mark_reg_unknown(env, state->regs, dst_regno);
3394                         }
3395                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3396                         return 0;
3397                 }
3398
3399                 if (dst_regno >= 0) {
3400                         /* restore register state from stack */
3401                         copy_register_state(&state->regs[dst_regno], reg);
3402                         /* mark reg as written since spilled pointer state likely
3403                          * has its liveness marks cleared by is_state_visited()
3404                          * which resets stack/reg liveness for state transitions
3405                          */
3406                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3407                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3408                         /* If dst_regno==-1, the caller is asking us whether
3409                          * it is acceptable to use this value as a SCALAR_VALUE
3410                          * (e.g. for XADD).
3411                          * We must not allow unprivileged callers to do that
3412                          * with spilled pointers.
3413                          */
3414                         verbose(env, "leaking pointer from stack off %d\n",
3415                                 off);
3416                         return -EACCES;
3417                 }
3418                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3419         } else {
3420                 for (i = 0; i < size; i++) {
3421                         type = stype[(slot - i) % BPF_REG_SIZE];
3422                         if (type == STACK_MISC)
3423                                 continue;
3424                         if (type == STACK_ZERO)
3425                                 continue;
3426                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3427                                 off, i, size);
3428                         return -EACCES;
3429                 }
3430                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3431                 if (dst_regno >= 0)
3432                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3433         }
3434         return 0;
3435 }
3436
3437 enum bpf_access_src {
3438         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3439         ACCESS_HELPER = 2,  /* the access is performed by a helper */
3440 };
3441
3442 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3443                                          int regno, int off, int access_size,
3444                                          bool zero_size_allowed,
3445                                          enum bpf_access_src type,
3446                                          struct bpf_call_arg_meta *meta);
3447
3448 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3449 {
3450         return cur_regs(env) + regno;
3451 }
3452
3453 /* Read the stack at 'ptr_regno + off' and put the result into the register
3454  * 'dst_regno'.
3455  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3456  * but not its variable offset.
3457  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3458  *
3459  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3460  * filling registers (i.e. reads of spilled register cannot be detected when
3461  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3462  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3463  * offset; for a fixed offset check_stack_read_fixed_off should be used
3464  * instead.
3465  */
3466 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3467                                     int ptr_regno, int off, int size, int dst_regno)
3468 {
3469         /* The state of the source register. */
3470         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3471         struct bpf_func_state *ptr_state = func(env, reg);
3472         int err;
3473         int min_off, max_off;
3474
3475         /* Note that we pass a NULL meta, so raw access will not be permitted.
3476          */
3477         err = check_stack_range_initialized(env, ptr_regno, off, size,
3478                                             false, ACCESS_DIRECT, NULL);
3479         if (err)
3480                 return err;
3481
3482         min_off = reg->smin_value + off;
3483         max_off = reg->smax_value + off;
3484         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3485         return 0;
3486 }
3487
3488 /* check_stack_read dispatches to check_stack_read_fixed_off or
3489  * check_stack_read_var_off.
3490  *
3491  * The caller must ensure that the offset falls within the allocated stack
3492  * bounds.
3493  *
3494  * 'dst_regno' is a register which will receive the value from the stack. It
3495  * can be -1, meaning that the read value is not going to a register.
3496  */
3497 static int check_stack_read(struct bpf_verifier_env *env,
3498                             int ptr_regno, int off, int size,
3499                             int dst_regno)
3500 {
3501         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3502         struct bpf_func_state *state = func(env, reg);
3503         int err;
3504         /* Some accesses are only permitted with a static offset. */
3505         bool var_off = !tnum_is_const(reg->var_off);
3506
3507         /* The offset is required to be static when reads don't go to a
3508          * register, in order to not leak pointers (see
3509          * check_stack_read_fixed_off).
3510          */
3511         if (dst_regno < 0 && var_off) {
3512                 char tn_buf[48];
3513
3514                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3515                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3516                         tn_buf, off, size);
3517                 return -EACCES;
3518         }
3519         /* Variable offset is prohibited for unprivileged mode for simplicity
3520          * since it requires corresponding support in Spectre masking for stack
3521          * ALU. See also retrieve_ptr_limit(). The check in
3522          * check_stack_access_for_ptr_arithmetic() called by
3523          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
3524          * with variable offsets, therefore no check is required here. Further,
3525          * just checking it here would be insufficient as speculative stack
3526          * writes could still lead to unsafe speculative behaviour.
3527          */
3528         if (!var_off) {
3529                 off += reg->var_off.value;
3530                 err = check_stack_read_fixed_off(env, state, off, size,
3531                                                  dst_regno);
3532         } else {
3533                 /* Variable offset stack reads need more conservative handling
3534                  * than fixed offset ones. Note that dst_regno >= 0 on this
3535                  * branch.
3536                  */
3537                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3538                                                dst_regno);
3539         }
3540         return err;
3541 }
3542
3543
3544 /* check_stack_write dispatches to check_stack_write_fixed_off or
3545  * check_stack_write_var_off.
3546  *
3547  * 'ptr_regno' is the register used as a pointer into the stack.
3548  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3549  * 'value_regno' is the register whose value we're writing to the stack. It can
3550  * be -1, meaning that we're not writing from a register.
3551  *
3552  * The caller must ensure that the offset falls within the maximum stack size.
3553  */
3554 static int check_stack_write(struct bpf_verifier_env *env,
3555                              int ptr_regno, int off, int size,
3556                              int value_regno, int insn_idx)
3557 {
3558         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3559         struct bpf_func_state *state = func(env, reg);
3560         int err;
3561
3562         if (tnum_is_const(reg->var_off)) {
3563                 off += reg->var_off.value;
3564                 err = check_stack_write_fixed_off(env, state, off, size,
3565                                                   value_regno, insn_idx);
3566         } else {
3567                 /* Variable offset stack reads need more conservative handling
3568                  * than fixed offset ones.
3569                  */
3570                 err = check_stack_write_var_off(env, state,
3571                                                 ptr_regno, off, size,
3572                                                 value_regno, insn_idx);
3573         }
3574         return err;
3575 }
3576
3577 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3578                                  int off, int size, enum bpf_access_type type)
3579 {
3580         struct bpf_reg_state *regs = cur_regs(env);
3581         struct bpf_map *map = regs[regno].map_ptr;
3582         u32 cap = bpf_map_flags_to_cap(map);
3583
3584         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3585                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3586                         map->value_size, off, size);
3587                 return -EACCES;
3588         }
3589
3590         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3591                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3592                         map->value_size, off, size);
3593                 return -EACCES;
3594         }
3595
3596         return 0;
3597 }
3598
3599 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3600 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3601                               int off, int size, u32 mem_size,
3602                               bool zero_size_allowed)
3603 {
3604         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3605         struct bpf_reg_state *reg;
3606
3607         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3608                 return 0;
3609
3610         reg = &cur_regs(env)[regno];
3611         switch (reg->type) {
3612         case PTR_TO_MAP_KEY:
3613                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3614                         mem_size, off, size);
3615                 break;
3616         case PTR_TO_MAP_VALUE:
3617                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3618                         mem_size, off, size);
3619                 break;
3620         case PTR_TO_PACKET:
3621         case PTR_TO_PACKET_META:
3622         case PTR_TO_PACKET_END:
3623                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3624                         off, size, regno, reg->id, off, mem_size);
3625                 break;
3626         case PTR_TO_MEM:
3627         default:
3628                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3629                         mem_size, off, size);
3630         }
3631
3632         return -EACCES;
3633 }
3634
3635 /* check read/write into a memory region with possible variable offset */
3636 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3637                                    int off, int size, u32 mem_size,
3638                                    bool zero_size_allowed)
3639 {
3640         struct bpf_verifier_state *vstate = env->cur_state;
3641         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3642         struct bpf_reg_state *reg = &state->regs[regno];
3643         int err;
3644
3645         /* We may have adjusted the register pointing to memory region, so we
3646          * need to try adding each of min_value and max_value to off
3647          * to make sure our theoretical access will be safe.
3648          *
3649          * The minimum value is only important with signed
3650          * comparisons where we can't assume the floor of a
3651          * value is 0.  If we are using signed variables for our
3652          * index'es we need to make sure that whatever we use
3653          * will have a set floor within our range.
3654          */
3655         if (reg->smin_value < 0 &&
3656             (reg->smin_value == S64_MIN ||
3657              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3658               reg->smin_value + off < 0)) {
3659                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3660                         regno);
3661                 return -EACCES;
3662         }
3663         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3664                                  mem_size, zero_size_allowed);
3665         if (err) {
3666                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3667                         regno);
3668                 return err;
3669         }
3670
3671         /* If we haven't set a max value then we need to bail since we can't be
3672          * sure we won't do bad things.
3673          * If reg->umax_value + off could overflow, treat that as unbounded too.
3674          */
3675         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3676                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3677                         regno);
3678                 return -EACCES;
3679         }
3680         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3681                                  mem_size, zero_size_allowed);
3682         if (err) {
3683                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3684                         regno);
3685                 return err;
3686         }
3687
3688         return 0;
3689 }
3690
3691 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3692                                const struct bpf_reg_state *reg, int regno,
3693                                bool fixed_off_ok)
3694 {
3695         /* Access to this pointer-typed register or passing it to a helper
3696          * is only allowed in its original, unmodified form.
3697          */
3698
3699         if (reg->off < 0) {
3700                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3701                         reg_type_str(env, reg->type), regno, reg->off);
3702                 return -EACCES;
3703         }
3704
3705         if (!fixed_off_ok && reg->off) {
3706                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3707                         reg_type_str(env, reg->type), regno, reg->off);
3708                 return -EACCES;
3709         }
3710
3711         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3712                 char tn_buf[48];
3713
3714                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3715                 verbose(env, "variable %s access var_off=%s disallowed\n",
3716                         reg_type_str(env, reg->type), tn_buf);
3717                 return -EACCES;
3718         }
3719
3720         return 0;
3721 }
3722
3723 int check_ptr_off_reg(struct bpf_verifier_env *env,
3724                       const struct bpf_reg_state *reg, int regno)
3725 {
3726         return __check_ptr_off_reg(env, reg, regno, false);
3727 }
3728
3729 static int map_kptr_match_type(struct bpf_verifier_env *env,
3730                                struct bpf_map_value_off_desc *off_desc,
3731                                struct bpf_reg_state *reg, u32 regno)
3732 {
3733         const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3734         int perm_flags = PTR_MAYBE_NULL;
3735         const char *reg_name = "";
3736
3737         /* Only unreferenced case accepts untrusted pointers */
3738         if (off_desc->type == BPF_KPTR_UNREF)
3739                 perm_flags |= PTR_UNTRUSTED;
3740
3741         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3742                 goto bad_type;
3743
3744         if (!btf_is_kernel(reg->btf)) {
3745                 verbose(env, "R%d must point to kernel BTF\n", regno);
3746                 return -EINVAL;
3747         }
3748         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3749         reg_name = kernel_type_name(reg->btf, reg->btf_id);
3750
3751         /* For ref_ptr case, release function check should ensure we get one
3752          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3753          * normal store of unreferenced kptr, we must ensure var_off is zero.
3754          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3755          * reg->off and reg->ref_obj_id are not needed here.
3756          */
3757         if (__check_ptr_off_reg(env, reg, regno, true))
3758                 return -EACCES;
3759
3760         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3761          * we also need to take into account the reg->off.
3762          *
3763          * We want to support cases like:
3764          *
3765          * struct foo {
3766          *         struct bar br;
3767          *         struct baz bz;
3768          * };
3769          *
3770          * struct foo *v;
3771          * v = func();        // PTR_TO_BTF_ID
3772          * val->foo = v;      // reg->off is zero, btf and btf_id match type
3773          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3774          *                    // first member type of struct after comparison fails
3775          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3776          *                    // to match type
3777          *
3778          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3779          * is zero. We must also ensure that btf_struct_ids_match does not walk
3780          * the struct to match type against first member of struct, i.e. reject
3781          * second case from above. Hence, when type is BPF_KPTR_REF, we set
3782          * strict mode to true for type match.
3783          */
3784         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3785                                   off_desc->kptr.btf, off_desc->kptr.btf_id,
3786                                   off_desc->type == BPF_KPTR_REF))
3787                 goto bad_type;
3788         return 0;
3789 bad_type:
3790         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3791                 reg_type_str(env, reg->type), reg_name);
3792         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3793         if (off_desc->type == BPF_KPTR_UNREF)
3794                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3795                         targ_name);
3796         else
3797                 verbose(env, "\n");
3798         return -EINVAL;
3799 }
3800
3801 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3802                                  int value_regno, int insn_idx,
3803                                  struct bpf_map_value_off_desc *off_desc)
3804 {
3805         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3806         int class = BPF_CLASS(insn->code);
3807         struct bpf_reg_state *val_reg;
3808
3809         /* Things we already checked for in check_map_access and caller:
3810          *  - Reject cases where variable offset may touch kptr
3811          *  - size of access (must be BPF_DW)
3812          *  - tnum_is_const(reg->var_off)
3813          *  - off_desc->offset == off + reg->var_off.value
3814          */
3815         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3816         if (BPF_MODE(insn->code) != BPF_MEM) {
3817                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3818                 return -EACCES;
3819         }
3820
3821         /* We only allow loading referenced kptr, since it will be marked as
3822          * untrusted, similar to unreferenced kptr.
3823          */
3824         if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3825                 verbose(env, "store to referenced kptr disallowed\n");
3826                 return -EACCES;
3827         }
3828
3829         if (class == BPF_LDX) {
3830                 val_reg = reg_state(env, value_regno);
3831                 /* We can simply mark the value_regno receiving the pointer
3832                  * value from map as PTR_TO_BTF_ID, with the correct type.
3833                  */
3834                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3835                                 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3836                 /* For mark_ptr_or_null_reg */
3837                 val_reg->id = ++env->id_gen;
3838         } else if (class == BPF_STX) {
3839                 val_reg = reg_state(env, value_regno);
3840                 if (!register_is_null(val_reg) &&
3841                     map_kptr_match_type(env, off_desc, val_reg, value_regno))
3842                         return -EACCES;
3843         } else if (class == BPF_ST) {
3844                 if (insn->imm) {
3845                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3846                                 off_desc->offset);
3847                         return -EACCES;
3848                 }
3849         } else {
3850                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3851                 return -EACCES;
3852         }
3853         return 0;
3854 }
3855
3856 /* check read/write into a map element with possible variable offset */
3857 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3858                             int off, int size, bool zero_size_allowed,
3859                             enum bpf_access_src src)
3860 {
3861         struct bpf_verifier_state *vstate = env->cur_state;
3862         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3863         struct bpf_reg_state *reg = &state->regs[regno];
3864         struct bpf_map *map = reg->map_ptr;
3865         int err;
3866
3867         err = check_mem_region_access(env, regno, off, size, map->value_size,
3868                                       zero_size_allowed);
3869         if (err)
3870                 return err;
3871
3872         if (map_value_has_spin_lock(map)) {
3873                 u32 lock = map->spin_lock_off;
3874
3875                 /* if any part of struct bpf_spin_lock can be touched by
3876                  * load/store reject this program.
3877                  * To check that [x1, x2) overlaps with [y1, y2)
3878                  * it is sufficient to check x1 < y2 && y1 < x2.
3879                  */
3880                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3881                      lock < reg->umax_value + off + size) {
3882                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3883                         return -EACCES;
3884                 }
3885         }
3886         if (map_value_has_timer(map)) {
3887                 u32 t = map->timer_off;
3888
3889                 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3890                      t < reg->umax_value + off + size) {
3891                         verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3892                         return -EACCES;
3893                 }
3894         }
3895         if (map_value_has_kptrs(map)) {
3896                 struct bpf_map_value_off *tab = map->kptr_off_tab;
3897                 int i;
3898
3899                 for (i = 0; i < tab->nr_off; i++) {
3900                         u32 p = tab->off[i].offset;
3901
3902                         if (reg->smin_value + off < p + sizeof(u64) &&
3903                             p < reg->umax_value + off + size) {
3904                                 if (src != ACCESS_DIRECT) {
3905                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
3906                                         return -EACCES;
3907                                 }
3908                                 if (!tnum_is_const(reg->var_off)) {
3909                                         verbose(env, "kptr access cannot have variable offset\n");
3910                                         return -EACCES;
3911                                 }
3912                                 if (p != off + reg->var_off.value) {
3913                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3914                                                 p, off + reg->var_off.value);
3915                                         return -EACCES;
3916                                 }
3917                                 if (size != bpf_size_to_bytes(BPF_DW)) {
3918                                         verbose(env, "kptr access size must be BPF_DW\n");
3919                                         return -EACCES;
3920                                 }
3921                                 break;
3922                         }
3923                 }
3924         }
3925         return err;
3926 }
3927
3928 #define MAX_PACKET_OFF 0xffff
3929
3930 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3931                                        const struct bpf_call_arg_meta *meta,
3932                                        enum bpf_access_type t)
3933 {
3934         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3935
3936         switch (prog_type) {
3937         /* Program types only with direct read access go here! */
3938         case BPF_PROG_TYPE_LWT_IN:
3939         case BPF_PROG_TYPE_LWT_OUT:
3940         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3941         case BPF_PROG_TYPE_SK_REUSEPORT:
3942         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3943         case BPF_PROG_TYPE_CGROUP_SKB:
3944                 if (t == BPF_WRITE)
3945                         return false;
3946                 fallthrough;
3947
3948         /* Program types with direct read + write access go here! */
3949         case BPF_PROG_TYPE_SCHED_CLS:
3950         case BPF_PROG_TYPE_SCHED_ACT:
3951         case BPF_PROG_TYPE_XDP:
3952         case BPF_PROG_TYPE_LWT_XMIT:
3953         case BPF_PROG_TYPE_SK_SKB:
3954         case BPF_PROG_TYPE_SK_MSG:
3955                 if (meta)
3956                         return meta->pkt_access;
3957
3958                 env->seen_direct_write = true;
3959                 return true;
3960
3961         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3962                 if (t == BPF_WRITE)
3963                         env->seen_direct_write = true;
3964
3965                 return true;
3966
3967         default:
3968                 return false;
3969         }
3970 }
3971
3972 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3973                                int size, bool zero_size_allowed)
3974 {
3975         struct bpf_reg_state *regs = cur_regs(env);
3976         struct bpf_reg_state *reg = &regs[regno];
3977         int err;
3978
3979         /* We may have added a variable offset to the packet pointer; but any
3980          * reg->range we have comes after that.  We are only checking the fixed
3981          * offset.
3982          */
3983
3984         /* We don't allow negative numbers, because we aren't tracking enough
3985          * detail to prove they're safe.
3986          */
3987         if (reg->smin_value < 0) {
3988                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3989                         regno);
3990                 return -EACCES;
3991         }
3992
3993         err = reg->range < 0 ? -EINVAL :
3994               __check_mem_access(env, regno, off, size, reg->range,
3995                                  zero_size_allowed);
3996         if (err) {
3997                 verbose(env, "R%d offset is outside of the packet\n", regno);
3998                 return err;
3999         }
4000
4001         /* __check_mem_access has made sure "off + size - 1" is within u16.
4002          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4003          * otherwise find_good_pkt_pointers would have refused to set range info
4004          * that __check_mem_access would have rejected this pkt access.
4005          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4006          */
4007         env->prog->aux->max_pkt_offset =
4008                 max_t(u32, env->prog->aux->max_pkt_offset,
4009                       off + reg->umax_value + size - 1);
4010
4011         return err;
4012 }
4013
4014 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4015 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4016                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
4017                             struct btf **btf, u32 *btf_id)
4018 {
4019         struct bpf_insn_access_aux info = {
4020                 .reg_type = *reg_type,
4021                 .log = &env->log,
4022         };
4023
4024         if (env->ops->is_valid_access &&
4025             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4026                 /* A non zero info.ctx_field_size indicates that this field is a
4027                  * candidate for later verifier transformation to load the whole
4028                  * field and then apply a mask when accessed with a narrower
4029                  * access than actual ctx access size. A zero info.ctx_field_size
4030                  * will only allow for whole field access and rejects any other
4031                  * type of narrower access.
4032                  */
4033                 *reg_type = info.reg_type;
4034
4035                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4036                         *btf = info.btf;
4037                         *btf_id = info.btf_id;
4038                 } else {
4039                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4040                 }
4041                 /* remember the offset of last byte accessed in ctx */
4042                 if (env->prog->aux->max_ctx_offset < off + size)
4043                         env->prog->aux->max_ctx_offset = off + size;
4044                 return 0;
4045         }
4046
4047         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4048         return -EACCES;
4049 }
4050
4051 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4052                                   int size)
4053 {
4054         if (size < 0 || off < 0 ||
4055             (u64)off + size > sizeof(struct bpf_flow_keys)) {
4056                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4057                         off, size);
4058                 return -EACCES;
4059         }
4060         return 0;
4061 }
4062
4063 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4064                              u32 regno, int off, int size,
4065                              enum bpf_access_type t)
4066 {
4067         struct bpf_reg_state *regs = cur_regs(env);
4068         struct bpf_reg_state *reg = &regs[regno];
4069         struct bpf_insn_access_aux info = {};
4070         bool valid;
4071
4072         if (reg->smin_value < 0) {
4073                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4074                         regno);
4075                 return -EACCES;
4076         }
4077
4078         switch (reg->type) {
4079         case PTR_TO_SOCK_COMMON:
4080                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4081                 break;
4082         case PTR_TO_SOCKET:
4083                 valid = bpf_sock_is_valid_access(off, size, t, &info);
4084                 break;
4085         case PTR_TO_TCP_SOCK:
4086                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4087                 break;
4088         case PTR_TO_XDP_SOCK:
4089                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4090                 break;
4091         default:
4092                 valid = false;
4093         }
4094
4095
4096         if (valid) {
4097                 env->insn_aux_data[insn_idx].ctx_field_size =
4098                         info.ctx_field_size;
4099                 return 0;
4100         }
4101
4102         verbose(env, "R%d invalid %s access off=%d size=%d\n",
4103                 regno, reg_type_str(env, reg->type), off, size);
4104
4105         return -EACCES;
4106 }
4107
4108 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4109 {
4110         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4111 }
4112
4113 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4114 {
4115         const struct bpf_reg_state *reg = reg_state(env, regno);
4116
4117         return reg->type == PTR_TO_CTX;
4118 }
4119
4120 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4121 {
4122         const struct bpf_reg_state *reg = reg_state(env, regno);
4123
4124         return type_is_sk_pointer(reg->type);
4125 }
4126
4127 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4128 {
4129         const struct bpf_reg_state *reg = reg_state(env, regno);
4130
4131         return type_is_pkt_pointer(reg->type);
4132 }
4133
4134 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4135 {
4136         const struct bpf_reg_state *reg = reg_state(env, regno);
4137
4138         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4139         return reg->type == PTR_TO_FLOW_KEYS;
4140 }
4141
4142 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4143                                    const struct bpf_reg_state *reg,
4144                                    int off, int size, bool strict)
4145 {
4146         struct tnum reg_off;
4147         int ip_align;
4148
4149         /* Byte size accesses are always allowed. */
4150         if (!strict || size == 1)
4151                 return 0;
4152
4153         /* For platforms that do not have a Kconfig enabling
4154          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4155          * NET_IP_ALIGN is universally set to '2'.  And on platforms
4156          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4157          * to this code only in strict mode where we want to emulate
4158          * the NET_IP_ALIGN==2 checking.  Therefore use an
4159          * unconditional IP align value of '2'.
4160          */
4161         ip_align = 2;
4162
4163         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4164         if (!tnum_is_aligned(reg_off, size)) {
4165                 char tn_buf[48];
4166
4167                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4168                 verbose(env,
4169                         "misaligned packet access off %d+%s+%d+%d size %d\n",
4170                         ip_align, tn_buf, reg->off, off, size);
4171                 return -EACCES;
4172         }
4173
4174         return 0;
4175 }
4176
4177 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4178                                        const struct bpf_reg_state *reg,
4179                                        const char *pointer_desc,
4180                                        int off, int size, bool strict)
4181 {
4182         struct tnum reg_off;
4183
4184         /* Byte size accesses are always allowed. */
4185         if (!strict || size == 1)
4186                 return 0;
4187
4188         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4189         if (!tnum_is_aligned(reg_off, size)) {
4190                 char tn_buf[48];
4191
4192                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4193                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4194                         pointer_desc, tn_buf, reg->off, off, size);
4195                 return -EACCES;
4196         }
4197
4198         return 0;
4199 }
4200
4201 static int check_ptr_alignment(struct bpf_verifier_env *env,
4202                                const struct bpf_reg_state *reg, int off,
4203                                int size, bool strict_alignment_once)
4204 {
4205         bool strict = env->strict_alignment || strict_alignment_once;
4206         const char *pointer_desc = "";
4207
4208         switch (reg->type) {
4209         case PTR_TO_PACKET:
4210         case PTR_TO_PACKET_META:
4211                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4212                  * right in front, treat it the very same way.
4213                  */
4214                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4215         case PTR_TO_FLOW_KEYS:
4216                 pointer_desc = "flow keys ";
4217                 break;
4218         case PTR_TO_MAP_KEY:
4219                 pointer_desc = "key ";
4220                 break;
4221         case PTR_TO_MAP_VALUE:
4222                 pointer_desc = "value ";
4223                 break;
4224         case PTR_TO_CTX:
4225                 pointer_desc = "context ";
4226                 break;
4227         case PTR_TO_STACK:
4228                 pointer_desc = "stack ";
4229                 /* The stack spill tracking logic in check_stack_write_fixed_off()
4230                  * and check_stack_read_fixed_off() relies on stack accesses being
4231                  * aligned.
4232                  */
4233                 strict = true;
4234                 break;
4235         case PTR_TO_SOCKET:
4236                 pointer_desc = "sock ";
4237                 break;
4238         case PTR_TO_SOCK_COMMON:
4239                 pointer_desc = "sock_common ";
4240                 break;
4241         case PTR_TO_TCP_SOCK:
4242                 pointer_desc = "tcp_sock ";
4243                 break;
4244         case PTR_TO_XDP_SOCK:
4245                 pointer_desc = "xdp_sock ";
4246                 break;
4247         default:
4248                 break;
4249         }
4250         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4251                                            strict);
4252 }
4253
4254 static int update_stack_depth(struct bpf_verifier_env *env,
4255                               const struct bpf_func_state *func,
4256                               int off)
4257 {
4258         u16 stack = env->subprog_info[func->subprogno].stack_depth;
4259
4260         if (stack >= -off)
4261                 return 0;
4262
4263         /* update known max for given subprogram */
4264         env->subprog_info[func->subprogno].stack_depth = -off;
4265         return 0;
4266 }
4267
4268 /* starting from main bpf function walk all instructions of the function
4269  * and recursively walk all callees that given function can call.
4270  * Ignore jump and exit insns.
4271  * Since recursion is prevented by check_cfg() this algorithm
4272  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4273  */
4274 static int check_max_stack_depth(struct bpf_verifier_env *env)
4275 {
4276         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4277         struct bpf_subprog_info *subprog = env->subprog_info;
4278         struct bpf_insn *insn = env->prog->insnsi;
4279         bool tail_call_reachable = false;
4280         int ret_insn[MAX_CALL_FRAMES];
4281         int ret_prog[MAX_CALL_FRAMES];
4282         int j;
4283
4284 process_func:
4285         /* protect against potential stack overflow that might happen when
4286          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4287          * depth for such case down to 256 so that the worst case scenario
4288          * would result in 8k stack size (32 which is tailcall limit * 256 =
4289          * 8k).
4290          *
4291          * To get the idea what might happen, see an example:
4292          * func1 -> sub rsp, 128
4293          *  subfunc1 -> sub rsp, 256
4294          *  tailcall1 -> add rsp, 256
4295          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4296          *   subfunc2 -> sub rsp, 64
4297          *   subfunc22 -> sub rsp, 128
4298          *   tailcall2 -> add rsp, 128
4299          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4300          *
4301          * tailcall will unwind the current stack frame but it will not get rid
4302          * of caller's stack as shown on the example above.
4303          */
4304         if (idx && subprog[idx].has_tail_call && depth >= 256) {
4305                 verbose(env,
4306                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4307                         depth);
4308                 return -EACCES;
4309         }
4310         /* round up to 32-bytes, since this is granularity
4311          * of interpreter stack size
4312          */
4313         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4314         if (depth > MAX_BPF_STACK) {
4315                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4316                         frame + 1, depth);
4317                 return -EACCES;
4318         }
4319 continue_func:
4320         subprog_end = subprog[idx + 1].start;
4321         for (; i < subprog_end; i++) {
4322                 int next_insn;
4323
4324                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4325                         continue;
4326                 /* remember insn and function to return to */
4327                 ret_insn[frame] = i + 1;
4328                 ret_prog[frame] = idx;
4329
4330                 /* find the callee */
4331                 next_insn = i + insn[i].imm + 1;
4332                 idx = find_subprog(env, next_insn);
4333                 if (idx < 0) {
4334                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4335                                   next_insn);
4336                         return -EFAULT;
4337                 }
4338                 if (subprog[idx].is_async_cb) {
4339                         if (subprog[idx].has_tail_call) {
4340                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4341                                 return -EFAULT;
4342                         }
4343                          /* async callbacks don't increase bpf prog stack size */
4344                         continue;
4345                 }
4346                 i = next_insn;
4347
4348                 if (subprog[idx].has_tail_call)
4349                         tail_call_reachable = true;
4350
4351                 frame++;
4352                 if (frame >= MAX_CALL_FRAMES) {
4353                         verbose(env, "the call stack of %d frames is too deep !\n",
4354                                 frame);
4355                         return -E2BIG;
4356                 }
4357                 goto process_func;
4358         }
4359         /* if tail call got detected across bpf2bpf calls then mark each of the
4360          * currently present subprog frames as tail call reachable subprogs;
4361          * this info will be utilized by JIT so that we will be preserving the
4362          * tail call counter throughout bpf2bpf calls combined with tailcalls
4363          */
4364         if (tail_call_reachable)
4365                 for (j = 0; j < frame; j++)
4366                         subprog[ret_prog[j]].tail_call_reachable = true;
4367         if (subprog[0].tail_call_reachable)
4368                 env->prog->aux->tail_call_reachable = true;
4369
4370         /* end of for() loop means the last insn of the 'subprog'
4371          * was reached. Doesn't matter whether it was JA or EXIT
4372          */
4373         if (frame == 0)
4374                 return 0;
4375         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4376         frame--;
4377         i = ret_insn[frame];
4378         idx = ret_prog[frame];
4379         goto continue_func;
4380 }
4381
4382 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4383 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4384                                   const struct bpf_insn *insn, int idx)
4385 {
4386         int start = idx + insn->imm + 1, subprog;
4387
4388         subprog = find_subprog(env, start);
4389         if (subprog < 0) {
4390                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4391                           start);
4392                 return -EFAULT;
4393         }
4394         return env->subprog_info[subprog].stack_depth;
4395 }
4396 #endif
4397
4398 static int __check_buffer_access(struct bpf_verifier_env *env,
4399                                  const char *buf_info,
4400                                  const struct bpf_reg_state *reg,
4401                                  int regno, int off, int size)
4402 {
4403         if (off < 0) {
4404                 verbose(env,
4405                         "R%d invalid %s buffer access: off=%d, size=%d\n",
4406                         regno, buf_info, off, size);
4407                 return -EACCES;
4408         }
4409         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4410                 char tn_buf[48];
4411
4412                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4413                 verbose(env,
4414                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4415                         regno, off, tn_buf);
4416                 return -EACCES;
4417         }
4418
4419         return 0;
4420 }
4421
4422 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4423                                   const struct bpf_reg_state *reg,
4424                                   int regno, int off, int size)
4425 {
4426         int err;
4427
4428         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4429         if (err)
4430                 return err;
4431
4432         if (off + size > env->prog->aux->max_tp_access)
4433                 env->prog->aux->max_tp_access = off + size;
4434
4435         return 0;
4436 }
4437
4438 static int check_buffer_access(struct bpf_verifier_env *env,
4439                                const struct bpf_reg_state *reg,
4440                                int regno, int off, int size,
4441                                bool zero_size_allowed,
4442                                u32 *max_access)
4443 {
4444         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4445         int err;
4446
4447         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4448         if (err)
4449                 return err;
4450
4451         if (off + size > *max_access)
4452                 *max_access = off + size;
4453
4454         return 0;
4455 }
4456
4457 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4458 static void zext_32_to_64(struct bpf_reg_state *reg)
4459 {
4460         reg->var_off = tnum_subreg(reg->var_off);
4461         __reg_assign_32_into_64(reg);
4462 }
4463
4464 /* truncate register to smaller size (in bytes)
4465  * must be called with size < BPF_REG_SIZE
4466  */
4467 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4468 {
4469         u64 mask;
4470
4471         /* clear high bits in bit representation */
4472         reg->var_off = tnum_cast(reg->var_off, size);
4473
4474         /* fix arithmetic bounds */
4475         mask = ((u64)1 << (size * 8)) - 1;
4476         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4477                 reg->umin_value &= mask;
4478                 reg->umax_value &= mask;
4479         } else {
4480                 reg->umin_value = 0;
4481                 reg->umax_value = mask;
4482         }
4483         reg->smin_value = reg->umin_value;
4484         reg->smax_value = reg->umax_value;
4485
4486         /* If size is smaller than 32bit register the 32bit register
4487          * values are also truncated so we push 64-bit bounds into
4488          * 32-bit bounds. Above were truncated < 32-bits already.
4489          */
4490         if (size >= 4)
4491                 return;
4492         __reg_combine_64_into_32(reg);
4493 }
4494
4495 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4496 {
4497         /* A map is considered read-only if the following condition are true:
4498          *
4499          * 1) BPF program side cannot change any of the map content. The
4500          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4501          *    and was set at map creation time.
4502          * 2) The map value(s) have been initialized from user space by a
4503          *    loader and then "frozen", such that no new map update/delete
4504          *    operations from syscall side are possible for the rest of
4505          *    the map's lifetime from that point onwards.
4506          * 3) Any parallel/pending map update/delete operations from syscall
4507          *    side have been completed. Only after that point, it's safe to
4508          *    assume that map value(s) are immutable.
4509          */
4510         return (map->map_flags & BPF_F_RDONLY_PROG) &&
4511                READ_ONCE(map->frozen) &&
4512                !bpf_map_write_active(map);
4513 }
4514
4515 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4516 {
4517         void *ptr;
4518         u64 addr;
4519         int err;
4520
4521         err = map->ops->map_direct_value_addr(map, &addr, off);
4522         if (err)
4523                 return err;
4524         ptr = (void *)(long)addr + off;
4525
4526         switch (size) {
4527         case sizeof(u8):
4528                 *val = (u64)*(u8 *)ptr;
4529                 break;
4530         case sizeof(u16):
4531                 *val = (u64)*(u16 *)ptr;
4532                 break;
4533         case sizeof(u32):
4534                 *val = (u64)*(u32 *)ptr;
4535                 break;
4536         case sizeof(u64):
4537                 *val = *(u64 *)ptr;
4538                 break;
4539         default:
4540                 return -EINVAL;
4541         }
4542         return 0;
4543 }
4544
4545 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4546                                    struct bpf_reg_state *regs,
4547                                    int regno, int off, int size,
4548                                    enum bpf_access_type atype,
4549                                    int value_regno)
4550 {
4551         struct bpf_reg_state *reg = regs + regno;
4552         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4553         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4554         enum bpf_type_flag flag = 0;
4555         u32 btf_id;
4556         int ret;
4557
4558         if (off < 0) {
4559                 verbose(env,
4560                         "R%d is ptr_%s invalid negative access: off=%d\n",
4561                         regno, tname, off);
4562                 return -EACCES;
4563         }
4564         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4565                 char tn_buf[48];
4566
4567                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4568                 verbose(env,
4569                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4570                         regno, tname, off, tn_buf);
4571                 return -EACCES;
4572         }
4573
4574         if (reg->type & MEM_USER) {
4575                 verbose(env,
4576                         "R%d is ptr_%s access user memory: off=%d\n",
4577                         regno, tname, off);
4578                 return -EACCES;
4579         }
4580
4581         if (reg->type & MEM_PERCPU) {
4582                 verbose(env,
4583                         "R%d is ptr_%s access percpu memory: off=%d\n",
4584                         regno, tname, off);
4585                 return -EACCES;
4586         }
4587
4588         if (env->ops->btf_struct_access) {
4589                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4590                                                   off, size, atype, &btf_id, &flag);
4591         } else {
4592                 if (atype != BPF_READ) {
4593                         verbose(env, "only read is supported\n");
4594                         return -EACCES;
4595                 }
4596
4597                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4598                                         atype, &btf_id, &flag);
4599         }
4600
4601         if (ret < 0)
4602                 return ret;
4603
4604         /* If this is an untrusted pointer, all pointers formed by walking it
4605          * also inherit the untrusted flag.
4606          */
4607         if (type_flag(reg->type) & PTR_UNTRUSTED)
4608                 flag |= PTR_UNTRUSTED;
4609
4610         if (atype == BPF_READ && value_regno >= 0)
4611                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4612
4613         return 0;
4614 }
4615
4616 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4617                                    struct bpf_reg_state *regs,
4618                                    int regno, int off, int size,
4619                                    enum bpf_access_type atype,
4620                                    int value_regno)
4621 {
4622         struct bpf_reg_state *reg = regs + regno;
4623         struct bpf_map *map = reg->map_ptr;
4624         enum bpf_type_flag flag = 0;
4625         const struct btf_type *t;
4626         const char *tname;
4627         u32 btf_id;
4628         int ret;
4629
4630         if (!btf_vmlinux) {
4631                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4632                 return -ENOTSUPP;
4633         }
4634
4635         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4636                 verbose(env, "map_ptr access not supported for map type %d\n",
4637                         map->map_type);
4638                 return -ENOTSUPP;
4639         }
4640
4641         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4642         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4643
4644         if (!env->allow_ptr_to_map_access) {
4645                 verbose(env,
4646                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4647                         tname);
4648                 return -EPERM;
4649         }
4650
4651         if (off < 0) {
4652                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4653                         regno, tname, off);
4654                 return -EACCES;
4655         }
4656
4657         if (atype != BPF_READ) {
4658                 verbose(env, "only read from %s is supported\n", tname);
4659                 return -EACCES;
4660         }
4661
4662         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4663         if (ret < 0)
4664                 return ret;
4665
4666         if (value_regno >= 0)
4667                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4668
4669         return 0;
4670 }
4671
4672 /* Check that the stack access at the given offset is within bounds. The
4673  * maximum valid offset is -1.
4674  *
4675  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4676  * -state->allocated_stack for reads.
4677  */
4678 static int check_stack_slot_within_bounds(int off,
4679                                           struct bpf_func_state *state,
4680                                           enum bpf_access_type t)
4681 {
4682         int min_valid_off;
4683
4684         if (t == BPF_WRITE)
4685                 min_valid_off = -MAX_BPF_STACK;
4686         else
4687                 min_valid_off = -state->allocated_stack;
4688
4689         if (off < min_valid_off || off > -1)
4690                 return -EACCES;
4691         return 0;
4692 }
4693
4694 /* Check that the stack access at 'regno + off' falls within the maximum stack
4695  * bounds.
4696  *
4697  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4698  */
4699 static int check_stack_access_within_bounds(
4700                 struct bpf_verifier_env *env,
4701                 int regno, int off, int access_size,
4702                 enum bpf_access_src src, enum bpf_access_type type)
4703 {
4704         struct bpf_reg_state *regs = cur_regs(env);
4705         struct bpf_reg_state *reg = regs + regno;
4706         struct bpf_func_state *state = func(env, reg);
4707         int min_off, max_off;
4708         int err;
4709         char *err_extra;
4710
4711         if (src == ACCESS_HELPER)
4712                 /* We don't know if helpers are reading or writing (or both). */
4713                 err_extra = " indirect access to";
4714         else if (type == BPF_READ)
4715                 err_extra = " read from";
4716         else
4717                 err_extra = " write to";
4718
4719         if (tnum_is_const(reg->var_off)) {
4720                 min_off = reg->var_off.value + off;
4721                 if (access_size > 0)
4722                         max_off = min_off + access_size - 1;
4723                 else
4724                         max_off = min_off;
4725         } else {
4726                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4727                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4728                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4729                                 err_extra, regno);
4730                         return -EACCES;
4731                 }
4732                 min_off = reg->smin_value + off;
4733                 if (access_size > 0)
4734                         max_off = reg->smax_value + off + access_size - 1;
4735                 else
4736                         max_off = min_off;
4737         }
4738
4739         err = check_stack_slot_within_bounds(min_off, state, type);
4740         if (!err)
4741                 err = check_stack_slot_within_bounds(max_off, state, type);
4742
4743         if (err) {
4744                 if (tnum_is_const(reg->var_off)) {
4745                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4746                                 err_extra, regno, off, access_size);
4747                 } else {
4748                         char tn_buf[48];
4749
4750                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4751                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4752                                 err_extra, regno, tn_buf, access_size);
4753                 }
4754         }
4755         return err;
4756 }
4757
4758 /* check whether memory at (regno + off) is accessible for t = (read | write)
4759  * if t==write, value_regno is a register which value is stored into memory
4760  * if t==read, value_regno is a register which will receive the value from memory
4761  * if t==write && value_regno==-1, some unknown value is stored into memory
4762  * if t==read && value_regno==-1, don't care what we read from memory
4763  */
4764 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4765                             int off, int bpf_size, enum bpf_access_type t,
4766                             int value_regno, bool strict_alignment_once)
4767 {
4768         struct bpf_reg_state *regs = cur_regs(env);
4769         struct bpf_reg_state *reg = regs + regno;
4770         struct bpf_func_state *state;
4771         int size, err = 0;
4772
4773         size = bpf_size_to_bytes(bpf_size);
4774         if (size < 0)
4775                 return size;
4776
4777         /* alignment checks will add in reg->off themselves */
4778         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4779         if (err)
4780                 return err;
4781
4782         /* for access checks, reg->off is just part of off */
4783         off += reg->off;
4784
4785         if (reg->type == PTR_TO_MAP_KEY) {
4786                 if (t == BPF_WRITE) {
4787                         verbose(env, "write to change key R%d not allowed\n", regno);
4788                         return -EACCES;
4789                 }
4790
4791                 err = check_mem_region_access(env, regno, off, size,
4792                                               reg->map_ptr->key_size, false);
4793                 if (err)
4794                         return err;
4795                 if (value_regno >= 0)
4796                         mark_reg_unknown(env, regs, value_regno);
4797         } else if (reg->type == PTR_TO_MAP_VALUE) {
4798                 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4799
4800                 if (t == BPF_WRITE && value_regno >= 0 &&
4801                     is_pointer_value(env, value_regno)) {
4802                         verbose(env, "R%d leaks addr into map\n", value_regno);
4803                         return -EACCES;
4804                 }
4805                 err = check_map_access_type(env, regno, off, size, t);
4806                 if (err)
4807                         return err;
4808                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4809                 if (err)
4810                         return err;
4811                 if (tnum_is_const(reg->var_off))
4812                         kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4813                                                                   off + reg->var_off.value);
4814                 if (kptr_off_desc) {
4815                         err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4816                                                     kptr_off_desc);
4817                 } else if (t == BPF_READ && value_regno >= 0) {
4818                         struct bpf_map *map = reg->map_ptr;
4819
4820                         /* if map is read-only, track its contents as scalars */
4821                         if (tnum_is_const(reg->var_off) &&
4822                             bpf_map_is_rdonly(map) &&
4823                             map->ops->map_direct_value_addr) {
4824                                 int map_off = off + reg->var_off.value;
4825                                 u64 val = 0;
4826
4827                                 err = bpf_map_direct_read(map, map_off, size,
4828                                                           &val);
4829                                 if (err)
4830                                         return err;
4831
4832                                 regs[value_regno].type = SCALAR_VALUE;
4833                                 __mark_reg_known(&regs[value_regno], val);
4834                         } else {
4835                                 mark_reg_unknown(env, regs, value_regno);
4836                         }
4837                 }
4838         } else if (base_type(reg->type) == PTR_TO_MEM) {
4839                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4840
4841                 if (type_may_be_null(reg->type)) {
4842                         verbose(env, "R%d invalid mem access '%s'\n", regno,
4843                                 reg_type_str(env, reg->type));
4844                         return -EACCES;
4845                 }
4846
4847                 if (t == BPF_WRITE && rdonly_mem) {
4848                         verbose(env, "R%d cannot write into %s\n",
4849                                 regno, reg_type_str(env, reg->type));
4850                         return -EACCES;
4851                 }
4852
4853                 if (t == BPF_WRITE && value_regno >= 0 &&
4854                     is_pointer_value(env, value_regno)) {
4855                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4856                         return -EACCES;
4857                 }
4858
4859                 err = check_mem_region_access(env, regno, off, size,
4860                                               reg->mem_size, false);
4861                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4862                         mark_reg_unknown(env, regs, value_regno);
4863         } else if (reg->type == PTR_TO_CTX) {
4864                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4865                 struct btf *btf = NULL;
4866                 u32 btf_id = 0;
4867
4868                 if (t == BPF_WRITE && value_regno >= 0 &&
4869                     is_pointer_value(env, value_regno)) {
4870                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4871                         return -EACCES;
4872                 }
4873
4874                 err = check_ptr_off_reg(env, reg, regno);
4875                 if (err < 0)
4876                         return err;
4877
4878                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4879                                        &btf_id);
4880                 if (err)
4881                         verbose_linfo(env, insn_idx, "; ");
4882                 if (!err && t == BPF_READ && value_regno >= 0) {
4883                         /* ctx access returns either a scalar, or a
4884                          * PTR_TO_PACKET[_META,_END]. In the latter
4885                          * case, we know the offset is zero.
4886                          */
4887                         if (reg_type == SCALAR_VALUE) {
4888                                 mark_reg_unknown(env, regs, value_regno);
4889                         } else {
4890                                 mark_reg_known_zero(env, regs,
4891                                                     value_regno);
4892                                 if (type_may_be_null(reg_type))
4893                                         regs[value_regno].id = ++env->id_gen;
4894                                 /* A load of ctx field could have different
4895                                  * actual load size with the one encoded in the
4896                                  * insn. When the dst is PTR, it is for sure not
4897                                  * a sub-register.
4898                                  */
4899                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4900                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4901                                         regs[value_regno].btf = btf;
4902                                         regs[value_regno].btf_id = btf_id;
4903                                 }
4904                         }
4905                         regs[value_regno].type = reg_type;
4906                 }
4907
4908         } else if (reg->type == PTR_TO_STACK) {
4909                 /* Basic bounds checks. */
4910                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4911                 if (err)
4912                         return err;
4913
4914                 state = func(env, reg);
4915                 err = update_stack_depth(env, state, off);
4916                 if (err)
4917                         return err;
4918
4919                 if (t == BPF_READ)
4920                         err = check_stack_read(env, regno, off, size,
4921                                                value_regno);
4922                 else
4923                         err = check_stack_write(env, regno, off, size,
4924                                                 value_regno, insn_idx);
4925         } else if (reg_is_pkt_pointer(reg)) {
4926                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4927                         verbose(env, "cannot write into packet\n");
4928                         return -EACCES;
4929                 }
4930                 if (t == BPF_WRITE && value_regno >= 0 &&
4931                     is_pointer_value(env, value_regno)) {
4932                         verbose(env, "R%d leaks addr into packet\n",
4933                                 value_regno);
4934                         return -EACCES;
4935                 }
4936                 err = check_packet_access(env, regno, off, size, false);
4937                 if (!err && t == BPF_READ && value_regno >= 0)
4938                         mark_reg_unknown(env, regs, value_regno);
4939         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4940                 if (t == BPF_WRITE && value_regno >= 0 &&
4941                     is_pointer_value(env, value_regno)) {
4942                         verbose(env, "R%d leaks addr into flow keys\n",
4943                                 value_regno);
4944                         return -EACCES;
4945                 }
4946
4947                 err = check_flow_keys_access(env, off, size);
4948                 if (!err && t == BPF_READ && value_regno >= 0)
4949                         mark_reg_unknown(env, regs, value_regno);
4950         } else if (type_is_sk_pointer(reg->type)) {
4951                 if (t == BPF_WRITE) {
4952                         verbose(env, "R%d cannot write into %s\n",
4953                                 regno, reg_type_str(env, reg->type));
4954                         return -EACCES;
4955                 }
4956                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4957                 if (!err && value_regno >= 0)
4958                         mark_reg_unknown(env, regs, value_regno);
4959         } else if (reg->type == PTR_TO_TP_BUFFER) {
4960                 err = check_tp_buffer_access(env, reg, regno, off, size);
4961                 if (!err && t == BPF_READ && value_regno >= 0)
4962                         mark_reg_unknown(env, regs, value_regno);
4963         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4964                    !type_may_be_null(reg->type)) {
4965                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4966                                               value_regno);
4967         } else if (reg->type == CONST_PTR_TO_MAP) {
4968                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4969                                               value_regno);
4970         } else if (base_type(reg->type) == PTR_TO_BUF) {
4971                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4972                 u32 *max_access;
4973
4974                 if (rdonly_mem) {
4975                         if (t == BPF_WRITE) {
4976                                 verbose(env, "R%d cannot write into %s\n",
4977                                         regno, reg_type_str(env, reg->type));
4978                                 return -EACCES;
4979                         }
4980                         max_access = &env->prog->aux->max_rdonly_access;
4981                 } else {
4982                         max_access = &env->prog->aux->max_rdwr_access;
4983                 }
4984
4985                 err = check_buffer_access(env, reg, regno, off, size, false,
4986                                           max_access);
4987
4988                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4989                         mark_reg_unknown(env, regs, value_regno);
4990         } else {
4991                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4992                         reg_type_str(env, reg->type));
4993                 return -EACCES;
4994         }
4995
4996         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4997             regs[value_regno].type == SCALAR_VALUE) {
4998                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4999                 coerce_reg_to_size(&regs[value_regno], size);
5000         }
5001         return err;
5002 }
5003
5004 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5005 {
5006         int load_reg;
5007         int err;
5008
5009         switch (insn->imm) {
5010         case BPF_ADD:
5011         case BPF_ADD | BPF_FETCH:
5012         case BPF_AND:
5013         case BPF_AND | BPF_FETCH:
5014         case BPF_OR:
5015         case BPF_OR | BPF_FETCH:
5016         case BPF_XOR:
5017         case BPF_XOR | BPF_FETCH:
5018         case BPF_XCHG:
5019         case BPF_CMPXCHG:
5020                 break;
5021         default:
5022                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5023                 return -EINVAL;
5024         }
5025
5026         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5027                 verbose(env, "invalid atomic operand size\n");
5028                 return -EINVAL;
5029         }
5030
5031         /* check src1 operand */
5032         err = check_reg_arg(env, insn->src_reg, SRC_OP);
5033         if (err)
5034                 return err;
5035
5036         /* check src2 operand */
5037         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5038         if (err)
5039                 return err;
5040
5041         if (insn->imm == BPF_CMPXCHG) {
5042                 /* Check comparison of R0 with memory location */
5043                 const u32 aux_reg = BPF_REG_0;
5044
5045                 err = check_reg_arg(env, aux_reg, SRC_OP);
5046                 if (err)
5047                         return err;
5048
5049                 if (is_pointer_value(env, aux_reg)) {
5050                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
5051                         return -EACCES;
5052                 }
5053         }
5054
5055         if (is_pointer_value(env, insn->src_reg)) {
5056                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5057                 return -EACCES;
5058         }
5059
5060         if (is_ctx_reg(env, insn->dst_reg) ||
5061             is_pkt_reg(env, insn->dst_reg) ||
5062             is_flow_key_reg(env, insn->dst_reg) ||
5063             is_sk_reg(env, insn->dst_reg)) {
5064                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5065                         insn->dst_reg,
5066                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5067                 return -EACCES;
5068         }
5069
5070         if (insn->imm & BPF_FETCH) {
5071                 if (insn->imm == BPF_CMPXCHG)
5072                         load_reg = BPF_REG_0;
5073                 else
5074                         load_reg = insn->src_reg;
5075
5076                 /* check and record load of old value */
5077                 err = check_reg_arg(env, load_reg, DST_OP);
5078                 if (err)
5079                         return err;
5080         } else {
5081                 /* This instruction accesses a memory location but doesn't
5082                  * actually load it into a register.
5083                  */
5084                 load_reg = -1;
5085         }
5086
5087         /* Check whether we can read the memory, with second call for fetch
5088          * case to simulate the register fill.
5089          */
5090         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5091                                BPF_SIZE(insn->code), BPF_READ, -1, true);
5092         if (!err && load_reg >= 0)
5093                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5094                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
5095                                        true);
5096         if (err)
5097                 return err;
5098
5099         /* Check whether we can write into the same memory. */
5100         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5101                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5102         if (err)
5103                 return err;
5104
5105         return 0;
5106 }
5107
5108 /* When register 'regno' is used to read the stack (either directly or through
5109  * a helper function) make sure that it's within stack boundary and, depending
5110  * on the access type, that all elements of the stack are initialized.
5111  *
5112  * 'off' includes 'regno->off', but not its dynamic part (if any).
5113  *
5114  * All registers that have been spilled on the stack in the slots within the
5115  * read offsets are marked as read.
5116  */
5117 static int check_stack_range_initialized(
5118                 struct bpf_verifier_env *env, int regno, int off,
5119                 int access_size, bool zero_size_allowed,
5120                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5121 {
5122         struct bpf_reg_state *reg = reg_state(env, regno);
5123         struct bpf_func_state *state = func(env, reg);
5124         int err, min_off, max_off, i, j, slot, spi;
5125         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5126         enum bpf_access_type bounds_check_type;
5127         /* Some accesses can write anything into the stack, others are
5128          * read-only.
5129          */
5130         bool clobber = false;
5131
5132         if (access_size == 0 && !zero_size_allowed) {
5133                 verbose(env, "invalid zero-sized read\n");
5134                 return -EACCES;
5135         }
5136
5137         if (type == ACCESS_HELPER) {
5138                 /* The bounds checks for writes are more permissive than for
5139                  * reads. However, if raw_mode is not set, we'll do extra
5140                  * checks below.
5141                  */
5142                 bounds_check_type = BPF_WRITE;
5143                 clobber = true;
5144         } else {
5145                 bounds_check_type = BPF_READ;
5146         }
5147         err = check_stack_access_within_bounds(env, regno, off, access_size,
5148                                                type, bounds_check_type);
5149         if (err)
5150                 return err;
5151
5152
5153         if (tnum_is_const(reg->var_off)) {
5154                 min_off = max_off = reg->var_off.value + off;
5155         } else {
5156                 /* Variable offset is prohibited for unprivileged mode for
5157                  * simplicity since it requires corresponding support in
5158                  * Spectre masking for stack ALU.
5159                  * See also retrieve_ptr_limit().
5160                  */
5161                 if (!env->bypass_spec_v1) {
5162                         char tn_buf[48];
5163
5164                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5165                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5166                                 regno, err_extra, tn_buf);
5167                         return -EACCES;
5168                 }
5169                 /* Only initialized buffer on stack is allowed to be accessed
5170                  * with variable offset. With uninitialized buffer it's hard to
5171                  * guarantee that whole memory is marked as initialized on
5172                  * helper return since specific bounds are unknown what may
5173                  * cause uninitialized stack leaking.
5174                  */
5175                 if (meta && meta->raw_mode)
5176                         meta = NULL;
5177
5178                 min_off = reg->smin_value + off;
5179                 max_off = reg->smax_value + off;
5180         }
5181
5182         if (meta && meta->raw_mode) {
5183                 meta->access_size = access_size;
5184                 meta->regno = regno;
5185                 return 0;
5186         }
5187
5188         for (i = min_off; i < max_off + access_size; i++) {
5189                 u8 *stype;
5190
5191                 slot = -i - 1;
5192                 spi = slot / BPF_REG_SIZE;
5193                 if (state->allocated_stack <= slot)
5194                         goto err;
5195                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5196                 if (*stype == STACK_MISC)
5197                         goto mark;
5198                 if (*stype == STACK_ZERO) {
5199                         if (clobber) {
5200                                 /* helper can write anything into the stack */
5201                                 *stype = STACK_MISC;
5202                         }
5203                         goto mark;
5204                 }
5205
5206                 if (is_spilled_reg(&state->stack[spi]) &&
5207                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5208                      env->allow_ptr_leaks)) {
5209                         if (clobber) {
5210                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5211                                 for (j = 0; j < BPF_REG_SIZE; j++)
5212                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5213                         }
5214                         goto mark;
5215                 }
5216
5217 err:
5218                 if (tnum_is_const(reg->var_off)) {
5219                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5220                                 err_extra, regno, min_off, i - min_off, access_size);
5221                 } else {
5222                         char tn_buf[48];
5223
5224                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5225                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5226                                 err_extra, regno, tn_buf, i - min_off, access_size);
5227                 }
5228                 return -EACCES;
5229 mark:
5230                 /* reading any byte out of 8-byte 'spill_slot' will cause
5231                  * the whole slot to be marked as 'read'
5232                  */
5233                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5234                               state->stack[spi].spilled_ptr.parent,
5235                               REG_LIVE_READ64);
5236                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5237                  * be sure that whether stack slot is written to or not. Hence,
5238                  * we must still conservatively propagate reads upwards even if
5239                  * helper may write to the entire memory range.
5240                  */
5241         }
5242         return update_stack_depth(env, state, min_off);
5243 }
5244
5245 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5246                                    int access_size, bool zero_size_allowed,
5247                                    struct bpf_call_arg_meta *meta)
5248 {
5249         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5250         u32 *max_access;
5251
5252         switch (base_type(reg->type)) {
5253         case PTR_TO_PACKET:
5254         case PTR_TO_PACKET_META:
5255                 return check_packet_access(env, regno, reg->off, access_size,
5256                                            zero_size_allowed);
5257         case PTR_TO_MAP_KEY:
5258                 if (meta && meta->raw_mode) {
5259                         verbose(env, "R%d cannot write into %s\n", regno,
5260                                 reg_type_str(env, reg->type));
5261                         return -EACCES;
5262                 }
5263                 return check_mem_region_access(env, regno, reg->off, access_size,
5264                                                reg->map_ptr->key_size, false);
5265         case PTR_TO_MAP_VALUE:
5266                 if (check_map_access_type(env, regno, reg->off, access_size,
5267                                           meta && meta->raw_mode ? BPF_WRITE :
5268                                           BPF_READ))
5269                         return -EACCES;
5270                 return check_map_access(env, regno, reg->off, access_size,
5271                                         zero_size_allowed, ACCESS_HELPER);
5272         case PTR_TO_MEM:
5273                 if (type_is_rdonly_mem(reg->type)) {
5274                         if (meta && meta->raw_mode) {
5275                                 verbose(env, "R%d cannot write into %s\n", regno,
5276                                         reg_type_str(env, reg->type));
5277                                 return -EACCES;
5278                         }
5279                 }
5280                 return check_mem_region_access(env, regno, reg->off,
5281                                                access_size, reg->mem_size,
5282                                                zero_size_allowed);
5283         case PTR_TO_BUF:
5284                 if (type_is_rdonly_mem(reg->type)) {
5285                         if (meta && meta->raw_mode) {
5286                                 verbose(env, "R%d cannot write into %s\n", regno,
5287                                         reg_type_str(env, reg->type));
5288                                 return -EACCES;
5289                         }
5290
5291                         max_access = &env->prog->aux->max_rdonly_access;
5292                 } else {
5293                         max_access = &env->prog->aux->max_rdwr_access;
5294                 }
5295                 return check_buffer_access(env, reg, regno, reg->off,
5296                                            access_size, zero_size_allowed,
5297                                            max_access);
5298         case PTR_TO_STACK:
5299                 return check_stack_range_initialized(
5300                                 env,
5301                                 regno, reg->off, access_size,
5302                                 zero_size_allowed, ACCESS_HELPER, meta);
5303         case PTR_TO_CTX:
5304                 /* in case the function doesn't know how to access the context,
5305                  * (because we are in a program of type SYSCALL for example), we
5306                  * can not statically check its size.
5307                  * Dynamically check it now.
5308                  */
5309                 if (!env->ops->convert_ctx_access) {
5310                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5311                         int offset = access_size - 1;
5312
5313                         /* Allow zero-byte read from PTR_TO_CTX */
5314                         if (access_size == 0)
5315                                 return zero_size_allowed ? 0 : -EACCES;
5316
5317                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5318                                                 atype, -1, false);
5319                 }
5320
5321                 fallthrough;
5322         default: /* scalar_value or invalid ptr */
5323                 /* Allow zero-byte read from NULL, regardless of pointer type */
5324                 if (zero_size_allowed && access_size == 0 &&
5325                     register_is_null(reg))
5326                         return 0;
5327
5328                 verbose(env, "R%d type=%s ", regno,
5329                         reg_type_str(env, reg->type));
5330                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5331                 return -EACCES;
5332         }
5333 }
5334
5335 static int check_mem_size_reg(struct bpf_verifier_env *env,
5336                               struct bpf_reg_state *reg, u32 regno,
5337                               bool zero_size_allowed,
5338                               struct bpf_call_arg_meta *meta)
5339 {
5340         int err;
5341
5342         /* This is used to refine r0 return value bounds for helpers
5343          * that enforce this value as an upper bound on return values.
5344          * See do_refine_retval_range() for helpers that can refine
5345          * the return value. C type of helper is u32 so we pull register
5346          * bound from umax_value however, if negative verifier errors
5347          * out. Only upper bounds can be learned because retval is an
5348          * int type and negative retvals are allowed.
5349          */
5350         meta->msize_max_value = reg->umax_value;
5351
5352         /* The register is SCALAR_VALUE; the access check
5353          * happens using its boundaries.
5354          */
5355         if (!tnum_is_const(reg->var_off))
5356                 /* For unprivileged variable accesses, disable raw
5357                  * mode so that the program is required to
5358                  * initialize all the memory that the helper could
5359                  * just partially fill up.
5360                  */
5361                 meta = NULL;
5362
5363         if (reg->smin_value < 0) {
5364                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5365                         regno);
5366                 return -EACCES;
5367         }
5368
5369         if (reg->umin_value == 0) {
5370                 err = check_helper_mem_access(env, regno - 1, 0,
5371                                               zero_size_allowed,
5372                                               meta);
5373                 if (err)
5374                         return err;
5375         }
5376
5377         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5378                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5379                         regno);
5380                 return -EACCES;
5381         }
5382         err = check_helper_mem_access(env, regno - 1,
5383                                       reg->umax_value,
5384                                       zero_size_allowed, meta);
5385         if (!err)
5386                 err = mark_chain_precision(env, regno);
5387         return err;
5388 }
5389
5390 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5391                    u32 regno, u32 mem_size)
5392 {
5393         bool may_be_null = type_may_be_null(reg->type);
5394         struct bpf_reg_state saved_reg;
5395         struct bpf_call_arg_meta meta;
5396         int err;
5397
5398         if (register_is_null(reg))
5399                 return 0;
5400
5401         memset(&meta, 0, sizeof(meta));
5402         /* Assuming that the register contains a value check if the memory
5403          * access is safe. Temporarily save and restore the register's state as
5404          * the conversion shouldn't be visible to a caller.
5405          */
5406         if (may_be_null) {
5407                 saved_reg = *reg;
5408                 mark_ptr_not_null_reg(reg);
5409         }
5410
5411         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5412         /* Check access for BPF_WRITE */
5413         meta.raw_mode = true;
5414         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5415
5416         if (may_be_null)
5417                 *reg = saved_reg;
5418
5419         return err;
5420 }
5421
5422 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5423                              u32 regno)
5424 {
5425         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5426         bool may_be_null = type_may_be_null(mem_reg->type);
5427         struct bpf_reg_state saved_reg;
5428         struct bpf_call_arg_meta meta;
5429         int err;
5430
5431         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5432
5433         memset(&meta, 0, sizeof(meta));
5434
5435         if (may_be_null) {
5436                 saved_reg = *mem_reg;
5437                 mark_ptr_not_null_reg(mem_reg);
5438         }
5439
5440         err = check_mem_size_reg(env, reg, regno, true, &meta);
5441         /* Check access for BPF_WRITE */
5442         meta.raw_mode = true;
5443         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5444
5445         if (may_be_null)
5446                 *mem_reg = saved_reg;
5447         return err;
5448 }
5449
5450 /* Implementation details:
5451  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5452  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5453  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5454  * value_or_null->value transition, since the verifier only cares about
5455  * the range of access to valid map value pointer and doesn't care about actual
5456  * address of the map element.
5457  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5458  * reg->id > 0 after value_or_null->value transition. By doing so
5459  * two bpf_map_lookups will be considered two different pointers that
5460  * point to different bpf_spin_locks.
5461  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5462  * dead-locks.
5463  * Since only one bpf_spin_lock is allowed the checks are simpler than
5464  * reg_is_refcounted() logic. The verifier needs to remember only
5465  * one spin_lock instead of array of acquired_refs.
5466  * cur_state->active_spin_lock remembers which map value element got locked
5467  * and clears it after bpf_spin_unlock.
5468  */
5469 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5470                              bool is_lock)
5471 {
5472         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5473         struct bpf_verifier_state *cur = env->cur_state;
5474         bool is_const = tnum_is_const(reg->var_off);
5475         struct bpf_map *map = reg->map_ptr;
5476         u64 val = reg->var_off.value;
5477
5478         if (!is_const) {
5479                 verbose(env,
5480                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5481                         regno);
5482                 return -EINVAL;
5483         }
5484         if (!map->btf) {
5485                 verbose(env,
5486                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5487                         map->name);
5488                 return -EINVAL;
5489         }
5490         if (!map_value_has_spin_lock(map)) {
5491                 if (map->spin_lock_off == -E2BIG)
5492                         verbose(env,
5493                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5494                                 map->name);
5495                 else if (map->spin_lock_off == -ENOENT)
5496                         verbose(env,
5497                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5498                                 map->name);
5499                 else
5500                         verbose(env,
5501                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5502                                 map->name);
5503                 return -EINVAL;
5504         }
5505         if (map->spin_lock_off != val + reg->off) {
5506                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5507                         val + reg->off);
5508                 return -EINVAL;
5509         }
5510         if (is_lock) {
5511                 if (cur->active_spin_lock) {
5512                         verbose(env,
5513                                 "Locking two bpf_spin_locks are not allowed\n");
5514                         return -EINVAL;
5515                 }
5516                 cur->active_spin_lock = reg->id;
5517         } else {
5518                 if (!cur->active_spin_lock) {
5519                         verbose(env, "bpf_spin_unlock without taking a lock\n");
5520                         return -EINVAL;
5521                 }
5522                 if (cur->active_spin_lock != reg->id) {
5523                         verbose(env, "bpf_spin_unlock of different lock\n");
5524                         return -EINVAL;
5525                 }
5526                 cur->active_spin_lock = 0;
5527         }
5528         return 0;
5529 }
5530
5531 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5532                               struct bpf_call_arg_meta *meta)
5533 {
5534         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5535         bool is_const = tnum_is_const(reg->var_off);
5536         struct bpf_map *map = reg->map_ptr;
5537         u64 val = reg->var_off.value;
5538
5539         if (!is_const) {
5540                 verbose(env,
5541                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5542                         regno);
5543                 return -EINVAL;
5544         }
5545         if (!map->btf) {
5546                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5547                         map->name);
5548                 return -EINVAL;
5549         }
5550         if (!map_value_has_timer(map)) {
5551                 if (map->timer_off == -E2BIG)
5552                         verbose(env,
5553                                 "map '%s' has more than one 'struct bpf_timer'\n",
5554                                 map->name);
5555                 else if (map->timer_off == -ENOENT)
5556                         verbose(env,
5557                                 "map '%s' doesn't have 'struct bpf_timer'\n",
5558                                 map->name);
5559                 else
5560                         verbose(env,
5561                                 "map '%s' is not a struct type or bpf_timer is mangled\n",
5562                                 map->name);
5563                 return -EINVAL;
5564         }
5565         if (map->timer_off != val + reg->off) {
5566                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5567                         val + reg->off, map->timer_off);
5568                 return -EINVAL;
5569         }
5570         if (meta->map_ptr) {
5571                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5572                 return -EFAULT;
5573         }
5574         meta->map_uid = reg->map_uid;
5575         meta->map_ptr = map;
5576         return 0;
5577 }
5578
5579 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5580                              struct bpf_call_arg_meta *meta)
5581 {
5582         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5583         struct bpf_map_value_off_desc *off_desc;
5584         struct bpf_map *map_ptr = reg->map_ptr;
5585         u32 kptr_off;
5586         int ret;
5587
5588         if (!tnum_is_const(reg->var_off)) {
5589                 verbose(env,
5590                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5591                         regno);
5592                 return -EINVAL;
5593         }
5594         if (!map_ptr->btf) {
5595                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5596                         map_ptr->name);
5597                 return -EINVAL;
5598         }
5599         if (!map_value_has_kptrs(map_ptr)) {
5600                 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5601                 if (ret == -E2BIG)
5602                         verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5603                                 BPF_MAP_VALUE_OFF_MAX);
5604                 else if (ret == -EEXIST)
5605                         verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5606                 else
5607                         verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5608                 return -EINVAL;
5609         }
5610
5611         meta->map_ptr = map_ptr;
5612         kptr_off = reg->off + reg->var_off.value;
5613         off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5614         if (!off_desc) {
5615                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5616                 return -EACCES;
5617         }
5618         if (off_desc->type != BPF_KPTR_REF) {
5619                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5620                 return -EACCES;
5621         }
5622         meta->kptr_off_desc = off_desc;
5623         return 0;
5624 }
5625
5626 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5627 {
5628         return type == ARG_CONST_SIZE ||
5629                type == ARG_CONST_SIZE_OR_ZERO;
5630 }
5631
5632 static bool arg_type_is_release(enum bpf_arg_type type)
5633 {
5634         return type & OBJ_RELEASE;
5635 }
5636
5637 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5638 {
5639         return base_type(type) == ARG_PTR_TO_DYNPTR;
5640 }
5641
5642 static int int_ptr_type_to_size(enum bpf_arg_type type)
5643 {
5644         if (type == ARG_PTR_TO_INT)
5645                 return sizeof(u32);
5646         else if (type == ARG_PTR_TO_LONG)
5647                 return sizeof(u64);
5648
5649         return -EINVAL;
5650 }
5651
5652 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5653                                  const struct bpf_call_arg_meta *meta,
5654                                  enum bpf_arg_type *arg_type)
5655 {
5656         if (!meta->map_ptr) {
5657                 /* kernel subsystem misconfigured verifier */
5658                 verbose(env, "invalid map_ptr to access map->type\n");
5659                 return -EACCES;
5660         }
5661
5662         switch (meta->map_ptr->map_type) {
5663         case BPF_MAP_TYPE_SOCKMAP:
5664         case BPF_MAP_TYPE_SOCKHASH:
5665                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5666                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5667                 } else {
5668                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
5669                         return -EINVAL;
5670                 }
5671                 break;
5672         case BPF_MAP_TYPE_BLOOM_FILTER:
5673                 if (meta->func_id == BPF_FUNC_map_peek_elem)
5674                         *arg_type = ARG_PTR_TO_MAP_VALUE;
5675                 break;
5676         default:
5677                 break;
5678         }
5679         return 0;
5680 }
5681
5682 struct bpf_reg_types {
5683         const enum bpf_reg_type types[10];
5684         u32 *btf_id;
5685 };
5686
5687 static const struct bpf_reg_types map_key_value_types = {
5688         .types = {
5689                 PTR_TO_STACK,
5690                 PTR_TO_PACKET,
5691                 PTR_TO_PACKET_META,
5692                 PTR_TO_MAP_KEY,
5693                 PTR_TO_MAP_VALUE,
5694         },
5695 };
5696
5697 static const struct bpf_reg_types sock_types = {
5698         .types = {
5699                 PTR_TO_SOCK_COMMON,
5700                 PTR_TO_SOCKET,
5701                 PTR_TO_TCP_SOCK,
5702                 PTR_TO_XDP_SOCK,
5703         },
5704 };
5705
5706 #ifdef CONFIG_NET
5707 static const struct bpf_reg_types btf_id_sock_common_types = {
5708         .types = {
5709                 PTR_TO_SOCK_COMMON,
5710                 PTR_TO_SOCKET,
5711                 PTR_TO_TCP_SOCK,
5712                 PTR_TO_XDP_SOCK,
5713                 PTR_TO_BTF_ID,
5714         },
5715         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5716 };
5717 #endif
5718
5719 static const struct bpf_reg_types mem_types = {
5720         .types = {
5721                 PTR_TO_STACK,
5722                 PTR_TO_PACKET,
5723                 PTR_TO_PACKET_META,
5724                 PTR_TO_MAP_KEY,
5725                 PTR_TO_MAP_VALUE,
5726                 PTR_TO_MEM,
5727                 PTR_TO_MEM | MEM_ALLOC,
5728                 PTR_TO_BUF,
5729         },
5730 };
5731
5732 static const struct bpf_reg_types int_ptr_types = {
5733         .types = {
5734                 PTR_TO_STACK,
5735                 PTR_TO_PACKET,
5736                 PTR_TO_PACKET_META,
5737                 PTR_TO_MAP_KEY,
5738                 PTR_TO_MAP_VALUE,
5739         },
5740 };
5741
5742 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5743 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5744 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5745 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5746 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5747 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5748 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5749 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5750 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5751 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5752 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5753 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5754 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5755 static const struct bpf_reg_types dynptr_types = {
5756         .types = {
5757                 PTR_TO_STACK,
5758                 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5759         }
5760 };
5761
5762 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5763         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
5764         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
5765         [ARG_CONST_SIZE]                = &scalar_types,
5766         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
5767         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
5768         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
5769         [ARG_PTR_TO_CTX]                = &context_types,
5770         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
5771 #ifdef CONFIG_NET
5772         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5773 #endif
5774         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
5775         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
5776         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
5777         [ARG_PTR_TO_MEM]                = &mem_types,
5778         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
5779         [ARG_PTR_TO_INT]                = &int_ptr_types,
5780         [ARG_PTR_TO_LONG]               = &int_ptr_types,
5781         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
5782         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
5783         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
5784         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
5785         [ARG_PTR_TO_TIMER]              = &timer_types,
5786         [ARG_PTR_TO_KPTR]               = &kptr_types,
5787         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
5788 };
5789
5790 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5791                           enum bpf_arg_type arg_type,
5792                           const u32 *arg_btf_id,
5793                           struct bpf_call_arg_meta *meta)
5794 {
5795         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5796         enum bpf_reg_type expected, type = reg->type;
5797         const struct bpf_reg_types *compatible;
5798         int i, j;
5799
5800         compatible = compatible_reg_types[base_type(arg_type)];
5801         if (!compatible) {
5802                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5803                 return -EFAULT;
5804         }
5805
5806         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5807          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5808          *
5809          * Same for MAYBE_NULL:
5810          *
5811          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5812          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5813          *
5814          * Therefore we fold these flags depending on the arg_type before comparison.
5815          */
5816         if (arg_type & MEM_RDONLY)
5817                 type &= ~MEM_RDONLY;
5818         if (arg_type & PTR_MAYBE_NULL)
5819                 type &= ~PTR_MAYBE_NULL;
5820
5821         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5822                 expected = compatible->types[i];
5823                 if (expected == NOT_INIT)
5824                         break;
5825
5826                 if (type == expected)
5827                         goto found;
5828         }
5829
5830         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5831         for (j = 0; j + 1 < i; j++)
5832                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5833         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5834         return -EACCES;
5835
5836 found:
5837         if (reg->type == PTR_TO_BTF_ID) {
5838                 /* For bpf_sk_release, it needs to match against first member
5839                  * 'struct sock_common', hence make an exception for it. This
5840                  * allows bpf_sk_release to work for multiple socket types.
5841                  */
5842                 bool strict_type_match = arg_type_is_release(arg_type) &&
5843                                          meta->func_id != BPF_FUNC_sk_release;
5844
5845                 if (!arg_btf_id) {
5846                         if (!compatible->btf_id) {
5847                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5848                                 return -EFAULT;
5849                         }
5850                         arg_btf_id = compatible->btf_id;
5851                 }
5852
5853                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5854                         if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5855                                 return -EACCES;
5856                 } else {
5857                         if (arg_btf_id == BPF_PTR_POISON) {
5858                                 verbose(env, "verifier internal error:");
5859                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5860                                         regno);
5861                                 return -EACCES;
5862                         }
5863
5864                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5865                                                   btf_vmlinux, *arg_btf_id,
5866                                                   strict_type_match)) {
5867                                 verbose(env, "R%d is of type %s but %s is expected\n",
5868                                         regno, kernel_type_name(reg->btf, reg->btf_id),
5869                                         kernel_type_name(btf_vmlinux, *arg_btf_id));
5870                                 return -EACCES;
5871                         }
5872                 }
5873         }
5874
5875         return 0;
5876 }
5877
5878 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5879                            const struct bpf_reg_state *reg, int regno,
5880                            enum bpf_arg_type arg_type)
5881 {
5882         enum bpf_reg_type type = reg->type;
5883         bool fixed_off_ok = false;
5884
5885         switch ((u32)type) {
5886         /* Pointer types where reg offset is explicitly allowed: */
5887         case PTR_TO_STACK:
5888                 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5889                         verbose(env, "cannot pass in dynptr at an offset\n");
5890                         return -EINVAL;
5891                 }
5892                 fallthrough;
5893         case PTR_TO_PACKET:
5894         case PTR_TO_PACKET_META:
5895         case PTR_TO_MAP_KEY:
5896         case PTR_TO_MAP_VALUE:
5897         case PTR_TO_MEM:
5898         case PTR_TO_MEM | MEM_RDONLY:
5899         case PTR_TO_MEM | MEM_ALLOC:
5900         case PTR_TO_BUF:
5901         case PTR_TO_BUF | MEM_RDONLY:
5902         case SCALAR_VALUE:
5903                 /* Some of the argument types nevertheless require a
5904                  * zero register offset.
5905                  */
5906                 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5907                         return 0;
5908                 break;
5909         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5910          * fixed offset.
5911          */
5912         case PTR_TO_BTF_ID:
5913                 /* When referenced PTR_TO_BTF_ID is passed to release function,
5914                  * it's fixed offset must be 0. In the other cases, fixed offset
5915                  * can be non-zero.
5916                  */
5917                 if (arg_type_is_release(arg_type) && reg->off) {
5918                         verbose(env, "R%d must have zero offset when passed to release func\n",
5919                                 regno);
5920                         return -EINVAL;
5921                 }
5922                 /* For arg is release pointer, fixed_off_ok must be false, but
5923                  * we already checked and rejected reg->off != 0 above, so set
5924                  * to true to allow fixed offset for all other cases.
5925                  */
5926                 fixed_off_ok = true;
5927                 break;
5928         default:
5929                 break;
5930         }
5931         return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5932 }
5933
5934 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5935 {
5936         struct bpf_func_state *state = func(env, reg);
5937         int spi = get_spi(reg->off);
5938
5939         return state->stack[spi].spilled_ptr.id;
5940 }
5941
5942 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5943                           struct bpf_call_arg_meta *meta,
5944                           const struct bpf_func_proto *fn)
5945 {
5946         u32 regno = BPF_REG_1 + arg;
5947         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5948         enum bpf_arg_type arg_type = fn->arg_type[arg];
5949         enum bpf_reg_type type = reg->type;
5950         u32 *arg_btf_id = NULL;
5951         int err = 0;
5952
5953         if (arg_type == ARG_DONTCARE)
5954                 return 0;
5955
5956         err = check_reg_arg(env, regno, SRC_OP);
5957         if (err)
5958                 return err;
5959
5960         if (arg_type == ARG_ANYTHING) {
5961                 if (is_pointer_value(env, regno)) {
5962                         verbose(env, "R%d leaks addr into helper function\n",
5963                                 regno);
5964                         return -EACCES;
5965                 }
5966                 return 0;
5967         }
5968
5969         if (type_is_pkt_pointer(type) &&
5970             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5971                 verbose(env, "helper access to the packet is not allowed\n");
5972                 return -EACCES;
5973         }
5974
5975         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5976                 err = resolve_map_arg_type(env, meta, &arg_type);
5977                 if (err)
5978                         return err;
5979         }
5980
5981         if (register_is_null(reg) && type_may_be_null(arg_type))
5982                 /* A NULL register has a SCALAR_VALUE type, so skip
5983                  * type checking.
5984                  */
5985                 goto skip_type_check;
5986
5987         /* arg_btf_id and arg_size are in a union. */
5988         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5989                 arg_btf_id = fn->arg_btf_id[arg];
5990
5991         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5992         if (err)
5993                 return err;
5994
5995         err = check_func_arg_reg_off(env, reg, regno, arg_type);
5996         if (err)
5997                 return err;
5998
5999 skip_type_check:
6000         if (arg_type_is_release(arg_type)) {
6001                 if (arg_type_is_dynptr(arg_type)) {
6002                         struct bpf_func_state *state = func(env, reg);
6003                         int spi = get_spi(reg->off);
6004
6005                         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6006                             !state->stack[spi].spilled_ptr.id) {
6007                                 verbose(env, "arg %d is an unacquired reference\n", regno);
6008                                 return -EINVAL;
6009                         }
6010                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6011                         verbose(env, "R%d must be referenced when passed to release function\n",
6012                                 regno);
6013                         return -EINVAL;
6014                 }
6015                 if (meta->release_regno) {
6016                         verbose(env, "verifier internal error: more than one release argument\n");
6017                         return -EFAULT;
6018                 }
6019                 meta->release_regno = regno;
6020         }
6021
6022         if (reg->ref_obj_id) {
6023                 if (meta->ref_obj_id) {
6024                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6025                                 regno, reg->ref_obj_id,
6026                                 meta->ref_obj_id);
6027                         return -EFAULT;
6028                 }
6029                 meta->ref_obj_id = reg->ref_obj_id;
6030         }
6031
6032         switch (base_type(arg_type)) {
6033         case ARG_CONST_MAP_PTR:
6034                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6035                 if (meta->map_ptr) {
6036                         /* Use map_uid (which is unique id of inner map) to reject:
6037                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6038                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6039                          * if (inner_map1 && inner_map2) {
6040                          *     timer = bpf_map_lookup_elem(inner_map1);
6041                          *     if (timer)
6042                          *         // mismatch would have been allowed
6043                          *         bpf_timer_init(timer, inner_map2);
6044                          * }
6045                          *
6046                          * Comparing map_ptr is enough to distinguish normal and outer maps.
6047                          */
6048                         if (meta->map_ptr != reg->map_ptr ||
6049                             meta->map_uid != reg->map_uid) {
6050                                 verbose(env,
6051                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6052                                         meta->map_uid, reg->map_uid);
6053                                 return -EINVAL;
6054                         }
6055                 }
6056                 meta->map_ptr = reg->map_ptr;
6057                 meta->map_uid = reg->map_uid;
6058                 break;
6059         case ARG_PTR_TO_MAP_KEY:
6060                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6061                  * check that [key, key + map->key_size) are within
6062                  * stack limits and initialized
6063                  */
6064                 if (!meta->map_ptr) {
6065                         /* in function declaration map_ptr must come before
6066                          * map_key, so that it's verified and known before
6067                          * we have to check map_key here. Otherwise it means
6068                          * that kernel subsystem misconfigured verifier
6069                          */
6070                         verbose(env, "invalid map_ptr to access map->key\n");
6071                         return -EACCES;
6072                 }
6073                 err = check_helper_mem_access(env, regno,
6074                                               meta->map_ptr->key_size, false,
6075                                               NULL);
6076                 break;
6077         case ARG_PTR_TO_MAP_VALUE:
6078                 if (type_may_be_null(arg_type) && register_is_null(reg))
6079                         return 0;
6080
6081                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6082                  * check [value, value + map->value_size) validity
6083                  */
6084                 if (!meta->map_ptr) {
6085                         /* kernel subsystem misconfigured verifier */
6086                         verbose(env, "invalid map_ptr to access map->value\n");
6087                         return -EACCES;
6088                 }
6089                 meta->raw_mode = arg_type & MEM_UNINIT;
6090                 err = check_helper_mem_access(env, regno,
6091                                               meta->map_ptr->value_size, false,
6092                                               meta);
6093                 break;
6094         case ARG_PTR_TO_PERCPU_BTF_ID:
6095                 if (!reg->btf_id) {
6096                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6097                         return -EACCES;
6098                 }
6099                 meta->ret_btf = reg->btf;
6100                 meta->ret_btf_id = reg->btf_id;
6101                 break;
6102         case ARG_PTR_TO_SPIN_LOCK:
6103                 if (meta->func_id == BPF_FUNC_spin_lock) {
6104                         if (process_spin_lock(env, regno, true))
6105                                 return -EACCES;
6106                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6107                         if (process_spin_lock(env, regno, false))
6108                                 return -EACCES;
6109                 } else {
6110                         verbose(env, "verifier internal error\n");
6111                         return -EFAULT;
6112                 }
6113                 break;
6114         case ARG_PTR_TO_TIMER:
6115                 if (process_timer_func(env, regno, meta))
6116                         return -EACCES;
6117                 break;
6118         case ARG_PTR_TO_FUNC:
6119                 meta->subprogno = reg->subprogno;
6120                 break;
6121         case ARG_PTR_TO_MEM:
6122                 /* The access to this pointer is only checked when we hit the
6123                  * next is_mem_size argument below.
6124                  */
6125                 meta->raw_mode = arg_type & MEM_UNINIT;
6126                 if (arg_type & MEM_FIXED_SIZE) {
6127                         err = check_helper_mem_access(env, regno,
6128                                                       fn->arg_size[arg], false,
6129                                                       meta);
6130                 }
6131                 break;
6132         case ARG_CONST_SIZE:
6133                 err = check_mem_size_reg(env, reg, regno, false, meta);
6134                 break;
6135         case ARG_CONST_SIZE_OR_ZERO:
6136                 err = check_mem_size_reg(env, reg, regno, true, meta);
6137                 break;
6138         case ARG_PTR_TO_DYNPTR:
6139                 /* We only need to check for initialized / uninitialized helper
6140                  * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6141                  * assumption is that if it is, that a helper function
6142                  * initialized the dynptr on behalf of the BPF program.
6143                  */
6144                 if (base_type(reg->type) == PTR_TO_DYNPTR)
6145                         break;
6146                 if (arg_type & MEM_UNINIT) {
6147                         if (!is_dynptr_reg_valid_uninit(env, reg)) {
6148                                 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6149                                 return -EINVAL;
6150                         }
6151
6152                         /* We only support one dynptr being uninitialized at the moment,
6153                          * which is sufficient for the helper functions we have right now.
6154                          */
6155                         if (meta->uninit_dynptr_regno) {
6156                                 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6157                                 return -EFAULT;
6158                         }
6159
6160                         meta->uninit_dynptr_regno = regno;
6161                 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6162                         verbose(env,
6163                                 "Expected an initialized dynptr as arg #%d\n",
6164                                 arg + 1);
6165                         return -EINVAL;
6166                 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6167                         const char *err_extra = "";
6168
6169                         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6170                         case DYNPTR_TYPE_LOCAL:
6171                                 err_extra = "local";
6172                                 break;
6173                         case DYNPTR_TYPE_RINGBUF:
6174                                 err_extra = "ringbuf";
6175                                 break;
6176                         default:
6177                                 err_extra = "<unknown>";
6178                                 break;
6179                         }
6180                         verbose(env,
6181                                 "Expected a dynptr of type %s as arg #%d\n",
6182                                 err_extra, arg + 1);
6183                         return -EINVAL;
6184                 }
6185                 break;
6186         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6187                 if (!tnum_is_const(reg->var_off)) {
6188                         verbose(env, "R%d is not a known constant'\n",
6189                                 regno);
6190                         return -EACCES;
6191                 }
6192                 meta->mem_size = reg->var_off.value;
6193                 err = mark_chain_precision(env, regno);
6194                 if (err)
6195                         return err;
6196                 break;
6197         case ARG_PTR_TO_INT:
6198         case ARG_PTR_TO_LONG:
6199         {
6200                 int size = int_ptr_type_to_size(arg_type);
6201
6202                 err = check_helper_mem_access(env, regno, size, false, meta);
6203                 if (err)
6204                         return err;
6205                 err = check_ptr_alignment(env, reg, 0, size, true);
6206                 break;
6207         }
6208         case ARG_PTR_TO_CONST_STR:
6209         {
6210                 struct bpf_map *map = reg->map_ptr;
6211                 int map_off;
6212                 u64 map_addr;
6213                 char *str_ptr;
6214
6215                 if (!bpf_map_is_rdonly(map)) {
6216                         verbose(env, "R%d does not point to a readonly map'\n", regno);
6217                         return -EACCES;
6218                 }
6219
6220                 if (!tnum_is_const(reg->var_off)) {
6221                         verbose(env, "R%d is not a constant address'\n", regno);
6222                         return -EACCES;
6223                 }
6224
6225                 if (!map->ops->map_direct_value_addr) {
6226                         verbose(env, "no direct value access support for this map type\n");
6227                         return -EACCES;
6228                 }
6229
6230                 err = check_map_access(env, regno, reg->off,
6231                                        map->value_size - reg->off, false,
6232                                        ACCESS_HELPER);
6233                 if (err)
6234                         return err;
6235
6236                 map_off = reg->off + reg->var_off.value;
6237                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6238                 if (err) {
6239                         verbose(env, "direct value access on string failed\n");
6240                         return err;
6241                 }
6242
6243                 str_ptr = (char *)(long)(map_addr);
6244                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6245                         verbose(env, "string is not zero-terminated\n");
6246                         return -EINVAL;
6247                 }
6248                 break;
6249         }
6250         case ARG_PTR_TO_KPTR:
6251                 if (process_kptr_func(env, regno, meta))
6252                         return -EACCES;
6253                 break;
6254         }
6255
6256         return err;
6257 }
6258
6259 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6260 {
6261         enum bpf_attach_type eatype = env->prog->expected_attach_type;
6262         enum bpf_prog_type type = resolve_prog_type(env->prog);
6263
6264         if (func_id != BPF_FUNC_map_update_elem)
6265                 return false;
6266
6267         /* It's not possible to get access to a locked struct sock in these
6268          * contexts, so updating is safe.
6269          */
6270         switch (type) {
6271         case BPF_PROG_TYPE_TRACING:
6272                 if (eatype == BPF_TRACE_ITER)
6273                         return true;
6274                 break;
6275         case BPF_PROG_TYPE_SOCKET_FILTER:
6276         case BPF_PROG_TYPE_SCHED_CLS:
6277         case BPF_PROG_TYPE_SCHED_ACT:
6278         case BPF_PROG_TYPE_XDP:
6279         case BPF_PROG_TYPE_SK_REUSEPORT:
6280         case BPF_PROG_TYPE_FLOW_DISSECTOR:
6281         case BPF_PROG_TYPE_SK_LOOKUP:
6282                 return true;
6283         default:
6284                 break;
6285         }
6286
6287         verbose(env, "cannot update sockmap in this context\n");
6288         return false;
6289 }
6290
6291 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6292 {
6293         return env->prog->jit_requested &&
6294                bpf_jit_supports_subprog_tailcalls();
6295 }
6296
6297 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6298                                         struct bpf_map *map, int func_id)
6299 {
6300         if (!map)
6301                 return 0;
6302
6303         /* We need a two way check, first is from map perspective ... */
6304         switch (map->map_type) {
6305         case BPF_MAP_TYPE_PROG_ARRAY:
6306                 if (func_id != BPF_FUNC_tail_call)
6307                         goto error;
6308                 break;
6309         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6310                 if (func_id != BPF_FUNC_perf_event_read &&
6311                     func_id != BPF_FUNC_perf_event_output &&
6312                     func_id != BPF_FUNC_skb_output &&
6313                     func_id != BPF_FUNC_perf_event_read_value &&
6314                     func_id != BPF_FUNC_xdp_output)
6315                         goto error;
6316                 break;
6317         case BPF_MAP_TYPE_RINGBUF:
6318                 if (func_id != BPF_FUNC_ringbuf_output &&
6319                     func_id != BPF_FUNC_ringbuf_reserve &&
6320                     func_id != BPF_FUNC_ringbuf_query &&
6321                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6322                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6323                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
6324                         goto error;
6325                 break;
6326         case BPF_MAP_TYPE_USER_RINGBUF:
6327                 if (func_id != BPF_FUNC_user_ringbuf_drain)
6328                         goto error;
6329                 break;
6330         case BPF_MAP_TYPE_STACK_TRACE:
6331                 if (func_id != BPF_FUNC_get_stackid)
6332                         goto error;
6333                 break;
6334         case BPF_MAP_TYPE_CGROUP_ARRAY:
6335                 if (func_id != BPF_FUNC_skb_under_cgroup &&
6336                     func_id != BPF_FUNC_current_task_under_cgroup)
6337                         goto error;
6338                 break;
6339         case BPF_MAP_TYPE_CGROUP_STORAGE:
6340         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6341                 if (func_id != BPF_FUNC_get_local_storage)
6342                         goto error;
6343                 break;
6344         case BPF_MAP_TYPE_DEVMAP:
6345         case BPF_MAP_TYPE_DEVMAP_HASH:
6346                 if (func_id != BPF_FUNC_redirect_map &&
6347                     func_id != BPF_FUNC_map_lookup_elem)
6348                         goto error;
6349                 break;
6350         /* Restrict bpf side of cpumap and xskmap, open when use-cases
6351          * appear.
6352          */
6353         case BPF_MAP_TYPE_CPUMAP:
6354                 if (func_id != BPF_FUNC_redirect_map)
6355                         goto error;
6356                 break;
6357         case BPF_MAP_TYPE_XSKMAP:
6358                 if (func_id != BPF_FUNC_redirect_map &&
6359                     func_id != BPF_FUNC_map_lookup_elem)
6360                         goto error;
6361                 break;
6362         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6363         case BPF_MAP_TYPE_HASH_OF_MAPS:
6364                 if (func_id != BPF_FUNC_map_lookup_elem)
6365                         goto error;
6366                 break;
6367         case BPF_MAP_TYPE_SOCKMAP:
6368                 if (func_id != BPF_FUNC_sk_redirect_map &&
6369                     func_id != BPF_FUNC_sock_map_update &&
6370                     func_id != BPF_FUNC_map_delete_elem &&
6371                     func_id != BPF_FUNC_msg_redirect_map &&
6372                     func_id != BPF_FUNC_sk_select_reuseport &&
6373                     func_id != BPF_FUNC_map_lookup_elem &&
6374                     !may_update_sockmap(env, func_id))
6375                         goto error;
6376                 break;
6377         case BPF_MAP_TYPE_SOCKHASH:
6378                 if (func_id != BPF_FUNC_sk_redirect_hash &&
6379                     func_id != BPF_FUNC_sock_hash_update &&
6380                     func_id != BPF_FUNC_map_delete_elem &&
6381                     func_id != BPF_FUNC_msg_redirect_hash &&
6382                     func_id != BPF_FUNC_sk_select_reuseport &&
6383                     func_id != BPF_FUNC_map_lookup_elem &&
6384                     !may_update_sockmap(env, func_id))
6385                         goto error;
6386                 break;
6387         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6388                 if (func_id != BPF_FUNC_sk_select_reuseport)
6389                         goto error;
6390                 break;
6391         case BPF_MAP_TYPE_QUEUE:
6392         case BPF_MAP_TYPE_STACK:
6393                 if (func_id != BPF_FUNC_map_peek_elem &&
6394                     func_id != BPF_FUNC_map_pop_elem &&
6395                     func_id != BPF_FUNC_map_push_elem)
6396                         goto error;
6397                 break;
6398         case BPF_MAP_TYPE_SK_STORAGE:
6399                 if (func_id != BPF_FUNC_sk_storage_get &&
6400                     func_id != BPF_FUNC_sk_storage_delete)
6401                         goto error;
6402                 break;
6403         case BPF_MAP_TYPE_INODE_STORAGE:
6404                 if (func_id != BPF_FUNC_inode_storage_get &&
6405                     func_id != BPF_FUNC_inode_storage_delete)
6406                         goto error;
6407                 break;
6408         case BPF_MAP_TYPE_TASK_STORAGE:
6409                 if (func_id != BPF_FUNC_task_storage_get &&
6410                     func_id != BPF_FUNC_task_storage_delete)
6411                         goto error;
6412                 break;
6413         case BPF_MAP_TYPE_BLOOM_FILTER:
6414                 if (func_id != BPF_FUNC_map_peek_elem &&
6415                     func_id != BPF_FUNC_map_push_elem)
6416                         goto error;
6417                 break;
6418         default:
6419                 break;
6420         }
6421
6422         /* ... and second from the function itself. */
6423         switch (func_id) {
6424         case BPF_FUNC_tail_call:
6425                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6426                         goto error;
6427                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6428                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6429                         return -EINVAL;
6430                 }
6431                 break;
6432         case BPF_FUNC_perf_event_read:
6433         case BPF_FUNC_perf_event_output:
6434         case BPF_FUNC_perf_event_read_value:
6435         case BPF_FUNC_skb_output:
6436         case BPF_FUNC_xdp_output:
6437                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6438                         goto error;
6439                 break;
6440         case BPF_FUNC_ringbuf_output:
6441         case BPF_FUNC_ringbuf_reserve:
6442         case BPF_FUNC_ringbuf_query:
6443         case BPF_FUNC_ringbuf_reserve_dynptr:
6444         case BPF_FUNC_ringbuf_submit_dynptr:
6445         case BPF_FUNC_ringbuf_discard_dynptr:
6446                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6447                         goto error;
6448                 break;
6449         case BPF_FUNC_user_ringbuf_drain:
6450                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6451                         goto error;
6452                 break;
6453         case BPF_FUNC_get_stackid:
6454                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6455                         goto error;
6456                 break;
6457         case BPF_FUNC_current_task_under_cgroup:
6458         case BPF_FUNC_skb_under_cgroup:
6459                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6460                         goto error;
6461                 break;
6462         case BPF_FUNC_redirect_map:
6463                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6464                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6465                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
6466                     map->map_type != BPF_MAP_TYPE_XSKMAP)
6467                         goto error;
6468                 break;
6469         case BPF_FUNC_sk_redirect_map:
6470         case BPF_FUNC_msg_redirect_map:
6471         case BPF_FUNC_sock_map_update:
6472                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6473                         goto error;
6474                 break;
6475         case BPF_FUNC_sk_redirect_hash:
6476         case BPF_FUNC_msg_redirect_hash:
6477         case BPF_FUNC_sock_hash_update:
6478                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6479                         goto error;
6480                 break;
6481         case BPF_FUNC_get_local_storage:
6482                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6483                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6484                         goto error;
6485                 break;
6486         case BPF_FUNC_sk_select_reuseport:
6487                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6488                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6489                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
6490                         goto error;
6491                 break;
6492         case BPF_FUNC_map_pop_elem:
6493                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6494                     map->map_type != BPF_MAP_TYPE_STACK)
6495                         goto error;
6496                 break;
6497         case BPF_FUNC_map_peek_elem:
6498         case BPF_FUNC_map_push_elem:
6499                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6500                     map->map_type != BPF_MAP_TYPE_STACK &&
6501                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6502                         goto error;
6503                 break;
6504         case BPF_FUNC_map_lookup_percpu_elem:
6505                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6506                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6507                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6508                         goto error;
6509                 break;
6510         case BPF_FUNC_sk_storage_get:
6511         case BPF_FUNC_sk_storage_delete:
6512                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6513                         goto error;
6514                 break;
6515         case BPF_FUNC_inode_storage_get:
6516         case BPF_FUNC_inode_storage_delete:
6517                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6518                         goto error;
6519                 break;
6520         case BPF_FUNC_task_storage_get:
6521         case BPF_FUNC_task_storage_delete:
6522                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6523                         goto error;
6524                 break;
6525         default:
6526                 break;
6527         }
6528
6529         return 0;
6530 error:
6531         verbose(env, "cannot pass map_type %d into func %s#%d\n",
6532                 map->map_type, func_id_name(func_id), func_id);
6533         return -EINVAL;
6534 }
6535
6536 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6537 {
6538         int count = 0;
6539
6540         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6541                 count++;
6542         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6543                 count++;
6544         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6545                 count++;
6546         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6547                 count++;
6548         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6549                 count++;
6550
6551         /* We only support one arg being in raw mode at the moment,
6552          * which is sufficient for the helper functions we have
6553          * right now.
6554          */
6555         return count <= 1;
6556 }
6557
6558 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6559 {
6560         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6561         bool has_size = fn->arg_size[arg] != 0;
6562         bool is_next_size = false;
6563
6564         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6565                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6566
6567         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6568                 return is_next_size;
6569
6570         return has_size == is_next_size || is_next_size == is_fixed;
6571 }
6572
6573 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6574 {
6575         /* bpf_xxx(..., buf, len) call will access 'len'
6576          * bytes from memory 'buf'. Both arg types need
6577          * to be paired, so make sure there's no buggy
6578          * helper function specification.
6579          */
6580         if (arg_type_is_mem_size(fn->arg1_type) ||
6581             check_args_pair_invalid(fn, 0) ||
6582             check_args_pair_invalid(fn, 1) ||
6583             check_args_pair_invalid(fn, 2) ||
6584             check_args_pair_invalid(fn, 3) ||
6585             check_args_pair_invalid(fn, 4))
6586                 return false;
6587
6588         return true;
6589 }
6590
6591 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6592 {
6593         int i;
6594
6595         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6596                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6597                         return false;
6598
6599                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6600                     /* arg_btf_id and arg_size are in a union. */
6601                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6602                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6603                         return false;
6604         }
6605
6606         return true;
6607 }
6608
6609 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6610 {
6611         return check_raw_mode_ok(fn) &&
6612                check_arg_pair_ok(fn) &&
6613                check_btf_id_ok(fn) ? 0 : -EINVAL;
6614 }
6615
6616 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6617  * are now invalid, so turn them into unknown SCALAR_VALUE.
6618  */
6619 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6620 {
6621         struct bpf_func_state *state;
6622         struct bpf_reg_state *reg;
6623
6624         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6625                 if (reg_is_pkt_pointer_any(reg))
6626                         __mark_reg_unknown(env, reg);
6627         }));
6628 }
6629
6630 enum {
6631         AT_PKT_END = -1,
6632         BEYOND_PKT_END = -2,
6633 };
6634
6635 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6636 {
6637         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6638         struct bpf_reg_state *reg = &state->regs[regn];
6639
6640         if (reg->type != PTR_TO_PACKET)
6641                 /* PTR_TO_PACKET_META is not supported yet */
6642                 return;
6643
6644         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6645          * How far beyond pkt_end it goes is unknown.
6646          * if (!range_open) it's the case of pkt >= pkt_end
6647          * if (range_open) it's the case of pkt > pkt_end
6648          * hence this pointer is at least 1 byte bigger than pkt_end
6649          */
6650         if (range_open)
6651                 reg->range = BEYOND_PKT_END;
6652         else
6653                 reg->range = AT_PKT_END;
6654 }
6655
6656 /* The pointer with the specified id has released its reference to kernel
6657  * resources. Identify all copies of the same pointer and clear the reference.
6658  */
6659 static int release_reference(struct bpf_verifier_env *env,
6660                              int ref_obj_id)
6661 {
6662         struct bpf_func_state *state;
6663         struct bpf_reg_state *reg;
6664         int err;
6665
6666         err = release_reference_state(cur_func(env), ref_obj_id);
6667         if (err)
6668                 return err;
6669
6670         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6671                 if (reg->ref_obj_id == ref_obj_id) {
6672                         if (!env->allow_ptr_leaks)
6673                                 __mark_reg_not_init(env, reg);
6674                         else
6675                                 __mark_reg_unknown(env, reg);
6676                 }
6677         }));
6678
6679         return 0;
6680 }
6681
6682 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6683                                     struct bpf_reg_state *regs)
6684 {
6685         int i;
6686
6687         /* after the call registers r0 - r5 were scratched */
6688         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6689                 mark_reg_not_init(env, regs, caller_saved[i]);
6690                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6691         }
6692 }
6693
6694 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6695                                    struct bpf_func_state *caller,
6696                                    struct bpf_func_state *callee,
6697                                    int insn_idx);
6698
6699 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6700                              int *insn_idx, int subprog,
6701                              set_callee_state_fn set_callee_state_cb)
6702 {
6703         struct bpf_verifier_state *state = env->cur_state;
6704         struct bpf_func_info_aux *func_info_aux;
6705         struct bpf_func_state *caller, *callee;
6706         int err;
6707         bool is_global = false;
6708
6709         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6710                 verbose(env, "the call stack of %d frames is too deep\n",
6711                         state->curframe + 2);
6712                 return -E2BIG;
6713         }
6714
6715         caller = state->frame[state->curframe];
6716         if (state->frame[state->curframe + 1]) {
6717                 verbose(env, "verifier bug. Frame %d already allocated\n",
6718                         state->curframe + 1);
6719                 return -EFAULT;
6720         }
6721
6722         func_info_aux = env->prog->aux->func_info_aux;
6723         if (func_info_aux)
6724                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6725         err = btf_check_subprog_call(env, subprog, caller->regs);
6726         if (err == -EFAULT)
6727                 return err;
6728         if (is_global) {
6729                 if (err) {
6730                         verbose(env, "Caller passes invalid args into func#%d\n",
6731                                 subprog);
6732                         return err;
6733                 } else {
6734                         if (env->log.level & BPF_LOG_LEVEL)
6735                                 verbose(env,
6736                                         "Func#%d is global and valid. Skipping.\n",
6737                                         subprog);
6738                         clear_caller_saved_regs(env, caller->regs);
6739
6740                         /* All global functions return a 64-bit SCALAR_VALUE */
6741                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
6742                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6743
6744                         /* continue with next insn after call */
6745                         return 0;
6746                 }
6747         }
6748
6749         if (insn->code == (BPF_JMP | BPF_CALL) &&
6750             insn->src_reg == 0 &&
6751             insn->imm == BPF_FUNC_timer_set_callback) {
6752                 struct bpf_verifier_state *async_cb;
6753
6754                 /* there is no real recursion here. timer callbacks are async */
6755                 env->subprog_info[subprog].is_async_cb = true;
6756                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6757                                          *insn_idx, subprog);
6758                 if (!async_cb)
6759                         return -EFAULT;
6760                 callee = async_cb->frame[0];
6761                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6762
6763                 /* Convert bpf_timer_set_callback() args into timer callback args */
6764                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6765                 if (err)
6766                         return err;
6767
6768                 clear_caller_saved_regs(env, caller->regs);
6769                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6770                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6771                 /* continue with next insn after call */
6772                 return 0;
6773         }
6774
6775         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6776         if (!callee)
6777                 return -ENOMEM;
6778         state->frame[state->curframe + 1] = callee;
6779
6780         /* callee cannot access r0, r6 - r9 for reading and has to write
6781          * into its own stack before reading from it.
6782          * callee can read/write into caller's stack
6783          */
6784         init_func_state(env, callee,
6785                         /* remember the callsite, it will be used by bpf_exit */
6786                         *insn_idx /* callsite */,
6787                         state->curframe + 1 /* frameno within this callchain */,
6788                         subprog /* subprog number within this prog */);
6789
6790         /* Transfer references to the callee */
6791         err = copy_reference_state(callee, caller);
6792         if (err)
6793                 goto err_out;
6794
6795         err = set_callee_state_cb(env, caller, callee, *insn_idx);
6796         if (err)
6797                 goto err_out;
6798
6799         clear_caller_saved_regs(env, caller->regs);
6800
6801         /* only increment it after check_reg_arg() finished */
6802         state->curframe++;
6803
6804         /* and go analyze first insn of the callee */
6805         *insn_idx = env->subprog_info[subprog].start - 1;
6806
6807         if (env->log.level & BPF_LOG_LEVEL) {
6808                 verbose(env, "caller:\n");
6809                 print_verifier_state(env, caller, true);
6810                 verbose(env, "callee:\n");
6811                 print_verifier_state(env, callee, true);
6812         }
6813         return 0;
6814
6815 err_out:
6816         free_func_state(callee);
6817         state->frame[state->curframe + 1] = NULL;
6818         return err;
6819 }
6820
6821 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6822                                    struct bpf_func_state *caller,
6823                                    struct bpf_func_state *callee)
6824 {
6825         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6826          *      void *callback_ctx, u64 flags);
6827          * callback_fn(struct bpf_map *map, void *key, void *value,
6828          *      void *callback_ctx);
6829          */
6830         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6831
6832         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6833         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6834         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6835
6836         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6837         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6838         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6839
6840         /* pointer to stack or null */
6841         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6842
6843         /* unused */
6844         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6845         return 0;
6846 }
6847
6848 static int set_callee_state(struct bpf_verifier_env *env,
6849                             struct bpf_func_state *caller,
6850                             struct bpf_func_state *callee, int insn_idx)
6851 {
6852         int i;
6853
6854         /* copy r1 - r5 args that callee can access.  The copy includes parent
6855          * pointers, which connects us up to the liveness chain
6856          */
6857         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6858                 callee->regs[i] = caller->regs[i];
6859         return 0;
6860 }
6861
6862 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6863                            int *insn_idx)
6864 {
6865         int subprog, target_insn;
6866
6867         target_insn = *insn_idx + insn->imm + 1;
6868         subprog = find_subprog(env, target_insn);
6869         if (subprog < 0) {
6870                 verbose(env, "verifier bug. No program starts at insn %d\n",
6871                         target_insn);
6872                 return -EFAULT;
6873         }
6874
6875         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6876 }
6877
6878 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6879                                        struct bpf_func_state *caller,
6880                                        struct bpf_func_state *callee,
6881                                        int insn_idx)
6882 {
6883         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6884         struct bpf_map *map;
6885         int err;
6886
6887         if (bpf_map_ptr_poisoned(insn_aux)) {
6888                 verbose(env, "tail_call abusing map_ptr\n");
6889                 return -EINVAL;
6890         }
6891
6892         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6893         if (!map->ops->map_set_for_each_callback_args ||
6894             !map->ops->map_for_each_callback) {
6895                 verbose(env, "callback function not allowed for map\n");
6896                 return -ENOTSUPP;
6897         }
6898
6899         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6900         if (err)
6901                 return err;
6902
6903         callee->in_callback_fn = true;
6904         callee->callback_ret_range = tnum_range(0, 1);
6905         return 0;
6906 }
6907
6908 static int set_loop_callback_state(struct bpf_verifier_env *env,
6909                                    struct bpf_func_state *caller,
6910                                    struct bpf_func_state *callee,
6911                                    int insn_idx)
6912 {
6913         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6914          *          u64 flags);
6915          * callback_fn(u32 index, void *callback_ctx);
6916          */
6917         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6918         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6919
6920         /* unused */
6921         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6922         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6923         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6924
6925         callee->in_callback_fn = true;
6926         callee->callback_ret_range = tnum_range(0, 1);
6927         return 0;
6928 }
6929
6930 static int set_timer_callback_state(struct bpf_verifier_env *env,
6931                                     struct bpf_func_state *caller,
6932                                     struct bpf_func_state *callee,
6933                                     int insn_idx)
6934 {
6935         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6936
6937         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6938          * callback_fn(struct bpf_map *map, void *key, void *value);
6939          */
6940         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6941         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6942         callee->regs[BPF_REG_1].map_ptr = map_ptr;
6943
6944         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6945         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6946         callee->regs[BPF_REG_2].map_ptr = map_ptr;
6947
6948         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6949         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6950         callee->regs[BPF_REG_3].map_ptr = map_ptr;
6951
6952         /* unused */
6953         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6954         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6955         callee->in_async_callback_fn = true;
6956         callee->callback_ret_range = tnum_range(0, 1);
6957         return 0;
6958 }
6959
6960 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6961                                        struct bpf_func_state *caller,
6962                                        struct bpf_func_state *callee,
6963                                        int insn_idx)
6964 {
6965         /* bpf_find_vma(struct task_struct *task, u64 addr,
6966          *               void *callback_fn, void *callback_ctx, u64 flags)
6967          * (callback_fn)(struct task_struct *task,
6968          *               struct vm_area_struct *vma, void *callback_ctx);
6969          */
6970         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6971
6972         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6973         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6974         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6975         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6976
6977         /* pointer to stack or null */
6978         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6979
6980         /* unused */
6981         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6982         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6983         callee->in_callback_fn = true;
6984         callee->callback_ret_range = tnum_range(0, 1);
6985         return 0;
6986 }
6987
6988 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
6989                                            struct bpf_func_state *caller,
6990                                            struct bpf_func_state *callee,
6991                                            int insn_idx)
6992 {
6993         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
6994          *                        callback_ctx, u64 flags);
6995          * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
6996          */
6997         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
6998         callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
6999         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7000         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7001
7002         /* unused */
7003         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7004         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7005         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7006
7007         callee->in_callback_fn = true;
7008         callee->callback_ret_range = tnum_range(0, 1);
7009         return 0;
7010 }
7011
7012 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7013 {
7014         struct bpf_verifier_state *state = env->cur_state;
7015         struct bpf_func_state *caller, *callee;
7016         struct bpf_reg_state *r0;
7017         int err;
7018
7019         callee = state->frame[state->curframe];
7020         r0 = &callee->regs[BPF_REG_0];
7021         if (r0->type == PTR_TO_STACK) {
7022                 /* technically it's ok to return caller's stack pointer
7023                  * (or caller's caller's pointer) back to the caller,
7024                  * since these pointers are valid. Only current stack
7025                  * pointer will be invalid as soon as function exits,
7026                  * but let's be conservative
7027                  */
7028                 verbose(env, "cannot return stack pointer to the caller\n");
7029                 return -EINVAL;
7030         }
7031
7032         caller = state->frame[state->curframe - 1];
7033         if (callee->in_callback_fn) {
7034                 /* enforce R0 return value range [0, 1]. */
7035                 struct tnum range = callee->callback_ret_range;
7036
7037                 if (r0->type != SCALAR_VALUE) {
7038                         verbose(env, "R0 not a scalar value\n");
7039                         return -EACCES;
7040                 }
7041                 if (!tnum_in(range, r0->var_off)) {
7042                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7043                         return -EINVAL;
7044                 }
7045         } else {
7046                 /* return to the caller whatever r0 had in the callee */
7047                 caller->regs[BPF_REG_0] = *r0;
7048         }
7049
7050         /* callback_fn frame should have released its own additions to parent's
7051          * reference state at this point, or check_reference_leak would
7052          * complain, hence it must be the same as the caller. There is no need
7053          * to copy it back.
7054          */
7055         if (!callee->in_callback_fn) {
7056                 /* Transfer references to the caller */
7057                 err = copy_reference_state(caller, callee);
7058                 if (err)
7059                         return err;
7060         }
7061
7062         *insn_idx = callee->callsite + 1;
7063         if (env->log.level & BPF_LOG_LEVEL) {
7064                 verbose(env, "returning from callee:\n");
7065                 print_verifier_state(env, callee, true);
7066                 verbose(env, "to caller at %d:\n", *insn_idx);
7067                 print_verifier_state(env, caller, true);
7068         }
7069         /* clear everything in the callee */
7070         free_func_state(callee);
7071         state->frame[state->curframe--] = NULL;
7072         return 0;
7073 }
7074
7075 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7076                                    int func_id,
7077                                    struct bpf_call_arg_meta *meta)
7078 {
7079         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7080
7081         if (ret_type != RET_INTEGER ||
7082             (func_id != BPF_FUNC_get_stack &&
7083              func_id != BPF_FUNC_get_task_stack &&
7084              func_id != BPF_FUNC_probe_read_str &&
7085              func_id != BPF_FUNC_probe_read_kernel_str &&
7086              func_id != BPF_FUNC_probe_read_user_str))
7087                 return;
7088
7089         ret_reg->smax_value = meta->msize_max_value;
7090         ret_reg->s32_max_value = meta->msize_max_value;
7091         ret_reg->smin_value = -MAX_ERRNO;
7092         ret_reg->s32_min_value = -MAX_ERRNO;
7093         reg_bounds_sync(ret_reg);
7094 }
7095
7096 static int
7097 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7098                 int func_id, int insn_idx)
7099 {
7100         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7101         struct bpf_map *map = meta->map_ptr;
7102
7103         if (func_id != BPF_FUNC_tail_call &&
7104             func_id != BPF_FUNC_map_lookup_elem &&
7105             func_id != BPF_FUNC_map_update_elem &&
7106             func_id != BPF_FUNC_map_delete_elem &&
7107             func_id != BPF_FUNC_map_push_elem &&
7108             func_id != BPF_FUNC_map_pop_elem &&
7109             func_id != BPF_FUNC_map_peek_elem &&
7110             func_id != BPF_FUNC_for_each_map_elem &&
7111             func_id != BPF_FUNC_redirect_map &&
7112             func_id != BPF_FUNC_map_lookup_percpu_elem)
7113                 return 0;
7114
7115         if (map == NULL) {
7116                 verbose(env, "kernel subsystem misconfigured verifier\n");
7117                 return -EINVAL;
7118         }
7119
7120         /* In case of read-only, some additional restrictions
7121          * need to be applied in order to prevent altering the
7122          * state of the map from program side.
7123          */
7124         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7125             (func_id == BPF_FUNC_map_delete_elem ||
7126              func_id == BPF_FUNC_map_update_elem ||
7127              func_id == BPF_FUNC_map_push_elem ||
7128              func_id == BPF_FUNC_map_pop_elem)) {
7129                 verbose(env, "write into map forbidden\n");
7130                 return -EACCES;
7131         }
7132
7133         if (!BPF_MAP_PTR(aux->map_ptr_state))
7134                 bpf_map_ptr_store(aux, meta->map_ptr,
7135                                   !meta->map_ptr->bypass_spec_v1);
7136         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7137                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7138                                   !meta->map_ptr->bypass_spec_v1);
7139         return 0;
7140 }
7141
7142 static int
7143 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7144                 int func_id, int insn_idx)
7145 {
7146         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7147         struct bpf_reg_state *regs = cur_regs(env), *reg;
7148         struct bpf_map *map = meta->map_ptr;
7149         u64 val, max;
7150         int err;
7151
7152         if (func_id != BPF_FUNC_tail_call)
7153                 return 0;
7154         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7155                 verbose(env, "kernel subsystem misconfigured verifier\n");
7156                 return -EINVAL;
7157         }
7158
7159         reg = &regs[BPF_REG_3];
7160         val = reg->var_off.value;
7161         max = map->max_entries;
7162
7163         if (!(register_is_const(reg) && val < max)) {
7164                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7165                 return 0;
7166         }
7167
7168         err = mark_chain_precision(env, BPF_REG_3);
7169         if (err)
7170                 return err;
7171         if (bpf_map_key_unseen(aux))
7172                 bpf_map_key_store(aux, val);
7173         else if (!bpf_map_key_poisoned(aux) &&
7174                   bpf_map_key_immediate(aux) != val)
7175                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7176         return 0;
7177 }
7178
7179 static int check_reference_leak(struct bpf_verifier_env *env)
7180 {
7181         struct bpf_func_state *state = cur_func(env);
7182         bool refs_lingering = false;
7183         int i;
7184
7185         if (state->frameno && !state->in_callback_fn)
7186                 return 0;
7187
7188         for (i = 0; i < state->acquired_refs; i++) {
7189                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7190                         continue;
7191                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7192                         state->refs[i].id, state->refs[i].insn_idx);
7193                 refs_lingering = true;
7194         }
7195         return refs_lingering ? -EINVAL : 0;
7196 }
7197
7198 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7199                                    struct bpf_reg_state *regs)
7200 {
7201         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7202         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7203         struct bpf_map *fmt_map = fmt_reg->map_ptr;
7204         int err, fmt_map_off, num_args;
7205         u64 fmt_addr;
7206         char *fmt;
7207
7208         /* data must be an array of u64 */
7209         if (data_len_reg->var_off.value % 8)
7210                 return -EINVAL;
7211         num_args = data_len_reg->var_off.value / 8;
7212
7213         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7214          * and map_direct_value_addr is set.
7215          */
7216         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7217         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7218                                                   fmt_map_off);
7219         if (err) {
7220                 verbose(env, "verifier bug\n");
7221                 return -EFAULT;
7222         }
7223         fmt = (char *)(long)fmt_addr + fmt_map_off;
7224
7225         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7226          * can focus on validating the format specifiers.
7227          */
7228         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7229         if (err < 0)
7230                 verbose(env, "Invalid format string\n");
7231
7232         return err;
7233 }
7234
7235 static int check_get_func_ip(struct bpf_verifier_env *env)
7236 {
7237         enum bpf_prog_type type = resolve_prog_type(env->prog);
7238         int func_id = BPF_FUNC_get_func_ip;
7239
7240         if (type == BPF_PROG_TYPE_TRACING) {
7241                 if (!bpf_prog_has_trampoline(env->prog)) {
7242                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7243                                 func_id_name(func_id), func_id);
7244                         return -ENOTSUPP;
7245                 }
7246                 return 0;
7247         } else if (type == BPF_PROG_TYPE_KPROBE) {
7248                 return 0;
7249         }
7250
7251         verbose(env, "func %s#%d not supported for program type %d\n",
7252                 func_id_name(func_id), func_id, type);
7253         return -ENOTSUPP;
7254 }
7255
7256 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7257 {
7258         return &env->insn_aux_data[env->insn_idx];
7259 }
7260
7261 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7262 {
7263         struct bpf_reg_state *regs = cur_regs(env);
7264         struct bpf_reg_state *reg = &regs[BPF_REG_4];
7265         bool reg_is_null = register_is_null(reg);
7266
7267         if (reg_is_null)
7268                 mark_chain_precision(env, BPF_REG_4);
7269
7270         return reg_is_null;
7271 }
7272
7273 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7274 {
7275         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7276
7277         if (!state->initialized) {
7278                 state->initialized = 1;
7279                 state->fit_for_inline = loop_flag_is_zero(env);
7280                 state->callback_subprogno = subprogno;
7281                 return;
7282         }
7283
7284         if (!state->fit_for_inline)
7285                 return;
7286
7287         state->fit_for_inline = (loop_flag_is_zero(env) &&
7288                                  state->callback_subprogno == subprogno);
7289 }
7290
7291 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7292                              int *insn_idx_p)
7293 {
7294         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7295         const struct bpf_func_proto *fn = NULL;
7296         enum bpf_return_type ret_type;
7297         enum bpf_type_flag ret_flag;
7298         struct bpf_reg_state *regs;
7299         struct bpf_call_arg_meta meta;
7300         int insn_idx = *insn_idx_p;
7301         bool changes_data;
7302         int i, err, func_id;
7303
7304         /* find function prototype */
7305         func_id = insn->imm;
7306         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7307                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7308                         func_id);
7309                 return -EINVAL;
7310         }
7311
7312         if (env->ops->get_func_proto)
7313                 fn = env->ops->get_func_proto(func_id, env->prog);
7314         if (!fn) {
7315                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7316                         func_id);
7317                 return -EINVAL;
7318         }
7319
7320         /* eBPF programs must be GPL compatible to use GPL-ed functions */
7321         if (!env->prog->gpl_compatible && fn->gpl_only) {
7322                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7323                 return -EINVAL;
7324         }
7325
7326         if (fn->allowed && !fn->allowed(env->prog)) {
7327                 verbose(env, "helper call is not allowed in probe\n");
7328                 return -EINVAL;
7329         }
7330
7331         /* With LD_ABS/IND some JITs save/restore skb from r1. */
7332         changes_data = bpf_helper_changes_pkt_data(fn->func);
7333         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7334                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7335                         func_id_name(func_id), func_id);
7336                 return -EINVAL;
7337         }
7338
7339         memset(&meta, 0, sizeof(meta));
7340         meta.pkt_access = fn->pkt_access;
7341
7342         err = check_func_proto(fn, func_id);
7343         if (err) {
7344                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7345                         func_id_name(func_id), func_id);
7346                 return err;
7347         }
7348
7349         meta.func_id = func_id;
7350         /* check args */
7351         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7352                 err = check_func_arg(env, i, &meta, fn);
7353                 if (err)
7354                         return err;
7355         }
7356
7357         err = record_func_map(env, &meta, func_id, insn_idx);
7358         if (err)
7359                 return err;
7360
7361         err = record_func_key(env, &meta, func_id, insn_idx);
7362         if (err)
7363                 return err;
7364
7365         /* Mark slots with STACK_MISC in case of raw mode, stack offset
7366          * is inferred from register state.
7367          */
7368         for (i = 0; i < meta.access_size; i++) {
7369                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7370                                        BPF_WRITE, -1, false);
7371                 if (err)
7372                         return err;
7373         }
7374
7375         regs = cur_regs(env);
7376
7377         if (meta.uninit_dynptr_regno) {
7378                 /* we write BPF_DW bits (8 bytes) at a time */
7379                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7380                         err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7381                                                i, BPF_DW, BPF_WRITE, -1, false);
7382                         if (err)
7383                                 return err;
7384                 }
7385
7386                 err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7387                                               fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7388                                               insn_idx);
7389                 if (err)
7390                         return err;
7391         }
7392
7393         if (meta.release_regno) {
7394                 err = -EINVAL;
7395                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7396                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7397                 else if (meta.ref_obj_id)
7398                         err = release_reference(env, meta.ref_obj_id);
7399                 /* meta.ref_obj_id can only be 0 if register that is meant to be
7400                  * released is NULL, which must be > R0.
7401                  */
7402                 else if (register_is_null(&regs[meta.release_regno]))
7403                         err = 0;
7404                 if (err) {
7405                         verbose(env, "func %s#%d reference has not been acquired before\n",
7406                                 func_id_name(func_id), func_id);
7407                         return err;
7408                 }
7409         }
7410
7411         switch (func_id) {
7412         case BPF_FUNC_tail_call:
7413                 err = check_reference_leak(env);
7414                 if (err) {
7415                         verbose(env, "tail_call would lead to reference leak\n");
7416                         return err;
7417                 }
7418                 break;
7419         case BPF_FUNC_get_local_storage:
7420                 /* check that flags argument in get_local_storage(map, flags) is 0,
7421                  * this is required because get_local_storage() can't return an error.
7422                  */
7423                 if (!register_is_null(&regs[BPF_REG_2])) {
7424                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7425                         return -EINVAL;
7426                 }
7427                 break;
7428         case BPF_FUNC_for_each_map_elem:
7429                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7430                                         set_map_elem_callback_state);
7431                 break;
7432         case BPF_FUNC_timer_set_callback:
7433                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7434                                         set_timer_callback_state);
7435                 break;
7436         case BPF_FUNC_find_vma:
7437                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7438                                         set_find_vma_callback_state);
7439                 break;
7440         case BPF_FUNC_snprintf:
7441                 err = check_bpf_snprintf_call(env, regs);
7442                 break;
7443         case BPF_FUNC_loop:
7444                 update_loop_inline_state(env, meta.subprogno);
7445                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7446                                         set_loop_callback_state);
7447                 break;
7448         case BPF_FUNC_dynptr_from_mem:
7449                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7450                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7451                                 reg_type_str(env, regs[BPF_REG_1].type));
7452                         return -EACCES;
7453                 }
7454                 break;
7455         case BPF_FUNC_set_retval:
7456                 if (prog_type == BPF_PROG_TYPE_LSM &&
7457                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7458                         if (!env->prog->aux->attach_func_proto->type) {
7459                                 /* Make sure programs that attach to void
7460                                  * hooks don't try to modify return value.
7461                                  */
7462                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7463                                 return -EINVAL;
7464                         }
7465                 }
7466                 break;
7467         case BPF_FUNC_dynptr_data:
7468                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7469                         if (arg_type_is_dynptr(fn->arg_type[i])) {
7470                                 struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7471
7472                                 if (meta.ref_obj_id) {
7473                                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7474                                         return -EFAULT;
7475                                 }
7476
7477                                 if (base_type(reg->type) != PTR_TO_DYNPTR)
7478                                         /* Find the id of the dynptr we're
7479                                          * tracking the reference of
7480                                          */
7481                                         meta.ref_obj_id = stack_slot_get_id(env, reg);
7482                                 break;
7483                         }
7484                 }
7485                 if (i == MAX_BPF_FUNC_REG_ARGS) {
7486                         verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7487                         return -EFAULT;
7488                 }
7489                 break;
7490         case BPF_FUNC_user_ringbuf_drain:
7491                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7492                                         set_user_ringbuf_callback_state);
7493                 break;
7494         }
7495
7496         if (err)
7497                 return err;
7498
7499         /* reset caller saved regs */
7500         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7501                 mark_reg_not_init(env, regs, caller_saved[i]);
7502                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7503         }
7504
7505         /* helper call returns 64-bit value. */
7506         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7507
7508         /* update return register (already marked as written above) */
7509         ret_type = fn->ret_type;
7510         ret_flag = type_flag(ret_type);
7511
7512         switch (base_type(ret_type)) {
7513         case RET_INTEGER:
7514                 /* sets type to SCALAR_VALUE */
7515                 mark_reg_unknown(env, regs, BPF_REG_0);
7516                 break;
7517         case RET_VOID:
7518                 regs[BPF_REG_0].type = NOT_INIT;
7519                 break;
7520         case RET_PTR_TO_MAP_VALUE:
7521                 /* There is no offset yet applied, variable or fixed */
7522                 mark_reg_known_zero(env, regs, BPF_REG_0);
7523                 /* remember map_ptr, so that check_map_access()
7524                  * can check 'value_size' boundary of memory access
7525                  * to map element returned from bpf_map_lookup_elem()
7526                  */
7527                 if (meta.map_ptr == NULL) {
7528                         verbose(env,
7529                                 "kernel subsystem misconfigured verifier\n");
7530                         return -EINVAL;
7531                 }
7532                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7533                 regs[BPF_REG_0].map_uid = meta.map_uid;
7534                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7535                 if (!type_may_be_null(ret_type) &&
7536                     map_value_has_spin_lock(meta.map_ptr)) {
7537                         regs[BPF_REG_0].id = ++env->id_gen;
7538                 }
7539                 break;
7540         case RET_PTR_TO_SOCKET:
7541                 mark_reg_known_zero(env, regs, BPF_REG_0);
7542                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7543                 break;
7544         case RET_PTR_TO_SOCK_COMMON:
7545                 mark_reg_known_zero(env, regs, BPF_REG_0);
7546                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7547                 break;
7548         case RET_PTR_TO_TCP_SOCK:
7549                 mark_reg_known_zero(env, regs, BPF_REG_0);
7550                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7551                 break;
7552         case RET_PTR_TO_ALLOC_MEM:
7553                 mark_reg_known_zero(env, regs, BPF_REG_0);
7554                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7555                 regs[BPF_REG_0].mem_size = meta.mem_size;
7556                 break;
7557         case RET_PTR_TO_MEM_OR_BTF_ID:
7558         {
7559                 const struct btf_type *t;
7560
7561                 mark_reg_known_zero(env, regs, BPF_REG_0);
7562                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7563                 if (!btf_type_is_struct(t)) {
7564                         u32 tsize;
7565                         const struct btf_type *ret;
7566                         const char *tname;
7567
7568                         /* resolve the type size of ksym. */
7569                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7570                         if (IS_ERR(ret)) {
7571                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7572                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7573                                         tname, PTR_ERR(ret));
7574                                 return -EINVAL;
7575                         }
7576                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7577                         regs[BPF_REG_0].mem_size = tsize;
7578                 } else {
7579                         /* MEM_RDONLY may be carried from ret_flag, but it
7580                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7581                          * it will confuse the check of PTR_TO_BTF_ID in
7582                          * check_mem_access().
7583                          */
7584                         ret_flag &= ~MEM_RDONLY;
7585
7586                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7587                         regs[BPF_REG_0].btf = meta.ret_btf;
7588                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7589                 }
7590                 break;
7591         }
7592         case RET_PTR_TO_BTF_ID:
7593         {
7594                 struct btf *ret_btf;
7595                 int ret_btf_id;
7596
7597                 mark_reg_known_zero(env, regs, BPF_REG_0);
7598                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7599                 if (func_id == BPF_FUNC_kptr_xchg) {
7600                         ret_btf = meta.kptr_off_desc->kptr.btf;
7601                         ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7602                 } else {
7603                         if (fn->ret_btf_id == BPF_PTR_POISON) {
7604                                 verbose(env, "verifier internal error:");
7605                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7606                                         func_id_name(func_id));
7607                                 return -EINVAL;
7608                         }
7609                         ret_btf = btf_vmlinux;
7610                         ret_btf_id = *fn->ret_btf_id;
7611                 }
7612                 if (ret_btf_id == 0) {
7613                         verbose(env, "invalid return type %u of func %s#%d\n",
7614                                 base_type(ret_type), func_id_name(func_id),
7615                                 func_id);
7616                         return -EINVAL;
7617                 }
7618                 regs[BPF_REG_0].btf = ret_btf;
7619                 regs[BPF_REG_0].btf_id = ret_btf_id;
7620                 break;
7621         }
7622         default:
7623                 verbose(env, "unknown return type %u of func %s#%d\n",
7624                         base_type(ret_type), func_id_name(func_id), func_id);
7625                 return -EINVAL;
7626         }
7627
7628         if (type_may_be_null(regs[BPF_REG_0].type))
7629                 regs[BPF_REG_0].id = ++env->id_gen;
7630
7631         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7632                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7633                         func_id_name(func_id), func_id);
7634                 return -EFAULT;
7635         }
7636
7637         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7638                 /* For release_reference() */
7639                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7640         } else if (is_acquire_function(func_id, meta.map_ptr)) {
7641                 int id = acquire_reference_state(env, insn_idx);
7642
7643                 if (id < 0)
7644                         return id;
7645                 /* For mark_ptr_or_null_reg() */
7646                 regs[BPF_REG_0].id = id;
7647                 /* For release_reference() */
7648                 regs[BPF_REG_0].ref_obj_id = id;
7649         }
7650
7651         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7652
7653         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7654         if (err)
7655                 return err;
7656
7657         if ((func_id == BPF_FUNC_get_stack ||
7658              func_id == BPF_FUNC_get_task_stack) &&
7659             !env->prog->has_callchain_buf) {
7660                 const char *err_str;
7661
7662 #ifdef CONFIG_PERF_EVENTS
7663                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7664                 err_str = "cannot get callchain buffer for func %s#%d\n";
7665 #else
7666                 err = -ENOTSUPP;
7667                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7668 #endif
7669                 if (err) {
7670                         verbose(env, err_str, func_id_name(func_id), func_id);
7671                         return err;
7672                 }
7673
7674                 env->prog->has_callchain_buf = true;
7675         }
7676
7677         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7678                 env->prog->call_get_stack = true;
7679
7680         if (func_id == BPF_FUNC_get_func_ip) {
7681                 if (check_get_func_ip(env))
7682                         return -ENOTSUPP;
7683                 env->prog->call_get_func_ip = true;
7684         }
7685
7686         if (changes_data)
7687                 clear_all_pkt_pointers(env);
7688         return 0;
7689 }
7690
7691 /* mark_btf_func_reg_size() is used when the reg size is determined by
7692  * the BTF func_proto's return value size and argument.
7693  */
7694 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7695                                    size_t reg_size)
7696 {
7697         struct bpf_reg_state *reg = &cur_regs(env)[regno];
7698
7699         if (regno == BPF_REG_0) {
7700                 /* Function return value */
7701                 reg->live |= REG_LIVE_WRITTEN;
7702                 reg->subreg_def = reg_size == sizeof(u64) ?
7703                         DEF_NOT_SUBREG : env->insn_idx + 1;
7704         } else {
7705                 /* Function argument */
7706                 if (reg_size == sizeof(u64)) {
7707                         mark_insn_zext(env, reg);
7708                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7709                 } else {
7710                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7711                 }
7712         }
7713 }
7714
7715 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7716                             int *insn_idx_p)
7717 {
7718         const struct btf_type *t, *func, *func_proto, *ptr_type;
7719         struct bpf_reg_state *regs = cur_regs(env);
7720         struct bpf_kfunc_arg_meta meta = { 0 };
7721         const char *func_name, *ptr_type_name;
7722         u32 i, nargs, func_id, ptr_type_id;
7723         int err, insn_idx = *insn_idx_p;
7724         const struct btf_param *args;
7725         struct btf *desc_btf;
7726         u32 *kfunc_flags;
7727         bool acq;
7728
7729         /* skip for now, but return error when we find this in fixup_kfunc_call */
7730         if (!insn->imm)
7731                 return 0;
7732
7733         desc_btf = find_kfunc_desc_btf(env, insn->off);
7734         if (IS_ERR(desc_btf))
7735                 return PTR_ERR(desc_btf);
7736
7737         func_id = insn->imm;
7738         func = btf_type_by_id(desc_btf, func_id);
7739         func_name = btf_name_by_offset(desc_btf, func->name_off);
7740         func_proto = btf_type_by_id(desc_btf, func->type);
7741
7742         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7743         if (!kfunc_flags) {
7744                 verbose(env, "calling kernel function %s is not allowed\n",
7745                         func_name);
7746                 return -EACCES;
7747         }
7748         if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7749                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7750                 return -EACCES;
7751         }
7752
7753         acq = *kfunc_flags & KF_ACQUIRE;
7754
7755         meta.flags = *kfunc_flags;
7756
7757         /* Check the arguments */
7758         err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7759         if (err < 0)
7760                 return err;
7761         /* In case of release function, we get register number of refcounted
7762          * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7763          */
7764         if (err) {
7765                 err = release_reference(env, regs[err].ref_obj_id);
7766                 if (err) {
7767                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7768                                 func_name, func_id);
7769                         return err;
7770                 }
7771         }
7772
7773         for (i = 0; i < CALLER_SAVED_REGS; i++)
7774                 mark_reg_not_init(env, regs, caller_saved[i]);
7775
7776         /* Check return type */
7777         t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7778
7779         if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7780                 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7781                 return -EINVAL;
7782         }
7783
7784         if (btf_type_is_scalar(t)) {
7785                 mark_reg_unknown(env, regs, BPF_REG_0);
7786                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7787         } else if (btf_type_is_ptr(t)) {
7788                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7789                                                    &ptr_type_id);
7790                 if (!btf_type_is_struct(ptr_type)) {
7791                         if (!meta.r0_size) {
7792                                 ptr_type_name = btf_name_by_offset(desc_btf,
7793                                                                    ptr_type->name_off);
7794                                 verbose(env,
7795                                         "kernel function %s returns pointer type %s %s is not supported\n",
7796                                         func_name,
7797                                         btf_type_str(ptr_type),
7798                                         ptr_type_name);
7799                                 return -EINVAL;
7800                         }
7801
7802                         mark_reg_known_zero(env, regs, BPF_REG_0);
7803                         regs[BPF_REG_0].type = PTR_TO_MEM;
7804                         regs[BPF_REG_0].mem_size = meta.r0_size;
7805
7806                         if (meta.r0_rdonly)
7807                                 regs[BPF_REG_0].type |= MEM_RDONLY;
7808
7809                         /* Ensures we don't access the memory after a release_reference() */
7810                         if (meta.ref_obj_id)
7811                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7812                 } else {
7813                         mark_reg_known_zero(env, regs, BPF_REG_0);
7814                         regs[BPF_REG_0].btf = desc_btf;
7815                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7816                         regs[BPF_REG_0].btf_id = ptr_type_id;
7817                 }
7818                 if (*kfunc_flags & KF_RET_NULL) {
7819                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7820                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7821                         regs[BPF_REG_0].id = ++env->id_gen;
7822                 }
7823                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7824                 if (acq) {
7825                         int id = acquire_reference_state(env, insn_idx);
7826
7827                         if (id < 0)
7828                                 return id;
7829                         regs[BPF_REG_0].id = id;
7830                         regs[BPF_REG_0].ref_obj_id = id;
7831                 }
7832         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7833
7834         nargs = btf_type_vlen(func_proto);
7835         args = (const struct btf_param *)(func_proto + 1);
7836         for (i = 0; i < nargs; i++) {
7837                 u32 regno = i + 1;
7838
7839                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7840                 if (btf_type_is_ptr(t))
7841                         mark_btf_func_reg_size(env, regno, sizeof(void *));
7842                 else
7843                         /* scalar. ensured by btf_check_kfunc_arg_match() */
7844                         mark_btf_func_reg_size(env, regno, t->size);
7845         }
7846
7847         return 0;
7848 }
7849
7850 static bool signed_add_overflows(s64 a, s64 b)
7851 {
7852         /* Do the add in u64, where overflow is well-defined */
7853         s64 res = (s64)((u64)a + (u64)b);
7854
7855         if (b < 0)
7856                 return res > a;
7857         return res < a;
7858 }
7859
7860 static bool signed_add32_overflows(s32 a, s32 b)
7861 {
7862         /* Do the add in u32, where overflow is well-defined */
7863         s32 res = (s32)((u32)a + (u32)b);
7864
7865         if (b < 0)
7866                 return res > a;
7867         return res < a;
7868 }
7869
7870 static bool signed_sub_overflows(s64 a, s64 b)
7871 {
7872         /* Do the sub in u64, where overflow is well-defined */
7873         s64 res = (s64)((u64)a - (u64)b);
7874
7875         if (b < 0)
7876                 return res < a;
7877         return res > a;
7878 }
7879
7880 static bool signed_sub32_overflows(s32 a, s32 b)
7881 {
7882         /* Do the sub in u32, where overflow is well-defined */
7883         s32 res = (s32)((u32)a - (u32)b);
7884
7885         if (b < 0)
7886                 return res < a;
7887         return res > a;
7888 }
7889
7890 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7891                                   const struct bpf_reg_state *reg,
7892                                   enum bpf_reg_type type)
7893 {
7894         bool known = tnum_is_const(reg->var_off);
7895         s64 val = reg->var_off.value;
7896         s64 smin = reg->smin_value;
7897
7898         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7899                 verbose(env, "math between %s pointer and %lld is not allowed\n",
7900                         reg_type_str(env, type), val);
7901                 return false;
7902         }
7903
7904         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7905                 verbose(env, "%s pointer offset %d is not allowed\n",
7906                         reg_type_str(env, type), reg->off);
7907                 return false;
7908         }
7909
7910         if (smin == S64_MIN) {
7911                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7912                         reg_type_str(env, type));
7913                 return false;
7914         }
7915
7916         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7917                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7918                         smin, reg_type_str(env, type));
7919                 return false;
7920         }
7921
7922         return true;
7923 }
7924
7925 enum {
7926         REASON_BOUNDS   = -1,
7927         REASON_TYPE     = -2,
7928         REASON_PATHS    = -3,
7929         REASON_LIMIT    = -4,
7930         REASON_STACK    = -5,
7931 };
7932
7933 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7934                               u32 *alu_limit, bool mask_to_left)
7935 {
7936         u32 max = 0, ptr_limit = 0;
7937
7938         switch (ptr_reg->type) {
7939         case PTR_TO_STACK:
7940                 /* Offset 0 is out-of-bounds, but acceptable start for the
7941                  * left direction, see BPF_REG_FP. Also, unknown scalar
7942                  * offset where we would need to deal with min/max bounds is
7943                  * currently prohibited for unprivileged.
7944                  */
7945                 max = MAX_BPF_STACK + mask_to_left;
7946                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7947                 break;
7948         case PTR_TO_MAP_VALUE:
7949                 max = ptr_reg->map_ptr->value_size;
7950                 ptr_limit = (mask_to_left ?
7951                              ptr_reg->smin_value :
7952                              ptr_reg->umax_value) + ptr_reg->off;
7953                 break;
7954         default:
7955                 return REASON_TYPE;
7956         }
7957
7958         if (ptr_limit >= max)
7959                 return REASON_LIMIT;
7960         *alu_limit = ptr_limit;
7961         return 0;
7962 }
7963
7964 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7965                                     const struct bpf_insn *insn)
7966 {
7967         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7968 }
7969
7970 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7971                                        u32 alu_state, u32 alu_limit)
7972 {
7973         /* If we arrived here from different branches with different
7974          * state or limits to sanitize, then this won't work.
7975          */
7976         if (aux->alu_state &&
7977             (aux->alu_state != alu_state ||
7978              aux->alu_limit != alu_limit))
7979                 return REASON_PATHS;
7980
7981         /* Corresponding fixup done in do_misc_fixups(). */
7982         aux->alu_state = alu_state;
7983         aux->alu_limit = alu_limit;
7984         return 0;
7985 }
7986
7987 static int sanitize_val_alu(struct bpf_verifier_env *env,
7988                             struct bpf_insn *insn)
7989 {
7990         struct bpf_insn_aux_data *aux = cur_aux(env);
7991
7992         if (can_skip_alu_sanitation(env, insn))
7993                 return 0;
7994
7995         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7996 }
7997
7998 static bool sanitize_needed(u8 opcode)
7999 {
8000         return opcode == BPF_ADD || opcode == BPF_SUB;
8001 }
8002
8003 struct bpf_sanitize_info {
8004         struct bpf_insn_aux_data aux;
8005         bool mask_to_left;
8006 };
8007
8008 static struct bpf_verifier_state *
8009 sanitize_speculative_path(struct bpf_verifier_env *env,
8010                           const struct bpf_insn *insn,
8011                           u32 next_idx, u32 curr_idx)
8012 {
8013         struct bpf_verifier_state *branch;
8014         struct bpf_reg_state *regs;
8015
8016         branch = push_stack(env, next_idx, curr_idx, true);
8017         if (branch && insn) {
8018                 regs = branch->frame[branch->curframe]->regs;
8019                 if (BPF_SRC(insn->code) == BPF_K) {
8020                         mark_reg_unknown(env, regs, insn->dst_reg);
8021                 } else if (BPF_SRC(insn->code) == BPF_X) {
8022                         mark_reg_unknown(env, regs, insn->dst_reg);
8023                         mark_reg_unknown(env, regs, insn->src_reg);
8024                 }
8025         }
8026         return branch;
8027 }
8028
8029 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8030                             struct bpf_insn *insn,
8031                             const struct bpf_reg_state *ptr_reg,
8032                             const struct bpf_reg_state *off_reg,
8033                             struct bpf_reg_state *dst_reg,
8034                             struct bpf_sanitize_info *info,
8035                             const bool commit_window)
8036 {
8037         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8038         struct bpf_verifier_state *vstate = env->cur_state;
8039         bool off_is_imm = tnum_is_const(off_reg->var_off);
8040         bool off_is_neg = off_reg->smin_value < 0;
8041         bool ptr_is_dst_reg = ptr_reg == dst_reg;
8042         u8 opcode = BPF_OP(insn->code);
8043         u32 alu_state, alu_limit;
8044         struct bpf_reg_state tmp;
8045         bool ret;
8046         int err;
8047
8048         if (can_skip_alu_sanitation(env, insn))
8049                 return 0;
8050
8051         /* We already marked aux for masking from non-speculative
8052          * paths, thus we got here in the first place. We only care
8053          * to explore bad access from here.
8054          */
8055         if (vstate->speculative)
8056                 goto do_sim;
8057
8058         if (!commit_window) {
8059                 if (!tnum_is_const(off_reg->var_off) &&
8060                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8061                         return REASON_BOUNDS;
8062
8063                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
8064                                      (opcode == BPF_SUB && !off_is_neg);
8065         }
8066
8067         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8068         if (err < 0)
8069                 return err;
8070
8071         if (commit_window) {
8072                 /* In commit phase we narrow the masking window based on
8073                  * the observed pointer move after the simulated operation.
8074                  */
8075                 alu_state = info->aux.alu_state;
8076                 alu_limit = abs(info->aux.alu_limit - alu_limit);
8077         } else {
8078                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8079                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8080                 alu_state |= ptr_is_dst_reg ?
8081                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8082
8083                 /* Limit pruning on unknown scalars to enable deep search for
8084                  * potential masking differences from other program paths.
8085                  */
8086                 if (!off_is_imm)
8087                         env->explore_alu_limits = true;
8088         }
8089
8090         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8091         if (err < 0)
8092                 return err;
8093 do_sim:
8094         /* If we're in commit phase, we're done here given we already
8095          * pushed the truncated dst_reg into the speculative verification
8096          * stack.
8097          *
8098          * Also, when register is a known constant, we rewrite register-based
8099          * operation to immediate-based, and thus do not need masking (and as
8100          * a consequence, do not need to simulate the zero-truncation either).
8101          */
8102         if (commit_window || off_is_imm)
8103                 return 0;
8104
8105         /* Simulate and find potential out-of-bounds access under
8106          * speculative execution from truncation as a result of
8107          * masking when off was not within expected range. If off
8108          * sits in dst, then we temporarily need to move ptr there
8109          * to simulate dst (== 0) +/-= ptr. Needed, for example,
8110          * for cases where we use K-based arithmetic in one direction
8111          * and truncated reg-based in the other in order to explore
8112          * bad access.
8113          */
8114         if (!ptr_is_dst_reg) {
8115                 tmp = *dst_reg;
8116                 copy_register_state(dst_reg, ptr_reg);
8117         }
8118         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8119                                         env->insn_idx);
8120         if (!ptr_is_dst_reg && ret)
8121                 *dst_reg = tmp;
8122         return !ret ? REASON_STACK : 0;
8123 }
8124
8125 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8126 {
8127         struct bpf_verifier_state *vstate = env->cur_state;
8128
8129         /* If we simulate paths under speculation, we don't update the
8130          * insn as 'seen' such that when we verify unreachable paths in
8131          * the non-speculative domain, sanitize_dead_code() can still
8132          * rewrite/sanitize them.
8133          */
8134         if (!vstate->speculative)
8135                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8136 }
8137
8138 static int sanitize_err(struct bpf_verifier_env *env,
8139                         const struct bpf_insn *insn, int reason,
8140                         const struct bpf_reg_state *off_reg,
8141                         const struct bpf_reg_state *dst_reg)
8142 {
8143         static const char *err = "pointer arithmetic with it prohibited for !root";
8144         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8145         u32 dst = insn->dst_reg, src = insn->src_reg;
8146
8147         switch (reason) {
8148         case REASON_BOUNDS:
8149                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8150                         off_reg == dst_reg ? dst : src, err);
8151                 break;
8152         case REASON_TYPE:
8153                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8154                         off_reg == dst_reg ? src : dst, err);
8155                 break;
8156         case REASON_PATHS:
8157                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8158                         dst, op, err);
8159                 break;
8160         case REASON_LIMIT:
8161                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8162                         dst, op, err);
8163                 break;
8164         case REASON_STACK:
8165                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8166                         dst, err);
8167                 break;
8168         default:
8169                 verbose(env, "verifier internal error: unknown reason (%d)\n",
8170                         reason);
8171                 break;
8172         }
8173
8174         return -EACCES;
8175 }
8176
8177 /* check that stack access falls within stack limits and that 'reg' doesn't
8178  * have a variable offset.
8179  *
8180  * Variable offset is prohibited for unprivileged mode for simplicity since it
8181  * requires corresponding support in Spectre masking for stack ALU.  See also
8182  * retrieve_ptr_limit().
8183  *
8184  *
8185  * 'off' includes 'reg->off'.
8186  */
8187 static int check_stack_access_for_ptr_arithmetic(
8188                                 struct bpf_verifier_env *env,
8189                                 int regno,
8190                                 const struct bpf_reg_state *reg,
8191                                 int off)
8192 {
8193         if (!tnum_is_const(reg->var_off)) {
8194                 char tn_buf[48];
8195
8196                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8197                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8198                         regno, tn_buf, off);
8199                 return -EACCES;
8200         }
8201
8202         if (off >= 0 || off < -MAX_BPF_STACK) {
8203                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8204                         "prohibited for !root; off=%d\n", regno, off);
8205                 return -EACCES;
8206         }
8207
8208         return 0;
8209 }
8210
8211 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8212                                  const struct bpf_insn *insn,
8213                                  const struct bpf_reg_state *dst_reg)
8214 {
8215         u32 dst = insn->dst_reg;
8216
8217         /* For unprivileged we require that resulting offset must be in bounds
8218          * in order to be able to sanitize access later on.
8219          */
8220         if (env->bypass_spec_v1)
8221                 return 0;
8222
8223         switch (dst_reg->type) {
8224         case PTR_TO_STACK:
8225                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8226                                         dst_reg->off + dst_reg->var_off.value))
8227                         return -EACCES;
8228                 break;
8229         case PTR_TO_MAP_VALUE:
8230                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8231                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8232                                 "prohibited for !root\n", dst);
8233                         return -EACCES;
8234                 }
8235                 break;
8236         default:
8237                 break;
8238         }
8239
8240         return 0;
8241 }
8242
8243 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8244  * Caller should also handle BPF_MOV case separately.
8245  * If we return -EACCES, caller may want to try again treating pointer as a
8246  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8247  */
8248 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8249                                    struct bpf_insn *insn,
8250                                    const struct bpf_reg_state *ptr_reg,
8251                                    const struct bpf_reg_state *off_reg)
8252 {
8253         struct bpf_verifier_state *vstate = env->cur_state;
8254         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8255         struct bpf_reg_state *regs = state->regs, *dst_reg;
8256         bool known = tnum_is_const(off_reg->var_off);
8257         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8258             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8259         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8260             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8261         struct bpf_sanitize_info info = {};
8262         u8 opcode = BPF_OP(insn->code);
8263         u32 dst = insn->dst_reg;
8264         int ret;
8265
8266         dst_reg = &regs[dst];
8267
8268         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8269             smin_val > smax_val || umin_val > umax_val) {
8270                 /* Taint dst register if offset had invalid bounds derived from
8271                  * e.g. dead branches.
8272                  */
8273                 __mark_reg_unknown(env, dst_reg);
8274                 return 0;
8275         }
8276
8277         if (BPF_CLASS(insn->code) != BPF_ALU64) {
8278                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8279                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8280                         __mark_reg_unknown(env, dst_reg);
8281                         return 0;
8282                 }
8283
8284                 verbose(env,
8285                         "R%d 32-bit pointer arithmetic prohibited\n",
8286                         dst);
8287                 return -EACCES;
8288         }
8289
8290         if (ptr_reg->type & PTR_MAYBE_NULL) {
8291                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8292                         dst, reg_type_str(env, ptr_reg->type));
8293                 return -EACCES;
8294         }
8295
8296         switch (base_type(ptr_reg->type)) {
8297         case CONST_PTR_TO_MAP:
8298                 /* smin_val represents the known value */
8299                 if (known && smin_val == 0 && opcode == BPF_ADD)
8300                         break;
8301                 fallthrough;
8302         case PTR_TO_PACKET_END:
8303         case PTR_TO_SOCKET:
8304         case PTR_TO_SOCK_COMMON:
8305         case PTR_TO_TCP_SOCK:
8306         case PTR_TO_XDP_SOCK:
8307                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8308                         dst, reg_type_str(env, ptr_reg->type));
8309                 return -EACCES;
8310         default:
8311                 break;
8312         }
8313
8314         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8315          * The id may be overwritten later if we create a new variable offset.
8316          */
8317         dst_reg->type = ptr_reg->type;
8318         dst_reg->id = ptr_reg->id;
8319
8320         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8321             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8322                 return -EINVAL;
8323
8324         /* pointer types do not carry 32-bit bounds at the moment. */
8325         __mark_reg32_unbounded(dst_reg);
8326
8327         if (sanitize_needed(opcode)) {
8328                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8329                                        &info, false);
8330                 if (ret < 0)
8331                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8332         }
8333
8334         switch (opcode) {
8335         case BPF_ADD:
8336                 /* We can take a fixed offset as long as it doesn't overflow
8337                  * the s32 'off' field
8338                  */
8339                 if (known && (ptr_reg->off + smin_val ==
8340                               (s64)(s32)(ptr_reg->off + smin_val))) {
8341                         /* pointer += K.  Accumulate it into fixed offset */
8342                         dst_reg->smin_value = smin_ptr;
8343                         dst_reg->smax_value = smax_ptr;
8344                         dst_reg->umin_value = umin_ptr;
8345                         dst_reg->umax_value = umax_ptr;
8346                         dst_reg->var_off = ptr_reg->var_off;
8347                         dst_reg->off = ptr_reg->off + smin_val;
8348                         dst_reg->raw = ptr_reg->raw;
8349                         break;
8350                 }
8351                 /* A new variable offset is created.  Note that off_reg->off
8352                  * == 0, since it's a scalar.
8353                  * dst_reg gets the pointer type and since some positive
8354                  * integer value was added to the pointer, give it a new 'id'
8355                  * if it's a PTR_TO_PACKET.
8356                  * this creates a new 'base' pointer, off_reg (variable) gets
8357                  * added into the variable offset, and we copy the fixed offset
8358                  * from ptr_reg.
8359                  */
8360                 if (signed_add_overflows(smin_ptr, smin_val) ||
8361                     signed_add_overflows(smax_ptr, smax_val)) {
8362                         dst_reg->smin_value = S64_MIN;
8363                         dst_reg->smax_value = S64_MAX;
8364                 } else {
8365                         dst_reg->smin_value = smin_ptr + smin_val;
8366                         dst_reg->smax_value = smax_ptr + smax_val;
8367                 }
8368                 if (umin_ptr + umin_val < umin_ptr ||
8369                     umax_ptr + umax_val < umax_ptr) {
8370                         dst_reg->umin_value = 0;
8371                         dst_reg->umax_value = U64_MAX;
8372                 } else {
8373                         dst_reg->umin_value = umin_ptr + umin_val;
8374                         dst_reg->umax_value = umax_ptr + umax_val;
8375                 }
8376                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8377                 dst_reg->off = ptr_reg->off;
8378                 dst_reg->raw = ptr_reg->raw;
8379                 if (reg_is_pkt_pointer(ptr_reg)) {
8380                         dst_reg->id = ++env->id_gen;
8381                         /* something was added to pkt_ptr, set range to zero */
8382                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8383                 }
8384                 break;
8385         case BPF_SUB:
8386                 if (dst_reg == off_reg) {
8387                         /* scalar -= pointer.  Creates an unknown scalar */
8388                         verbose(env, "R%d tried to subtract pointer from scalar\n",
8389                                 dst);
8390                         return -EACCES;
8391                 }
8392                 /* We don't allow subtraction from FP, because (according to
8393                  * test_verifier.c test "invalid fp arithmetic", JITs might not
8394                  * be able to deal with it.
8395                  */
8396                 if (ptr_reg->type == PTR_TO_STACK) {
8397                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
8398                                 dst);
8399                         return -EACCES;
8400                 }
8401                 if (known && (ptr_reg->off - smin_val ==
8402                               (s64)(s32)(ptr_reg->off - smin_val))) {
8403                         /* pointer -= K.  Subtract it from fixed offset */
8404                         dst_reg->smin_value = smin_ptr;
8405                         dst_reg->smax_value = smax_ptr;
8406                         dst_reg->umin_value = umin_ptr;
8407                         dst_reg->umax_value = umax_ptr;
8408                         dst_reg->var_off = ptr_reg->var_off;
8409                         dst_reg->id = ptr_reg->id;
8410                         dst_reg->off = ptr_reg->off - smin_val;
8411                         dst_reg->raw = ptr_reg->raw;
8412                         break;
8413                 }
8414                 /* A new variable offset is created.  If the subtrahend is known
8415                  * nonnegative, then any reg->range we had before is still good.
8416                  */
8417                 if (signed_sub_overflows(smin_ptr, smax_val) ||
8418                     signed_sub_overflows(smax_ptr, smin_val)) {
8419                         /* Overflow possible, we know nothing */
8420                         dst_reg->smin_value = S64_MIN;
8421                         dst_reg->smax_value = S64_MAX;
8422                 } else {
8423                         dst_reg->smin_value = smin_ptr - smax_val;
8424                         dst_reg->smax_value = smax_ptr - smin_val;
8425                 }
8426                 if (umin_ptr < umax_val) {
8427                         /* Overflow possible, we know nothing */
8428                         dst_reg->umin_value = 0;
8429                         dst_reg->umax_value = U64_MAX;
8430                 } else {
8431                         /* Cannot overflow (as long as bounds are consistent) */
8432                         dst_reg->umin_value = umin_ptr - umax_val;
8433                         dst_reg->umax_value = umax_ptr - umin_val;
8434                 }
8435                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8436                 dst_reg->off = ptr_reg->off;
8437                 dst_reg->raw = ptr_reg->raw;
8438                 if (reg_is_pkt_pointer(ptr_reg)) {
8439                         dst_reg->id = ++env->id_gen;
8440                         /* something was added to pkt_ptr, set range to zero */
8441                         if (smin_val < 0)
8442                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8443                 }
8444                 break;
8445         case BPF_AND:
8446         case BPF_OR:
8447         case BPF_XOR:
8448                 /* bitwise ops on pointers are troublesome, prohibit. */
8449                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8450                         dst, bpf_alu_string[opcode >> 4]);
8451                 return -EACCES;
8452         default:
8453                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8454                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8455                         dst, bpf_alu_string[opcode >> 4]);
8456                 return -EACCES;
8457         }
8458
8459         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8460                 return -EINVAL;
8461         reg_bounds_sync(dst_reg);
8462         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8463                 return -EACCES;
8464         if (sanitize_needed(opcode)) {
8465                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8466                                        &info, true);
8467                 if (ret < 0)
8468                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8469         }
8470
8471         return 0;
8472 }
8473
8474 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8475                                  struct bpf_reg_state *src_reg)
8476 {
8477         s32 smin_val = src_reg->s32_min_value;
8478         s32 smax_val = src_reg->s32_max_value;
8479         u32 umin_val = src_reg->u32_min_value;
8480         u32 umax_val = src_reg->u32_max_value;
8481
8482         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8483             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8484                 dst_reg->s32_min_value = S32_MIN;
8485                 dst_reg->s32_max_value = S32_MAX;
8486         } else {
8487                 dst_reg->s32_min_value += smin_val;
8488                 dst_reg->s32_max_value += smax_val;
8489         }
8490         if (dst_reg->u32_min_value + umin_val < umin_val ||
8491             dst_reg->u32_max_value + umax_val < umax_val) {
8492                 dst_reg->u32_min_value = 0;
8493                 dst_reg->u32_max_value = U32_MAX;
8494         } else {
8495                 dst_reg->u32_min_value += umin_val;
8496                 dst_reg->u32_max_value += umax_val;
8497         }
8498 }
8499
8500 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8501                                struct bpf_reg_state *src_reg)
8502 {
8503         s64 smin_val = src_reg->smin_value;
8504         s64 smax_val = src_reg->smax_value;
8505         u64 umin_val = src_reg->umin_value;
8506         u64 umax_val = src_reg->umax_value;
8507
8508         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8509             signed_add_overflows(dst_reg->smax_value, smax_val)) {
8510                 dst_reg->smin_value = S64_MIN;
8511                 dst_reg->smax_value = S64_MAX;
8512         } else {
8513                 dst_reg->smin_value += smin_val;
8514                 dst_reg->smax_value += smax_val;
8515         }
8516         if (dst_reg->umin_value + umin_val < umin_val ||
8517             dst_reg->umax_value + umax_val < umax_val) {
8518                 dst_reg->umin_value = 0;
8519                 dst_reg->umax_value = U64_MAX;
8520         } else {
8521                 dst_reg->umin_value += umin_val;
8522                 dst_reg->umax_value += umax_val;
8523         }
8524 }
8525
8526 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8527                                  struct bpf_reg_state *src_reg)
8528 {
8529         s32 smin_val = src_reg->s32_min_value;
8530         s32 smax_val = src_reg->s32_max_value;
8531         u32 umin_val = src_reg->u32_min_value;
8532         u32 umax_val = src_reg->u32_max_value;
8533
8534         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8535             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8536                 /* Overflow possible, we know nothing */
8537                 dst_reg->s32_min_value = S32_MIN;
8538                 dst_reg->s32_max_value = S32_MAX;
8539         } else {
8540                 dst_reg->s32_min_value -= smax_val;
8541                 dst_reg->s32_max_value -= smin_val;
8542         }
8543         if (dst_reg->u32_min_value < umax_val) {
8544                 /* Overflow possible, we know nothing */
8545                 dst_reg->u32_min_value = 0;
8546                 dst_reg->u32_max_value = U32_MAX;
8547         } else {
8548                 /* Cannot overflow (as long as bounds are consistent) */
8549                 dst_reg->u32_min_value -= umax_val;
8550                 dst_reg->u32_max_value -= umin_val;
8551         }
8552 }
8553
8554 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8555                                struct bpf_reg_state *src_reg)
8556 {
8557         s64 smin_val = src_reg->smin_value;
8558         s64 smax_val = src_reg->smax_value;
8559         u64 umin_val = src_reg->umin_value;
8560         u64 umax_val = src_reg->umax_value;
8561
8562         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8563             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8564                 /* Overflow possible, we know nothing */
8565                 dst_reg->smin_value = S64_MIN;
8566                 dst_reg->smax_value = S64_MAX;
8567         } else {
8568                 dst_reg->smin_value -= smax_val;
8569                 dst_reg->smax_value -= smin_val;
8570         }
8571         if (dst_reg->umin_value < umax_val) {
8572                 /* Overflow possible, we know nothing */
8573                 dst_reg->umin_value = 0;
8574                 dst_reg->umax_value = U64_MAX;
8575         } else {
8576                 /* Cannot overflow (as long as bounds are consistent) */
8577                 dst_reg->umin_value -= umax_val;
8578                 dst_reg->umax_value -= umin_val;
8579         }
8580 }
8581
8582 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8583                                  struct bpf_reg_state *src_reg)
8584 {
8585         s32 smin_val = src_reg->s32_min_value;
8586         u32 umin_val = src_reg->u32_min_value;
8587         u32 umax_val = src_reg->u32_max_value;
8588
8589         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8590                 /* Ain't nobody got time to multiply that sign */
8591                 __mark_reg32_unbounded(dst_reg);
8592                 return;
8593         }
8594         /* Both values are positive, so we can work with unsigned and
8595          * copy the result to signed (unless it exceeds S32_MAX).
8596          */
8597         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8598                 /* Potential overflow, we know nothing */
8599                 __mark_reg32_unbounded(dst_reg);
8600                 return;
8601         }
8602         dst_reg->u32_min_value *= umin_val;
8603         dst_reg->u32_max_value *= umax_val;
8604         if (dst_reg->u32_max_value > S32_MAX) {
8605                 /* Overflow possible, we know nothing */
8606                 dst_reg->s32_min_value = S32_MIN;
8607                 dst_reg->s32_max_value = S32_MAX;
8608         } else {
8609                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8610                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8611         }
8612 }
8613
8614 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8615                                struct bpf_reg_state *src_reg)
8616 {
8617         s64 smin_val = src_reg->smin_value;
8618         u64 umin_val = src_reg->umin_value;
8619         u64 umax_val = src_reg->umax_value;
8620
8621         if (smin_val < 0 || dst_reg->smin_value < 0) {
8622                 /* Ain't nobody got time to multiply that sign */
8623                 __mark_reg64_unbounded(dst_reg);
8624                 return;
8625         }
8626         /* Both values are positive, so we can work with unsigned and
8627          * copy the result to signed (unless it exceeds S64_MAX).
8628          */
8629         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8630                 /* Potential overflow, we know nothing */
8631                 __mark_reg64_unbounded(dst_reg);
8632                 return;
8633         }
8634         dst_reg->umin_value *= umin_val;
8635         dst_reg->umax_value *= umax_val;
8636         if (dst_reg->umax_value > S64_MAX) {
8637                 /* Overflow possible, we know nothing */
8638                 dst_reg->smin_value = S64_MIN;
8639                 dst_reg->smax_value = S64_MAX;
8640         } else {
8641                 dst_reg->smin_value = dst_reg->umin_value;
8642                 dst_reg->smax_value = dst_reg->umax_value;
8643         }
8644 }
8645
8646 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8647                                  struct bpf_reg_state *src_reg)
8648 {
8649         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8650         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8651         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8652         s32 smin_val = src_reg->s32_min_value;
8653         u32 umax_val = src_reg->u32_max_value;
8654
8655         if (src_known && dst_known) {
8656                 __mark_reg32_known(dst_reg, var32_off.value);
8657                 return;
8658         }
8659
8660         /* We get our minimum from the var_off, since that's inherently
8661          * bitwise.  Our maximum is the minimum of the operands' maxima.
8662          */
8663         dst_reg->u32_min_value = var32_off.value;
8664         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8665         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8666                 /* Lose signed bounds when ANDing negative numbers,
8667                  * ain't nobody got time for that.
8668                  */
8669                 dst_reg->s32_min_value = S32_MIN;
8670                 dst_reg->s32_max_value = S32_MAX;
8671         } else {
8672                 /* ANDing two positives gives a positive, so safe to
8673                  * cast result into s64.
8674                  */
8675                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8676                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8677         }
8678 }
8679
8680 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8681                                struct bpf_reg_state *src_reg)
8682 {
8683         bool src_known = tnum_is_const(src_reg->var_off);
8684         bool dst_known = tnum_is_const(dst_reg->var_off);
8685         s64 smin_val = src_reg->smin_value;
8686         u64 umax_val = src_reg->umax_value;
8687
8688         if (src_known && dst_known) {
8689                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8690                 return;
8691         }
8692
8693         /* We get our minimum from the var_off, since that's inherently
8694          * bitwise.  Our maximum is the minimum of the operands' maxima.
8695          */
8696         dst_reg->umin_value = dst_reg->var_off.value;
8697         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8698         if (dst_reg->smin_value < 0 || smin_val < 0) {
8699                 /* Lose signed bounds when ANDing negative numbers,
8700                  * ain't nobody got time for that.
8701                  */
8702                 dst_reg->smin_value = S64_MIN;
8703                 dst_reg->smax_value = S64_MAX;
8704         } else {
8705                 /* ANDing two positives gives a positive, so safe to
8706                  * cast result into s64.
8707                  */
8708                 dst_reg->smin_value = dst_reg->umin_value;
8709                 dst_reg->smax_value = dst_reg->umax_value;
8710         }
8711         /* We may learn something more from the var_off */
8712         __update_reg_bounds(dst_reg);
8713 }
8714
8715 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8716                                 struct bpf_reg_state *src_reg)
8717 {
8718         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8719         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8720         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8721         s32 smin_val = src_reg->s32_min_value;
8722         u32 umin_val = src_reg->u32_min_value;
8723
8724         if (src_known && dst_known) {
8725                 __mark_reg32_known(dst_reg, var32_off.value);
8726                 return;
8727         }
8728
8729         /* We get our maximum from the var_off, and our minimum is the
8730          * maximum of the operands' minima
8731          */
8732         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8733         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8734         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8735                 /* Lose signed bounds when ORing negative numbers,
8736                  * ain't nobody got time for that.
8737                  */
8738                 dst_reg->s32_min_value = S32_MIN;
8739                 dst_reg->s32_max_value = S32_MAX;
8740         } else {
8741                 /* ORing two positives gives a positive, so safe to
8742                  * cast result into s64.
8743                  */
8744                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8745                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8746         }
8747 }
8748
8749 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8750                               struct bpf_reg_state *src_reg)
8751 {
8752         bool src_known = tnum_is_const(src_reg->var_off);
8753         bool dst_known = tnum_is_const(dst_reg->var_off);
8754         s64 smin_val = src_reg->smin_value;
8755         u64 umin_val = src_reg->umin_value;
8756
8757         if (src_known && dst_known) {
8758                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8759                 return;
8760         }
8761
8762         /* We get our maximum from the var_off, and our minimum is the
8763          * maximum of the operands' minima
8764          */
8765         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8766         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8767         if (dst_reg->smin_value < 0 || smin_val < 0) {
8768                 /* Lose signed bounds when ORing negative numbers,
8769                  * ain't nobody got time for that.
8770                  */
8771                 dst_reg->smin_value = S64_MIN;
8772                 dst_reg->smax_value = S64_MAX;
8773         } else {
8774                 /* ORing two positives gives a positive, so safe to
8775                  * cast result into s64.
8776                  */
8777                 dst_reg->smin_value = dst_reg->umin_value;
8778                 dst_reg->smax_value = dst_reg->umax_value;
8779         }
8780         /* We may learn something more from the var_off */
8781         __update_reg_bounds(dst_reg);
8782 }
8783
8784 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8785                                  struct bpf_reg_state *src_reg)
8786 {
8787         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8788         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8789         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8790         s32 smin_val = src_reg->s32_min_value;
8791
8792         if (src_known && dst_known) {
8793                 __mark_reg32_known(dst_reg, var32_off.value);
8794                 return;
8795         }
8796
8797         /* We get both minimum and maximum from the var32_off. */
8798         dst_reg->u32_min_value = var32_off.value;
8799         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8800
8801         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8802                 /* XORing two positive sign numbers gives a positive,
8803                  * so safe to cast u32 result into s32.
8804                  */
8805                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8806                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8807         } else {
8808                 dst_reg->s32_min_value = S32_MIN;
8809                 dst_reg->s32_max_value = S32_MAX;
8810         }
8811 }
8812
8813 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8814                                struct bpf_reg_state *src_reg)
8815 {
8816         bool src_known = tnum_is_const(src_reg->var_off);
8817         bool dst_known = tnum_is_const(dst_reg->var_off);
8818         s64 smin_val = src_reg->smin_value;
8819
8820         if (src_known && dst_known) {
8821                 /* dst_reg->var_off.value has been updated earlier */
8822                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8823                 return;
8824         }
8825
8826         /* We get both minimum and maximum from the var_off. */
8827         dst_reg->umin_value = dst_reg->var_off.value;
8828         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8829
8830         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8831                 /* XORing two positive sign numbers gives a positive,
8832                  * so safe to cast u64 result into s64.
8833                  */
8834                 dst_reg->smin_value = dst_reg->umin_value;
8835                 dst_reg->smax_value = dst_reg->umax_value;
8836         } else {
8837                 dst_reg->smin_value = S64_MIN;
8838                 dst_reg->smax_value = S64_MAX;
8839         }
8840
8841         __update_reg_bounds(dst_reg);
8842 }
8843
8844 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8845                                    u64 umin_val, u64 umax_val)
8846 {
8847         /* We lose all sign bit information (except what we can pick
8848          * up from var_off)
8849          */
8850         dst_reg->s32_min_value = S32_MIN;
8851         dst_reg->s32_max_value = S32_MAX;
8852         /* If we might shift our top bit out, then we know nothing */
8853         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8854                 dst_reg->u32_min_value = 0;
8855                 dst_reg->u32_max_value = U32_MAX;
8856         } else {
8857                 dst_reg->u32_min_value <<= umin_val;
8858                 dst_reg->u32_max_value <<= umax_val;
8859         }
8860 }
8861
8862 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8863                                  struct bpf_reg_state *src_reg)
8864 {
8865         u32 umax_val = src_reg->u32_max_value;
8866         u32 umin_val = src_reg->u32_min_value;
8867         /* u32 alu operation will zext upper bits */
8868         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8869
8870         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8871         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8872         /* Not required but being careful mark reg64 bounds as unknown so
8873          * that we are forced to pick them up from tnum and zext later and
8874          * if some path skips this step we are still safe.
8875          */
8876         __mark_reg64_unbounded(dst_reg);
8877         __update_reg32_bounds(dst_reg);
8878 }
8879
8880 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8881                                    u64 umin_val, u64 umax_val)
8882 {
8883         /* Special case <<32 because it is a common compiler pattern to sign
8884          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8885          * positive we know this shift will also be positive so we can track
8886          * bounds correctly. Otherwise we lose all sign bit information except
8887          * what we can pick up from var_off. Perhaps we can generalize this
8888          * later to shifts of any length.
8889          */
8890         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8891                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8892         else
8893                 dst_reg->smax_value = S64_MAX;
8894
8895         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8896                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8897         else
8898                 dst_reg->smin_value = S64_MIN;
8899
8900         /* If we might shift our top bit out, then we know nothing */
8901         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8902                 dst_reg->umin_value = 0;
8903                 dst_reg->umax_value = U64_MAX;
8904         } else {
8905                 dst_reg->umin_value <<= umin_val;
8906                 dst_reg->umax_value <<= umax_val;
8907         }
8908 }
8909
8910 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8911                                struct bpf_reg_state *src_reg)
8912 {
8913         u64 umax_val = src_reg->umax_value;
8914         u64 umin_val = src_reg->umin_value;
8915
8916         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8917         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8918         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8919
8920         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8921         /* We may learn something more from the var_off */
8922         __update_reg_bounds(dst_reg);
8923 }
8924
8925 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8926                                  struct bpf_reg_state *src_reg)
8927 {
8928         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8929         u32 umax_val = src_reg->u32_max_value;
8930         u32 umin_val = src_reg->u32_min_value;
8931
8932         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8933          * be negative, then either:
8934          * 1) src_reg might be zero, so the sign bit of the result is
8935          *    unknown, so we lose our signed bounds
8936          * 2) it's known negative, thus the unsigned bounds capture the
8937          *    signed bounds
8938          * 3) the signed bounds cross zero, so they tell us nothing
8939          *    about the result
8940          * If the value in dst_reg is known nonnegative, then again the
8941          * unsigned bounds capture the signed bounds.
8942          * Thus, in all cases it suffices to blow away our signed bounds
8943          * and rely on inferring new ones from the unsigned bounds and
8944          * var_off of the result.
8945          */
8946         dst_reg->s32_min_value = S32_MIN;
8947         dst_reg->s32_max_value = S32_MAX;
8948
8949         dst_reg->var_off = tnum_rshift(subreg, umin_val);
8950         dst_reg->u32_min_value >>= umax_val;
8951         dst_reg->u32_max_value >>= umin_val;
8952
8953         __mark_reg64_unbounded(dst_reg);
8954         __update_reg32_bounds(dst_reg);
8955 }
8956
8957 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8958                                struct bpf_reg_state *src_reg)
8959 {
8960         u64 umax_val = src_reg->umax_value;
8961         u64 umin_val = src_reg->umin_value;
8962
8963         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8964          * be negative, then either:
8965          * 1) src_reg might be zero, so the sign bit of the result is
8966          *    unknown, so we lose our signed bounds
8967          * 2) it's known negative, thus the unsigned bounds capture the
8968          *    signed bounds
8969          * 3) the signed bounds cross zero, so they tell us nothing
8970          *    about the result
8971          * If the value in dst_reg is known nonnegative, then again the
8972          * unsigned bounds capture the signed bounds.
8973          * Thus, in all cases it suffices to blow away our signed bounds
8974          * and rely on inferring new ones from the unsigned bounds and
8975          * var_off of the result.
8976          */
8977         dst_reg->smin_value = S64_MIN;
8978         dst_reg->smax_value = S64_MAX;
8979         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8980         dst_reg->umin_value >>= umax_val;
8981         dst_reg->umax_value >>= umin_val;
8982
8983         /* Its not easy to operate on alu32 bounds here because it depends
8984          * on bits being shifted in. Take easy way out and mark unbounded
8985          * so we can recalculate later from tnum.
8986          */
8987         __mark_reg32_unbounded(dst_reg);
8988         __update_reg_bounds(dst_reg);
8989 }
8990
8991 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8992                                   struct bpf_reg_state *src_reg)
8993 {
8994         u64 umin_val = src_reg->u32_min_value;
8995
8996         /* Upon reaching here, src_known is true and
8997          * umax_val is equal to umin_val.
8998          */
8999         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
9000         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
9001
9002         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
9003
9004         /* blow away the dst_reg umin_value/umax_value and rely on
9005          * dst_reg var_off to refine the result.
9006          */
9007         dst_reg->u32_min_value = 0;
9008         dst_reg->u32_max_value = U32_MAX;
9009
9010         __mark_reg64_unbounded(dst_reg);
9011         __update_reg32_bounds(dst_reg);
9012 }
9013
9014 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
9015                                 struct bpf_reg_state *src_reg)
9016 {
9017         u64 umin_val = src_reg->umin_value;
9018
9019         /* Upon reaching here, src_known is true and umax_val is equal
9020          * to umin_val.
9021          */
9022         dst_reg->smin_value >>= umin_val;
9023         dst_reg->smax_value >>= umin_val;
9024
9025         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
9026
9027         /* blow away the dst_reg umin_value/umax_value and rely on
9028          * dst_reg var_off to refine the result.
9029          */
9030         dst_reg->umin_value = 0;
9031         dst_reg->umax_value = U64_MAX;
9032
9033         /* Its not easy to operate on alu32 bounds here because it depends
9034          * on bits being shifted in from upper 32-bits. Take easy way out
9035          * and mark unbounded so we can recalculate later from tnum.
9036          */
9037         __mark_reg32_unbounded(dst_reg);
9038         __update_reg_bounds(dst_reg);
9039 }
9040
9041 /* WARNING: This function does calculations on 64-bit values, but the actual
9042  * execution may occur on 32-bit values. Therefore, things like bitshifts
9043  * need extra checks in the 32-bit case.
9044  */
9045 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9046                                       struct bpf_insn *insn,
9047                                       struct bpf_reg_state *dst_reg,
9048                                       struct bpf_reg_state src_reg)
9049 {
9050         struct bpf_reg_state *regs = cur_regs(env);
9051         u8 opcode = BPF_OP(insn->code);
9052         bool src_known;
9053         s64 smin_val, smax_val;
9054         u64 umin_val, umax_val;
9055         s32 s32_min_val, s32_max_val;
9056         u32 u32_min_val, u32_max_val;
9057         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9058         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9059         int ret;
9060
9061         smin_val = src_reg.smin_value;
9062         smax_val = src_reg.smax_value;
9063         umin_val = src_reg.umin_value;
9064         umax_val = src_reg.umax_value;
9065
9066         s32_min_val = src_reg.s32_min_value;
9067         s32_max_val = src_reg.s32_max_value;
9068         u32_min_val = src_reg.u32_min_value;
9069         u32_max_val = src_reg.u32_max_value;
9070
9071         if (alu32) {
9072                 src_known = tnum_subreg_is_const(src_reg.var_off);
9073                 if ((src_known &&
9074                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9075                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9076                         /* Taint dst register if offset had invalid bounds
9077                          * derived from e.g. dead branches.
9078                          */
9079                         __mark_reg_unknown(env, dst_reg);
9080                         return 0;
9081                 }
9082         } else {
9083                 src_known = tnum_is_const(src_reg.var_off);
9084                 if ((src_known &&
9085                      (smin_val != smax_val || umin_val != umax_val)) ||
9086                     smin_val > smax_val || umin_val > umax_val) {
9087                         /* Taint dst register if offset had invalid bounds
9088                          * derived from e.g. dead branches.
9089                          */
9090                         __mark_reg_unknown(env, dst_reg);
9091                         return 0;
9092                 }
9093         }
9094
9095         if (!src_known &&
9096             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9097                 __mark_reg_unknown(env, dst_reg);
9098                 return 0;
9099         }
9100
9101         if (sanitize_needed(opcode)) {
9102                 ret = sanitize_val_alu(env, insn);
9103                 if (ret < 0)
9104                         return sanitize_err(env, insn, ret, NULL, NULL);
9105         }
9106
9107         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9108          * There are two classes of instructions: The first class we track both
9109          * alu32 and alu64 sign/unsigned bounds independently this provides the
9110          * greatest amount of precision when alu operations are mixed with jmp32
9111          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9112          * and BPF_OR. This is possible because these ops have fairly easy to
9113          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9114          * See alu32 verifier tests for examples. The second class of
9115          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9116          * with regards to tracking sign/unsigned bounds because the bits may
9117          * cross subreg boundaries in the alu64 case. When this happens we mark
9118          * the reg unbounded in the subreg bound space and use the resulting
9119          * tnum to calculate an approximation of the sign/unsigned bounds.
9120          */
9121         switch (opcode) {
9122         case BPF_ADD:
9123                 scalar32_min_max_add(dst_reg, &src_reg);
9124                 scalar_min_max_add(dst_reg, &src_reg);
9125                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9126                 break;
9127         case BPF_SUB:
9128                 scalar32_min_max_sub(dst_reg, &src_reg);
9129                 scalar_min_max_sub(dst_reg, &src_reg);
9130                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9131                 break;
9132         case BPF_MUL:
9133                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9134                 scalar32_min_max_mul(dst_reg, &src_reg);
9135                 scalar_min_max_mul(dst_reg, &src_reg);
9136                 break;
9137         case BPF_AND:
9138                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9139                 scalar32_min_max_and(dst_reg, &src_reg);
9140                 scalar_min_max_and(dst_reg, &src_reg);
9141                 break;
9142         case BPF_OR:
9143                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9144                 scalar32_min_max_or(dst_reg, &src_reg);
9145                 scalar_min_max_or(dst_reg, &src_reg);
9146                 break;
9147         case BPF_XOR:
9148                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9149                 scalar32_min_max_xor(dst_reg, &src_reg);
9150                 scalar_min_max_xor(dst_reg, &src_reg);
9151                 break;
9152         case BPF_LSH:
9153                 if (umax_val >= insn_bitness) {
9154                         /* Shifts greater than 31 or 63 are undefined.
9155                          * This includes shifts by a negative number.
9156                          */
9157                         mark_reg_unknown(env, regs, insn->dst_reg);
9158                         break;
9159                 }
9160                 if (alu32)
9161                         scalar32_min_max_lsh(dst_reg, &src_reg);
9162                 else
9163                         scalar_min_max_lsh(dst_reg, &src_reg);
9164                 break;
9165         case BPF_RSH:
9166                 if (umax_val >= insn_bitness) {
9167                         /* Shifts greater than 31 or 63 are undefined.
9168                          * This includes shifts by a negative number.
9169                          */
9170                         mark_reg_unknown(env, regs, insn->dst_reg);
9171                         break;
9172                 }
9173                 if (alu32)
9174                         scalar32_min_max_rsh(dst_reg, &src_reg);
9175                 else
9176                         scalar_min_max_rsh(dst_reg, &src_reg);
9177                 break;
9178         case BPF_ARSH:
9179                 if (umax_val >= insn_bitness) {
9180                         /* Shifts greater than 31 or 63 are undefined.
9181                          * This includes shifts by a negative number.
9182                          */
9183                         mark_reg_unknown(env, regs, insn->dst_reg);
9184                         break;
9185                 }
9186                 if (alu32)
9187                         scalar32_min_max_arsh(dst_reg, &src_reg);
9188                 else
9189                         scalar_min_max_arsh(dst_reg, &src_reg);
9190                 break;
9191         default:
9192                 mark_reg_unknown(env, regs, insn->dst_reg);
9193                 break;
9194         }
9195
9196         /* ALU32 ops are zero extended into 64bit register */
9197         if (alu32)
9198                 zext_32_to_64(dst_reg);
9199         reg_bounds_sync(dst_reg);
9200         return 0;
9201 }
9202
9203 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9204  * and var_off.
9205  */
9206 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9207                                    struct bpf_insn *insn)
9208 {
9209         struct bpf_verifier_state *vstate = env->cur_state;
9210         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9211         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9212         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9213         u8 opcode = BPF_OP(insn->code);
9214         int err;
9215
9216         dst_reg = &regs[insn->dst_reg];
9217         src_reg = NULL;
9218         if (dst_reg->type != SCALAR_VALUE)
9219                 ptr_reg = dst_reg;
9220         else
9221                 /* Make sure ID is cleared otherwise dst_reg min/max could be
9222                  * incorrectly propagated into other registers by find_equal_scalars()
9223                  */
9224                 dst_reg->id = 0;
9225         if (BPF_SRC(insn->code) == BPF_X) {
9226                 src_reg = &regs[insn->src_reg];
9227                 if (src_reg->type != SCALAR_VALUE) {
9228                         if (dst_reg->type != SCALAR_VALUE) {
9229                                 /* Combining two pointers by any ALU op yields
9230                                  * an arbitrary scalar. Disallow all math except
9231                                  * pointer subtraction
9232                                  */
9233                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9234                                         mark_reg_unknown(env, regs, insn->dst_reg);
9235                                         return 0;
9236                                 }
9237                                 verbose(env, "R%d pointer %s pointer prohibited\n",
9238                                         insn->dst_reg,
9239                                         bpf_alu_string[opcode >> 4]);
9240                                 return -EACCES;
9241                         } else {
9242                                 /* scalar += pointer
9243                                  * This is legal, but we have to reverse our
9244                                  * src/dest handling in computing the range
9245                                  */
9246                                 err = mark_chain_precision(env, insn->dst_reg);
9247                                 if (err)
9248                                         return err;
9249                                 return adjust_ptr_min_max_vals(env, insn,
9250                                                                src_reg, dst_reg);
9251                         }
9252                 } else if (ptr_reg) {
9253                         /* pointer += scalar */
9254                         err = mark_chain_precision(env, insn->src_reg);
9255                         if (err)
9256                                 return err;
9257                         return adjust_ptr_min_max_vals(env, insn,
9258                                                        dst_reg, src_reg);
9259                 } else if (dst_reg->precise) {
9260                         /* if dst_reg is precise, src_reg should be precise as well */
9261                         err = mark_chain_precision(env, insn->src_reg);
9262                         if (err)
9263                                 return err;
9264                 }
9265         } else {
9266                 /* Pretend the src is a reg with a known value, since we only
9267                  * need to be able to read from this state.
9268                  */
9269                 off_reg.type = SCALAR_VALUE;
9270                 __mark_reg_known(&off_reg, insn->imm);
9271                 src_reg = &off_reg;
9272                 if (ptr_reg) /* pointer += K */
9273                         return adjust_ptr_min_max_vals(env, insn,
9274                                                        ptr_reg, src_reg);
9275         }
9276
9277         /* Got here implies adding two SCALAR_VALUEs */
9278         if (WARN_ON_ONCE(ptr_reg)) {
9279                 print_verifier_state(env, state, true);
9280                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9281                 return -EINVAL;
9282         }
9283         if (WARN_ON(!src_reg)) {
9284                 print_verifier_state(env, state, true);
9285                 verbose(env, "verifier internal error: no src_reg\n");
9286                 return -EINVAL;
9287         }
9288         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9289 }
9290
9291 /* check validity of 32-bit and 64-bit arithmetic operations */
9292 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9293 {
9294         struct bpf_reg_state *regs = cur_regs(env);
9295         u8 opcode = BPF_OP(insn->code);
9296         int err;
9297
9298         if (opcode == BPF_END || opcode == BPF_NEG) {
9299                 if (opcode == BPF_NEG) {
9300                         if (BPF_SRC(insn->code) != BPF_K ||
9301                             insn->src_reg != BPF_REG_0 ||
9302                             insn->off != 0 || insn->imm != 0) {
9303                                 verbose(env, "BPF_NEG uses reserved fields\n");
9304                                 return -EINVAL;
9305                         }
9306                 } else {
9307                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9308                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9309                             BPF_CLASS(insn->code) == BPF_ALU64) {
9310                                 verbose(env, "BPF_END uses reserved fields\n");
9311                                 return -EINVAL;
9312                         }
9313                 }
9314
9315                 /* check src operand */
9316                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9317                 if (err)
9318                         return err;
9319
9320                 if (is_pointer_value(env, insn->dst_reg)) {
9321                         verbose(env, "R%d pointer arithmetic prohibited\n",
9322                                 insn->dst_reg);
9323                         return -EACCES;
9324                 }
9325
9326                 /* check dest operand */
9327                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9328                 if (err)
9329                         return err;
9330
9331         } else if (opcode == BPF_MOV) {
9332
9333                 if (BPF_SRC(insn->code) == BPF_X) {
9334                         if (insn->imm != 0 || insn->off != 0) {
9335                                 verbose(env, "BPF_MOV uses reserved fields\n");
9336                                 return -EINVAL;
9337                         }
9338
9339                         /* check src operand */
9340                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9341                         if (err)
9342                                 return err;
9343                 } else {
9344                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9345                                 verbose(env, "BPF_MOV uses reserved fields\n");
9346                                 return -EINVAL;
9347                         }
9348                 }
9349
9350                 /* check dest operand, mark as required later */
9351                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9352                 if (err)
9353                         return err;
9354
9355                 if (BPF_SRC(insn->code) == BPF_X) {
9356                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
9357                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9358
9359                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9360                                 /* case: R1 = R2
9361                                  * copy register state to dest reg
9362                                  */
9363                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9364                                         /* Assign src and dst registers the same ID
9365                                          * that will be used by find_equal_scalars()
9366                                          * to propagate min/max range.
9367                                          */
9368                                         src_reg->id = ++env->id_gen;
9369                                 copy_register_state(dst_reg, src_reg);
9370                                 dst_reg->live |= REG_LIVE_WRITTEN;
9371                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
9372                         } else {
9373                                 /* R1 = (u32) R2 */
9374                                 if (is_pointer_value(env, insn->src_reg)) {
9375                                         verbose(env,
9376                                                 "R%d partial copy of pointer\n",
9377                                                 insn->src_reg);
9378                                         return -EACCES;
9379                                 } else if (src_reg->type == SCALAR_VALUE) {
9380                                         copy_register_state(dst_reg, src_reg);
9381                                         /* Make sure ID is cleared otherwise
9382                                          * dst_reg min/max could be incorrectly
9383                                          * propagated into src_reg by find_equal_scalars()
9384                                          */
9385                                         dst_reg->id = 0;
9386                                         dst_reg->live |= REG_LIVE_WRITTEN;
9387                                         dst_reg->subreg_def = env->insn_idx + 1;
9388                                 } else {
9389                                         mark_reg_unknown(env, regs,
9390                                                          insn->dst_reg);
9391                                 }
9392                                 zext_32_to_64(dst_reg);
9393                                 reg_bounds_sync(dst_reg);
9394                         }
9395                 } else {
9396                         /* case: R = imm
9397                          * remember the value we stored into this reg
9398                          */
9399                         /* clear any state __mark_reg_known doesn't set */
9400                         mark_reg_unknown(env, regs, insn->dst_reg);
9401                         regs[insn->dst_reg].type = SCALAR_VALUE;
9402                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9403                                 __mark_reg_known(regs + insn->dst_reg,
9404                                                  insn->imm);
9405                         } else {
9406                                 __mark_reg_known(regs + insn->dst_reg,
9407                                                  (u32)insn->imm);
9408                         }
9409                 }
9410
9411         } else if (opcode > BPF_END) {
9412                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9413                 return -EINVAL;
9414
9415         } else {        /* all other ALU ops: and, sub, xor, add, ... */
9416
9417                 if (BPF_SRC(insn->code) == BPF_X) {
9418                         if (insn->imm != 0 || insn->off != 0) {
9419                                 verbose(env, "BPF_ALU uses reserved fields\n");
9420                                 return -EINVAL;
9421                         }
9422                         /* check src1 operand */
9423                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9424                         if (err)
9425                                 return err;
9426                 } else {
9427                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9428                                 verbose(env, "BPF_ALU uses reserved fields\n");
9429                                 return -EINVAL;
9430                         }
9431                 }
9432
9433                 /* check src2 operand */
9434                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9435                 if (err)
9436                         return err;
9437
9438                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9439                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9440                         verbose(env, "div by zero\n");
9441                         return -EINVAL;
9442                 }
9443
9444                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9445                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9446                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9447
9448                         if (insn->imm < 0 || insn->imm >= size) {
9449                                 verbose(env, "invalid shift %d\n", insn->imm);
9450                                 return -EINVAL;
9451                         }
9452                 }
9453
9454                 /* check dest operand */
9455                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9456                 if (err)
9457                         return err;
9458
9459                 return adjust_reg_min_max_vals(env, insn);
9460         }
9461
9462         return 0;
9463 }
9464
9465 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9466                                    struct bpf_reg_state *dst_reg,
9467                                    enum bpf_reg_type type,
9468                                    bool range_right_open)
9469 {
9470         struct bpf_func_state *state;
9471         struct bpf_reg_state *reg;
9472         int new_range;
9473
9474         if (dst_reg->off < 0 ||
9475             (dst_reg->off == 0 && range_right_open))
9476                 /* This doesn't give us any range */
9477                 return;
9478
9479         if (dst_reg->umax_value > MAX_PACKET_OFF ||
9480             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9481                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
9482                  * than pkt_end, but that's because it's also less than pkt.
9483                  */
9484                 return;
9485
9486         new_range = dst_reg->off;
9487         if (range_right_open)
9488                 new_range++;
9489
9490         /* Examples for register markings:
9491          *
9492          * pkt_data in dst register:
9493          *
9494          *   r2 = r3;
9495          *   r2 += 8;
9496          *   if (r2 > pkt_end) goto <handle exception>
9497          *   <access okay>
9498          *
9499          *   r2 = r3;
9500          *   r2 += 8;
9501          *   if (r2 < pkt_end) goto <access okay>
9502          *   <handle exception>
9503          *
9504          *   Where:
9505          *     r2 == dst_reg, pkt_end == src_reg
9506          *     r2=pkt(id=n,off=8,r=0)
9507          *     r3=pkt(id=n,off=0,r=0)
9508          *
9509          * pkt_data in src register:
9510          *
9511          *   r2 = r3;
9512          *   r2 += 8;
9513          *   if (pkt_end >= r2) goto <access okay>
9514          *   <handle exception>
9515          *
9516          *   r2 = r3;
9517          *   r2 += 8;
9518          *   if (pkt_end <= r2) goto <handle exception>
9519          *   <access okay>
9520          *
9521          *   Where:
9522          *     pkt_end == dst_reg, r2 == src_reg
9523          *     r2=pkt(id=n,off=8,r=0)
9524          *     r3=pkt(id=n,off=0,r=0)
9525          *
9526          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9527          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9528          * and [r3, r3 + 8-1) respectively is safe to access depending on
9529          * the check.
9530          */
9531
9532         /* If our ids match, then we must have the same max_value.  And we
9533          * don't care about the other reg's fixed offset, since if it's too big
9534          * the range won't allow anything.
9535          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9536          */
9537         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9538                 if (reg->type == type && reg->id == dst_reg->id)
9539                         /* keep the maximum range already checked */
9540                         reg->range = max(reg->range, new_range);
9541         }));
9542 }
9543
9544 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9545 {
9546         struct tnum subreg = tnum_subreg(reg->var_off);
9547         s32 sval = (s32)val;
9548
9549         switch (opcode) {
9550         case BPF_JEQ:
9551                 if (tnum_is_const(subreg))
9552                         return !!tnum_equals_const(subreg, val);
9553                 break;
9554         case BPF_JNE:
9555                 if (tnum_is_const(subreg))
9556                         return !tnum_equals_const(subreg, val);
9557                 break;
9558         case BPF_JSET:
9559                 if ((~subreg.mask & subreg.value) & val)
9560                         return 1;
9561                 if (!((subreg.mask | subreg.value) & val))
9562                         return 0;
9563                 break;
9564         case BPF_JGT:
9565                 if (reg->u32_min_value > val)
9566                         return 1;
9567                 else if (reg->u32_max_value <= val)
9568                         return 0;
9569                 break;
9570         case BPF_JSGT:
9571                 if (reg->s32_min_value > sval)
9572                         return 1;
9573                 else if (reg->s32_max_value <= sval)
9574                         return 0;
9575                 break;
9576         case BPF_JLT:
9577                 if (reg->u32_max_value < val)
9578                         return 1;
9579                 else if (reg->u32_min_value >= val)
9580                         return 0;
9581                 break;
9582         case BPF_JSLT:
9583                 if (reg->s32_max_value < sval)
9584                         return 1;
9585                 else if (reg->s32_min_value >= sval)
9586                         return 0;
9587                 break;
9588         case BPF_JGE:
9589                 if (reg->u32_min_value >= val)
9590                         return 1;
9591                 else if (reg->u32_max_value < val)
9592                         return 0;
9593                 break;
9594         case BPF_JSGE:
9595                 if (reg->s32_min_value >= sval)
9596                         return 1;
9597                 else if (reg->s32_max_value < sval)
9598                         return 0;
9599                 break;
9600         case BPF_JLE:
9601                 if (reg->u32_max_value <= val)
9602                         return 1;
9603                 else if (reg->u32_min_value > val)
9604                         return 0;
9605                 break;
9606         case BPF_JSLE:
9607                 if (reg->s32_max_value <= sval)
9608                         return 1;
9609                 else if (reg->s32_min_value > sval)
9610                         return 0;
9611                 break;
9612         }
9613
9614         return -1;
9615 }
9616
9617
9618 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9619 {
9620         s64 sval = (s64)val;
9621
9622         switch (opcode) {
9623         case BPF_JEQ:
9624                 if (tnum_is_const(reg->var_off))
9625                         return !!tnum_equals_const(reg->var_off, val);
9626                 break;
9627         case BPF_JNE:
9628                 if (tnum_is_const(reg->var_off))
9629                         return !tnum_equals_const(reg->var_off, val);
9630                 break;
9631         case BPF_JSET:
9632                 if ((~reg->var_off.mask & reg->var_off.value) & val)
9633                         return 1;
9634                 if (!((reg->var_off.mask | reg->var_off.value) & val))
9635                         return 0;
9636                 break;
9637         case BPF_JGT:
9638                 if (reg->umin_value > val)
9639                         return 1;
9640                 else if (reg->umax_value <= val)
9641                         return 0;
9642                 break;
9643         case BPF_JSGT:
9644                 if (reg->smin_value > sval)
9645                         return 1;
9646                 else if (reg->smax_value <= sval)
9647                         return 0;
9648                 break;
9649         case BPF_JLT:
9650                 if (reg->umax_value < val)
9651                         return 1;
9652                 else if (reg->umin_value >= val)
9653                         return 0;
9654                 break;
9655         case BPF_JSLT:
9656                 if (reg->smax_value < sval)
9657                         return 1;
9658                 else if (reg->smin_value >= sval)
9659                         return 0;
9660                 break;
9661         case BPF_JGE:
9662                 if (reg->umin_value >= val)
9663                         return 1;
9664                 else if (reg->umax_value < val)
9665                         return 0;
9666                 break;
9667         case BPF_JSGE:
9668                 if (reg->smin_value >= sval)
9669                         return 1;
9670                 else if (reg->smax_value < sval)
9671                         return 0;
9672                 break;
9673         case BPF_JLE:
9674                 if (reg->umax_value <= val)
9675                         return 1;
9676                 else if (reg->umin_value > val)
9677                         return 0;
9678                 break;
9679         case BPF_JSLE:
9680                 if (reg->smax_value <= sval)
9681                         return 1;
9682                 else if (reg->smin_value > sval)
9683                         return 0;
9684                 break;
9685         }
9686
9687         return -1;
9688 }
9689
9690 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9691  * and return:
9692  *  1 - branch will be taken and "goto target" will be executed
9693  *  0 - branch will not be taken and fall-through to next insn
9694  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9695  *      range [0,10]
9696  */
9697 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9698                            bool is_jmp32)
9699 {
9700         if (__is_pointer_value(false, reg)) {
9701                 if (!reg_type_not_null(reg->type))
9702                         return -1;
9703
9704                 /* If pointer is valid tests against zero will fail so we can
9705                  * use this to direct branch taken.
9706                  */
9707                 if (val != 0)
9708                         return -1;
9709
9710                 switch (opcode) {
9711                 case BPF_JEQ:
9712                         return 0;
9713                 case BPF_JNE:
9714                         return 1;
9715                 default:
9716                         return -1;
9717                 }
9718         }
9719
9720         if (is_jmp32)
9721                 return is_branch32_taken(reg, val, opcode);
9722         return is_branch64_taken(reg, val, opcode);
9723 }
9724
9725 static int flip_opcode(u32 opcode)
9726 {
9727         /* How can we transform "a <op> b" into "b <op> a"? */
9728         static const u8 opcode_flip[16] = {
9729                 /* these stay the same */
9730                 [BPF_JEQ  >> 4] = BPF_JEQ,
9731                 [BPF_JNE  >> 4] = BPF_JNE,
9732                 [BPF_JSET >> 4] = BPF_JSET,
9733                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9734                 [BPF_JGE  >> 4] = BPF_JLE,
9735                 [BPF_JGT  >> 4] = BPF_JLT,
9736                 [BPF_JLE  >> 4] = BPF_JGE,
9737                 [BPF_JLT  >> 4] = BPF_JGT,
9738                 [BPF_JSGE >> 4] = BPF_JSLE,
9739                 [BPF_JSGT >> 4] = BPF_JSLT,
9740                 [BPF_JSLE >> 4] = BPF_JSGE,
9741                 [BPF_JSLT >> 4] = BPF_JSGT
9742         };
9743         return opcode_flip[opcode >> 4];
9744 }
9745
9746 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9747                                    struct bpf_reg_state *src_reg,
9748                                    u8 opcode)
9749 {
9750         struct bpf_reg_state *pkt;
9751
9752         if (src_reg->type == PTR_TO_PACKET_END) {
9753                 pkt = dst_reg;
9754         } else if (dst_reg->type == PTR_TO_PACKET_END) {
9755                 pkt = src_reg;
9756                 opcode = flip_opcode(opcode);
9757         } else {
9758                 return -1;
9759         }
9760
9761         if (pkt->range >= 0)
9762                 return -1;
9763
9764         switch (opcode) {
9765         case BPF_JLE:
9766                 /* pkt <= pkt_end */
9767                 fallthrough;
9768         case BPF_JGT:
9769                 /* pkt > pkt_end */
9770                 if (pkt->range == BEYOND_PKT_END)
9771                         /* pkt has at last one extra byte beyond pkt_end */
9772                         return opcode == BPF_JGT;
9773                 break;
9774         case BPF_JLT:
9775                 /* pkt < pkt_end */
9776                 fallthrough;
9777         case BPF_JGE:
9778                 /* pkt >= pkt_end */
9779                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9780                         return opcode == BPF_JGE;
9781                 break;
9782         }
9783         return -1;
9784 }
9785
9786 /* Adjusts the register min/max values in the case that the dst_reg is the
9787  * variable register that we are working on, and src_reg is a constant or we're
9788  * simply doing a BPF_K check.
9789  * In JEQ/JNE cases we also adjust the var_off values.
9790  */
9791 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9792                             struct bpf_reg_state *false_reg,
9793                             u64 val, u32 val32,
9794                             u8 opcode, bool is_jmp32)
9795 {
9796         struct tnum false_32off = tnum_subreg(false_reg->var_off);
9797         struct tnum false_64off = false_reg->var_off;
9798         struct tnum true_32off = tnum_subreg(true_reg->var_off);
9799         struct tnum true_64off = true_reg->var_off;
9800         s64 sval = (s64)val;
9801         s32 sval32 = (s32)val32;
9802
9803         /* If the dst_reg is a pointer, we can't learn anything about its
9804          * variable offset from the compare (unless src_reg were a pointer into
9805          * the same object, but we don't bother with that.
9806          * Since false_reg and true_reg have the same type by construction, we
9807          * only need to check one of them for pointerness.
9808          */
9809         if (__is_pointer_value(false, false_reg))
9810                 return;
9811
9812         switch (opcode) {
9813         /* JEQ/JNE comparison doesn't change the register equivalence.
9814          *
9815          * r1 = r2;
9816          * if (r1 == 42) goto label;
9817          * ...
9818          * label: // here both r1 and r2 are known to be 42.
9819          *
9820          * Hence when marking register as known preserve it's ID.
9821          */
9822         case BPF_JEQ:
9823                 if (is_jmp32) {
9824                         __mark_reg32_known(true_reg, val32);
9825                         true_32off = tnum_subreg(true_reg->var_off);
9826                 } else {
9827                         ___mark_reg_known(true_reg, val);
9828                         true_64off = true_reg->var_off;
9829                 }
9830                 break;
9831         case BPF_JNE:
9832                 if (is_jmp32) {
9833                         __mark_reg32_known(false_reg, val32);
9834                         false_32off = tnum_subreg(false_reg->var_off);
9835                 } else {
9836                         ___mark_reg_known(false_reg, val);
9837                         false_64off = false_reg->var_off;
9838                 }
9839                 break;
9840         case BPF_JSET:
9841                 if (is_jmp32) {
9842                         false_32off = tnum_and(false_32off, tnum_const(~val32));
9843                         if (is_power_of_2(val32))
9844                                 true_32off = tnum_or(true_32off,
9845                                                      tnum_const(val32));
9846                 } else {
9847                         false_64off = tnum_and(false_64off, tnum_const(~val));
9848                         if (is_power_of_2(val))
9849                                 true_64off = tnum_or(true_64off,
9850                                                      tnum_const(val));
9851                 }
9852                 break;
9853         case BPF_JGE:
9854         case BPF_JGT:
9855         {
9856                 if (is_jmp32) {
9857                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9858                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9859
9860                         false_reg->u32_max_value = min(false_reg->u32_max_value,
9861                                                        false_umax);
9862                         true_reg->u32_min_value = max(true_reg->u32_min_value,
9863                                                       true_umin);
9864                 } else {
9865                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9866                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9867
9868                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
9869                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
9870                 }
9871                 break;
9872         }
9873         case BPF_JSGE:
9874         case BPF_JSGT:
9875         {
9876                 if (is_jmp32) {
9877                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9878                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9879
9880                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9881                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9882                 } else {
9883                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9884                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9885
9886                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
9887                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
9888                 }
9889                 break;
9890         }
9891         case BPF_JLE:
9892         case BPF_JLT:
9893         {
9894                 if (is_jmp32) {
9895                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9896                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9897
9898                         false_reg->u32_min_value = max(false_reg->u32_min_value,
9899                                                        false_umin);
9900                         true_reg->u32_max_value = min(true_reg->u32_max_value,
9901                                                       true_umax);
9902                 } else {
9903                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9904                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9905
9906                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
9907                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
9908                 }
9909                 break;
9910         }
9911         case BPF_JSLE:
9912         case BPF_JSLT:
9913         {
9914                 if (is_jmp32) {
9915                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9916                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9917
9918                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9919                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9920                 } else {
9921                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9922                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9923
9924                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
9925                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
9926                 }
9927                 break;
9928         }
9929         default:
9930                 return;
9931         }
9932
9933         if (is_jmp32) {
9934                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9935                                              tnum_subreg(false_32off));
9936                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9937                                             tnum_subreg(true_32off));
9938                 __reg_combine_32_into_64(false_reg);
9939                 __reg_combine_32_into_64(true_reg);
9940         } else {
9941                 false_reg->var_off = false_64off;
9942                 true_reg->var_off = true_64off;
9943                 __reg_combine_64_into_32(false_reg);
9944                 __reg_combine_64_into_32(true_reg);
9945         }
9946 }
9947
9948 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9949  * the variable reg.
9950  */
9951 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9952                                 struct bpf_reg_state *false_reg,
9953                                 u64 val, u32 val32,
9954                                 u8 opcode, bool is_jmp32)
9955 {
9956         opcode = flip_opcode(opcode);
9957         /* This uses zero as "not present in table"; luckily the zero opcode,
9958          * BPF_JA, can't get here.
9959          */
9960         if (opcode)
9961                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9962 }
9963
9964 /* Regs are known to be equal, so intersect their min/max/var_off */
9965 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9966                                   struct bpf_reg_state *dst_reg)
9967 {
9968         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9969                                                         dst_reg->umin_value);
9970         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9971                                                         dst_reg->umax_value);
9972         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9973                                                         dst_reg->smin_value);
9974         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9975                                                         dst_reg->smax_value);
9976         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9977                                                              dst_reg->var_off);
9978         reg_bounds_sync(src_reg);
9979         reg_bounds_sync(dst_reg);
9980 }
9981
9982 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9983                                 struct bpf_reg_state *true_dst,
9984                                 struct bpf_reg_state *false_src,
9985                                 struct bpf_reg_state *false_dst,
9986                                 u8 opcode)
9987 {
9988         switch (opcode) {
9989         case BPF_JEQ:
9990                 __reg_combine_min_max(true_src, true_dst);
9991                 break;
9992         case BPF_JNE:
9993                 __reg_combine_min_max(false_src, false_dst);
9994                 break;
9995         }
9996 }
9997
9998 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9999                                  struct bpf_reg_state *reg, u32 id,
10000                                  bool is_null)
10001 {
10002         if (type_may_be_null(reg->type) && reg->id == id &&
10003             !WARN_ON_ONCE(!reg->id)) {
10004                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
10005                                  !tnum_equals_const(reg->var_off, 0) ||
10006                                  reg->off)) {
10007                         /* Old offset (both fixed and variable parts) should
10008                          * have been known-zero, because we don't allow pointer
10009                          * arithmetic on pointers that might be NULL. If we
10010                          * see this happening, don't convert the register.
10011                          */
10012                         return;
10013                 }
10014                 if (is_null) {
10015                         reg->type = SCALAR_VALUE;
10016                         /* We don't need id and ref_obj_id from this point
10017                          * onwards anymore, thus we should better reset it,
10018                          * so that state pruning has chances to take effect.
10019                          */
10020                         reg->id = 0;
10021                         reg->ref_obj_id = 0;
10022
10023                         return;
10024                 }
10025
10026                 mark_ptr_not_null_reg(reg);
10027
10028                 if (!reg_may_point_to_spin_lock(reg)) {
10029                         /* For not-NULL ptr, reg->ref_obj_id will be reset
10030                          * in release_reference().
10031                          *
10032                          * reg->id is still used by spin_lock ptr. Other
10033                          * than spin_lock ptr type, reg->id can be reset.
10034                          */
10035                         reg->id = 0;
10036                 }
10037         }
10038 }
10039
10040 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10041  * be folded together at some point.
10042  */
10043 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10044                                   bool is_null)
10045 {
10046         struct bpf_func_state *state = vstate->frame[vstate->curframe];
10047         struct bpf_reg_state *regs = state->regs, *reg;
10048         u32 ref_obj_id = regs[regno].ref_obj_id;
10049         u32 id = regs[regno].id;
10050
10051         if (ref_obj_id && ref_obj_id == id && is_null)
10052                 /* regs[regno] is in the " == NULL" branch.
10053                  * No one could have freed the reference state before
10054                  * doing the NULL check.
10055                  */
10056                 WARN_ON_ONCE(release_reference_state(state, id));
10057
10058         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10059                 mark_ptr_or_null_reg(state, reg, id, is_null);
10060         }));
10061 }
10062
10063 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10064                                    struct bpf_reg_state *dst_reg,
10065                                    struct bpf_reg_state *src_reg,
10066                                    struct bpf_verifier_state *this_branch,
10067                                    struct bpf_verifier_state *other_branch)
10068 {
10069         if (BPF_SRC(insn->code) != BPF_X)
10070                 return false;
10071
10072         /* Pointers are always 64-bit. */
10073         if (BPF_CLASS(insn->code) == BPF_JMP32)
10074                 return false;
10075
10076         switch (BPF_OP(insn->code)) {
10077         case BPF_JGT:
10078                 if ((dst_reg->type == PTR_TO_PACKET &&
10079                      src_reg->type == PTR_TO_PACKET_END) ||
10080                     (dst_reg->type == PTR_TO_PACKET_META &&
10081                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10082                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10083                         find_good_pkt_pointers(this_branch, dst_reg,
10084                                                dst_reg->type, false);
10085                         mark_pkt_end(other_branch, insn->dst_reg, true);
10086                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10087                             src_reg->type == PTR_TO_PACKET) ||
10088                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10089                             src_reg->type == PTR_TO_PACKET_META)) {
10090                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10091                         find_good_pkt_pointers(other_branch, src_reg,
10092                                                src_reg->type, true);
10093                         mark_pkt_end(this_branch, insn->src_reg, false);
10094                 } else {
10095                         return false;
10096                 }
10097                 break;
10098         case BPF_JLT:
10099                 if ((dst_reg->type == PTR_TO_PACKET &&
10100                      src_reg->type == PTR_TO_PACKET_END) ||
10101                     (dst_reg->type == PTR_TO_PACKET_META &&
10102                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10103                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10104                         find_good_pkt_pointers(other_branch, dst_reg,
10105                                                dst_reg->type, true);
10106                         mark_pkt_end(this_branch, insn->dst_reg, false);
10107                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10108                             src_reg->type == PTR_TO_PACKET) ||
10109                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10110                             src_reg->type == PTR_TO_PACKET_META)) {
10111                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10112                         find_good_pkt_pointers(this_branch, src_reg,
10113                                                src_reg->type, false);
10114                         mark_pkt_end(other_branch, insn->src_reg, true);
10115                 } else {
10116                         return false;
10117                 }
10118                 break;
10119         case BPF_JGE:
10120                 if ((dst_reg->type == PTR_TO_PACKET &&
10121                      src_reg->type == PTR_TO_PACKET_END) ||
10122                     (dst_reg->type == PTR_TO_PACKET_META &&
10123                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10124                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10125                         find_good_pkt_pointers(this_branch, dst_reg,
10126                                                dst_reg->type, true);
10127                         mark_pkt_end(other_branch, insn->dst_reg, false);
10128                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10129                             src_reg->type == PTR_TO_PACKET) ||
10130                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10131                             src_reg->type == PTR_TO_PACKET_META)) {
10132                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10133                         find_good_pkt_pointers(other_branch, src_reg,
10134                                                src_reg->type, false);
10135                         mark_pkt_end(this_branch, insn->src_reg, true);
10136                 } else {
10137                         return false;
10138                 }
10139                 break;
10140         case BPF_JLE:
10141                 if ((dst_reg->type == PTR_TO_PACKET &&
10142                      src_reg->type == PTR_TO_PACKET_END) ||
10143                     (dst_reg->type == PTR_TO_PACKET_META &&
10144                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10145                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10146                         find_good_pkt_pointers(other_branch, dst_reg,
10147                                                dst_reg->type, false);
10148                         mark_pkt_end(this_branch, insn->dst_reg, true);
10149                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10150                             src_reg->type == PTR_TO_PACKET) ||
10151                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10152                             src_reg->type == PTR_TO_PACKET_META)) {
10153                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10154                         find_good_pkt_pointers(this_branch, src_reg,
10155                                                src_reg->type, true);
10156                         mark_pkt_end(other_branch, insn->src_reg, false);
10157                 } else {
10158                         return false;
10159                 }
10160                 break;
10161         default:
10162                 return false;
10163         }
10164
10165         return true;
10166 }
10167
10168 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10169                                struct bpf_reg_state *known_reg)
10170 {
10171         struct bpf_func_state *state;
10172         struct bpf_reg_state *reg;
10173
10174         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10175                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10176                         copy_register_state(reg, known_reg);
10177         }));
10178 }
10179
10180 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10181                              struct bpf_insn *insn, int *insn_idx)
10182 {
10183         struct bpf_verifier_state *this_branch = env->cur_state;
10184         struct bpf_verifier_state *other_branch;
10185         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10186         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10187         u8 opcode = BPF_OP(insn->code);
10188         bool is_jmp32;
10189         int pred = -1;
10190         int err;
10191
10192         /* Only conditional jumps are expected to reach here. */
10193         if (opcode == BPF_JA || opcode > BPF_JSLE) {
10194                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10195                 return -EINVAL;
10196         }
10197
10198         if (BPF_SRC(insn->code) == BPF_X) {
10199                 if (insn->imm != 0) {
10200                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10201                         return -EINVAL;
10202                 }
10203
10204                 /* check src1 operand */
10205                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10206                 if (err)
10207                         return err;
10208
10209                 if (is_pointer_value(env, insn->src_reg)) {
10210                         verbose(env, "R%d pointer comparison prohibited\n",
10211                                 insn->src_reg);
10212                         return -EACCES;
10213                 }
10214                 src_reg = &regs[insn->src_reg];
10215         } else {
10216                 if (insn->src_reg != BPF_REG_0) {
10217                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10218                         return -EINVAL;
10219                 }
10220         }
10221
10222         /* check src2 operand */
10223         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10224         if (err)
10225                 return err;
10226
10227         dst_reg = &regs[insn->dst_reg];
10228         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10229
10230         if (BPF_SRC(insn->code) == BPF_K) {
10231                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10232         } else if (src_reg->type == SCALAR_VALUE &&
10233                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10234                 pred = is_branch_taken(dst_reg,
10235                                        tnum_subreg(src_reg->var_off).value,
10236                                        opcode,
10237                                        is_jmp32);
10238         } else if (src_reg->type == SCALAR_VALUE &&
10239                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10240                 pred = is_branch_taken(dst_reg,
10241                                        src_reg->var_off.value,
10242                                        opcode,
10243                                        is_jmp32);
10244         } else if (reg_is_pkt_pointer_any(dst_reg) &&
10245                    reg_is_pkt_pointer_any(src_reg) &&
10246                    !is_jmp32) {
10247                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10248         }
10249
10250         if (pred >= 0) {
10251                 /* If we get here with a dst_reg pointer type it is because
10252                  * above is_branch_taken() special cased the 0 comparison.
10253                  */
10254                 if (!__is_pointer_value(false, dst_reg))
10255                         err = mark_chain_precision(env, insn->dst_reg);
10256                 if (BPF_SRC(insn->code) == BPF_X && !err &&
10257                     !__is_pointer_value(false, src_reg))
10258                         err = mark_chain_precision(env, insn->src_reg);
10259                 if (err)
10260                         return err;
10261         }
10262
10263         if (pred == 1) {
10264                 /* Only follow the goto, ignore fall-through. If needed, push
10265                  * the fall-through branch for simulation under speculative
10266                  * execution.
10267                  */
10268                 if (!env->bypass_spec_v1 &&
10269                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
10270                                                *insn_idx))
10271                         return -EFAULT;
10272                 *insn_idx += insn->off;
10273                 return 0;
10274         } else if (pred == 0) {
10275                 /* Only follow the fall-through branch, since that's where the
10276                  * program will go. If needed, push the goto branch for
10277                  * simulation under speculative execution.
10278                  */
10279                 if (!env->bypass_spec_v1 &&
10280                     !sanitize_speculative_path(env, insn,
10281                                                *insn_idx + insn->off + 1,
10282                                                *insn_idx))
10283                         return -EFAULT;
10284                 return 0;
10285         }
10286
10287         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10288                                   false);
10289         if (!other_branch)
10290                 return -EFAULT;
10291         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10292
10293         /* detect if we are comparing against a constant value so we can adjust
10294          * our min/max values for our dst register.
10295          * this is only legit if both are scalars (or pointers to the same
10296          * object, I suppose, but we don't support that right now), because
10297          * otherwise the different base pointers mean the offsets aren't
10298          * comparable.
10299          */
10300         if (BPF_SRC(insn->code) == BPF_X) {
10301                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10302
10303                 if (dst_reg->type == SCALAR_VALUE &&
10304                     src_reg->type == SCALAR_VALUE) {
10305                         if (tnum_is_const(src_reg->var_off) ||
10306                             (is_jmp32 &&
10307                              tnum_is_const(tnum_subreg(src_reg->var_off))))
10308                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10309                                                 dst_reg,
10310                                                 src_reg->var_off.value,
10311                                                 tnum_subreg(src_reg->var_off).value,
10312                                                 opcode, is_jmp32);
10313                         else if (tnum_is_const(dst_reg->var_off) ||
10314                                  (is_jmp32 &&
10315                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
10316                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10317                                                     src_reg,
10318                                                     dst_reg->var_off.value,
10319                                                     tnum_subreg(dst_reg->var_off).value,
10320                                                     opcode, is_jmp32);
10321                         else if (!is_jmp32 &&
10322                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
10323                                 /* Comparing for equality, we can combine knowledge */
10324                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10325                                                     &other_branch_regs[insn->dst_reg],
10326                                                     src_reg, dst_reg, opcode);
10327                         if (src_reg->id &&
10328                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10329                                 find_equal_scalars(this_branch, src_reg);
10330                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10331                         }
10332
10333                 }
10334         } else if (dst_reg->type == SCALAR_VALUE) {
10335                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10336                                         dst_reg, insn->imm, (u32)insn->imm,
10337                                         opcode, is_jmp32);
10338         }
10339
10340         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10341             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10342                 find_equal_scalars(this_branch, dst_reg);
10343                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10344         }
10345
10346         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10347          * NOTE: these optimizations below are related with pointer comparison
10348          *       which will never be JMP32.
10349          */
10350         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10351             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10352             type_may_be_null(dst_reg->type)) {
10353                 /* Mark all identical registers in each branch as either
10354                  * safe or unknown depending R == 0 or R != 0 conditional.
10355                  */
10356                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10357                                       opcode == BPF_JNE);
10358                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10359                                       opcode == BPF_JEQ);
10360         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10361                                            this_branch, other_branch) &&
10362                    is_pointer_value(env, insn->dst_reg)) {
10363                 verbose(env, "R%d pointer comparison prohibited\n",
10364                         insn->dst_reg);
10365                 return -EACCES;
10366         }
10367         if (env->log.level & BPF_LOG_LEVEL)
10368                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10369         return 0;
10370 }
10371
10372 /* verify BPF_LD_IMM64 instruction */
10373 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10374 {
10375         struct bpf_insn_aux_data *aux = cur_aux(env);
10376         struct bpf_reg_state *regs = cur_regs(env);
10377         struct bpf_reg_state *dst_reg;
10378         struct bpf_map *map;
10379         int err;
10380
10381         if (BPF_SIZE(insn->code) != BPF_DW) {
10382                 verbose(env, "invalid BPF_LD_IMM insn\n");
10383                 return -EINVAL;
10384         }
10385         if (insn->off != 0) {
10386                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10387                 return -EINVAL;
10388         }
10389
10390         err = check_reg_arg(env, insn->dst_reg, DST_OP);
10391         if (err)
10392                 return err;
10393
10394         dst_reg = &regs[insn->dst_reg];
10395         if (insn->src_reg == 0) {
10396                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10397
10398                 dst_reg->type = SCALAR_VALUE;
10399                 __mark_reg_known(&regs[insn->dst_reg], imm);
10400                 return 0;
10401         }
10402
10403         /* All special src_reg cases are listed below. From this point onwards
10404          * we either succeed and assign a corresponding dst_reg->type after
10405          * zeroing the offset, or fail and reject the program.
10406          */
10407         mark_reg_known_zero(env, regs, insn->dst_reg);
10408
10409         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10410                 dst_reg->type = aux->btf_var.reg_type;
10411                 switch (base_type(dst_reg->type)) {
10412                 case PTR_TO_MEM:
10413                         dst_reg->mem_size = aux->btf_var.mem_size;
10414                         break;
10415                 case PTR_TO_BTF_ID:
10416                         dst_reg->btf = aux->btf_var.btf;
10417                         dst_reg->btf_id = aux->btf_var.btf_id;
10418                         break;
10419                 default:
10420                         verbose(env, "bpf verifier is misconfigured\n");
10421                         return -EFAULT;
10422                 }
10423                 return 0;
10424         }
10425
10426         if (insn->src_reg == BPF_PSEUDO_FUNC) {
10427                 struct bpf_prog_aux *aux = env->prog->aux;
10428                 u32 subprogno = find_subprog(env,
10429                                              env->insn_idx + insn->imm + 1);
10430
10431                 if (!aux->func_info) {
10432                         verbose(env, "missing btf func_info\n");
10433                         return -EINVAL;
10434                 }
10435                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10436                         verbose(env, "callback function not static\n");
10437                         return -EINVAL;
10438                 }
10439
10440                 dst_reg->type = PTR_TO_FUNC;
10441                 dst_reg->subprogno = subprogno;
10442                 return 0;
10443         }
10444
10445         map = env->used_maps[aux->map_index];
10446         dst_reg->map_ptr = map;
10447
10448         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10449             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10450                 dst_reg->type = PTR_TO_MAP_VALUE;
10451                 dst_reg->off = aux->map_off;
10452                 if (map_value_has_spin_lock(map))
10453                         dst_reg->id = ++env->id_gen;
10454         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10455                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10456                 dst_reg->type = CONST_PTR_TO_MAP;
10457         } else {
10458                 verbose(env, "bpf verifier is misconfigured\n");
10459                 return -EINVAL;
10460         }
10461
10462         return 0;
10463 }
10464
10465 static bool may_access_skb(enum bpf_prog_type type)
10466 {
10467         switch (type) {
10468         case BPF_PROG_TYPE_SOCKET_FILTER:
10469         case BPF_PROG_TYPE_SCHED_CLS:
10470         case BPF_PROG_TYPE_SCHED_ACT:
10471                 return true;
10472         default:
10473                 return false;
10474         }
10475 }
10476
10477 /* verify safety of LD_ABS|LD_IND instructions:
10478  * - they can only appear in the programs where ctx == skb
10479  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10480  *   preserve R6-R9, and store return value into R0
10481  *
10482  * Implicit input:
10483  *   ctx == skb == R6 == CTX
10484  *
10485  * Explicit input:
10486  *   SRC == any register
10487  *   IMM == 32-bit immediate
10488  *
10489  * Output:
10490  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10491  */
10492 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10493 {
10494         struct bpf_reg_state *regs = cur_regs(env);
10495         static const int ctx_reg = BPF_REG_6;
10496         u8 mode = BPF_MODE(insn->code);
10497         int i, err;
10498
10499         if (!may_access_skb(resolve_prog_type(env->prog))) {
10500                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10501                 return -EINVAL;
10502         }
10503
10504         if (!env->ops->gen_ld_abs) {
10505                 verbose(env, "bpf verifier is misconfigured\n");
10506                 return -EINVAL;
10507         }
10508
10509         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10510             BPF_SIZE(insn->code) == BPF_DW ||
10511             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10512                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10513                 return -EINVAL;
10514         }
10515
10516         /* check whether implicit source operand (register R6) is readable */
10517         err = check_reg_arg(env, ctx_reg, SRC_OP);
10518         if (err)
10519                 return err;
10520
10521         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10522          * gen_ld_abs() may terminate the program at runtime, leading to
10523          * reference leak.
10524          */
10525         err = check_reference_leak(env);
10526         if (err) {
10527                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10528                 return err;
10529         }
10530
10531         if (env->cur_state->active_spin_lock) {
10532                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10533                 return -EINVAL;
10534         }
10535
10536         if (regs[ctx_reg].type != PTR_TO_CTX) {
10537                 verbose(env,
10538                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10539                 return -EINVAL;
10540         }
10541
10542         if (mode == BPF_IND) {
10543                 /* check explicit source operand */
10544                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10545                 if (err)
10546                         return err;
10547         }
10548
10549         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10550         if (err < 0)
10551                 return err;
10552
10553         /* reset caller saved regs to unreadable */
10554         for (i = 0; i < CALLER_SAVED_REGS; i++) {
10555                 mark_reg_not_init(env, regs, caller_saved[i]);
10556                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10557         }
10558
10559         /* mark destination R0 register as readable, since it contains
10560          * the value fetched from the packet.
10561          * Already marked as written above.
10562          */
10563         mark_reg_unknown(env, regs, BPF_REG_0);
10564         /* ld_abs load up to 32-bit skb data. */
10565         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10566         return 0;
10567 }
10568
10569 static int check_return_code(struct bpf_verifier_env *env)
10570 {
10571         struct tnum enforce_attach_type_range = tnum_unknown;
10572         const struct bpf_prog *prog = env->prog;
10573         struct bpf_reg_state *reg;
10574         struct tnum range = tnum_range(0, 1);
10575         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10576         int err;
10577         struct bpf_func_state *frame = env->cur_state->frame[0];
10578         const bool is_subprog = frame->subprogno;
10579
10580         /* LSM and struct_ops func-ptr's return type could be "void" */
10581         if (!is_subprog) {
10582                 switch (prog_type) {
10583                 case BPF_PROG_TYPE_LSM:
10584                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
10585                                 /* See below, can be 0 or 0-1 depending on hook. */
10586                                 break;
10587                         fallthrough;
10588                 case BPF_PROG_TYPE_STRUCT_OPS:
10589                         if (!prog->aux->attach_func_proto->type)
10590                                 return 0;
10591                         break;
10592                 default:
10593                         break;
10594                 }
10595         }
10596
10597         /* eBPF calling convention is such that R0 is used
10598          * to return the value from eBPF program.
10599          * Make sure that it's readable at this time
10600          * of bpf_exit, which means that program wrote
10601          * something into it earlier
10602          */
10603         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10604         if (err)
10605                 return err;
10606
10607         if (is_pointer_value(env, BPF_REG_0)) {
10608                 verbose(env, "R0 leaks addr as return value\n");
10609                 return -EACCES;
10610         }
10611
10612         reg = cur_regs(env) + BPF_REG_0;
10613
10614         if (frame->in_async_callback_fn) {
10615                 /* enforce return zero from async callbacks like timer */
10616                 if (reg->type != SCALAR_VALUE) {
10617                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10618                                 reg_type_str(env, reg->type));
10619                         return -EINVAL;
10620                 }
10621
10622                 if (!tnum_in(tnum_const(0), reg->var_off)) {
10623                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10624                         return -EINVAL;
10625                 }
10626                 return 0;
10627         }
10628
10629         if (is_subprog) {
10630                 if (reg->type != SCALAR_VALUE) {
10631                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10632                                 reg_type_str(env, reg->type));
10633                         return -EINVAL;
10634                 }
10635                 return 0;
10636         }
10637
10638         switch (prog_type) {
10639         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10640                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10641                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10642                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10643                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10644                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10645                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10646                         range = tnum_range(1, 1);
10647                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10648                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10649                         range = tnum_range(0, 3);
10650                 break;
10651         case BPF_PROG_TYPE_CGROUP_SKB:
10652                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10653                         range = tnum_range(0, 3);
10654                         enforce_attach_type_range = tnum_range(2, 3);
10655                 }
10656                 break;
10657         case BPF_PROG_TYPE_CGROUP_SOCK:
10658         case BPF_PROG_TYPE_SOCK_OPS:
10659         case BPF_PROG_TYPE_CGROUP_DEVICE:
10660         case BPF_PROG_TYPE_CGROUP_SYSCTL:
10661         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10662                 break;
10663         case BPF_PROG_TYPE_RAW_TRACEPOINT:
10664                 if (!env->prog->aux->attach_btf_id)
10665                         return 0;
10666                 range = tnum_const(0);
10667                 break;
10668         case BPF_PROG_TYPE_TRACING:
10669                 switch (env->prog->expected_attach_type) {
10670                 case BPF_TRACE_FENTRY:
10671                 case BPF_TRACE_FEXIT:
10672                         range = tnum_const(0);
10673                         break;
10674                 case BPF_TRACE_RAW_TP:
10675                 case BPF_MODIFY_RETURN:
10676                         return 0;
10677                 case BPF_TRACE_ITER:
10678                         break;
10679                 default:
10680                         return -ENOTSUPP;
10681                 }
10682                 break;
10683         case BPF_PROG_TYPE_SK_LOOKUP:
10684                 range = tnum_range(SK_DROP, SK_PASS);
10685                 break;
10686
10687         case BPF_PROG_TYPE_LSM:
10688                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10689                         /* Regular BPF_PROG_TYPE_LSM programs can return
10690                          * any value.
10691                          */
10692                         return 0;
10693                 }
10694                 if (!env->prog->aux->attach_func_proto->type) {
10695                         /* Make sure programs that attach to void
10696                          * hooks don't try to modify return value.
10697                          */
10698                         range = tnum_range(1, 1);
10699                 }
10700                 break;
10701
10702         case BPF_PROG_TYPE_EXT:
10703                 /* freplace program can return anything as its return value
10704                  * depends on the to-be-replaced kernel func or bpf program.
10705                  */
10706         default:
10707                 return 0;
10708         }
10709
10710         if (reg->type != SCALAR_VALUE) {
10711                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10712                         reg_type_str(env, reg->type));
10713                 return -EINVAL;
10714         }
10715
10716         if (!tnum_in(range, reg->var_off)) {
10717                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10718                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10719                     prog_type == BPF_PROG_TYPE_LSM &&
10720                     !prog->aux->attach_func_proto->type)
10721                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10722                 return -EINVAL;
10723         }
10724
10725         if (!tnum_is_unknown(enforce_attach_type_range) &&
10726             tnum_in(enforce_attach_type_range, reg->var_off))
10727                 env->prog->enforce_expected_attach_type = 1;
10728         return 0;
10729 }
10730
10731 /* non-recursive DFS pseudo code
10732  * 1  procedure DFS-iterative(G,v):
10733  * 2      label v as discovered
10734  * 3      let S be a stack
10735  * 4      S.push(v)
10736  * 5      while S is not empty
10737  * 6            t <- S.pop()
10738  * 7            if t is what we're looking for:
10739  * 8                return t
10740  * 9            for all edges e in G.adjacentEdges(t) do
10741  * 10               if edge e is already labelled
10742  * 11                   continue with the next edge
10743  * 12               w <- G.adjacentVertex(t,e)
10744  * 13               if vertex w is not discovered and not explored
10745  * 14                   label e as tree-edge
10746  * 15                   label w as discovered
10747  * 16                   S.push(w)
10748  * 17                   continue at 5
10749  * 18               else if vertex w is discovered
10750  * 19                   label e as back-edge
10751  * 20               else
10752  * 21                   // vertex w is explored
10753  * 22                   label e as forward- or cross-edge
10754  * 23           label t as explored
10755  * 24           S.pop()
10756  *
10757  * convention:
10758  * 0x10 - discovered
10759  * 0x11 - discovered and fall-through edge labelled
10760  * 0x12 - discovered and fall-through and branch edges labelled
10761  * 0x20 - explored
10762  */
10763
10764 enum {
10765         DISCOVERED = 0x10,
10766         EXPLORED = 0x20,
10767         FALLTHROUGH = 1,
10768         BRANCH = 2,
10769 };
10770
10771 static u32 state_htab_size(struct bpf_verifier_env *env)
10772 {
10773         return env->prog->len;
10774 }
10775
10776 static struct bpf_verifier_state_list **explored_state(
10777                                         struct bpf_verifier_env *env,
10778                                         int idx)
10779 {
10780         struct bpf_verifier_state *cur = env->cur_state;
10781         struct bpf_func_state *state = cur->frame[cur->curframe];
10782
10783         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10784 }
10785
10786 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10787 {
10788         env->insn_aux_data[idx].prune_point = true;
10789 }
10790
10791 enum {
10792         DONE_EXPLORING = 0,
10793         KEEP_EXPLORING = 1,
10794 };
10795
10796 /* t, w, e - match pseudo-code above:
10797  * t - index of current instruction
10798  * w - next instruction
10799  * e - edge
10800  */
10801 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10802                      bool loop_ok)
10803 {
10804         int *insn_stack = env->cfg.insn_stack;
10805         int *insn_state = env->cfg.insn_state;
10806
10807         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10808                 return DONE_EXPLORING;
10809
10810         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10811                 return DONE_EXPLORING;
10812
10813         if (w < 0 || w >= env->prog->len) {
10814                 verbose_linfo(env, t, "%d: ", t);
10815                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10816                 return -EINVAL;
10817         }
10818
10819         if (e == BRANCH)
10820                 /* mark branch target for state pruning */
10821                 init_explored_state(env, w);
10822
10823         if (insn_state[w] == 0) {
10824                 /* tree-edge */
10825                 insn_state[t] = DISCOVERED | e;
10826                 insn_state[w] = DISCOVERED;
10827                 if (env->cfg.cur_stack >= env->prog->len)
10828                         return -E2BIG;
10829                 insn_stack[env->cfg.cur_stack++] = w;
10830                 return KEEP_EXPLORING;
10831         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10832                 if (loop_ok && env->bpf_capable)
10833                         return DONE_EXPLORING;
10834                 verbose_linfo(env, t, "%d: ", t);
10835                 verbose_linfo(env, w, "%d: ", w);
10836                 verbose(env, "back-edge from insn %d to %d\n", t, w);
10837                 return -EINVAL;
10838         } else if (insn_state[w] == EXPLORED) {
10839                 /* forward- or cross-edge */
10840                 insn_state[t] = DISCOVERED | e;
10841         } else {
10842                 verbose(env, "insn state internal bug\n");
10843                 return -EFAULT;
10844         }
10845         return DONE_EXPLORING;
10846 }
10847
10848 static int visit_func_call_insn(int t, int insn_cnt,
10849                                 struct bpf_insn *insns,
10850                                 struct bpf_verifier_env *env,
10851                                 bool visit_callee)
10852 {
10853         int ret;
10854
10855         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10856         if (ret)
10857                 return ret;
10858
10859         if (t + 1 < insn_cnt)
10860                 init_explored_state(env, t + 1);
10861         if (visit_callee) {
10862                 init_explored_state(env, t);
10863                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10864                                 /* It's ok to allow recursion from CFG point of
10865                                  * view. __check_func_call() will do the actual
10866                                  * check.
10867                                  */
10868                                 bpf_pseudo_func(insns + t));
10869         }
10870         return ret;
10871 }
10872
10873 /* Visits the instruction at index t and returns one of the following:
10874  *  < 0 - an error occurred
10875  *  DONE_EXPLORING - the instruction was fully explored
10876  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10877  */
10878 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10879 {
10880         struct bpf_insn *insns = env->prog->insnsi;
10881         int ret;
10882
10883         if (bpf_pseudo_func(insns + t))
10884                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10885
10886         /* All non-branch instructions have a single fall-through edge. */
10887         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10888             BPF_CLASS(insns[t].code) != BPF_JMP32)
10889                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10890
10891         switch (BPF_OP(insns[t].code)) {
10892         case BPF_EXIT:
10893                 return DONE_EXPLORING;
10894
10895         case BPF_CALL:
10896                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10897                         /* Mark this call insn to trigger is_state_visited() check
10898                          * before call itself is processed by __check_func_call().
10899                          * Otherwise new async state will be pushed for further
10900                          * exploration.
10901                          */
10902                         init_explored_state(env, t);
10903                 return visit_func_call_insn(t, insn_cnt, insns, env,
10904                                             insns[t].src_reg == BPF_PSEUDO_CALL);
10905
10906         case BPF_JA:
10907                 if (BPF_SRC(insns[t].code) != BPF_K)
10908                         return -EINVAL;
10909
10910                 /* unconditional jump with single edge */
10911                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10912                                 true);
10913                 if (ret)
10914                         return ret;
10915
10916                 /* unconditional jmp is not a good pruning point,
10917                  * but it's marked, since backtracking needs
10918                  * to record jmp history in is_state_visited().
10919                  */
10920                 init_explored_state(env, t + insns[t].off + 1);
10921                 /* tell verifier to check for equivalent states
10922                  * after every call and jump
10923                  */
10924                 if (t + 1 < insn_cnt)
10925                         init_explored_state(env, t + 1);
10926
10927                 return ret;
10928
10929         default:
10930                 /* conditional jump with two edges */
10931                 init_explored_state(env, t);
10932                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10933                 if (ret)
10934                         return ret;
10935
10936                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10937         }
10938 }
10939
10940 /* non-recursive depth-first-search to detect loops in BPF program
10941  * loop == back-edge in directed graph
10942  */
10943 static int check_cfg(struct bpf_verifier_env *env)
10944 {
10945         int insn_cnt = env->prog->len;
10946         int *insn_stack, *insn_state;
10947         int ret = 0;
10948         int i;
10949
10950         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10951         if (!insn_state)
10952                 return -ENOMEM;
10953
10954         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10955         if (!insn_stack) {
10956                 kvfree(insn_state);
10957                 return -ENOMEM;
10958         }
10959
10960         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10961         insn_stack[0] = 0; /* 0 is the first instruction */
10962         env->cfg.cur_stack = 1;
10963
10964         while (env->cfg.cur_stack > 0) {
10965                 int t = insn_stack[env->cfg.cur_stack - 1];
10966
10967                 ret = visit_insn(t, insn_cnt, env);
10968                 switch (ret) {
10969                 case DONE_EXPLORING:
10970                         insn_state[t] = EXPLORED;
10971                         env->cfg.cur_stack--;
10972                         break;
10973                 case KEEP_EXPLORING:
10974                         break;
10975                 default:
10976                         if (ret > 0) {
10977                                 verbose(env, "visit_insn internal bug\n");
10978                                 ret = -EFAULT;
10979                         }
10980                         goto err_free;
10981                 }
10982         }
10983
10984         if (env->cfg.cur_stack < 0) {
10985                 verbose(env, "pop stack internal bug\n");
10986                 ret = -EFAULT;
10987                 goto err_free;
10988         }
10989
10990         for (i = 0; i < insn_cnt; i++) {
10991                 if (insn_state[i] != EXPLORED) {
10992                         verbose(env, "unreachable insn %d\n", i);
10993                         ret = -EINVAL;
10994                         goto err_free;
10995                 }
10996         }
10997         ret = 0; /* cfg looks good */
10998
10999 err_free:
11000         kvfree(insn_state);
11001         kvfree(insn_stack);
11002         env->cfg.insn_state = env->cfg.insn_stack = NULL;
11003         return ret;
11004 }
11005
11006 static int check_abnormal_return(struct bpf_verifier_env *env)
11007 {
11008         int i;
11009
11010         for (i = 1; i < env->subprog_cnt; i++) {
11011                 if (env->subprog_info[i].has_ld_abs) {
11012                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
11013                         return -EINVAL;
11014                 }
11015                 if (env->subprog_info[i].has_tail_call) {
11016                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
11017                         return -EINVAL;
11018                 }
11019         }
11020         return 0;
11021 }
11022
11023 /* The minimum supported BTF func info size */
11024 #define MIN_BPF_FUNCINFO_SIZE   8
11025 #define MAX_FUNCINFO_REC_SIZE   252
11026
11027 static int check_btf_func(struct bpf_verifier_env *env,
11028                           const union bpf_attr *attr,
11029                           bpfptr_t uattr)
11030 {
11031         const struct btf_type *type, *func_proto, *ret_type;
11032         u32 i, nfuncs, urec_size, min_size;
11033         u32 krec_size = sizeof(struct bpf_func_info);
11034         struct bpf_func_info *krecord;
11035         struct bpf_func_info_aux *info_aux = NULL;
11036         struct bpf_prog *prog;
11037         const struct btf *btf;
11038         bpfptr_t urecord;
11039         u32 prev_offset = 0;
11040         bool scalar_return;
11041         int ret = -ENOMEM;
11042
11043         nfuncs = attr->func_info_cnt;
11044         if (!nfuncs) {
11045                 if (check_abnormal_return(env))
11046                         return -EINVAL;
11047                 return 0;
11048         }
11049
11050         if (nfuncs != env->subprog_cnt) {
11051                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11052                 return -EINVAL;
11053         }
11054
11055         urec_size = attr->func_info_rec_size;
11056         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11057             urec_size > MAX_FUNCINFO_REC_SIZE ||
11058             urec_size % sizeof(u32)) {
11059                 verbose(env, "invalid func info rec size %u\n", urec_size);
11060                 return -EINVAL;
11061         }
11062
11063         prog = env->prog;
11064         btf = prog->aux->btf;
11065
11066         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11067         min_size = min_t(u32, krec_size, urec_size);
11068
11069         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11070         if (!krecord)
11071                 return -ENOMEM;
11072         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11073         if (!info_aux)
11074                 goto err_free;
11075
11076         for (i = 0; i < nfuncs; i++) {
11077                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11078                 if (ret) {
11079                         if (ret == -E2BIG) {
11080                                 verbose(env, "nonzero tailing record in func info");
11081                                 /* set the size kernel expects so loader can zero
11082                                  * out the rest of the record.
11083                                  */
11084                                 if (copy_to_bpfptr_offset(uattr,
11085                                                           offsetof(union bpf_attr, func_info_rec_size),
11086                                                           &min_size, sizeof(min_size)))
11087                                         ret = -EFAULT;
11088                         }
11089                         goto err_free;
11090                 }
11091
11092                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11093                         ret = -EFAULT;
11094                         goto err_free;
11095                 }
11096
11097                 /* check insn_off */
11098                 ret = -EINVAL;
11099                 if (i == 0) {
11100                         if (krecord[i].insn_off) {
11101                                 verbose(env,
11102                                         "nonzero insn_off %u for the first func info record",
11103                                         krecord[i].insn_off);
11104                                 goto err_free;
11105                         }
11106                 } else if (krecord[i].insn_off <= prev_offset) {
11107                         verbose(env,
11108                                 "same or smaller insn offset (%u) than previous func info record (%u)",
11109                                 krecord[i].insn_off, prev_offset);
11110                         goto err_free;
11111                 }
11112
11113                 if (env->subprog_info[i].start != krecord[i].insn_off) {
11114                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11115                         goto err_free;
11116                 }
11117
11118                 /* check type_id */
11119                 type = btf_type_by_id(btf, krecord[i].type_id);
11120                 if (!type || !btf_type_is_func(type)) {
11121                         verbose(env, "invalid type id %d in func info",
11122                                 krecord[i].type_id);
11123                         goto err_free;
11124                 }
11125                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11126
11127                 func_proto = btf_type_by_id(btf, type->type);
11128                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11129                         /* btf_func_check() already verified it during BTF load */
11130                         goto err_free;
11131                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11132                 scalar_return =
11133                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11134                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11135                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11136                         goto err_free;
11137                 }
11138                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11139                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11140                         goto err_free;
11141                 }
11142
11143                 prev_offset = krecord[i].insn_off;
11144                 bpfptr_add(&urecord, urec_size);
11145         }
11146
11147         prog->aux->func_info = krecord;
11148         prog->aux->func_info_cnt = nfuncs;
11149         prog->aux->func_info_aux = info_aux;
11150         return 0;
11151
11152 err_free:
11153         kvfree(krecord);
11154         kfree(info_aux);
11155         return ret;
11156 }
11157
11158 static void adjust_btf_func(struct bpf_verifier_env *env)
11159 {
11160         struct bpf_prog_aux *aux = env->prog->aux;
11161         int i;
11162
11163         if (!aux->func_info)
11164                 return;
11165
11166         for (i = 0; i < env->subprog_cnt; i++)
11167                 aux->func_info[i].insn_off = env->subprog_info[i].start;
11168 }
11169
11170 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
11171 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
11172
11173 static int check_btf_line(struct bpf_verifier_env *env,
11174                           const union bpf_attr *attr,
11175                           bpfptr_t uattr)
11176 {
11177         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11178         struct bpf_subprog_info *sub;
11179         struct bpf_line_info *linfo;
11180         struct bpf_prog *prog;
11181         const struct btf *btf;
11182         bpfptr_t ulinfo;
11183         int err;
11184
11185         nr_linfo = attr->line_info_cnt;
11186         if (!nr_linfo)
11187                 return 0;
11188         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11189                 return -EINVAL;
11190
11191         rec_size = attr->line_info_rec_size;
11192         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11193             rec_size > MAX_LINEINFO_REC_SIZE ||
11194             rec_size & (sizeof(u32) - 1))
11195                 return -EINVAL;
11196
11197         /* Need to zero it in case the userspace may
11198          * pass in a smaller bpf_line_info object.
11199          */
11200         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11201                          GFP_KERNEL | __GFP_NOWARN);
11202         if (!linfo)
11203                 return -ENOMEM;
11204
11205         prog = env->prog;
11206         btf = prog->aux->btf;
11207
11208         s = 0;
11209         sub = env->subprog_info;
11210         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11211         expected_size = sizeof(struct bpf_line_info);
11212         ncopy = min_t(u32, expected_size, rec_size);
11213         for (i = 0; i < nr_linfo; i++) {
11214                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11215                 if (err) {
11216                         if (err == -E2BIG) {
11217                                 verbose(env, "nonzero tailing record in line_info");
11218                                 if (copy_to_bpfptr_offset(uattr,
11219                                                           offsetof(union bpf_attr, line_info_rec_size),
11220                                                           &expected_size, sizeof(expected_size)))
11221                                         err = -EFAULT;
11222                         }
11223                         goto err_free;
11224                 }
11225
11226                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11227                         err = -EFAULT;
11228                         goto err_free;
11229                 }
11230
11231                 /*
11232                  * Check insn_off to ensure
11233                  * 1) strictly increasing AND
11234                  * 2) bounded by prog->len
11235                  *
11236                  * The linfo[0].insn_off == 0 check logically falls into
11237                  * the later "missing bpf_line_info for func..." case
11238                  * because the first linfo[0].insn_off must be the
11239                  * first sub also and the first sub must have
11240                  * subprog_info[0].start == 0.
11241                  */
11242                 if ((i && linfo[i].insn_off <= prev_offset) ||
11243                     linfo[i].insn_off >= prog->len) {
11244                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11245                                 i, linfo[i].insn_off, prev_offset,
11246                                 prog->len);
11247                         err = -EINVAL;
11248                         goto err_free;
11249                 }
11250
11251                 if (!prog->insnsi[linfo[i].insn_off].code) {
11252                         verbose(env,
11253                                 "Invalid insn code at line_info[%u].insn_off\n",
11254                                 i);
11255                         err = -EINVAL;
11256                         goto err_free;
11257                 }
11258
11259                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11260                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11261                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11262                         err = -EINVAL;
11263                         goto err_free;
11264                 }
11265
11266                 if (s != env->subprog_cnt) {
11267                         if (linfo[i].insn_off == sub[s].start) {
11268                                 sub[s].linfo_idx = i;
11269                                 s++;
11270                         } else if (sub[s].start < linfo[i].insn_off) {
11271                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
11272                                 err = -EINVAL;
11273                                 goto err_free;
11274                         }
11275                 }
11276
11277                 prev_offset = linfo[i].insn_off;
11278                 bpfptr_add(&ulinfo, rec_size);
11279         }
11280
11281         if (s != env->subprog_cnt) {
11282                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11283                         env->subprog_cnt - s, s);
11284                 err = -EINVAL;
11285                 goto err_free;
11286         }
11287
11288         prog->aux->linfo = linfo;
11289         prog->aux->nr_linfo = nr_linfo;
11290
11291         return 0;
11292
11293 err_free:
11294         kvfree(linfo);
11295         return err;
11296 }
11297
11298 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
11299 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
11300
11301 static int check_core_relo(struct bpf_verifier_env *env,
11302                            const union bpf_attr *attr,
11303                            bpfptr_t uattr)
11304 {
11305         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11306         struct bpf_core_relo core_relo = {};
11307         struct bpf_prog *prog = env->prog;
11308         const struct btf *btf = prog->aux->btf;
11309         struct bpf_core_ctx ctx = {
11310                 .log = &env->log,
11311                 .btf = btf,
11312         };
11313         bpfptr_t u_core_relo;
11314         int err;
11315
11316         nr_core_relo = attr->core_relo_cnt;
11317         if (!nr_core_relo)
11318                 return 0;
11319         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11320                 return -EINVAL;
11321
11322         rec_size = attr->core_relo_rec_size;
11323         if (rec_size < MIN_CORE_RELO_SIZE ||
11324             rec_size > MAX_CORE_RELO_SIZE ||
11325             rec_size % sizeof(u32))
11326                 return -EINVAL;
11327
11328         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11329         expected_size = sizeof(struct bpf_core_relo);
11330         ncopy = min_t(u32, expected_size, rec_size);
11331
11332         /* Unlike func_info and line_info, copy and apply each CO-RE
11333          * relocation record one at a time.
11334          */
11335         for (i = 0; i < nr_core_relo; i++) {
11336                 /* future proofing when sizeof(bpf_core_relo) changes */
11337                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11338                 if (err) {
11339                         if (err == -E2BIG) {
11340                                 verbose(env, "nonzero tailing record in core_relo");
11341                                 if (copy_to_bpfptr_offset(uattr,
11342                                                           offsetof(union bpf_attr, core_relo_rec_size),
11343                                                           &expected_size, sizeof(expected_size)))
11344                                         err = -EFAULT;
11345                         }
11346                         break;
11347                 }
11348
11349                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11350                         err = -EFAULT;
11351                         break;
11352                 }
11353
11354                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11355                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11356                                 i, core_relo.insn_off, prog->len);
11357                         err = -EINVAL;
11358                         break;
11359                 }
11360
11361                 err = bpf_core_apply(&ctx, &core_relo, i,
11362                                      &prog->insnsi[core_relo.insn_off / 8]);
11363                 if (err)
11364                         break;
11365                 bpfptr_add(&u_core_relo, rec_size);
11366         }
11367         return err;
11368 }
11369
11370 static int check_btf_info(struct bpf_verifier_env *env,
11371                           const union bpf_attr *attr,
11372                           bpfptr_t uattr)
11373 {
11374         struct btf *btf;
11375         int err;
11376
11377         if (!attr->func_info_cnt && !attr->line_info_cnt) {
11378                 if (check_abnormal_return(env))
11379                         return -EINVAL;
11380                 return 0;
11381         }
11382
11383         btf = btf_get_by_fd(attr->prog_btf_fd);
11384         if (IS_ERR(btf))
11385                 return PTR_ERR(btf);
11386         if (btf_is_kernel(btf)) {
11387                 btf_put(btf);
11388                 return -EACCES;
11389         }
11390         env->prog->aux->btf = btf;
11391
11392         err = check_btf_func(env, attr, uattr);
11393         if (err)
11394                 return err;
11395
11396         err = check_btf_line(env, attr, uattr);
11397         if (err)
11398                 return err;
11399
11400         err = check_core_relo(env, attr, uattr);
11401         if (err)
11402                 return err;
11403
11404         return 0;
11405 }
11406
11407 /* check %cur's range satisfies %old's */
11408 static bool range_within(struct bpf_reg_state *old,
11409                          struct bpf_reg_state *cur)
11410 {
11411         return old->umin_value <= cur->umin_value &&
11412                old->umax_value >= cur->umax_value &&
11413                old->smin_value <= cur->smin_value &&
11414                old->smax_value >= cur->smax_value &&
11415                old->u32_min_value <= cur->u32_min_value &&
11416                old->u32_max_value >= cur->u32_max_value &&
11417                old->s32_min_value <= cur->s32_min_value &&
11418                old->s32_max_value >= cur->s32_max_value;
11419 }
11420
11421 /* If in the old state two registers had the same id, then they need to have
11422  * the same id in the new state as well.  But that id could be different from
11423  * the old state, so we need to track the mapping from old to new ids.
11424  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11425  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11426  * regs with a different old id could still have new id 9, we don't care about
11427  * that.
11428  * So we look through our idmap to see if this old id has been seen before.  If
11429  * so, we require the new id to match; otherwise, we add the id pair to the map.
11430  */
11431 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11432 {
11433         unsigned int i;
11434
11435         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11436                 if (!idmap[i].old) {
11437                         /* Reached an empty slot; haven't seen this id before */
11438                         idmap[i].old = old_id;
11439                         idmap[i].cur = cur_id;
11440                         return true;
11441                 }
11442                 if (idmap[i].old == old_id)
11443                         return idmap[i].cur == cur_id;
11444         }
11445         /* We ran out of idmap slots, which should be impossible */
11446         WARN_ON_ONCE(1);
11447         return false;
11448 }
11449
11450 static void clean_func_state(struct bpf_verifier_env *env,
11451                              struct bpf_func_state *st)
11452 {
11453         enum bpf_reg_liveness live;
11454         int i, j;
11455
11456         for (i = 0; i < BPF_REG_FP; i++) {
11457                 live = st->regs[i].live;
11458                 /* liveness must not touch this register anymore */
11459                 st->regs[i].live |= REG_LIVE_DONE;
11460                 if (!(live & REG_LIVE_READ))
11461                         /* since the register is unused, clear its state
11462                          * to make further comparison simpler
11463                          */
11464                         __mark_reg_not_init(env, &st->regs[i]);
11465         }
11466
11467         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11468                 live = st->stack[i].spilled_ptr.live;
11469                 /* liveness must not touch this stack slot anymore */
11470                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11471                 if (!(live & REG_LIVE_READ)) {
11472                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11473                         for (j = 0; j < BPF_REG_SIZE; j++)
11474                                 st->stack[i].slot_type[j] = STACK_INVALID;
11475                 }
11476         }
11477 }
11478
11479 static void clean_verifier_state(struct bpf_verifier_env *env,
11480                                  struct bpf_verifier_state *st)
11481 {
11482         int i;
11483
11484         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11485                 /* all regs in this state in all frames were already marked */
11486                 return;
11487
11488         for (i = 0; i <= st->curframe; i++)
11489                 clean_func_state(env, st->frame[i]);
11490 }
11491
11492 /* the parentage chains form a tree.
11493  * the verifier states are added to state lists at given insn and
11494  * pushed into state stack for future exploration.
11495  * when the verifier reaches bpf_exit insn some of the verifer states
11496  * stored in the state lists have their final liveness state already,
11497  * but a lot of states will get revised from liveness point of view when
11498  * the verifier explores other branches.
11499  * Example:
11500  * 1: r0 = 1
11501  * 2: if r1 == 100 goto pc+1
11502  * 3: r0 = 2
11503  * 4: exit
11504  * when the verifier reaches exit insn the register r0 in the state list of
11505  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11506  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11507  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11508  *
11509  * Since the verifier pushes the branch states as it sees them while exploring
11510  * the program the condition of walking the branch instruction for the second
11511  * time means that all states below this branch were already explored and
11512  * their final liveness marks are already propagated.
11513  * Hence when the verifier completes the search of state list in is_state_visited()
11514  * we can call this clean_live_states() function to mark all liveness states
11515  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11516  * will not be used.
11517  * This function also clears the registers and stack for states that !READ
11518  * to simplify state merging.
11519  *
11520  * Important note here that walking the same branch instruction in the callee
11521  * doesn't meant that the states are DONE. The verifier has to compare
11522  * the callsites
11523  */
11524 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11525                               struct bpf_verifier_state *cur)
11526 {
11527         struct bpf_verifier_state_list *sl;
11528         int i;
11529
11530         sl = *explored_state(env, insn);
11531         while (sl) {
11532                 if (sl->state.branches)
11533                         goto next;
11534                 if (sl->state.insn_idx != insn ||
11535                     sl->state.curframe != cur->curframe)
11536                         goto next;
11537                 for (i = 0; i <= cur->curframe; i++)
11538                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11539                                 goto next;
11540                 clean_verifier_state(env, &sl->state);
11541 next:
11542                 sl = sl->next;
11543         }
11544 }
11545
11546 /* Returns true if (rold safe implies rcur safe) */
11547 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11548                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11549 {
11550         bool equal;
11551
11552         if (!(rold->live & REG_LIVE_READ))
11553                 /* explored state didn't use this */
11554                 return true;
11555
11556         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11557
11558         if (rold->type == PTR_TO_STACK)
11559                 /* two stack pointers are equal only if they're pointing to
11560                  * the same stack frame, since fp-8 in foo != fp-8 in bar
11561                  */
11562                 return equal && rold->frameno == rcur->frameno;
11563
11564         if (equal)
11565                 return true;
11566
11567         if (rold->type == NOT_INIT)
11568                 /* explored state can't have used this */
11569                 return true;
11570         if (rcur->type == NOT_INIT)
11571                 return false;
11572         switch (base_type(rold->type)) {
11573         case SCALAR_VALUE:
11574                 if (env->explore_alu_limits)
11575                         return false;
11576                 if (rcur->type == SCALAR_VALUE) {
11577                         if (!rold->precise && !rcur->precise)
11578                                 return true;
11579                         /* new val must satisfy old val knowledge */
11580                         return range_within(rold, rcur) &&
11581                                tnum_in(rold->var_off, rcur->var_off);
11582                 } else {
11583                         /* We're trying to use a pointer in place of a scalar.
11584                          * Even if the scalar was unbounded, this could lead to
11585                          * pointer leaks because scalars are allowed to leak
11586                          * while pointers are not. We could make this safe in
11587                          * special cases if root is calling us, but it's
11588                          * probably not worth the hassle.
11589                          */
11590                         return false;
11591                 }
11592         case PTR_TO_MAP_KEY:
11593         case PTR_TO_MAP_VALUE:
11594                 /* a PTR_TO_MAP_VALUE could be safe to use as a
11595                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11596                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11597                  * checked, doing so could have affected others with the same
11598                  * id, and we can't check for that because we lost the id when
11599                  * we converted to a PTR_TO_MAP_VALUE.
11600                  */
11601                 if (type_may_be_null(rold->type)) {
11602                         if (!type_may_be_null(rcur->type))
11603                                 return false;
11604                         if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11605                                 return false;
11606                         /* Check our ids match any regs they're supposed to */
11607                         return check_ids(rold->id, rcur->id, idmap);
11608                 }
11609
11610                 /* If the new min/max/var_off satisfy the old ones and
11611                  * everything else matches, we are OK.
11612                  * 'id' is not compared, since it's only used for maps with
11613                  * bpf_spin_lock inside map element and in such cases if
11614                  * the rest of the prog is valid for one map element then
11615                  * it's valid for all map elements regardless of the key
11616                  * used in bpf_map_lookup()
11617                  */
11618                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11619                        range_within(rold, rcur) &&
11620                        tnum_in(rold->var_off, rcur->var_off);
11621         case PTR_TO_PACKET_META:
11622         case PTR_TO_PACKET:
11623                 if (rcur->type != rold->type)
11624                         return false;
11625                 /* We must have at least as much range as the old ptr
11626                  * did, so that any accesses which were safe before are
11627                  * still safe.  This is true even if old range < old off,
11628                  * since someone could have accessed through (ptr - k), or
11629                  * even done ptr -= k in a register, to get a safe access.
11630                  */
11631                 if (rold->range > rcur->range)
11632                         return false;
11633                 /* If the offsets don't match, we can't trust our alignment;
11634                  * nor can we be sure that we won't fall out of range.
11635                  */
11636                 if (rold->off != rcur->off)
11637                         return false;
11638                 /* id relations must be preserved */
11639                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11640                         return false;
11641                 /* new val must satisfy old val knowledge */
11642                 return range_within(rold, rcur) &&
11643                        tnum_in(rold->var_off, rcur->var_off);
11644         case PTR_TO_CTX:
11645         case CONST_PTR_TO_MAP:
11646         case PTR_TO_PACKET_END:
11647         case PTR_TO_FLOW_KEYS:
11648         case PTR_TO_SOCKET:
11649         case PTR_TO_SOCK_COMMON:
11650         case PTR_TO_TCP_SOCK:
11651         case PTR_TO_XDP_SOCK:
11652                 /* Only valid matches are exact, which memcmp() above
11653                  * would have accepted
11654                  */
11655         default:
11656                 /* Don't know what's going on, just say it's not safe */
11657                 return false;
11658         }
11659
11660         /* Shouldn't get here; if we do, say it's not safe */
11661         WARN_ON_ONCE(1);
11662         return false;
11663 }
11664
11665 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11666                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11667 {
11668         int i, spi;
11669
11670         /* walk slots of the explored stack and ignore any additional
11671          * slots in the current stack, since explored(safe) state
11672          * didn't use them
11673          */
11674         for (i = 0; i < old->allocated_stack; i++) {
11675                 spi = i / BPF_REG_SIZE;
11676
11677                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11678                         i += BPF_REG_SIZE - 1;
11679                         /* explored state didn't use this */
11680                         continue;
11681                 }
11682
11683                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11684                         continue;
11685
11686                 /* explored stack has more populated slots than current stack
11687                  * and these slots were used
11688                  */
11689                 if (i >= cur->allocated_stack)
11690                         return false;
11691
11692                 /* if old state was safe with misc data in the stack
11693                  * it will be safe with zero-initialized stack.
11694                  * The opposite is not true
11695                  */
11696                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11697                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11698                         continue;
11699                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11700                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11701                         /* Ex: old explored (safe) state has STACK_SPILL in
11702                          * this stack slot, but current has STACK_MISC ->
11703                          * this verifier states are not equivalent,
11704                          * return false to continue verification of this path
11705                          */
11706                         return false;
11707                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11708                         continue;
11709                 if (!is_spilled_reg(&old->stack[spi]))
11710                         continue;
11711                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11712                              &cur->stack[spi].spilled_ptr, idmap))
11713                         /* when explored and current stack slot are both storing
11714                          * spilled registers, check that stored pointers types
11715                          * are the same as well.
11716                          * Ex: explored safe path could have stored
11717                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11718                          * but current path has stored:
11719                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11720                          * such verifier states are not equivalent.
11721                          * return false to continue verification of this path
11722                          */
11723                         return false;
11724         }
11725         return true;
11726 }
11727
11728 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11729 {
11730         if (old->acquired_refs != cur->acquired_refs)
11731                 return false;
11732         return !memcmp(old->refs, cur->refs,
11733                        sizeof(*old->refs) * old->acquired_refs);
11734 }
11735
11736 /* compare two verifier states
11737  *
11738  * all states stored in state_list are known to be valid, since
11739  * verifier reached 'bpf_exit' instruction through them
11740  *
11741  * this function is called when verifier exploring different branches of
11742  * execution popped from the state stack. If it sees an old state that has
11743  * more strict register state and more strict stack state then this execution
11744  * branch doesn't need to be explored further, since verifier already
11745  * concluded that more strict state leads to valid finish.
11746  *
11747  * Therefore two states are equivalent if register state is more conservative
11748  * and explored stack state is more conservative than the current one.
11749  * Example:
11750  *       explored                   current
11751  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11752  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11753  *
11754  * In other words if current stack state (one being explored) has more
11755  * valid slots than old one that already passed validation, it means
11756  * the verifier can stop exploring and conclude that current state is valid too
11757  *
11758  * Similarly with registers. If explored state has register type as invalid
11759  * whereas register type in current state is meaningful, it means that
11760  * the current state will reach 'bpf_exit' instruction safely
11761  */
11762 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11763                               struct bpf_func_state *cur)
11764 {
11765         int i;
11766
11767         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11768         for (i = 0; i < MAX_BPF_REG; i++)
11769                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11770                              env->idmap_scratch))
11771                         return false;
11772
11773         if (!stacksafe(env, old, cur, env->idmap_scratch))
11774                 return false;
11775
11776         if (!refsafe(old, cur))
11777                 return false;
11778
11779         return true;
11780 }
11781
11782 static bool states_equal(struct bpf_verifier_env *env,
11783                          struct bpf_verifier_state *old,
11784                          struct bpf_verifier_state *cur)
11785 {
11786         int i;
11787
11788         if (old->curframe != cur->curframe)
11789                 return false;
11790
11791         /* Verification state from speculative execution simulation
11792          * must never prune a non-speculative execution one.
11793          */
11794         if (old->speculative && !cur->speculative)
11795                 return false;
11796
11797         if (old->active_spin_lock != cur->active_spin_lock)
11798                 return false;
11799
11800         /* for states to be equal callsites have to be the same
11801          * and all frame states need to be equivalent
11802          */
11803         for (i = 0; i <= old->curframe; i++) {
11804                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11805                         return false;
11806                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11807                         return false;
11808         }
11809         return true;
11810 }
11811
11812 /* Return 0 if no propagation happened. Return negative error code if error
11813  * happened. Otherwise, return the propagated bit.
11814  */
11815 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11816                                   struct bpf_reg_state *reg,
11817                                   struct bpf_reg_state *parent_reg)
11818 {
11819         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11820         u8 flag = reg->live & REG_LIVE_READ;
11821         int err;
11822
11823         /* When comes here, read flags of PARENT_REG or REG could be any of
11824          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11825          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11826          */
11827         if (parent_flag == REG_LIVE_READ64 ||
11828             /* Or if there is no read flag from REG. */
11829             !flag ||
11830             /* Or if the read flag from REG is the same as PARENT_REG. */
11831             parent_flag == flag)
11832                 return 0;
11833
11834         err = mark_reg_read(env, reg, parent_reg, flag);
11835         if (err)
11836                 return err;
11837
11838         return flag;
11839 }
11840
11841 /* A write screens off any subsequent reads; but write marks come from the
11842  * straight-line code between a state and its parent.  When we arrive at an
11843  * equivalent state (jump target or such) we didn't arrive by the straight-line
11844  * code, so read marks in the state must propagate to the parent regardless
11845  * of the state's write marks. That's what 'parent == state->parent' comparison
11846  * in mark_reg_read() is for.
11847  */
11848 static int propagate_liveness(struct bpf_verifier_env *env,
11849                               const struct bpf_verifier_state *vstate,
11850                               struct bpf_verifier_state *vparent)
11851 {
11852         struct bpf_reg_state *state_reg, *parent_reg;
11853         struct bpf_func_state *state, *parent;
11854         int i, frame, err = 0;
11855
11856         if (vparent->curframe != vstate->curframe) {
11857                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11858                      vparent->curframe, vstate->curframe);
11859                 return -EFAULT;
11860         }
11861         /* Propagate read liveness of registers... */
11862         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11863         for (frame = 0; frame <= vstate->curframe; frame++) {
11864                 parent = vparent->frame[frame];
11865                 state = vstate->frame[frame];
11866                 parent_reg = parent->regs;
11867                 state_reg = state->regs;
11868                 /* We don't need to worry about FP liveness, it's read-only */
11869                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11870                         err = propagate_liveness_reg(env, &state_reg[i],
11871                                                      &parent_reg[i]);
11872                         if (err < 0)
11873                                 return err;
11874                         if (err == REG_LIVE_READ64)
11875                                 mark_insn_zext(env, &parent_reg[i]);
11876                 }
11877
11878                 /* Propagate stack slots. */
11879                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11880                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11881                         parent_reg = &parent->stack[i].spilled_ptr;
11882                         state_reg = &state->stack[i].spilled_ptr;
11883                         err = propagate_liveness_reg(env, state_reg,
11884                                                      parent_reg);
11885                         if (err < 0)
11886                                 return err;
11887                 }
11888         }
11889         return 0;
11890 }
11891
11892 /* find precise scalars in the previous equivalent state and
11893  * propagate them into the current state
11894  */
11895 static int propagate_precision(struct bpf_verifier_env *env,
11896                                const struct bpf_verifier_state *old)
11897 {
11898         struct bpf_reg_state *state_reg;
11899         struct bpf_func_state *state;
11900         int i, err = 0, fr;
11901
11902         for (fr = old->curframe; fr >= 0; fr--) {
11903                 state = old->frame[fr];
11904                 state_reg = state->regs;
11905                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11906                         if (state_reg->type != SCALAR_VALUE ||
11907                             !state_reg->precise ||
11908                             !(state_reg->live & REG_LIVE_READ))
11909                                 continue;
11910                         if (env->log.level & BPF_LOG_LEVEL2)
11911                                 verbose(env, "frame %d: propagating r%d\n", fr, i);
11912                         err = mark_chain_precision_frame(env, fr, i);
11913                         if (err < 0)
11914                                 return err;
11915                 }
11916
11917                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11918                         if (!is_spilled_reg(&state->stack[i]))
11919                                 continue;
11920                         state_reg = &state->stack[i].spilled_ptr;
11921                         if (state_reg->type != SCALAR_VALUE ||
11922                             !state_reg->precise ||
11923                             !(state_reg->live & REG_LIVE_READ))
11924                                 continue;
11925                         if (env->log.level & BPF_LOG_LEVEL2)
11926                                 verbose(env, "frame %d: propagating fp%d\n",
11927                                         fr, (-i - 1) * BPF_REG_SIZE);
11928                         err = mark_chain_precision_stack_frame(env, fr, i);
11929                         if (err < 0)
11930                                 return err;
11931                 }
11932         }
11933         return 0;
11934 }
11935
11936 static bool states_maybe_looping(struct bpf_verifier_state *old,
11937                                  struct bpf_verifier_state *cur)
11938 {
11939         struct bpf_func_state *fold, *fcur;
11940         int i, fr = cur->curframe;
11941
11942         if (old->curframe != fr)
11943                 return false;
11944
11945         fold = old->frame[fr];
11946         fcur = cur->frame[fr];
11947         for (i = 0; i < MAX_BPF_REG; i++)
11948                 if (memcmp(&fold->regs[i], &fcur->regs[i],
11949                            offsetof(struct bpf_reg_state, parent)))
11950                         return false;
11951         return true;
11952 }
11953
11954
11955 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11956 {
11957         struct bpf_verifier_state_list *new_sl;
11958         struct bpf_verifier_state_list *sl, **pprev;
11959         struct bpf_verifier_state *cur = env->cur_state, *new;
11960         int i, j, err, states_cnt = 0;
11961         bool add_new_state = env->test_state_freq ? true : false;
11962
11963         cur->last_insn_idx = env->prev_insn_idx;
11964         if (!env->insn_aux_data[insn_idx].prune_point)
11965                 /* this 'insn_idx' instruction wasn't marked, so we will not
11966                  * be doing state search here
11967                  */
11968                 return 0;
11969
11970         /* bpf progs typically have pruning point every 4 instructions
11971          * http://vger.kernel.org/bpfconf2019.html#session-1
11972          * Do not add new state for future pruning if the verifier hasn't seen
11973          * at least 2 jumps and at least 8 instructions.
11974          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11975          * In tests that amounts to up to 50% reduction into total verifier
11976          * memory consumption and 20% verifier time speedup.
11977          */
11978         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11979             env->insn_processed - env->prev_insn_processed >= 8)
11980                 add_new_state = true;
11981
11982         pprev = explored_state(env, insn_idx);
11983         sl = *pprev;
11984
11985         clean_live_states(env, insn_idx, cur);
11986
11987         while (sl) {
11988                 states_cnt++;
11989                 if (sl->state.insn_idx != insn_idx)
11990                         goto next;
11991
11992                 if (sl->state.branches) {
11993                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11994
11995                         if (frame->in_async_callback_fn &&
11996                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11997                                 /* Different async_entry_cnt means that the verifier is
11998                                  * processing another entry into async callback.
11999                                  * Seeing the same state is not an indication of infinite
12000                                  * loop or infinite recursion.
12001                                  * But finding the same state doesn't mean that it's safe
12002                                  * to stop processing the current state. The previous state
12003                                  * hasn't yet reached bpf_exit, since state.branches > 0.
12004                                  * Checking in_async_callback_fn alone is not enough either.
12005                                  * Since the verifier still needs to catch infinite loops
12006                                  * inside async callbacks.
12007                                  */
12008                         } else if (states_maybe_looping(&sl->state, cur) &&
12009                                    states_equal(env, &sl->state, cur)) {
12010                                 verbose_linfo(env, insn_idx, "; ");
12011                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
12012                                 return -EINVAL;
12013                         }
12014                         /* if the verifier is processing a loop, avoid adding new state
12015                          * too often, since different loop iterations have distinct
12016                          * states and may not help future pruning.
12017                          * This threshold shouldn't be too low to make sure that
12018                          * a loop with large bound will be rejected quickly.
12019                          * The most abusive loop will be:
12020                          * r1 += 1
12021                          * if r1 < 1000000 goto pc-2
12022                          * 1M insn_procssed limit / 100 == 10k peak states.
12023                          * This threshold shouldn't be too high either, since states
12024                          * at the end of the loop are likely to be useful in pruning.
12025                          */
12026                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
12027                             env->insn_processed - env->prev_insn_processed < 100)
12028                                 add_new_state = false;
12029                         goto miss;
12030                 }
12031                 if (states_equal(env, &sl->state, cur)) {
12032                         sl->hit_cnt++;
12033                         /* reached equivalent register/stack state,
12034                          * prune the search.
12035                          * Registers read by the continuation are read by us.
12036                          * If we have any write marks in env->cur_state, they
12037                          * will prevent corresponding reads in the continuation
12038                          * from reaching our parent (an explored_state).  Our
12039                          * own state will get the read marks recorded, but
12040                          * they'll be immediately forgotten as we're pruning
12041                          * this state and will pop a new one.
12042                          */
12043                         err = propagate_liveness(env, &sl->state, cur);
12044
12045                         /* if previous state reached the exit with precision and
12046                          * current state is equivalent to it (except precsion marks)
12047                          * the precision needs to be propagated back in
12048                          * the current state.
12049                          */
12050                         err = err ? : push_jmp_history(env, cur);
12051                         err = err ? : propagate_precision(env, &sl->state);
12052                         if (err)
12053                                 return err;
12054                         return 1;
12055                 }
12056 miss:
12057                 /* when new state is not going to be added do not increase miss count.
12058                  * Otherwise several loop iterations will remove the state
12059                  * recorded earlier. The goal of these heuristics is to have
12060                  * states from some iterations of the loop (some in the beginning
12061                  * and some at the end) to help pruning.
12062                  */
12063                 if (add_new_state)
12064                         sl->miss_cnt++;
12065                 /* heuristic to determine whether this state is beneficial
12066                  * to keep checking from state equivalence point of view.
12067                  * Higher numbers increase max_states_per_insn and verification time,
12068                  * but do not meaningfully decrease insn_processed.
12069                  */
12070                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12071                         /* the state is unlikely to be useful. Remove it to
12072                          * speed up verification
12073                          */
12074                         *pprev = sl->next;
12075                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12076                                 u32 br = sl->state.branches;
12077
12078                                 WARN_ONCE(br,
12079                                           "BUG live_done but branches_to_explore %d\n",
12080                                           br);
12081                                 free_verifier_state(&sl->state, false);
12082                                 kfree(sl);
12083                                 env->peak_states--;
12084                         } else {
12085                                 /* cannot free this state, since parentage chain may
12086                                  * walk it later. Add it for free_list instead to
12087                                  * be freed at the end of verification
12088                                  */
12089                                 sl->next = env->free_list;
12090                                 env->free_list = sl;
12091                         }
12092                         sl = *pprev;
12093                         continue;
12094                 }
12095 next:
12096                 pprev = &sl->next;
12097                 sl = *pprev;
12098         }
12099
12100         if (env->max_states_per_insn < states_cnt)
12101                 env->max_states_per_insn = states_cnt;
12102
12103         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12104                 return push_jmp_history(env, cur);
12105
12106         if (!add_new_state)
12107                 return push_jmp_history(env, cur);
12108
12109         /* There were no equivalent states, remember the current one.
12110          * Technically the current state is not proven to be safe yet,
12111          * but it will either reach outer most bpf_exit (which means it's safe)
12112          * or it will be rejected. When there are no loops the verifier won't be
12113          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12114          * again on the way to bpf_exit.
12115          * When looping the sl->state.branches will be > 0 and this state
12116          * will not be considered for equivalence until branches == 0.
12117          */
12118         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12119         if (!new_sl)
12120                 return -ENOMEM;
12121         env->total_states++;
12122         env->peak_states++;
12123         env->prev_jmps_processed = env->jmps_processed;
12124         env->prev_insn_processed = env->insn_processed;
12125
12126         /* add new state to the head of linked list */
12127         new = &new_sl->state;
12128         err = copy_verifier_state(new, cur);
12129         if (err) {
12130                 free_verifier_state(new, false);
12131                 kfree(new_sl);
12132                 return err;
12133         }
12134         new->insn_idx = insn_idx;
12135         WARN_ONCE(new->branches != 1,
12136                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12137
12138         cur->parent = new;
12139         cur->first_insn_idx = insn_idx;
12140         clear_jmp_history(cur);
12141         new_sl->next = *explored_state(env, insn_idx);
12142         *explored_state(env, insn_idx) = new_sl;
12143         /* connect new state to parentage chain. Current frame needs all
12144          * registers connected. Only r6 - r9 of the callers are alive (pushed
12145          * to the stack implicitly by JITs) so in callers' frames connect just
12146          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12147          * the state of the call instruction (with WRITTEN set), and r0 comes
12148          * from callee with its full parentage chain, anyway.
12149          */
12150         /* clear write marks in current state: the writes we did are not writes
12151          * our child did, so they don't screen off its reads from us.
12152          * (There are no read marks in current state, because reads always mark
12153          * their parent and current state never has children yet.  Only
12154          * explored_states can get read marks.)
12155          */
12156         for (j = 0; j <= cur->curframe; j++) {
12157                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12158                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12159                 for (i = 0; i < BPF_REG_FP; i++)
12160                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12161         }
12162
12163         /* all stack frames are accessible from callee, clear them all */
12164         for (j = 0; j <= cur->curframe; j++) {
12165                 struct bpf_func_state *frame = cur->frame[j];
12166                 struct bpf_func_state *newframe = new->frame[j];
12167
12168                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12169                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12170                         frame->stack[i].spilled_ptr.parent =
12171                                                 &newframe->stack[i].spilled_ptr;
12172                 }
12173         }
12174         return 0;
12175 }
12176
12177 /* Return true if it's OK to have the same insn return a different type. */
12178 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12179 {
12180         switch (base_type(type)) {
12181         case PTR_TO_CTX:
12182         case PTR_TO_SOCKET:
12183         case PTR_TO_SOCK_COMMON:
12184         case PTR_TO_TCP_SOCK:
12185         case PTR_TO_XDP_SOCK:
12186         case PTR_TO_BTF_ID:
12187                 return false;
12188         default:
12189                 return true;
12190         }
12191 }
12192
12193 /* If an instruction was previously used with particular pointer types, then we
12194  * need to be careful to avoid cases such as the below, where it may be ok
12195  * for one branch accessing the pointer, but not ok for the other branch:
12196  *
12197  * R1 = sock_ptr
12198  * goto X;
12199  * ...
12200  * R1 = some_other_valid_ptr;
12201  * goto X;
12202  * ...
12203  * R2 = *(u32 *)(R1 + 0);
12204  */
12205 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12206 {
12207         return src != prev && (!reg_type_mismatch_ok(src) ||
12208                                !reg_type_mismatch_ok(prev));
12209 }
12210
12211 static int do_check(struct bpf_verifier_env *env)
12212 {
12213         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12214         struct bpf_verifier_state *state = env->cur_state;
12215         struct bpf_insn *insns = env->prog->insnsi;
12216         struct bpf_reg_state *regs;
12217         int insn_cnt = env->prog->len;
12218         bool do_print_state = false;
12219         int prev_insn_idx = -1;
12220
12221         for (;;) {
12222                 struct bpf_insn *insn;
12223                 u8 class;
12224                 int err;
12225
12226                 env->prev_insn_idx = prev_insn_idx;
12227                 if (env->insn_idx >= insn_cnt) {
12228                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
12229                                 env->insn_idx, insn_cnt);
12230                         return -EFAULT;
12231                 }
12232
12233                 insn = &insns[env->insn_idx];
12234                 class = BPF_CLASS(insn->code);
12235
12236                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12237                         verbose(env,
12238                                 "BPF program is too large. Processed %d insn\n",
12239                                 env->insn_processed);
12240                         return -E2BIG;
12241                 }
12242
12243                 err = is_state_visited(env, env->insn_idx);
12244                 if (err < 0)
12245                         return err;
12246                 if (err == 1) {
12247                         /* found equivalent state, can prune the search */
12248                         if (env->log.level & BPF_LOG_LEVEL) {
12249                                 if (do_print_state)
12250                                         verbose(env, "\nfrom %d to %d%s: safe\n",
12251                                                 env->prev_insn_idx, env->insn_idx,
12252                                                 env->cur_state->speculative ?
12253                                                 " (speculative execution)" : "");
12254                                 else
12255                                         verbose(env, "%d: safe\n", env->insn_idx);
12256                         }
12257                         goto process_bpf_exit;
12258                 }
12259
12260                 if (signal_pending(current))
12261                         return -EAGAIN;
12262
12263                 if (need_resched())
12264                         cond_resched();
12265
12266                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12267                         verbose(env, "\nfrom %d to %d%s:",
12268                                 env->prev_insn_idx, env->insn_idx,
12269                                 env->cur_state->speculative ?
12270                                 " (speculative execution)" : "");
12271                         print_verifier_state(env, state->frame[state->curframe], true);
12272                         do_print_state = false;
12273                 }
12274
12275                 if (env->log.level & BPF_LOG_LEVEL) {
12276                         const struct bpf_insn_cbs cbs = {
12277                                 .cb_call        = disasm_kfunc_name,
12278                                 .cb_print       = verbose,
12279                                 .private_data   = env,
12280                         };
12281
12282                         if (verifier_state_scratched(env))
12283                                 print_insn_state(env, state->frame[state->curframe]);
12284
12285                         verbose_linfo(env, env->insn_idx, "; ");
12286                         env->prev_log_len = env->log.len_used;
12287                         verbose(env, "%d: ", env->insn_idx);
12288                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12289                         env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12290                         env->prev_log_len = env->log.len_used;
12291                 }
12292
12293                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12294                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12295                                                            env->prev_insn_idx);
12296                         if (err)
12297                                 return err;
12298                 }
12299
12300                 regs = cur_regs(env);
12301                 sanitize_mark_insn_seen(env);
12302                 prev_insn_idx = env->insn_idx;
12303
12304                 if (class == BPF_ALU || class == BPF_ALU64) {
12305                         err = check_alu_op(env, insn);
12306                         if (err)
12307                                 return err;
12308
12309                 } else if (class == BPF_LDX) {
12310                         enum bpf_reg_type *prev_src_type, src_reg_type;
12311
12312                         /* check for reserved fields is already done */
12313
12314                         /* check src operand */
12315                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12316                         if (err)
12317                                 return err;
12318
12319                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12320                         if (err)
12321                                 return err;
12322
12323                         src_reg_type = regs[insn->src_reg].type;
12324
12325                         /* check that memory (src_reg + off) is readable,
12326                          * the state of dst_reg will be updated by this func
12327                          */
12328                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
12329                                                insn->off, BPF_SIZE(insn->code),
12330                                                BPF_READ, insn->dst_reg, false);
12331                         if (err)
12332                                 return err;
12333
12334                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12335
12336                         if (*prev_src_type == NOT_INIT) {
12337                                 /* saw a valid insn
12338                                  * dst_reg = *(u32 *)(src_reg + off)
12339                                  * save type to validate intersecting paths
12340                                  */
12341                                 *prev_src_type = src_reg_type;
12342
12343                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12344                                 /* ABuser program is trying to use the same insn
12345                                  * dst_reg = *(u32*) (src_reg + off)
12346                                  * with different pointer types:
12347                                  * src_reg == ctx in one branch and
12348                                  * src_reg == stack|map in some other branch.
12349                                  * Reject it.
12350                                  */
12351                                 verbose(env, "same insn cannot be used with different pointers\n");
12352                                 return -EINVAL;
12353                         }
12354
12355                 } else if (class == BPF_STX) {
12356                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
12357
12358                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12359                                 err = check_atomic(env, env->insn_idx, insn);
12360                                 if (err)
12361                                         return err;
12362                                 env->insn_idx++;
12363                                 continue;
12364                         }
12365
12366                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12367                                 verbose(env, "BPF_STX uses reserved fields\n");
12368                                 return -EINVAL;
12369                         }
12370
12371                         /* check src1 operand */
12372                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12373                         if (err)
12374                                 return err;
12375                         /* check src2 operand */
12376                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12377                         if (err)
12378                                 return err;
12379
12380                         dst_reg_type = regs[insn->dst_reg].type;
12381
12382                         /* check that memory (dst_reg + off) is writeable */
12383                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12384                                                insn->off, BPF_SIZE(insn->code),
12385                                                BPF_WRITE, insn->src_reg, false);
12386                         if (err)
12387                                 return err;
12388
12389                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12390
12391                         if (*prev_dst_type == NOT_INIT) {
12392                                 *prev_dst_type = dst_reg_type;
12393                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12394                                 verbose(env, "same insn cannot be used with different pointers\n");
12395                                 return -EINVAL;
12396                         }
12397
12398                 } else if (class == BPF_ST) {
12399                         if (BPF_MODE(insn->code) != BPF_MEM ||
12400                             insn->src_reg != BPF_REG_0) {
12401                                 verbose(env, "BPF_ST uses reserved fields\n");
12402                                 return -EINVAL;
12403                         }
12404                         /* check src operand */
12405                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12406                         if (err)
12407                                 return err;
12408
12409                         if (is_ctx_reg(env, insn->dst_reg)) {
12410                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12411                                         insn->dst_reg,
12412                                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12413                                 return -EACCES;
12414                         }
12415
12416                         /* check that memory (dst_reg + off) is writeable */
12417                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12418                                                insn->off, BPF_SIZE(insn->code),
12419                                                BPF_WRITE, -1, false);
12420                         if (err)
12421                                 return err;
12422
12423                 } else if (class == BPF_JMP || class == BPF_JMP32) {
12424                         u8 opcode = BPF_OP(insn->code);
12425
12426                         env->jmps_processed++;
12427                         if (opcode == BPF_CALL) {
12428                                 if (BPF_SRC(insn->code) != BPF_K ||
12429                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12430                                      && insn->off != 0) ||
12431                                     (insn->src_reg != BPF_REG_0 &&
12432                                      insn->src_reg != BPF_PSEUDO_CALL &&
12433                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12434                                     insn->dst_reg != BPF_REG_0 ||
12435                                     class == BPF_JMP32) {
12436                                         verbose(env, "BPF_CALL uses reserved fields\n");
12437                                         return -EINVAL;
12438                                 }
12439
12440                                 if (env->cur_state->active_spin_lock &&
12441                                     (insn->src_reg == BPF_PSEUDO_CALL ||
12442                                      insn->imm != BPF_FUNC_spin_unlock)) {
12443                                         verbose(env, "function calls are not allowed while holding a lock\n");
12444                                         return -EINVAL;
12445                                 }
12446                                 if (insn->src_reg == BPF_PSEUDO_CALL)
12447                                         err = check_func_call(env, insn, &env->insn_idx);
12448                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12449                                         err = check_kfunc_call(env, insn, &env->insn_idx);
12450                                 else
12451                                         err = check_helper_call(env, insn, &env->insn_idx);
12452                                 if (err)
12453                                         return err;
12454                         } else if (opcode == BPF_JA) {
12455                                 if (BPF_SRC(insn->code) != BPF_K ||
12456                                     insn->imm != 0 ||
12457                                     insn->src_reg != BPF_REG_0 ||
12458                                     insn->dst_reg != BPF_REG_0 ||
12459                                     class == BPF_JMP32) {
12460                                         verbose(env, "BPF_JA uses reserved fields\n");
12461                                         return -EINVAL;
12462                                 }
12463
12464                                 env->insn_idx += insn->off + 1;
12465                                 continue;
12466
12467                         } else if (opcode == BPF_EXIT) {
12468                                 if (BPF_SRC(insn->code) != BPF_K ||
12469                                     insn->imm != 0 ||
12470                                     insn->src_reg != BPF_REG_0 ||
12471                                     insn->dst_reg != BPF_REG_0 ||
12472                                     class == BPF_JMP32) {
12473                                         verbose(env, "BPF_EXIT uses reserved fields\n");
12474                                         return -EINVAL;
12475                                 }
12476
12477                                 if (env->cur_state->active_spin_lock) {
12478                                         verbose(env, "bpf_spin_unlock is missing\n");
12479                                         return -EINVAL;
12480                                 }
12481
12482                                 /* We must do check_reference_leak here before
12483                                  * prepare_func_exit to handle the case when
12484                                  * state->curframe > 0, it may be a callback
12485                                  * function, for which reference_state must
12486                                  * match caller reference state when it exits.
12487                                  */
12488                                 err = check_reference_leak(env);
12489                                 if (err)
12490                                         return err;
12491
12492                                 if (state->curframe) {
12493                                         /* exit from nested function */
12494                                         err = prepare_func_exit(env, &env->insn_idx);
12495                                         if (err)
12496                                                 return err;
12497                                         do_print_state = true;
12498                                         continue;
12499                                 }
12500
12501                                 err = check_return_code(env);
12502                                 if (err)
12503                                         return err;
12504 process_bpf_exit:
12505                                 mark_verifier_state_scratched(env);
12506                                 update_branch_counts(env, env->cur_state);
12507                                 err = pop_stack(env, &prev_insn_idx,
12508                                                 &env->insn_idx, pop_log);
12509                                 if (err < 0) {
12510                                         if (err != -ENOENT)
12511                                                 return err;
12512                                         break;
12513                                 } else {
12514                                         do_print_state = true;
12515                                         continue;
12516                                 }
12517                         } else {
12518                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12519                                 if (err)
12520                                         return err;
12521                         }
12522                 } else if (class == BPF_LD) {
12523                         u8 mode = BPF_MODE(insn->code);
12524
12525                         if (mode == BPF_ABS || mode == BPF_IND) {
12526                                 err = check_ld_abs(env, insn);
12527                                 if (err)
12528                                         return err;
12529
12530                         } else if (mode == BPF_IMM) {
12531                                 err = check_ld_imm(env, insn);
12532                                 if (err)
12533                                         return err;
12534
12535                                 env->insn_idx++;
12536                                 sanitize_mark_insn_seen(env);
12537                         } else {
12538                                 verbose(env, "invalid BPF_LD mode\n");
12539                                 return -EINVAL;
12540                         }
12541                 } else {
12542                         verbose(env, "unknown insn class %d\n", class);
12543                         return -EINVAL;
12544                 }
12545
12546                 env->insn_idx++;
12547         }
12548
12549         return 0;
12550 }
12551
12552 static int find_btf_percpu_datasec(struct btf *btf)
12553 {
12554         const struct btf_type *t;
12555         const char *tname;
12556         int i, n;
12557
12558         /*
12559          * Both vmlinux and module each have their own ".data..percpu"
12560          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12561          * types to look at only module's own BTF types.
12562          */
12563         n = btf_nr_types(btf);
12564         if (btf_is_module(btf))
12565                 i = btf_nr_types(btf_vmlinux);
12566         else
12567                 i = 1;
12568
12569         for(; i < n; i++) {
12570                 t = btf_type_by_id(btf, i);
12571                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12572                         continue;
12573
12574                 tname = btf_name_by_offset(btf, t->name_off);
12575                 if (!strcmp(tname, ".data..percpu"))
12576                         return i;
12577         }
12578
12579         return -ENOENT;
12580 }
12581
12582 /* replace pseudo btf_id with kernel symbol address */
12583 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12584                                struct bpf_insn *insn,
12585                                struct bpf_insn_aux_data *aux)
12586 {
12587         const struct btf_var_secinfo *vsi;
12588         const struct btf_type *datasec;
12589         struct btf_mod_pair *btf_mod;
12590         const struct btf_type *t;
12591         const char *sym_name;
12592         bool percpu = false;
12593         u32 type, id = insn->imm;
12594         struct btf *btf;
12595         s32 datasec_id;
12596         u64 addr;
12597         int i, btf_fd, err;
12598
12599         btf_fd = insn[1].imm;
12600         if (btf_fd) {
12601                 btf = btf_get_by_fd(btf_fd);
12602                 if (IS_ERR(btf)) {
12603                         verbose(env, "invalid module BTF object FD specified.\n");
12604                         return -EINVAL;
12605                 }
12606         } else {
12607                 if (!btf_vmlinux) {
12608                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12609                         return -EINVAL;
12610                 }
12611                 btf = btf_vmlinux;
12612                 btf_get(btf);
12613         }
12614
12615         t = btf_type_by_id(btf, id);
12616         if (!t) {
12617                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12618                 err = -ENOENT;
12619                 goto err_put;
12620         }
12621
12622         if (!btf_type_is_var(t)) {
12623                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12624                 err = -EINVAL;
12625                 goto err_put;
12626         }
12627
12628         sym_name = btf_name_by_offset(btf, t->name_off);
12629         addr = kallsyms_lookup_name(sym_name);
12630         if (!addr) {
12631                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12632                         sym_name);
12633                 err = -ENOENT;
12634                 goto err_put;
12635         }
12636
12637         datasec_id = find_btf_percpu_datasec(btf);
12638         if (datasec_id > 0) {
12639                 datasec = btf_type_by_id(btf, datasec_id);
12640                 for_each_vsi(i, datasec, vsi) {
12641                         if (vsi->type == id) {
12642                                 percpu = true;
12643                                 break;
12644                         }
12645                 }
12646         }
12647
12648         insn[0].imm = (u32)addr;
12649         insn[1].imm = addr >> 32;
12650
12651         type = t->type;
12652         t = btf_type_skip_modifiers(btf, type, NULL);
12653         if (percpu) {
12654                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12655                 aux->btf_var.btf = btf;
12656                 aux->btf_var.btf_id = type;
12657         } else if (!btf_type_is_struct(t)) {
12658                 const struct btf_type *ret;
12659                 const char *tname;
12660                 u32 tsize;
12661
12662                 /* resolve the type size of ksym. */
12663                 ret = btf_resolve_size(btf, t, &tsize);
12664                 if (IS_ERR(ret)) {
12665                         tname = btf_name_by_offset(btf, t->name_off);
12666                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12667                                 tname, PTR_ERR(ret));
12668                         err = -EINVAL;
12669                         goto err_put;
12670                 }
12671                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12672                 aux->btf_var.mem_size = tsize;
12673         } else {
12674                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12675                 aux->btf_var.btf = btf;
12676                 aux->btf_var.btf_id = type;
12677         }
12678
12679         /* check whether we recorded this BTF (and maybe module) already */
12680         for (i = 0; i < env->used_btf_cnt; i++) {
12681                 if (env->used_btfs[i].btf == btf) {
12682                         btf_put(btf);
12683                         return 0;
12684                 }
12685         }
12686
12687         if (env->used_btf_cnt >= MAX_USED_BTFS) {
12688                 err = -E2BIG;
12689                 goto err_put;
12690         }
12691
12692         btf_mod = &env->used_btfs[env->used_btf_cnt];
12693         btf_mod->btf = btf;
12694         btf_mod->module = NULL;
12695
12696         /* if we reference variables from kernel module, bump its refcount */
12697         if (btf_is_module(btf)) {
12698                 btf_mod->module = btf_try_get_module(btf);
12699                 if (!btf_mod->module) {
12700                         err = -ENXIO;
12701                         goto err_put;
12702                 }
12703         }
12704
12705         env->used_btf_cnt++;
12706
12707         return 0;
12708 err_put:
12709         btf_put(btf);
12710         return err;
12711 }
12712
12713 static bool is_tracing_prog_type(enum bpf_prog_type type)
12714 {
12715         switch (type) {
12716         case BPF_PROG_TYPE_KPROBE:
12717         case BPF_PROG_TYPE_TRACEPOINT:
12718         case BPF_PROG_TYPE_PERF_EVENT:
12719         case BPF_PROG_TYPE_RAW_TRACEPOINT:
12720         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12721                 return true;
12722         default:
12723                 return false;
12724         }
12725 }
12726
12727 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12728                                         struct bpf_map *map,
12729                                         struct bpf_prog *prog)
12730
12731 {
12732         enum bpf_prog_type prog_type = resolve_prog_type(prog);
12733
12734         if (map_value_has_spin_lock(map)) {
12735                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12736                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12737                         return -EINVAL;
12738                 }
12739
12740                 if (is_tracing_prog_type(prog_type)) {
12741                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12742                         return -EINVAL;
12743                 }
12744
12745                 if (prog->aux->sleepable) {
12746                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12747                         return -EINVAL;
12748                 }
12749         }
12750
12751         if (map_value_has_timer(map)) {
12752                 if (is_tracing_prog_type(prog_type)) {
12753                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
12754                         return -EINVAL;
12755                 }
12756         }
12757
12758         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12759             !bpf_offload_prog_map_match(prog, map)) {
12760                 verbose(env, "offload device mismatch between prog and map\n");
12761                 return -EINVAL;
12762         }
12763
12764         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12765                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12766                 return -EINVAL;
12767         }
12768
12769         if (prog->aux->sleepable)
12770                 switch (map->map_type) {
12771                 case BPF_MAP_TYPE_HASH:
12772                 case BPF_MAP_TYPE_LRU_HASH:
12773                 case BPF_MAP_TYPE_ARRAY:
12774                 case BPF_MAP_TYPE_PERCPU_HASH:
12775                 case BPF_MAP_TYPE_PERCPU_ARRAY:
12776                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12777                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12778                 case BPF_MAP_TYPE_HASH_OF_MAPS:
12779                 case BPF_MAP_TYPE_RINGBUF:
12780                 case BPF_MAP_TYPE_USER_RINGBUF:
12781                 case BPF_MAP_TYPE_INODE_STORAGE:
12782                 case BPF_MAP_TYPE_SK_STORAGE:
12783                 case BPF_MAP_TYPE_TASK_STORAGE:
12784                         break;
12785                 default:
12786                         verbose(env,
12787                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12788                         return -EINVAL;
12789                 }
12790
12791         return 0;
12792 }
12793
12794 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12795 {
12796         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12797                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12798 }
12799
12800 /* find and rewrite pseudo imm in ld_imm64 instructions:
12801  *
12802  * 1. if it accesses map FD, replace it with actual map pointer.
12803  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12804  *
12805  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12806  */
12807 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12808 {
12809         struct bpf_insn *insn = env->prog->insnsi;
12810         int insn_cnt = env->prog->len;
12811         int i, j, err;
12812
12813         err = bpf_prog_calc_tag(env->prog);
12814         if (err)
12815                 return err;
12816
12817         for (i = 0; i < insn_cnt; i++, insn++) {
12818                 if (BPF_CLASS(insn->code) == BPF_LDX &&
12819                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12820                         verbose(env, "BPF_LDX uses reserved fields\n");
12821                         return -EINVAL;
12822                 }
12823
12824                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12825                         struct bpf_insn_aux_data *aux;
12826                         struct bpf_map *map;
12827                         struct fd f;
12828                         u64 addr;
12829                         u32 fd;
12830
12831                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
12832                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12833                             insn[1].off != 0) {
12834                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
12835                                 return -EINVAL;
12836                         }
12837
12838                         if (insn[0].src_reg == 0)
12839                                 /* valid generic load 64-bit imm */
12840                                 goto next_insn;
12841
12842                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12843                                 aux = &env->insn_aux_data[i];
12844                                 err = check_pseudo_btf_id(env, insn, aux);
12845                                 if (err)
12846                                         return err;
12847                                 goto next_insn;
12848                         }
12849
12850                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12851                                 aux = &env->insn_aux_data[i];
12852                                 aux->ptr_type = PTR_TO_FUNC;
12853                                 goto next_insn;
12854                         }
12855
12856                         /* In final convert_pseudo_ld_imm64() step, this is
12857                          * converted into regular 64-bit imm load insn.
12858                          */
12859                         switch (insn[0].src_reg) {
12860                         case BPF_PSEUDO_MAP_VALUE:
12861                         case BPF_PSEUDO_MAP_IDX_VALUE:
12862                                 break;
12863                         case BPF_PSEUDO_MAP_FD:
12864                         case BPF_PSEUDO_MAP_IDX:
12865                                 if (insn[1].imm == 0)
12866                                         break;
12867                                 fallthrough;
12868                         default:
12869                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12870                                 return -EINVAL;
12871                         }
12872
12873                         switch (insn[0].src_reg) {
12874                         case BPF_PSEUDO_MAP_IDX_VALUE:
12875                         case BPF_PSEUDO_MAP_IDX:
12876                                 if (bpfptr_is_null(env->fd_array)) {
12877                                         verbose(env, "fd_idx without fd_array is invalid\n");
12878                                         return -EPROTO;
12879                                 }
12880                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12881                                                             insn[0].imm * sizeof(fd),
12882                                                             sizeof(fd)))
12883                                         return -EFAULT;
12884                                 break;
12885                         default:
12886                                 fd = insn[0].imm;
12887                                 break;
12888                         }
12889
12890                         f = fdget(fd);
12891                         map = __bpf_map_get(f);
12892                         if (IS_ERR(map)) {
12893                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12894                                         insn[0].imm);
12895                                 return PTR_ERR(map);
12896                         }
12897
12898                         err = check_map_prog_compatibility(env, map, env->prog);
12899                         if (err) {
12900                                 fdput(f);
12901                                 return err;
12902                         }
12903
12904                         aux = &env->insn_aux_data[i];
12905                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12906                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12907                                 addr = (unsigned long)map;
12908                         } else {
12909                                 u32 off = insn[1].imm;
12910
12911                                 if (off >= BPF_MAX_VAR_OFF) {
12912                                         verbose(env, "direct value offset of %u is not allowed\n", off);
12913                                         fdput(f);
12914                                         return -EINVAL;
12915                                 }
12916
12917                                 if (!map->ops->map_direct_value_addr) {
12918                                         verbose(env, "no direct value access support for this map type\n");
12919                                         fdput(f);
12920                                         return -EINVAL;
12921                                 }
12922
12923                                 err = map->ops->map_direct_value_addr(map, &addr, off);
12924                                 if (err) {
12925                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12926                                                 map->value_size, off);
12927                                         fdput(f);
12928                                         return err;
12929                                 }
12930
12931                                 aux->map_off = off;
12932                                 addr += off;
12933                         }
12934
12935                         insn[0].imm = (u32)addr;
12936                         insn[1].imm = addr >> 32;
12937
12938                         /* check whether we recorded this map already */
12939                         for (j = 0; j < env->used_map_cnt; j++) {
12940                                 if (env->used_maps[j] == map) {
12941                                         aux->map_index = j;
12942                                         fdput(f);
12943                                         goto next_insn;
12944                                 }
12945                         }
12946
12947                         if (env->used_map_cnt >= MAX_USED_MAPS) {
12948                                 fdput(f);
12949                                 return -E2BIG;
12950                         }
12951
12952                         /* hold the map. If the program is rejected by verifier,
12953                          * the map will be released by release_maps() or it
12954                          * will be used by the valid program until it's unloaded
12955                          * and all maps are released in free_used_maps()
12956                          */
12957                         bpf_map_inc(map);
12958
12959                         aux->map_index = env->used_map_cnt;
12960                         env->used_maps[env->used_map_cnt++] = map;
12961
12962                         if (bpf_map_is_cgroup_storage(map) &&
12963                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
12964                                 verbose(env, "only one cgroup storage of each type is allowed\n");
12965                                 fdput(f);
12966                                 return -EBUSY;
12967                         }
12968
12969                         fdput(f);
12970 next_insn:
12971                         insn++;
12972                         i++;
12973                         continue;
12974                 }
12975
12976                 /* Basic sanity check before we invest more work here. */
12977                 if (!bpf_opcode_in_insntable(insn->code)) {
12978                         verbose(env, "unknown opcode %02x\n", insn->code);
12979                         return -EINVAL;
12980                 }
12981         }
12982
12983         /* now all pseudo BPF_LD_IMM64 instructions load valid
12984          * 'struct bpf_map *' into a register instead of user map_fd.
12985          * These pointers will be used later by verifier to validate map access.
12986          */
12987         return 0;
12988 }
12989
12990 /* drop refcnt of maps used by the rejected program */
12991 static void release_maps(struct bpf_verifier_env *env)
12992 {
12993         __bpf_free_used_maps(env->prog->aux, env->used_maps,
12994                              env->used_map_cnt);
12995 }
12996
12997 /* drop refcnt of maps used by the rejected program */
12998 static void release_btfs(struct bpf_verifier_env *env)
12999 {
13000         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
13001                              env->used_btf_cnt);
13002 }
13003
13004 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
13005 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
13006 {
13007         struct bpf_insn *insn = env->prog->insnsi;
13008         int insn_cnt = env->prog->len;
13009         int i;
13010
13011         for (i = 0; i < insn_cnt; i++, insn++) {
13012                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
13013                         continue;
13014                 if (insn->src_reg == BPF_PSEUDO_FUNC)
13015                         continue;
13016                 insn->src_reg = 0;
13017         }
13018 }
13019
13020 /* single env->prog->insni[off] instruction was replaced with the range
13021  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
13022  * [0, off) and [off, end) to new locations, so the patched range stays zero
13023  */
13024 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
13025                                  struct bpf_insn_aux_data *new_data,
13026                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
13027 {
13028         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
13029         struct bpf_insn *insn = new_prog->insnsi;
13030         u32 old_seen = old_data[off].seen;
13031         u32 prog_len;
13032         int i;
13033
13034         /* aux info at OFF always needs adjustment, no matter fast path
13035          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13036          * original insn at old prog.
13037          */
13038         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13039
13040         if (cnt == 1)
13041                 return;
13042         prog_len = new_prog->len;
13043
13044         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13045         memcpy(new_data + off + cnt - 1, old_data + off,
13046                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13047         for (i = off; i < off + cnt - 1; i++) {
13048                 /* Expand insni[off]'s seen count to the patched range. */
13049                 new_data[i].seen = old_seen;
13050                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
13051         }
13052         env->insn_aux_data = new_data;
13053         vfree(old_data);
13054 }
13055
13056 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13057 {
13058         int i;
13059
13060         if (len == 1)
13061                 return;
13062         /* NOTE: fake 'exit' subprog should be updated as well. */
13063         for (i = 0; i <= env->subprog_cnt; i++) {
13064                 if (env->subprog_info[i].start <= off)
13065                         continue;
13066                 env->subprog_info[i].start += len - 1;
13067         }
13068 }
13069
13070 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13071 {
13072         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13073         int i, sz = prog->aux->size_poke_tab;
13074         struct bpf_jit_poke_descriptor *desc;
13075
13076         for (i = 0; i < sz; i++) {
13077                 desc = &tab[i];
13078                 if (desc->insn_idx <= off)
13079                         continue;
13080                 desc->insn_idx += len - 1;
13081         }
13082 }
13083
13084 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13085                                             const struct bpf_insn *patch, u32 len)
13086 {
13087         struct bpf_prog *new_prog;
13088         struct bpf_insn_aux_data *new_data = NULL;
13089
13090         if (len > 1) {
13091                 new_data = vzalloc(array_size(env->prog->len + len - 1,
13092                                               sizeof(struct bpf_insn_aux_data)));
13093                 if (!new_data)
13094                         return NULL;
13095         }
13096
13097         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13098         if (IS_ERR(new_prog)) {
13099                 if (PTR_ERR(new_prog) == -ERANGE)
13100                         verbose(env,
13101                                 "insn %d cannot be patched due to 16-bit range\n",
13102                                 env->insn_aux_data[off].orig_idx);
13103                 vfree(new_data);
13104                 return NULL;
13105         }
13106         adjust_insn_aux_data(env, new_data, new_prog, off, len);
13107         adjust_subprog_starts(env, off, len);
13108         adjust_poke_descs(new_prog, off, len);
13109         return new_prog;
13110 }
13111
13112 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13113                                               u32 off, u32 cnt)
13114 {
13115         int i, j;
13116
13117         /* find first prog starting at or after off (first to remove) */
13118         for (i = 0; i < env->subprog_cnt; i++)
13119                 if (env->subprog_info[i].start >= off)
13120                         break;
13121         /* find first prog starting at or after off + cnt (first to stay) */
13122         for (j = i; j < env->subprog_cnt; j++)
13123                 if (env->subprog_info[j].start >= off + cnt)
13124                         break;
13125         /* if j doesn't start exactly at off + cnt, we are just removing
13126          * the front of previous prog
13127          */
13128         if (env->subprog_info[j].start != off + cnt)
13129                 j--;
13130
13131         if (j > i) {
13132                 struct bpf_prog_aux *aux = env->prog->aux;
13133                 int move;
13134
13135                 /* move fake 'exit' subprog as well */
13136                 move = env->subprog_cnt + 1 - j;
13137
13138                 memmove(env->subprog_info + i,
13139                         env->subprog_info + j,
13140                         sizeof(*env->subprog_info) * move);
13141                 env->subprog_cnt -= j - i;
13142
13143                 /* remove func_info */
13144                 if (aux->func_info) {
13145                         move = aux->func_info_cnt - j;
13146
13147                         memmove(aux->func_info + i,
13148                                 aux->func_info + j,
13149                                 sizeof(*aux->func_info) * move);
13150                         aux->func_info_cnt -= j - i;
13151                         /* func_info->insn_off is set after all code rewrites,
13152                          * in adjust_btf_func() - no need to adjust
13153                          */
13154                 }
13155         } else {
13156                 /* convert i from "first prog to remove" to "first to adjust" */
13157                 if (env->subprog_info[i].start == off)
13158                         i++;
13159         }
13160
13161         /* update fake 'exit' subprog as well */
13162         for (; i <= env->subprog_cnt; i++)
13163                 env->subprog_info[i].start -= cnt;
13164
13165         return 0;
13166 }
13167
13168 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13169                                       u32 cnt)
13170 {
13171         struct bpf_prog *prog = env->prog;
13172         u32 i, l_off, l_cnt, nr_linfo;
13173         struct bpf_line_info *linfo;
13174
13175         nr_linfo = prog->aux->nr_linfo;
13176         if (!nr_linfo)
13177                 return 0;
13178
13179         linfo = prog->aux->linfo;
13180
13181         /* find first line info to remove, count lines to be removed */
13182         for (i = 0; i < nr_linfo; i++)
13183                 if (linfo[i].insn_off >= off)
13184                         break;
13185
13186         l_off = i;
13187         l_cnt = 0;
13188         for (; i < nr_linfo; i++)
13189                 if (linfo[i].insn_off < off + cnt)
13190                         l_cnt++;
13191                 else
13192                         break;
13193
13194         /* First live insn doesn't match first live linfo, it needs to "inherit"
13195          * last removed linfo.  prog is already modified, so prog->len == off
13196          * means no live instructions after (tail of the program was removed).
13197          */
13198         if (prog->len != off && l_cnt &&
13199             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13200                 l_cnt--;
13201                 linfo[--i].insn_off = off + cnt;
13202         }
13203
13204         /* remove the line info which refer to the removed instructions */
13205         if (l_cnt) {
13206                 memmove(linfo + l_off, linfo + i,
13207                         sizeof(*linfo) * (nr_linfo - i));
13208
13209                 prog->aux->nr_linfo -= l_cnt;
13210                 nr_linfo = prog->aux->nr_linfo;
13211         }
13212
13213         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13214         for (i = l_off; i < nr_linfo; i++)
13215                 linfo[i].insn_off -= cnt;
13216
13217         /* fix up all subprogs (incl. 'exit') which start >= off */
13218         for (i = 0; i <= env->subprog_cnt; i++)
13219                 if (env->subprog_info[i].linfo_idx > l_off) {
13220                         /* program may have started in the removed region but
13221                          * may not be fully removed
13222                          */
13223                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13224                                 env->subprog_info[i].linfo_idx -= l_cnt;
13225                         else
13226                                 env->subprog_info[i].linfo_idx = l_off;
13227                 }
13228
13229         return 0;
13230 }
13231
13232 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13233 {
13234         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13235         unsigned int orig_prog_len = env->prog->len;
13236         int err;
13237
13238         if (bpf_prog_is_dev_bound(env->prog->aux))
13239                 bpf_prog_offload_remove_insns(env, off, cnt);
13240
13241         err = bpf_remove_insns(env->prog, off, cnt);
13242         if (err)
13243                 return err;
13244
13245         err = adjust_subprog_starts_after_remove(env, off, cnt);
13246         if (err)
13247                 return err;
13248
13249         err = bpf_adj_linfo_after_remove(env, off, cnt);
13250         if (err)
13251                 return err;
13252
13253         memmove(aux_data + off, aux_data + off + cnt,
13254                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13255
13256         return 0;
13257 }
13258
13259 /* The verifier does more data flow analysis than llvm and will not
13260  * explore branches that are dead at run time. Malicious programs can
13261  * have dead code too. Therefore replace all dead at-run-time code
13262  * with 'ja -1'.
13263  *
13264  * Just nops are not optimal, e.g. if they would sit at the end of the
13265  * program and through another bug we would manage to jump there, then
13266  * we'd execute beyond program memory otherwise. Returning exception
13267  * code also wouldn't work since we can have subprogs where the dead
13268  * code could be located.
13269  */
13270 static void sanitize_dead_code(struct bpf_verifier_env *env)
13271 {
13272         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13273         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13274         struct bpf_insn *insn = env->prog->insnsi;
13275         const int insn_cnt = env->prog->len;
13276         int i;
13277
13278         for (i = 0; i < insn_cnt; i++) {
13279                 if (aux_data[i].seen)
13280                         continue;
13281                 memcpy(insn + i, &trap, sizeof(trap));
13282                 aux_data[i].zext_dst = false;
13283         }
13284 }
13285
13286 static bool insn_is_cond_jump(u8 code)
13287 {
13288         u8 op;
13289
13290         if (BPF_CLASS(code) == BPF_JMP32)
13291                 return true;
13292
13293         if (BPF_CLASS(code) != BPF_JMP)
13294                 return false;
13295
13296         op = BPF_OP(code);
13297         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13298 }
13299
13300 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13301 {
13302         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13303         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13304         struct bpf_insn *insn = env->prog->insnsi;
13305         const int insn_cnt = env->prog->len;
13306         int i;
13307
13308         for (i = 0; i < insn_cnt; i++, insn++) {
13309                 if (!insn_is_cond_jump(insn->code))
13310                         continue;
13311
13312                 if (!aux_data[i + 1].seen)
13313                         ja.off = insn->off;
13314                 else if (!aux_data[i + 1 + insn->off].seen)
13315                         ja.off = 0;
13316                 else
13317                         continue;
13318
13319                 if (bpf_prog_is_dev_bound(env->prog->aux))
13320                         bpf_prog_offload_replace_insn(env, i, &ja);
13321
13322                 memcpy(insn, &ja, sizeof(ja));
13323         }
13324 }
13325
13326 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13327 {
13328         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13329         int insn_cnt = env->prog->len;
13330         int i, err;
13331
13332         for (i = 0; i < insn_cnt; i++) {
13333                 int j;
13334
13335                 j = 0;
13336                 while (i + j < insn_cnt && !aux_data[i + j].seen)
13337                         j++;
13338                 if (!j)
13339                         continue;
13340
13341                 err = verifier_remove_insns(env, i, j);
13342                 if (err)
13343                         return err;
13344                 insn_cnt = env->prog->len;
13345         }
13346
13347         return 0;
13348 }
13349
13350 static int opt_remove_nops(struct bpf_verifier_env *env)
13351 {
13352         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13353         struct bpf_insn *insn = env->prog->insnsi;
13354         int insn_cnt = env->prog->len;
13355         int i, err;
13356
13357         for (i = 0; i < insn_cnt; i++) {
13358                 if (memcmp(&insn[i], &ja, sizeof(ja)))
13359                         continue;
13360
13361                 err = verifier_remove_insns(env, i, 1);
13362                 if (err)
13363                         return err;
13364                 insn_cnt--;
13365                 i--;
13366         }
13367
13368         return 0;
13369 }
13370
13371 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13372                                          const union bpf_attr *attr)
13373 {
13374         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13375         struct bpf_insn_aux_data *aux = env->insn_aux_data;
13376         int i, patch_len, delta = 0, len = env->prog->len;
13377         struct bpf_insn *insns = env->prog->insnsi;
13378         struct bpf_prog *new_prog;
13379         bool rnd_hi32;
13380
13381         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13382         zext_patch[1] = BPF_ZEXT_REG(0);
13383         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13384         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13385         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13386         for (i = 0; i < len; i++) {
13387                 int adj_idx = i + delta;
13388                 struct bpf_insn insn;
13389                 int load_reg;
13390
13391                 insn = insns[adj_idx];
13392                 load_reg = insn_def_regno(&insn);
13393                 if (!aux[adj_idx].zext_dst) {
13394                         u8 code, class;
13395                         u32 imm_rnd;
13396
13397                         if (!rnd_hi32)
13398                                 continue;
13399
13400                         code = insn.code;
13401                         class = BPF_CLASS(code);
13402                         if (load_reg == -1)
13403                                 continue;
13404
13405                         /* NOTE: arg "reg" (the fourth one) is only used for
13406                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
13407                          *       here.
13408                          */
13409                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13410                                 if (class == BPF_LD &&
13411                                     BPF_MODE(code) == BPF_IMM)
13412                                         i++;
13413                                 continue;
13414                         }
13415
13416                         /* ctx load could be transformed into wider load. */
13417                         if (class == BPF_LDX &&
13418                             aux[adj_idx].ptr_type == PTR_TO_CTX)
13419                                 continue;
13420
13421                         imm_rnd = get_random_u32();
13422                         rnd_hi32_patch[0] = insn;
13423                         rnd_hi32_patch[1].imm = imm_rnd;
13424                         rnd_hi32_patch[3].dst_reg = load_reg;
13425                         patch = rnd_hi32_patch;
13426                         patch_len = 4;
13427                         goto apply_patch_buffer;
13428                 }
13429
13430                 /* Add in an zero-extend instruction if a) the JIT has requested
13431                  * it or b) it's a CMPXCHG.
13432                  *
13433                  * The latter is because: BPF_CMPXCHG always loads a value into
13434                  * R0, therefore always zero-extends. However some archs'
13435                  * equivalent instruction only does this load when the
13436                  * comparison is successful. This detail of CMPXCHG is
13437                  * orthogonal to the general zero-extension behaviour of the
13438                  * CPU, so it's treated independently of bpf_jit_needs_zext.
13439                  */
13440                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13441                         continue;
13442
13443                 /* Zero-extension is done by the caller. */
13444                 if (bpf_pseudo_kfunc_call(&insn))
13445                         continue;
13446
13447                 if (WARN_ON(load_reg == -1)) {
13448                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13449                         return -EFAULT;
13450                 }
13451
13452                 zext_patch[0] = insn;
13453                 zext_patch[1].dst_reg = load_reg;
13454                 zext_patch[1].src_reg = load_reg;
13455                 patch = zext_patch;
13456                 patch_len = 2;
13457 apply_patch_buffer:
13458                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13459                 if (!new_prog)
13460                         return -ENOMEM;
13461                 env->prog = new_prog;
13462                 insns = new_prog->insnsi;
13463                 aux = env->insn_aux_data;
13464                 delta += patch_len - 1;
13465         }
13466
13467         return 0;
13468 }
13469
13470 /* convert load instructions that access fields of a context type into a
13471  * sequence of instructions that access fields of the underlying structure:
13472  *     struct __sk_buff    -> struct sk_buff
13473  *     struct bpf_sock_ops -> struct sock
13474  */
13475 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13476 {
13477         const struct bpf_verifier_ops *ops = env->ops;
13478         int i, cnt, size, ctx_field_size, delta = 0;
13479         const int insn_cnt = env->prog->len;
13480         struct bpf_insn insn_buf[16], *insn;
13481         u32 target_size, size_default, off;
13482         struct bpf_prog *new_prog;
13483         enum bpf_access_type type;
13484         bool is_narrower_load;
13485
13486         if (ops->gen_prologue || env->seen_direct_write) {
13487                 if (!ops->gen_prologue) {
13488                         verbose(env, "bpf verifier is misconfigured\n");
13489                         return -EINVAL;
13490                 }
13491                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13492                                         env->prog);
13493                 if (cnt >= ARRAY_SIZE(insn_buf)) {
13494                         verbose(env, "bpf verifier is misconfigured\n");
13495                         return -EINVAL;
13496                 } else if (cnt) {
13497                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13498                         if (!new_prog)
13499                                 return -ENOMEM;
13500
13501                         env->prog = new_prog;
13502                         delta += cnt - 1;
13503                 }
13504         }
13505
13506         if (bpf_prog_is_dev_bound(env->prog->aux))
13507                 return 0;
13508
13509         insn = env->prog->insnsi + delta;
13510
13511         for (i = 0; i < insn_cnt; i++, insn++) {
13512                 bpf_convert_ctx_access_t convert_ctx_access;
13513                 bool ctx_access;
13514
13515                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13516                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13517                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13518                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13519                         type = BPF_READ;
13520                         ctx_access = true;
13521                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13522                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13523                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13524                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13525                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13526                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13527                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13528                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13529                         type = BPF_WRITE;
13530                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13531                 } else {
13532                         continue;
13533                 }
13534
13535                 if (type == BPF_WRITE &&
13536                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
13537                         struct bpf_insn patch[] = {
13538                                 *insn,
13539                                 BPF_ST_NOSPEC(),
13540                         };
13541
13542                         cnt = ARRAY_SIZE(patch);
13543                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13544                         if (!new_prog)
13545                                 return -ENOMEM;
13546
13547                         delta    += cnt - 1;
13548                         env->prog = new_prog;
13549                         insn      = new_prog->insnsi + i + delta;
13550                         continue;
13551                 }
13552
13553                 if (!ctx_access)
13554                         continue;
13555
13556                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13557                 case PTR_TO_CTX:
13558                         if (!ops->convert_ctx_access)
13559                                 continue;
13560                         convert_ctx_access = ops->convert_ctx_access;
13561                         break;
13562                 case PTR_TO_SOCKET:
13563                 case PTR_TO_SOCK_COMMON:
13564                         convert_ctx_access = bpf_sock_convert_ctx_access;
13565                         break;
13566                 case PTR_TO_TCP_SOCK:
13567                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13568                         break;
13569                 case PTR_TO_XDP_SOCK:
13570                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13571                         break;
13572                 case PTR_TO_BTF_ID:
13573                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13574                         if (type == BPF_READ) {
13575                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
13576                                         BPF_SIZE((insn)->code);
13577                                 env->prog->aux->num_exentries++;
13578                         }
13579                         continue;
13580                 default:
13581                         continue;
13582                 }
13583
13584                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13585                 size = BPF_LDST_BYTES(insn);
13586
13587                 /* If the read access is a narrower load of the field,
13588                  * convert to a 4/8-byte load, to minimum program type specific
13589                  * convert_ctx_access changes. If conversion is successful,
13590                  * we will apply proper mask to the result.
13591                  */
13592                 is_narrower_load = size < ctx_field_size;
13593                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13594                 off = insn->off;
13595                 if (is_narrower_load) {
13596                         u8 size_code;
13597
13598                         if (type == BPF_WRITE) {
13599                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13600                                 return -EINVAL;
13601                         }
13602
13603                         size_code = BPF_H;
13604                         if (ctx_field_size == 4)
13605                                 size_code = BPF_W;
13606                         else if (ctx_field_size == 8)
13607                                 size_code = BPF_DW;
13608
13609                         insn->off = off & ~(size_default - 1);
13610                         insn->code = BPF_LDX | BPF_MEM | size_code;
13611                 }
13612
13613                 target_size = 0;
13614                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13615                                          &target_size);
13616                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13617                     (ctx_field_size && !target_size)) {
13618                         verbose(env, "bpf verifier is misconfigured\n");
13619                         return -EINVAL;
13620                 }
13621
13622                 if (is_narrower_load && size < target_size) {
13623                         u8 shift = bpf_ctx_narrow_access_offset(
13624                                 off, size, size_default) * 8;
13625                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13626                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13627                                 return -EINVAL;
13628                         }
13629                         if (ctx_field_size <= 4) {
13630                                 if (shift)
13631                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13632                                                                         insn->dst_reg,
13633                                                                         shift);
13634                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13635                                                                 (1 << size * 8) - 1);
13636                         } else {
13637                                 if (shift)
13638                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13639                                                                         insn->dst_reg,
13640                                                                         shift);
13641                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13642                                                                 (1ULL << size * 8) - 1);
13643                         }
13644                 }
13645
13646                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13647                 if (!new_prog)
13648                         return -ENOMEM;
13649
13650                 delta += cnt - 1;
13651
13652                 /* keep walking new program and skip insns we just inserted */
13653                 env->prog = new_prog;
13654                 insn      = new_prog->insnsi + i + delta;
13655         }
13656
13657         return 0;
13658 }
13659
13660 static int jit_subprogs(struct bpf_verifier_env *env)
13661 {
13662         struct bpf_prog *prog = env->prog, **func, *tmp;
13663         int i, j, subprog_start, subprog_end = 0, len, subprog;
13664         struct bpf_map *map_ptr;
13665         struct bpf_insn *insn;
13666         void *old_bpf_func;
13667         int err, num_exentries;
13668
13669         if (env->subprog_cnt <= 1)
13670                 return 0;
13671
13672         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13673                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13674                         continue;
13675
13676                 /* Upon error here we cannot fall back to interpreter but
13677                  * need a hard reject of the program. Thus -EFAULT is
13678                  * propagated in any case.
13679                  */
13680                 subprog = find_subprog(env, i + insn->imm + 1);
13681                 if (subprog < 0) {
13682                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13683                                   i + insn->imm + 1);
13684                         return -EFAULT;
13685                 }
13686                 /* temporarily remember subprog id inside insn instead of
13687                  * aux_data, since next loop will split up all insns into funcs
13688                  */
13689                 insn->off = subprog;
13690                 /* remember original imm in case JIT fails and fallback
13691                  * to interpreter will be needed
13692                  */
13693                 env->insn_aux_data[i].call_imm = insn->imm;
13694                 /* point imm to __bpf_call_base+1 from JITs point of view */
13695                 insn->imm = 1;
13696                 if (bpf_pseudo_func(insn))
13697                         /* jit (e.g. x86_64) may emit fewer instructions
13698                          * if it learns a u32 imm is the same as a u64 imm.
13699                          * Force a non zero here.
13700                          */
13701                         insn[1].imm = 1;
13702         }
13703
13704         err = bpf_prog_alloc_jited_linfo(prog);
13705         if (err)
13706                 goto out_undo_insn;
13707
13708         err = -ENOMEM;
13709         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13710         if (!func)
13711                 goto out_undo_insn;
13712
13713         for (i = 0; i < env->subprog_cnt; i++) {
13714                 subprog_start = subprog_end;
13715                 subprog_end = env->subprog_info[i + 1].start;
13716
13717                 len = subprog_end - subprog_start;
13718                 /* bpf_prog_run() doesn't call subprogs directly,
13719                  * hence main prog stats include the runtime of subprogs.
13720                  * subprogs don't have IDs and not reachable via prog_get_next_id
13721                  * func[i]->stats will never be accessed and stays NULL
13722                  */
13723                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13724                 if (!func[i])
13725                         goto out_free;
13726                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13727                        len * sizeof(struct bpf_insn));
13728                 func[i]->type = prog->type;
13729                 func[i]->len = len;
13730                 if (bpf_prog_calc_tag(func[i]))
13731                         goto out_free;
13732                 func[i]->is_func = 1;
13733                 func[i]->aux->func_idx = i;
13734                 /* Below members will be freed only at prog->aux */
13735                 func[i]->aux->btf = prog->aux->btf;
13736                 func[i]->aux->func_info = prog->aux->func_info;
13737                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13738                 func[i]->aux->poke_tab = prog->aux->poke_tab;
13739                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13740
13741                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13742                         struct bpf_jit_poke_descriptor *poke;
13743
13744                         poke = &prog->aux->poke_tab[j];
13745                         if (poke->insn_idx < subprog_end &&
13746                             poke->insn_idx >= subprog_start)
13747                                 poke->aux = func[i]->aux;
13748                 }
13749
13750                 func[i]->aux->name[0] = 'F';
13751                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13752                 func[i]->jit_requested = 1;
13753                 func[i]->blinding_requested = prog->blinding_requested;
13754                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13755                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13756                 func[i]->aux->linfo = prog->aux->linfo;
13757                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13758                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13759                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13760                 num_exentries = 0;
13761                 insn = func[i]->insnsi;
13762                 for (j = 0; j < func[i]->len; j++, insn++) {
13763                         if (BPF_CLASS(insn->code) == BPF_LDX &&
13764                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
13765                                 num_exentries++;
13766                 }
13767                 func[i]->aux->num_exentries = num_exentries;
13768                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13769                 func[i] = bpf_int_jit_compile(func[i]);
13770                 if (!func[i]->jited) {
13771                         err = -ENOTSUPP;
13772                         goto out_free;
13773                 }
13774                 cond_resched();
13775         }
13776
13777         /* at this point all bpf functions were successfully JITed
13778          * now populate all bpf_calls with correct addresses and
13779          * run last pass of JIT
13780          */
13781         for (i = 0; i < env->subprog_cnt; i++) {
13782                 insn = func[i]->insnsi;
13783                 for (j = 0; j < func[i]->len; j++, insn++) {
13784                         if (bpf_pseudo_func(insn)) {
13785                                 subprog = insn->off;
13786                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13787                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13788                                 continue;
13789                         }
13790                         if (!bpf_pseudo_call(insn))
13791                                 continue;
13792                         subprog = insn->off;
13793                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13794                 }
13795
13796                 /* we use the aux data to keep a list of the start addresses
13797                  * of the JITed images for each function in the program
13798                  *
13799                  * for some architectures, such as powerpc64, the imm field
13800                  * might not be large enough to hold the offset of the start
13801                  * address of the callee's JITed image from __bpf_call_base
13802                  *
13803                  * in such cases, we can lookup the start address of a callee
13804                  * by using its subprog id, available from the off field of
13805                  * the call instruction, as an index for this list
13806                  */
13807                 func[i]->aux->func = func;
13808                 func[i]->aux->func_cnt = env->subprog_cnt;
13809         }
13810         for (i = 0; i < env->subprog_cnt; i++) {
13811                 old_bpf_func = func[i]->bpf_func;
13812                 tmp = bpf_int_jit_compile(func[i]);
13813                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13814                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13815                         err = -ENOTSUPP;
13816                         goto out_free;
13817                 }
13818                 cond_resched();
13819         }
13820
13821         /* finally lock prog and jit images for all functions and
13822          * populate kallsysm
13823          */
13824         for (i = 0; i < env->subprog_cnt; i++) {
13825                 bpf_prog_lock_ro(func[i]);
13826                 bpf_prog_kallsyms_add(func[i]);
13827         }
13828
13829         /* Last step: make now unused interpreter insns from main
13830          * prog consistent for later dump requests, so they can
13831          * later look the same as if they were interpreted only.
13832          */
13833         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13834                 if (bpf_pseudo_func(insn)) {
13835                         insn[0].imm = env->insn_aux_data[i].call_imm;
13836                         insn[1].imm = insn->off;
13837                         insn->off = 0;
13838                         continue;
13839                 }
13840                 if (!bpf_pseudo_call(insn))
13841                         continue;
13842                 insn->off = env->insn_aux_data[i].call_imm;
13843                 subprog = find_subprog(env, i + insn->off + 1);
13844                 insn->imm = subprog;
13845         }
13846
13847         prog->jited = 1;
13848         prog->bpf_func = func[0]->bpf_func;
13849         prog->jited_len = func[0]->jited_len;
13850         prog->aux->func = func;
13851         prog->aux->func_cnt = env->subprog_cnt;
13852         bpf_prog_jit_attempt_done(prog);
13853         return 0;
13854 out_free:
13855         /* We failed JIT'ing, so at this point we need to unregister poke
13856          * descriptors from subprogs, so that kernel is not attempting to
13857          * patch it anymore as we're freeing the subprog JIT memory.
13858          */
13859         for (i = 0; i < prog->aux->size_poke_tab; i++) {
13860                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13861                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13862         }
13863         /* At this point we're guaranteed that poke descriptors are not
13864          * live anymore. We can just unlink its descriptor table as it's
13865          * released with the main prog.
13866          */
13867         for (i = 0; i < env->subprog_cnt; i++) {
13868                 if (!func[i])
13869                         continue;
13870                 func[i]->aux->poke_tab = NULL;
13871                 bpf_jit_free(func[i]);
13872         }
13873         kfree(func);
13874 out_undo_insn:
13875         /* cleanup main prog to be interpreted */
13876         prog->jit_requested = 0;
13877         prog->blinding_requested = 0;
13878         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13879                 if (!bpf_pseudo_call(insn))
13880                         continue;
13881                 insn->off = 0;
13882                 insn->imm = env->insn_aux_data[i].call_imm;
13883         }
13884         bpf_prog_jit_attempt_done(prog);
13885         return err;
13886 }
13887
13888 static int fixup_call_args(struct bpf_verifier_env *env)
13889 {
13890 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13891         struct bpf_prog *prog = env->prog;
13892         struct bpf_insn *insn = prog->insnsi;
13893         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13894         int i, depth;
13895 #endif
13896         int err = 0;
13897
13898         if (env->prog->jit_requested &&
13899             !bpf_prog_is_dev_bound(env->prog->aux)) {
13900                 err = jit_subprogs(env);
13901                 if (err == 0)
13902                         return 0;
13903                 if (err == -EFAULT)
13904                         return err;
13905         }
13906 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13907         if (has_kfunc_call) {
13908                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13909                 return -EINVAL;
13910         }
13911         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13912                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13913                  * have to be rejected, since interpreter doesn't support them yet.
13914                  */
13915                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13916                 return -EINVAL;
13917         }
13918         for (i = 0; i < prog->len; i++, insn++) {
13919                 if (bpf_pseudo_func(insn)) {
13920                         /* When JIT fails the progs with callback calls
13921                          * have to be rejected, since interpreter doesn't support them yet.
13922                          */
13923                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
13924                         return -EINVAL;
13925                 }
13926
13927                 if (!bpf_pseudo_call(insn))
13928                         continue;
13929                 depth = get_callee_stack_depth(env, insn, i);
13930                 if (depth < 0)
13931                         return depth;
13932                 bpf_patch_call_args(insn, depth);
13933         }
13934         err = 0;
13935 #endif
13936         return err;
13937 }
13938
13939 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13940                             struct bpf_insn *insn)
13941 {
13942         const struct bpf_kfunc_desc *desc;
13943
13944         if (!insn->imm) {
13945                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13946                 return -EINVAL;
13947         }
13948
13949         /* insn->imm has the btf func_id. Replace it with
13950          * an address (relative to __bpf_base_call).
13951          */
13952         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13953         if (!desc) {
13954                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13955                         insn->imm);
13956                 return -EFAULT;
13957         }
13958
13959         insn->imm = desc->imm;
13960
13961         return 0;
13962 }
13963
13964 /* Do various post-verification rewrites in a single program pass.
13965  * These rewrites simplify JIT and interpreter implementations.
13966  */
13967 static int do_misc_fixups(struct bpf_verifier_env *env)
13968 {
13969         struct bpf_prog *prog = env->prog;
13970         enum bpf_attach_type eatype = prog->expected_attach_type;
13971         enum bpf_prog_type prog_type = resolve_prog_type(prog);
13972         struct bpf_insn *insn = prog->insnsi;
13973         const struct bpf_func_proto *fn;
13974         const int insn_cnt = prog->len;
13975         const struct bpf_map_ops *ops;
13976         struct bpf_insn_aux_data *aux;
13977         struct bpf_insn insn_buf[16];
13978         struct bpf_prog *new_prog;
13979         struct bpf_map *map_ptr;
13980         int i, ret, cnt, delta = 0;
13981
13982         for (i = 0; i < insn_cnt; i++, insn++) {
13983                 /* Make divide-by-zero exceptions impossible. */
13984                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13985                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13986                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13987                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13988                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13989                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13990                         struct bpf_insn *patchlet;
13991                         struct bpf_insn chk_and_div[] = {
13992                                 /* [R,W]x div 0 -> 0 */
13993                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13994                                              BPF_JNE | BPF_K, insn->src_reg,
13995                                              0, 2, 0),
13996                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13997                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13998                                 *insn,
13999                         };
14000                         struct bpf_insn chk_and_mod[] = {
14001                                 /* [R,W]x mod 0 -> [R,W]x */
14002                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14003                                              BPF_JEQ | BPF_K, insn->src_reg,
14004                                              0, 1 + (is64 ? 0 : 1), 0),
14005                                 *insn,
14006                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14007                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
14008                         };
14009
14010                         patchlet = isdiv ? chk_and_div : chk_and_mod;
14011                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
14012                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
14013
14014                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
14015                         if (!new_prog)
14016                                 return -ENOMEM;
14017
14018                         delta    += cnt - 1;
14019                         env->prog = prog = new_prog;
14020                         insn      = new_prog->insnsi + i + delta;
14021                         continue;
14022                 }
14023
14024                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
14025                 if (BPF_CLASS(insn->code) == BPF_LD &&
14026                     (BPF_MODE(insn->code) == BPF_ABS ||
14027                      BPF_MODE(insn->code) == BPF_IND)) {
14028                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
14029                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14030                                 verbose(env, "bpf verifier is misconfigured\n");
14031                                 return -EINVAL;
14032                         }
14033
14034                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 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                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
14045                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14046                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14047                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14048                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14049                         struct bpf_insn *patch = &insn_buf[0];
14050                         bool issrc, isneg, isimm;
14051                         u32 off_reg;
14052
14053                         aux = &env->insn_aux_data[i + delta];
14054                         if (!aux->alu_state ||
14055                             aux->alu_state == BPF_ALU_NON_POINTER)
14056                                 continue;
14057
14058                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14059                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14060                                 BPF_ALU_SANITIZE_SRC;
14061                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14062
14063                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
14064                         if (isimm) {
14065                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14066                         } else {
14067                                 if (isneg)
14068                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14069                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14070                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14071                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14072                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14073                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14074                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14075                         }
14076                         if (!issrc)
14077                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14078                         insn->src_reg = BPF_REG_AX;
14079                         if (isneg)
14080                                 insn->code = insn->code == code_add ?
14081                                              code_sub : code_add;
14082                         *patch++ = *insn;
14083                         if (issrc && isneg && !isimm)
14084                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14085                         cnt = patch - insn_buf;
14086
14087                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14088                         if (!new_prog)
14089                                 return -ENOMEM;
14090
14091                         delta    += cnt - 1;
14092                         env->prog = prog = new_prog;
14093                         insn      = new_prog->insnsi + i + delta;
14094                         continue;
14095                 }
14096
14097                 if (insn->code != (BPF_JMP | BPF_CALL))
14098                         continue;
14099                 if (insn->src_reg == BPF_PSEUDO_CALL)
14100                         continue;
14101                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14102                         ret = fixup_kfunc_call(env, insn);
14103                         if (ret)
14104                                 return ret;
14105                         continue;
14106                 }
14107
14108                 if (insn->imm == BPF_FUNC_get_route_realm)
14109                         prog->dst_needed = 1;
14110                 if (insn->imm == BPF_FUNC_get_prandom_u32)
14111                         bpf_user_rnd_init_once();
14112                 if (insn->imm == BPF_FUNC_override_return)
14113                         prog->kprobe_override = 1;
14114                 if (insn->imm == BPF_FUNC_tail_call) {
14115                         /* If we tail call into other programs, we
14116                          * cannot make any assumptions since they can
14117                          * be replaced dynamically during runtime in
14118                          * the program array.
14119                          */
14120                         prog->cb_access = 1;
14121                         if (!allow_tail_call_in_subprogs(env))
14122                                 prog->aux->stack_depth = MAX_BPF_STACK;
14123                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14124
14125                         /* mark bpf_tail_call as different opcode to avoid
14126                          * conditional branch in the interpreter for every normal
14127                          * call and to prevent accidental JITing by JIT compiler
14128                          * that doesn't support bpf_tail_call yet
14129                          */
14130                         insn->imm = 0;
14131                         insn->code = BPF_JMP | BPF_TAIL_CALL;
14132
14133                         aux = &env->insn_aux_data[i + delta];
14134                         if (env->bpf_capable && !prog->blinding_requested &&
14135                             prog->jit_requested &&
14136                             !bpf_map_key_poisoned(aux) &&
14137                             !bpf_map_ptr_poisoned(aux) &&
14138                             !bpf_map_ptr_unpriv(aux)) {
14139                                 struct bpf_jit_poke_descriptor desc = {
14140                                         .reason = BPF_POKE_REASON_TAIL_CALL,
14141                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14142                                         .tail_call.key = bpf_map_key_immediate(aux),
14143                                         .insn_idx = i + delta,
14144                                 };
14145
14146                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14147                                 if (ret < 0) {
14148                                         verbose(env, "adding tail call poke descriptor failed\n");
14149                                         return ret;
14150                                 }
14151
14152                                 insn->imm = ret + 1;
14153                                 continue;
14154                         }
14155
14156                         if (!bpf_map_ptr_unpriv(aux))
14157                                 continue;
14158
14159                         /* instead of changing every JIT dealing with tail_call
14160                          * emit two extra insns:
14161                          * if (index >= max_entries) goto out;
14162                          * index &= array->index_mask;
14163                          * to avoid out-of-bounds cpu speculation
14164                          */
14165                         if (bpf_map_ptr_poisoned(aux)) {
14166                                 verbose(env, "tail_call abusing map_ptr\n");
14167                                 return -EINVAL;
14168                         }
14169
14170                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14171                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14172                                                   map_ptr->max_entries, 2);
14173                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14174                                                     container_of(map_ptr,
14175                                                                  struct bpf_array,
14176                                                                  map)->index_mask);
14177                         insn_buf[2] = *insn;
14178                         cnt = 3;
14179                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14180                         if (!new_prog)
14181                                 return -ENOMEM;
14182
14183                         delta    += cnt - 1;
14184                         env->prog = prog = new_prog;
14185                         insn      = new_prog->insnsi + i + delta;
14186                         continue;
14187                 }
14188
14189                 if (insn->imm == BPF_FUNC_timer_set_callback) {
14190                         /* The verifier will process callback_fn as many times as necessary
14191                          * with different maps and the register states prepared by
14192                          * set_timer_callback_state will be accurate.
14193                          *
14194                          * The following use case is valid:
14195                          *   map1 is shared by prog1, prog2, prog3.
14196                          *   prog1 calls bpf_timer_init for some map1 elements
14197                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
14198                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
14199                          *   prog3 calls bpf_timer_start for some map1 elements.
14200                          *     Those that were not both bpf_timer_init-ed and
14201                          *     bpf_timer_set_callback-ed will return -EINVAL.
14202                          */
14203                         struct bpf_insn ld_addrs[2] = {
14204                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14205                         };
14206
14207                         insn_buf[0] = ld_addrs[0];
14208                         insn_buf[1] = ld_addrs[1];
14209                         insn_buf[2] = *insn;
14210                         cnt = 3;
14211
14212                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14213                         if (!new_prog)
14214                                 return -ENOMEM;
14215
14216                         delta    += cnt - 1;
14217                         env->prog = prog = new_prog;
14218                         insn      = new_prog->insnsi + i + delta;
14219                         goto patch_call_imm;
14220                 }
14221
14222                 if (insn->imm == BPF_FUNC_task_storage_get ||
14223                     insn->imm == BPF_FUNC_sk_storage_get ||
14224                     insn->imm == BPF_FUNC_inode_storage_get) {
14225                         if (env->prog->aux->sleepable)
14226                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14227                         else
14228                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14229                         insn_buf[1] = *insn;
14230                         cnt = 2;
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                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14243                  * and other inlining handlers are currently limited to 64 bit
14244                  * only.
14245                  */
14246                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14247                     (insn->imm == BPF_FUNC_map_lookup_elem ||
14248                      insn->imm == BPF_FUNC_map_update_elem ||
14249                      insn->imm == BPF_FUNC_map_delete_elem ||
14250                      insn->imm == BPF_FUNC_map_push_elem   ||
14251                      insn->imm == BPF_FUNC_map_pop_elem    ||
14252                      insn->imm == BPF_FUNC_map_peek_elem   ||
14253                      insn->imm == BPF_FUNC_redirect_map    ||
14254                      insn->imm == BPF_FUNC_for_each_map_elem ||
14255                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14256                         aux = &env->insn_aux_data[i + delta];
14257                         if (bpf_map_ptr_poisoned(aux))
14258                                 goto patch_call_imm;
14259
14260                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14261                         ops = map_ptr->ops;
14262                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
14263                             ops->map_gen_lookup) {
14264                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14265                                 if (cnt == -EOPNOTSUPP)
14266                                         goto patch_map_ops_generic;
14267                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14268                                         verbose(env, "bpf verifier is misconfigured\n");
14269                                         return -EINVAL;
14270                                 }
14271
14272                                 new_prog = bpf_patch_insn_data(env, i + delta,
14273                                                                insn_buf, cnt);
14274                                 if (!new_prog)
14275                                         return -ENOMEM;
14276
14277                                 delta    += cnt - 1;
14278                                 env->prog = prog = new_prog;
14279                                 insn      = new_prog->insnsi + i + delta;
14280                                 continue;
14281                         }
14282
14283                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14284                                      (void *(*)(struct bpf_map *map, void *key))NULL));
14285                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14286                                      (int (*)(struct bpf_map *map, void *key))NULL));
14287                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14288                                      (int (*)(struct bpf_map *map, void *key, void *value,
14289                                               u64 flags))NULL));
14290                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14291                                      (int (*)(struct bpf_map *map, void *value,
14292                                               u64 flags))NULL));
14293                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14294                                      (int (*)(struct bpf_map *map, void *value))NULL));
14295                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14296                                      (int (*)(struct bpf_map *map, void *value))NULL));
14297                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
14298                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14299                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14300                                      (int (*)(struct bpf_map *map,
14301                                               bpf_callback_t callback_fn,
14302                                               void *callback_ctx,
14303                                               u64 flags))NULL));
14304                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14305                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14306
14307 patch_map_ops_generic:
14308                         switch (insn->imm) {
14309                         case BPF_FUNC_map_lookup_elem:
14310                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14311                                 continue;
14312                         case BPF_FUNC_map_update_elem:
14313                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14314                                 continue;
14315                         case BPF_FUNC_map_delete_elem:
14316                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14317                                 continue;
14318                         case BPF_FUNC_map_push_elem:
14319                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14320                                 continue;
14321                         case BPF_FUNC_map_pop_elem:
14322                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14323                                 continue;
14324                         case BPF_FUNC_map_peek_elem:
14325                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14326                                 continue;
14327                         case BPF_FUNC_redirect_map:
14328                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14329                                 continue;
14330                         case BPF_FUNC_for_each_map_elem:
14331                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14332                                 continue;
14333                         case BPF_FUNC_map_lookup_percpu_elem:
14334                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14335                                 continue;
14336                         }
14337
14338                         goto patch_call_imm;
14339                 }
14340
14341                 /* Implement bpf_jiffies64 inline. */
14342                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14343                     insn->imm == BPF_FUNC_jiffies64) {
14344                         struct bpf_insn ld_jiffies_addr[2] = {
14345                                 BPF_LD_IMM64(BPF_REG_0,
14346                                              (unsigned long)&jiffies),
14347                         };
14348
14349                         insn_buf[0] = ld_jiffies_addr[0];
14350                         insn_buf[1] = ld_jiffies_addr[1];
14351                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14352                                                   BPF_REG_0, 0);
14353                         cnt = 3;
14354
14355                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14356                                                        cnt);
14357                         if (!new_prog)
14358                                 return -ENOMEM;
14359
14360                         delta    += cnt - 1;
14361                         env->prog = prog = new_prog;
14362                         insn      = new_prog->insnsi + i + delta;
14363                         continue;
14364                 }
14365
14366                 /* Implement bpf_get_func_arg inline. */
14367                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14368                     insn->imm == BPF_FUNC_get_func_arg) {
14369                         /* Load nr_args from ctx - 8 */
14370                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14371                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14372                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14373                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14374                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14375                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14376                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14377                         insn_buf[7] = BPF_JMP_A(1);
14378                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14379                         cnt = 9;
14380
14381                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14382                         if (!new_prog)
14383                                 return -ENOMEM;
14384
14385                         delta    += cnt - 1;
14386                         env->prog = prog = new_prog;
14387                         insn      = new_prog->insnsi + i + delta;
14388                         continue;
14389                 }
14390
14391                 /* Implement bpf_get_func_ret inline. */
14392                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14393                     insn->imm == BPF_FUNC_get_func_ret) {
14394                         if (eatype == BPF_TRACE_FEXIT ||
14395                             eatype == BPF_MODIFY_RETURN) {
14396                                 /* Load nr_args from ctx - 8 */
14397                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14398                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14399                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14400                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14401                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14402                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14403                                 cnt = 6;
14404                         } else {
14405                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14406                                 cnt = 1;
14407                         }
14408
14409                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14410                         if (!new_prog)
14411                                 return -ENOMEM;
14412
14413                         delta    += cnt - 1;
14414                         env->prog = prog = new_prog;
14415                         insn      = new_prog->insnsi + i + delta;
14416                         continue;
14417                 }
14418
14419                 /* Implement get_func_arg_cnt inline. */
14420                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14421                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
14422                         /* Load nr_args from ctx - 8 */
14423                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14424
14425                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14426                         if (!new_prog)
14427                                 return -ENOMEM;
14428
14429                         env->prog = prog = new_prog;
14430                         insn      = new_prog->insnsi + i + delta;
14431                         continue;
14432                 }
14433
14434                 /* Implement bpf_get_func_ip inline. */
14435                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14436                     insn->imm == BPF_FUNC_get_func_ip) {
14437                         /* Load IP address from ctx - 16 */
14438                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14439
14440                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14441                         if (!new_prog)
14442                                 return -ENOMEM;
14443
14444                         env->prog = prog = new_prog;
14445                         insn      = new_prog->insnsi + i + delta;
14446                         continue;
14447                 }
14448
14449 patch_call_imm:
14450                 fn = env->ops->get_func_proto(insn->imm, env->prog);
14451                 /* all functions that have prototype and verifier allowed
14452                  * programs to call them, must be real in-kernel functions
14453                  */
14454                 if (!fn->func) {
14455                         verbose(env,
14456                                 "kernel subsystem misconfigured func %s#%d\n",
14457                                 func_id_name(insn->imm), insn->imm);
14458                         return -EFAULT;
14459                 }
14460                 insn->imm = fn->func - __bpf_call_base;
14461         }
14462
14463         /* Since poke tab is now finalized, publish aux to tracker. */
14464         for (i = 0; i < prog->aux->size_poke_tab; i++) {
14465                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14466                 if (!map_ptr->ops->map_poke_track ||
14467                     !map_ptr->ops->map_poke_untrack ||
14468                     !map_ptr->ops->map_poke_run) {
14469                         verbose(env, "bpf verifier is misconfigured\n");
14470                         return -EINVAL;
14471                 }
14472
14473                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14474                 if (ret < 0) {
14475                         verbose(env, "tracking tail call prog failed\n");
14476                         return ret;
14477                 }
14478         }
14479
14480         sort_kfunc_descs_by_imm(env->prog);
14481
14482         return 0;
14483 }
14484
14485 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14486                                         int position,
14487                                         s32 stack_base,
14488                                         u32 callback_subprogno,
14489                                         u32 *cnt)
14490 {
14491         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14492         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14493         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14494         int reg_loop_max = BPF_REG_6;
14495         int reg_loop_cnt = BPF_REG_7;
14496         int reg_loop_ctx = BPF_REG_8;
14497
14498         struct bpf_prog *new_prog;
14499         u32 callback_start;
14500         u32 call_insn_offset;
14501         s32 callback_offset;
14502
14503         /* This represents an inlined version of bpf_iter.c:bpf_loop,
14504          * be careful to modify this code in sync.
14505          */
14506         struct bpf_insn insn_buf[] = {
14507                 /* Return error and jump to the end of the patch if
14508                  * expected number of iterations is too big.
14509                  */
14510                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14511                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14512                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14513                 /* spill R6, R7, R8 to use these as loop vars */
14514                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14515                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14516                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14517                 /* initialize loop vars */
14518                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14519                 BPF_MOV32_IMM(reg_loop_cnt, 0),
14520                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14521                 /* loop header,
14522                  * if reg_loop_cnt >= reg_loop_max skip the loop body
14523                  */
14524                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14525                 /* callback call,
14526                  * correct callback offset would be set after patching
14527                  */
14528                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14529                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14530                 BPF_CALL_REL(0),
14531                 /* increment loop counter */
14532                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14533                 /* jump to loop header if callback returned 0 */
14534                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14535                 /* return value of bpf_loop,
14536                  * set R0 to the number of iterations
14537                  */
14538                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14539                 /* restore original values of R6, R7, R8 */
14540                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14541                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14542                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14543         };
14544
14545         *cnt = ARRAY_SIZE(insn_buf);
14546         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14547         if (!new_prog)
14548                 return new_prog;
14549
14550         /* callback start is known only after patching */
14551         callback_start = env->subprog_info[callback_subprogno].start;
14552         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14553         call_insn_offset = position + 12;
14554         callback_offset = callback_start - call_insn_offset - 1;
14555         new_prog->insnsi[call_insn_offset].imm = callback_offset;
14556
14557         return new_prog;
14558 }
14559
14560 static bool is_bpf_loop_call(struct bpf_insn *insn)
14561 {
14562         return insn->code == (BPF_JMP | BPF_CALL) &&
14563                 insn->src_reg == 0 &&
14564                 insn->imm == BPF_FUNC_loop;
14565 }
14566
14567 /* For all sub-programs in the program (including main) check
14568  * insn_aux_data to see if there are bpf_loop calls that require
14569  * inlining. If such calls are found the calls are replaced with a
14570  * sequence of instructions produced by `inline_bpf_loop` function and
14571  * subprog stack_depth is increased by the size of 3 registers.
14572  * This stack space is used to spill values of the R6, R7, R8.  These
14573  * registers are used to store the loop bound, counter and context
14574  * variables.
14575  */
14576 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14577 {
14578         struct bpf_subprog_info *subprogs = env->subprog_info;
14579         int i, cur_subprog = 0, cnt, delta = 0;
14580         struct bpf_insn *insn = env->prog->insnsi;
14581         int insn_cnt = env->prog->len;
14582         u16 stack_depth = subprogs[cur_subprog].stack_depth;
14583         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14584         u16 stack_depth_extra = 0;
14585
14586         for (i = 0; i < insn_cnt; i++, insn++) {
14587                 struct bpf_loop_inline_state *inline_state =
14588                         &env->insn_aux_data[i + delta].loop_inline_state;
14589
14590                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14591                         struct bpf_prog *new_prog;
14592
14593                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14594                         new_prog = inline_bpf_loop(env,
14595                                                    i + delta,
14596                                                    -(stack_depth + stack_depth_extra),
14597                                                    inline_state->callback_subprogno,
14598                                                    &cnt);
14599                         if (!new_prog)
14600                                 return -ENOMEM;
14601
14602                         delta     += cnt - 1;
14603                         env->prog  = new_prog;
14604                         insn       = new_prog->insnsi + i + delta;
14605                 }
14606
14607                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14608                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
14609                         cur_subprog++;
14610                         stack_depth = subprogs[cur_subprog].stack_depth;
14611                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14612                         stack_depth_extra = 0;
14613                 }
14614         }
14615
14616         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14617
14618         return 0;
14619 }
14620
14621 static void free_states(struct bpf_verifier_env *env)
14622 {
14623         struct bpf_verifier_state_list *sl, *sln;
14624         int i;
14625
14626         sl = env->free_list;
14627         while (sl) {
14628                 sln = sl->next;
14629                 free_verifier_state(&sl->state, false);
14630                 kfree(sl);
14631                 sl = sln;
14632         }
14633         env->free_list = NULL;
14634
14635         if (!env->explored_states)
14636                 return;
14637
14638         for (i = 0; i < state_htab_size(env); i++) {
14639                 sl = env->explored_states[i];
14640
14641                 while (sl) {
14642                         sln = sl->next;
14643                         free_verifier_state(&sl->state, false);
14644                         kfree(sl);
14645                         sl = sln;
14646                 }
14647                 env->explored_states[i] = NULL;
14648         }
14649 }
14650
14651 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14652 {
14653         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14654         struct bpf_verifier_state *state;
14655         struct bpf_reg_state *regs;
14656         int ret, i;
14657
14658         env->prev_linfo = NULL;
14659         env->pass_cnt++;
14660
14661         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14662         if (!state)
14663                 return -ENOMEM;
14664         state->curframe = 0;
14665         state->speculative = false;
14666         state->branches = 1;
14667         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14668         if (!state->frame[0]) {
14669                 kfree(state);
14670                 return -ENOMEM;
14671         }
14672         env->cur_state = state;
14673         init_func_state(env, state->frame[0],
14674                         BPF_MAIN_FUNC /* callsite */,
14675                         0 /* frameno */,
14676                         subprog);
14677
14678         regs = state->frame[state->curframe]->regs;
14679         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14680                 ret = btf_prepare_func_args(env, subprog, regs);
14681                 if (ret)
14682                         goto out;
14683                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14684                         if (regs[i].type == PTR_TO_CTX)
14685                                 mark_reg_known_zero(env, regs, i);
14686                         else if (regs[i].type == SCALAR_VALUE)
14687                                 mark_reg_unknown(env, regs, i);
14688                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
14689                                 const u32 mem_size = regs[i].mem_size;
14690
14691                                 mark_reg_known_zero(env, regs, i);
14692                                 regs[i].mem_size = mem_size;
14693                                 regs[i].id = ++env->id_gen;
14694                         }
14695                 }
14696         } else {
14697                 /* 1st arg to a function */
14698                 regs[BPF_REG_1].type = PTR_TO_CTX;
14699                 mark_reg_known_zero(env, regs, BPF_REG_1);
14700                 ret = btf_check_subprog_arg_match(env, subprog, regs);
14701                 if (ret == -EFAULT)
14702                         /* unlikely verifier bug. abort.
14703                          * ret == 0 and ret < 0 are sadly acceptable for
14704                          * main() function due to backward compatibility.
14705                          * Like socket filter program may be written as:
14706                          * int bpf_prog(struct pt_regs *ctx)
14707                          * and never dereference that ctx in the program.
14708                          * 'struct pt_regs' is a type mismatch for socket
14709                          * filter that should be using 'struct __sk_buff'.
14710                          */
14711                         goto out;
14712         }
14713
14714         ret = do_check(env);
14715 out:
14716         /* check for NULL is necessary, since cur_state can be freed inside
14717          * do_check() under memory pressure.
14718          */
14719         if (env->cur_state) {
14720                 free_verifier_state(env->cur_state, true);
14721                 env->cur_state = NULL;
14722         }
14723         while (!pop_stack(env, NULL, NULL, false));
14724         if (!ret && pop_log)
14725                 bpf_vlog_reset(&env->log, 0);
14726         free_states(env);
14727         return ret;
14728 }
14729
14730 /* Verify all global functions in a BPF program one by one based on their BTF.
14731  * All global functions must pass verification. Otherwise the whole program is rejected.
14732  * Consider:
14733  * int bar(int);
14734  * int foo(int f)
14735  * {
14736  *    return bar(f);
14737  * }
14738  * int bar(int b)
14739  * {
14740  *    ...
14741  * }
14742  * foo() will be verified first for R1=any_scalar_value. During verification it
14743  * will be assumed that bar() already verified successfully and call to bar()
14744  * from foo() will be checked for type match only. Later bar() will be verified
14745  * independently to check that it's safe for R1=any_scalar_value.
14746  */
14747 static int do_check_subprogs(struct bpf_verifier_env *env)
14748 {
14749         struct bpf_prog_aux *aux = env->prog->aux;
14750         int i, ret;
14751
14752         if (!aux->func_info)
14753                 return 0;
14754
14755         for (i = 1; i < env->subprog_cnt; i++) {
14756                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14757                         continue;
14758                 env->insn_idx = env->subprog_info[i].start;
14759                 WARN_ON_ONCE(env->insn_idx == 0);
14760                 ret = do_check_common(env, i);
14761                 if (ret) {
14762                         return ret;
14763                 } else if (env->log.level & BPF_LOG_LEVEL) {
14764                         verbose(env,
14765                                 "Func#%d is safe for any args that match its prototype\n",
14766                                 i);
14767                 }
14768         }
14769         return 0;
14770 }
14771
14772 static int do_check_main(struct bpf_verifier_env *env)
14773 {
14774         int ret;
14775
14776         env->insn_idx = 0;
14777         ret = do_check_common(env, 0);
14778         if (!ret)
14779                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14780         return ret;
14781 }
14782
14783
14784 static void print_verification_stats(struct bpf_verifier_env *env)
14785 {
14786         int i;
14787
14788         if (env->log.level & BPF_LOG_STATS) {
14789                 verbose(env, "verification time %lld usec\n",
14790                         div_u64(env->verification_time, 1000));
14791                 verbose(env, "stack depth ");
14792                 for (i = 0; i < env->subprog_cnt; i++) {
14793                         u32 depth = env->subprog_info[i].stack_depth;
14794
14795                         verbose(env, "%d", depth);
14796                         if (i + 1 < env->subprog_cnt)
14797                                 verbose(env, "+");
14798                 }
14799                 verbose(env, "\n");
14800         }
14801         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14802                 "total_states %d peak_states %d mark_read %d\n",
14803                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14804                 env->max_states_per_insn, env->total_states,
14805                 env->peak_states, env->longest_mark_read_walk);
14806 }
14807
14808 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14809 {
14810         const struct btf_type *t, *func_proto;
14811         const struct bpf_struct_ops *st_ops;
14812         const struct btf_member *member;
14813         struct bpf_prog *prog = env->prog;
14814         u32 btf_id, member_idx;
14815         const char *mname;
14816
14817         if (!prog->gpl_compatible) {
14818                 verbose(env, "struct ops programs must have a GPL compatible license\n");
14819                 return -EINVAL;
14820         }
14821
14822         btf_id = prog->aux->attach_btf_id;
14823         st_ops = bpf_struct_ops_find(btf_id);
14824         if (!st_ops) {
14825                 verbose(env, "attach_btf_id %u is not a supported struct\n",
14826                         btf_id);
14827                 return -ENOTSUPP;
14828         }
14829
14830         t = st_ops->type;
14831         member_idx = prog->expected_attach_type;
14832         if (member_idx >= btf_type_vlen(t)) {
14833                 verbose(env, "attach to invalid member idx %u of struct %s\n",
14834                         member_idx, st_ops->name);
14835                 return -EINVAL;
14836         }
14837
14838         member = &btf_type_member(t)[member_idx];
14839         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14840         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14841                                                NULL);
14842         if (!func_proto) {
14843                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14844                         mname, member_idx, st_ops->name);
14845                 return -EINVAL;
14846         }
14847
14848         if (st_ops->check_member) {
14849                 int err = st_ops->check_member(t, member);
14850
14851                 if (err) {
14852                         verbose(env, "attach to unsupported member %s of struct %s\n",
14853                                 mname, st_ops->name);
14854                         return err;
14855                 }
14856         }
14857
14858         prog->aux->attach_func_proto = func_proto;
14859         prog->aux->attach_func_name = mname;
14860         env->ops = st_ops->verifier_ops;
14861
14862         return 0;
14863 }
14864 #define SECURITY_PREFIX "security_"
14865
14866 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14867 {
14868         if (within_error_injection_list(addr) ||
14869             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14870                 return 0;
14871
14872         return -EINVAL;
14873 }
14874
14875 /* list of non-sleepable functions that are otherwise on
14876  * ALLOW_ERROR_INJECTION list
14877  */
14878 BTF_SET_START(btf_non_sleepable_error_inject)
14879 /* Three functions below can be called from sleepable and non-sleepable context.
14880  * Assume non-sleepable from bpf safety point of view.
14881  */
14882 BTF_ID(func, __filemap_add_folio)
14883 BTF_ID(func, should_fail_alloc_page)
14884 BTF_ID(func, should_failslab)
14885 BTF_SET_END(btf_non_sleepable_error_inject)
14886
14887 static int check_non_sleepable_error_inject(u32 btf_id)
14888 {
14889         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14890 }
14891
14892 int bpf_check_attach_target(struct bpf_verifier_log *log,
14893                             const struct bpf_prog *prog,
14894                             const struct bpf_prog *tgt_prog,
14895                             u32 btf_id,
14896                             struct bpf_attach_target_info *tgt_info)
14897 {
14898         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14899         const char prefix[] = "btf_trace_";
14900         int ret = 0, subprog = -1, i;
14901         const struct btf_type *t;
14902         bool conservative = true;
14903         const char *tname;
14904         struct btf *btf;
14905         long addr = 0;
14906
14907         if (!btf_id) {
14908                 bpf_log(log, "Tracing programs must provide btf_id\n");
14909                 return -EINVAL;
14910         }
14911         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14912         if (!btf) {
14913                 bpf_log(log,
14914                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14915                 return -EINVAL;
14916         }
14917         t = btf_type_by_id(btf, btf_id);
14918         if (!t) {
14919                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14920                 return -EINVAL;
14921         }
14922         tname = btf_name_by_offset(btf, t->name_off);
14923         if (!tname) {
14924                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14925                 return -EINVAL;
14926         }
14927         if (tgt_prog) {
14928                 struct bpf_prog_aux *aux = tgt_prog->aux;
14929
14930                 for (i = 0; i < aux->func_info_cnt; i++)
14931                         if (aux->func_info[i].type_id == btf_id) {
14932                                 subprog = i;
14933                                 break;
14934                         }
14935                 if (subprog == -1) {
14936                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
14937                         return -EINVAL;
14938                 }
14939                 conservative = aux->func_info_aux[subprog].unreliable;
14940                 if (prog_extension) {
14941                         if (conservative) {
14942                                 bpf_log(log,
14943                                         "Cannot replace static functions\n");
14944                                 return -EINVAL;
14945                         }
14946                         if (!prog->jit_requested) {
14947                                 bpf_log(log,
14948                                         "Extension programs should be JITed\n");
14949                                 return -EINVAL;
14950                         }
14951                 }
14952                 if (!tgt_prog->jited) {
14953                         bpf_log(log, "Can attach to only JITed progs\n");
14954                         return -EINVAL;
14955                 }
14956                 if (tgt_prog->type == prog->type) {
14957                         /* Cannot fentry/fexit another fentry/fexit program.
14958                          * Cannot attach program extension to another extension.
14959                          * It's ok to attach fentry/fexit to extension program.
14960                          */
14961                         bpf_log(log, "Cannot recursively attach\n");
14962                         return -EINVAL;
14963                 }
14964                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14965                     prog_extension &&
14966                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14967                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14968                         /* Program extensions can extend all program types
14969                          * except fentry/fexit. The reason is the following.
14970                          * The fentry/fexit programs are used for performance
14971                          * analysis, stats and can be attached to any program
14972                          * type except themselves. When extension program is
14973                          * replacing XDP function it is necessary to allow
14974                          * performance analysis of all functions. Both original
14975                          * XDP program and its program extension. Hence
14976                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14977                          * allowed. If extending of fentry/fexit was allowed it
14978                          * would be possible to create long call chain
14979                          * fentry->extension->fentry->extension beyond
14980                          * reasonable stack size. Hence extending fentry is not
14981                          * allowed.
14982                          */
14983                         bpf_log(log, "Cannot extend fentry/fexit\n");
14984                         return -EINVAL;
14985                 }
14986         } else {
14987                 if (prog_extension) {
14988                         bpf_log(log, "Cannot replace kernel functions\n");
14989                         return -EINVAL;
14990                 }
14991         }
14992
14993         switch (prog->expected_attach_type) {
14994         case BPF_TRACE_RAW_TP:
14995                 if (tgt_prog) {
14996                         bpf_log(log,
14997                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14998                         return -EINVAL;
14999                 }
15000                 if (!btf_type_is_typedef(t)) {
15001                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
15002                                 btf_id);
15003                         return -EINVAL;
15004                 }
15005                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
15006                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
15007                                 btf_id, tname);
15008                         return -EINVAL;
15009                 }
15010                 tname += sizeof(prefix) - 1;
15011                 t = btf_type_by_id(btf, t->type);
15012                 if (!btf_type_is_ptr(t))
15013                         /* should never happen in valid vmlinux build */
15014                         return -EINVAL;
15015                 t = btf_type_by_id(btf, t->type);
15016                 if (!btf_type_is_func_proto(t))
15017                         /* should never happen in valid vmlinux build */
15018                         return -EINVAL;
15019
15020                 break;
15021         case BPF_TRACE_ITER:
15022                 if (!btf_type_is_func(t)) {
15023                         bpf_log(log, "attach_btf_id %u is not a function\n",
15024                                 btf_id);
15025                         return -EINVAL;
15026                 }
15027                 t = btf_type_by_id(btf, t->type);
15028                 if (!btf_type_is_func_proto(t))
15029                         return -EINVAL;
15030                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15031                 if (ret)
15032                         return ret;
15033                 break;
15034         default:
15035                 if (!prog_extension)
15036                         return -EINVAL;
15037                 fallthrough;
15038         case BPF_MODIFY_RETURN:
15039         case BPF_LSM_MAC:
15040         case BPF_LSM_CGROUP:
15041         case BPF_TRACE_FENTRY:
15042         case BPF_TRACE_FEXIT:
15043                 if (!btf_type_is_func(t)) {
15044                         bpf_log(log, "attach_btf_id %u is not a function\n",
15045                                 btf_id);
15046                         return -EINVAL;
15047                 }
15048                 if (prog_extension &&
15049                     btf_check_type_match(log, prog, btf, t))
15050                         return -EINVAL;
15051                 t = btf_type_by_id(btf, t->type);
15052                 if (!btf_type_is_func_proto(t))
15053                         return -EINVAL;
15054
15055                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15056                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15057                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15058                         return -EINVAL;
15059
15060                 if (tgt_prog && conservative)
15061                         t = NULL;
15062
15063                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15064                 if (ret < 0)
15065                         return ret;
15066
15067                 if (tgt_prog) {
15068                         if (subprog == 0)
15069                                 addr = (long) tgt_prog->bpf_func;
15070                         else
15071                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15072                 } else {
15073                         addr = kallsyms_lookup_name(tname);
15074                         if (!addr) {
15075                                 bpf_log(log,
15076                                         "The address of function %s cannot be found\n",
15077                                         tname);
15078                                 return -ENOENT;
15079                         }
15080                 }
15081
15082                 if (prog->aux->sleepable) {
15083                         ret = -EINVAL;
15084                         switch (prog->type) {
15085                         case BPF_PROG_TYPE_TRACING:
15086                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15087                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15088                                  */
15089                                 if (!check_non_sleepable_error_inject(btf_id) &&
15090                                     within_error_injection_list(addr))
15091                                         ret = 0;
15092                                 break;
15093                         case BPF_PROG_TYPE_LSM:
15094                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15095                                  * Only some of them are sleepable.
15096                                  */
15097                                 if (bpf_lsm_is_sleepable_hook(btf_id))
15098                                         ret = 0;
15099                                 break;
15100                         default:
15101                                 break;
15102                         }
15103                         if (ret) {
15104                                 bpf_log(log, "%s is not sleepable\n", tname);
15105                                 return ret;
15106                         }
15107                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15108                         if (tgt_prog) {
15109                                 bpf_log(log, "can't modify return codes of BPF programs\n");
15110                                 return -EINVAL;
15111                         }
15112                         ret = check_attach_modify_return(addr, tname);
15113                         if (ret) {
15114                                 bpf_log(log, "%s() is not modifiable\n", tname);
15115                                 return ret;
15116                         }
15117                 }
15118
15119                 break;
15120         }
15121         tgt_info->tgt_addr = addr;
15122         tgt_info->tgt_name = tname;
15123         tgt_info->tgt_type = t;
15124         return 0;
15125 }
15126
15127 BTF_SET_START(btf_id_deny)
15128 BTF_ID_UNUSED
15129 #ifdef CONFIG_SMP
15130 BTF_ID(func, migrate_disable)
15131 BTF_ID(func, migrate_enable)
15132 #endif
15133 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15134 BTF_ID(func, rcu_read_unlock_strict)
15135 #endif
15136 BTF_SET_END(btf_id_deny)
15137
15138 static int check_attach_btf_id(struct bpf_verifier_env *env)
15139 {
15140         struct bpf_prog *prog = env->prog;
15141         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15142         struct bpf_attach_target_info tgt_info = {};
15143         u32 btf_id = prog->aux->attach_btf_id;
15144         struct bpf_trampoline *tr;
15145         int ret;
15146         u64 key;
15147
15148         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15149                 if (prog->aux->sleepable)
15150                         /* attach_btf_id checked to be zero already */
15151                         return 0;
15152                 verbose(env, "Syscall programs can only be sleepable\n");
15153                 return -EINVAL;
15154         }
15155
15156         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15157             prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15158                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15159                 return -EINVAL;
15160         }
15161
15162         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15163                 return check_struct_ops_btf_id(env);
15164
15165         if (prog->type != BPF_PROG_TYPE_TRACING &&
15166             prog->type != BPF_PROG_TYPE_LSM &&
15167             prog->type != BPF_PROG_TYPE_EXT)
15168                 return 0;
15169
15170         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15171         if (ret)
15172                 return ret;
15173
15174         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15175                 /* to make freplace equivalent to their targets, they need to
15176                  * inherit env->ops and expected_attach_type for the rest of the
15177                  * verification
15178                  */
15179                 env->ops = bpf_verifier_ops[tgt_prog->type];
15180                 prog->expected_attach_type = tgt_prog->expected_attach_type;
15181         }
15182
15183         /* store info about the attachment target that will be used later */
15184         prog->aux->attach_func_proto = tgt_info.tgt_type;
15185         prog->aux->attach_func_name = tgt_info.tgt_name;
15186
15187         if (tgt_prog) {
15188                 prog->aux->saved_dst_prog_type = tgt_prog->type;
15189                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15190         }
15191
15192         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15193                 prog->aux->attach_btf_trace = true;
15194                 return 0;
15195         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15196                 if (!bpf_iter_prog_supported(prog))
15197                         return -EINVAL;
15198                 return 0;
15199         }
15200
15201         if (prog->type == BPF_PROG_TYPE_LSM) {
15202                 ret = bpf_lsm_verify_prog(&env->log, prog);
15203                 if (ret < 0)
15204                         return ret;
15205         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15206                    btf_id_set_contains(&btf_id_deny, btf_id)) {
15207                 return -EINVAL;
15208         }
15209
15210         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15211         tr = bpf_trampoline_get(key, &tgt_info);
15212         if (!tr)
15213                 return -ENOMEM;
15214
15215         prog->aux->dst_trampoline = tr;
15216         return 0;
15217 }
15218
15219 struct btf *bpf_get_btf_vmlinux(void)
15220 {
15221         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15222                 mutex_lock(&bpf_verifier_lock);
15223                 if (!btf_vmlinux)
15224                         btf_vmlinux = btf_parse_vmlinux();
15225                 mutex_unlock(&bpf_verifier_lock);
15226         }
15227         return btf_vmlinux;
15228 }
15229
15230 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15231 {
15232         u64 start_time = ktime_get_ns();
15233         struct bpf_verifier_env *env;
15234         struct bpf_verifier_log *log;
15235         int i, len, ret = -EINVAL;
15236         bool is_priv;
15237
15238         /* no program is valid */
15239         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15240                 return -EINVAL;
15241
15242         /* 'struct bpf_verifier_env' can be global, but since it's not small,
15243          * allocate/free it every time bpf_check() is called
15244          */
15245         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15246         if (!env)
15247                 return -ENOMEM;
15248         log = &env->log;
15249
15250         len = (*prog)->len;
15251         env->insn_aux_data =
15252                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15253         ret = -ENOMEM;
15254         if (!env->insn_aux_data)
15255                 goto err_free_env;
15256         for (i = 0; i < len; i++)
15257                 env->insn_aux_data[i].orig_idx = i;
15258         env->prog = *prog;
15259         env->ops = bpf_verifier_ops[env->prog->type];
15260         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15261         is_priv = bpf_capable();
15262
15263         bpf_get_btf_vmlinux();
15264
15265         /* grab the mutex to protect few globals used by verifier */
15266         if (!is_priv)
15267                 mutex_lock(&bpf_verifier_lock);
15268
15269         if (attr->log_level || attr->log_buf || attr->log_size) {
15270                 /* user requested verbose verifier output
15271                  * and supplied buffer to store the verification trace
15272                  */
15273                 log->level = attr->log_level;
15274                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15275                 log->len_total = attr->log_size;
15276
15277                 /* log attributes have to be sane */
15278                 if (!bpf_verifier_log_attr_valid(log)) {
15279                         ret = -EINVAL;
15280                         goto err_unlock;
15281                 }
15282         }
15283
15284         mark_verifier_state_clean(env);
15285
15286         if (IS_ERR(btf_vmlinux)) {
15287                 /* Either gcc or pahole or kernel are broken. */
15288                 verbose(env, "in-kernel BTF is malformed\n");
15289                 ret = PTR_ERR(btf_vmlinux);
15290                 goto skip_full_check;
15291         }
15292
15293         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15294         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15295                 env->strict_alignment = true;
15296         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15297                 env->strict_alignment = false;
15298
15299         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15300         env->allow_uninit_stack = bpf_allow_uninit_stack();
15301         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15302         env->bypass_spec_v1 = bpf_bypass_spec_v1();
15303         env->bypass_spec_v4 = bpf_bypass_spec_v4();
15304         env->bpf_capable = bpf_capable();
15305
15306         if (is_priv)
15307                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15308
15309         env->explored_states = kvcalloc(state_htab_size(env),
15310                                        sizeof(struct bpf_verifier_state_list *),
15311                                        GFP_USER);
15312         ret = -ENOMEM;
15313         if (!env->explored_states)
15314                 goto skip_full_check;
15315
15316         ret = add_subprog_and_kfunc(env);
15317         if (ret < 0)
15318                 goto skip_full_check;
15319
15320         ret = check_subprogs(env);
15321         if (ret < 0)
15322                 goto skip_full_check;
15323
15324         ret = check_btf_info(env, attr, uattr);
15325         if (ret < 0)
15326                 goto skip_full_check;
15327
15328         ret = check_attach_btf_id(env);
15329         if (ret)
15330                 goto skip_full_check;
15331
15332         ret = resolve_pseudo_ldimm64(env);
15333         if (ret < 0)
15334                 goto skip_full_check;
15335
15336         if (bpf_prog_is_dev_bound(env->prog->aux)) {
15337                 ret = bpf_prog_offload_verifier_prep(env->prog);
15338                 if (ret)
15339                         goto skip_full_check;
15340         }
15341
15342         ret = check_cfg(env);
15343         if (ret < 0)
15344                 goto skip_full_check;
15345
15346         ret = do_check_subprogs(env);
15347         ret = ret ?: do_check_main(env);
15348
15349         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15350                 ret = bpf_prog_offload_finalize(env);
15351
15352 skip_full_check:
15353         kvfree(env->explored_states);
15354
15355         if (ret == 0)
15356                 ret = check_max_stack_depth(env);
15357
15358         /* instruction rewrites happen after this point */
15359         if (ret == 0)
15360                 ret = optimize_bpf_loop(env);
15361
15362         if (is_priv) {
15363                 if (ret == 0)
15364                         opt_hard_wire_dead_code_branches(env);
15365                 if (ret == 0)
15366                         ret = opt_remove_dead_code(env);
15367                 if (ret == 0)
15368                         ret = opt_remove_nops(env);
15369         } else {
15370                 if (ret == 0)
15371                         sanitize_dead_code(env);
15372         }
15373
15374         if (ret == 0)
15375                 /* program is valid, convert *(u32*)(ctx + off) accesses */
15376                 ret = convert_ctx_accesses(env);
15377
15378         if (ret == 0)
15379                 ret = do_misc_fixups(env);
15380
15381         /* do 32-bit optimization after insn patching has done so those patched
15382          * insns could be handled correctly.
15383          */
15384         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15385                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15386                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15387                                                                      : false;
15388         }
15389
15390         if (ret == 0)
15391                 ret = fixup_call_args(env);
15392
15393         env->verification_time = ktime_get_ns() - start_time;
15394         print_verification_stats(env);
15395         env->prog->aux->verified_insns = env->insn_processed;
15396
15397         if (log->level && bpf_verifier_log_full(log))
15398                 ret = -ENOSPC;
15399         if (log->level && !log->ubuf) {
15400                 ret = -EFAULT;
15401                 goto err_release_maps;
15402         }
15403
15404         if (ret)
15405                 goto err_release_maps;
15406
15407         if (env->used_map_cnt) {
15408                 /* if program passed verifier, update used_maps in bpf_prog_info */
15409                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15410                                                           sizeof(env->used_maps[0]),
15411                                                           GFP_KERNEL);
15412
15413                 if (!env->prog->aux->used_maps) {
15414                         ret = -ENOMEM;
15415                         goto err_release_maps;
15416                 }
15417
15418                 memcpy(env->prog->aux->used_maps, env->used_maps,
15419                        sizeof(env->used_maps[0]) * env->used_map_cnt);
15420                 env->prog->aux->used_map_cnt = env->used_map_cnt;
15421         }
15422         if (env->used_btf_cnt) {
15423                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15424                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15425                                                           sizeof(env->used_btfs[0]),
15426                                                           GFP_KERNEL);
15427                 if (!env->prog->aux->used_btfs) {
15428                         ret = -ENOMEM;
15429                         goto err_release_maps;
15430                 }
15431
15432                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15433                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15434                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15435         }
15436         if (env->used_map_cnt || env->used_btf_cnt) {
15437                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15438                  * bpf_ld_imm64 instructions
15439                  */
15440                 convert_pseudo_ld_imm64(env);
15441         }
15442
15443         adjust_btf_func(env);
15444
15445 err_release_maps:
15446         if (!env->prog->aux->used_maps)
15447                 /* if we didn't copy map pointers into bpf_prog_info, release
15448                  * them now. Otherwise free_used_maps() will release them.
15449                  */
15450                 release_maps(env);
15451         if (!env->prog->aux->used_btfs)
15452                 release_btfs(env);
15453
15454         /* extension progs temporarily inherit the attach_type of their targets
15455            for verification purposes, so set it back to zero before returning
15456          */
15457         if (env->prog->type == BPF_PROG_TYPE_EXT)
15458                 env->prog->expected_attach_type = 0;
15459
15460         *prog = env->prog;
15461 err_unlock:
15462         if (!is_priv)
15463                 mutex_unlock(&bpf_verifier_lock);
15464         vfree(env->insn_aux_data);
15465 err_free_env:
15466         kfree(env);
15467         return ret;
15468 }